branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>MJPB0/BattlingBalloons<file_sep>/BattlingBaloons/Assets/Scripts/UI/VolumeSlider.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class VolumeSlider : MonoBehaviour { [SerializeField] Slider _volumeSlider; private void Start() { _volumeSlider.value = PlayerPrefsController.GetMasterVolume(); } public void SetVolume() { PlayerPrefsController.SetMasterVolume(_volumeSlider.value); AudioManager.Instance.SetVolumes(PlayerPrefsController.GetMasterVolume()); } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/PausedGameUI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PausedGameUI : MonoBehaviour { [SerializeField] Button resumeButton; [SerializeField] Button mainMenuButton; [SerializeField] Button quitButton; [SerializeField] GameObject gameUI; private void Start() { resumeButton.onClick.AddListener(HandleResumeClicked); mainMenuButton.onClick.AddListener(HandleMainMenuClicked); quitButton.onClick.AddListener(HandleQuitClicked); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape) && GameManager.Instance.CurrentGameState == GameManager.GameState.PAUSED) { ToggleGameUI(true); GameManager.Instance.UpdateGameState(GameManager.GameState.PLAYING); } } void HandleResumeClicked() { ToggleGameUI(true); GameManager.Instance.UpdateGameState(GameManager.GameState.PLAYING); AudioManager.Instance.PlayMenuClick(); } void HandleMainMenuClicked() { GameManager.Instance.UpdateGameState(GameManager.GameState.PREGAME); AudioManager.Instance.PlayMenuClick(); } void HandleQuitClicked() { AudioManager.Instance.PlayMenuClick(); Application.Quit(); } void ToggleGameUI(bool active) { gameUI.SetActive(active); gameObject.SetActive(!active); AudioManager.Instance.PlayMenuClick(); } } <file_sep>/BattlingBaloons/Assets/Scripts/RoundConfiguration.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using EZCameraShake; using System; public class RoundConfiguration : MonoBehaviour { [SerializeField] Dropdown _roundTime; [SerializeField] Dropdown _roundCount; private void Start() { _roundTime.value = 5; _roundCount.value = 2; } public void RoundTimeChanged() { PlayerPrefsController.SetRoundsTime((_roundTime.value != 0) ? _roundTime.value * 60 : 30f); } public void RoundCountChanged() { PlayerPrefsController.SetRoundsCount(_roundCount.value + 1); } } <file_sep>/BattlingBaloons/Assets/Scripts/Tutorial/TutorialButtons.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TutorialButtons : MonoBehaviour { [SerializeField] Button quitButton; [SerializeField] Button mainMenuButton; // Start is called before the first frame update void Start() { mainMenuButton.onClick.AddListener(HandleMainMenuClicked); quitButton.onClick.AddListener(HandleQuitClicked); } void HandleMainMenuClicked() { GameManager.Instance.LoadMainMenu(); AudioManager.Instance.PlayMenuClick(); } void HandleQuitClicked() { AudioManager.Instance.PlayMenuClick(); Application.Quit(); } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/KeybindsMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class KeybindsMenu : MonoBehaviour { [SerializeField] Button _returnButton; [SerializeField] GameObject optionsMenu; [SerializeField] GameObject ground; [SerializeField] GameObject returnScreen; [SerializeField] Button saveKeybindsButton; [SerializeField] Button discardKeybindsButton; private void Start() { _returnButton.onClick.AddListener(HandleReturnClicked); discardKeybindsButton.onClick.AddListener(HandleDiscardKeybindsClicked); saveKeybindsButton.onClick.AddListener(HandleSaveKeybindsClicked); } void HandleReturnClicked() { returnScreen.SetActive(true); } void ToggleOptionsMenu() { optionsMenu.SetActive(true); gameObject.SetActive(false); returnScreen.SetActive(false); ground.SetActive(true); } void HandleDiscardKeybindsClicked() { ToggleOptionsMenu(); } void HandleSaveKeybindsClicked() { GetComponent<KeybindsManager>().SaveKeybinds(); ToggleOptionsMenu(); } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/ScoreboardUI.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SocialPlatforms.Impl; using UnityEngine.UI; public class ScoreboardUI : MonoBehaviour { [SerializeField] Button mainMenuButton; [SerializeField] Button quitButton; [SerializeField] Text player1RoundsWon; [SerializeField] Text player1OverallScore; [SerializeField] Text player2RoundsWon; [SerializeField] Text player2OverallScore; private void Start() { mainMenuButton.onClick.AddListener(HandleMainMenuClicked); quitButton.onClick.AddListener(HandleQuitButtonClicked); ProcessScore(); } void HandleMainMenuClicked() { GameManager.Instance.LoadMainMenu(); GameManager.Instance.ScoreBoard.Clear(); GameManager.Instance.CurrentRound = 1; AudioManager.Instance.PlayMenuClick(); } void HandleQuitButtonClicked() { AudioManager.Instance.PlayMenuClick(); Application.Quit(); } void ProcessScore() { int score1 = 0, score2 = 0, rounds1 = 0, rounds2 = 0; for(int i = 0; i < GameManager.Instance.ScoreBoard.Count; i++) { string s = GameManager.Instance.ScoreBoard[i]; int[] nums = new int[2]; string pom = ""; int index = 0; for(int j = 0; j < s.Length; j++) { if (s[j] == ';') { if(index == 0) { nums[0] = Convert.ToInt32(pom); score1 += Convert.ToInt32(pom); }else if(index == 1) { nums[1] = Convert.ToInt32(pom); score2 += Convert.ToInt32(pom); } index++; pom = ""; } else { pom += s[j]; } } if (nums[0] > nums[1]) rounds1++; else if (nums[0] < nums[1]) rounds2++; else if (nums[0] == nums[1]) { rounds1++; rounds2++; } } player1RoundsWon.text = rounds1.ToString(); player1OverallScore.text = score1.ToString(); player2RoundsWon.text = rounds2.ToString(); player2OverallScore.text = score2.ToString(); } } <file_sep>/BattlingBaloons/Assets/Scripts/Core/RoundManager.cs using System; using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; public class RoundManager : MonoBehaviour { public UnityAction OnRoundEnded; [Header("Round")] [SerializeField] int roundCount; [Space] [SerializeField] float roundTime; [SerializeField] float noAmmoDeathTime; public bool timeRunning { get; set; } [Space] [SerializeField] Slider roundTimeSlider; [SerializeField] Slider noAmmoDeathSlider; [Space] [SerializeField] GameObject countdownIndicator; [Space] [SerializeField] GameObject nextRound; public int RoundCount { get { return roundCount; } set { roundCount = value; } } private void Start() { roundCount = PlayerPrefsController.GetRoundsCount(); roundTime = PlayerPrefsController.GetRoundTime(); roundTimeSlider.maxValue = PlayerPrefsController.GetRoundTime(); OnRoundEnded += RoundEnded; } private void Update() { if (PlayerManager.Instance.Player1.OutOFAmmo && PlayerManager.Instance.Player2.OutOFAmmo) { CountDeathTime(); } else if ((!PlayerManager.Instance.Player1.OutOFAmmo || !PlayerManager.Instance.Player2.OutOFAmmo) && noAmmoDeathSlider.value < 5f) { noAmmoDeathTime = 5f; noAmmoDeathSlider.value = noAmmoDeathTime; } if(timeRunning) CountRoundTime(); } void CountRoundTime() { if (roundTime > 0) { roundTime -= Time.deltaTime; roundTimeSlider.value = roundTime; } else if (roundTime <= 0) { roundTime = PlayerPrefsController.GetRoundTime(); roundTimeSlider.value = roundTime; // Debug.Log("[Round Manager] Round time ended."); OnRoundEnded?.Invoke(); } } void CountDeathTime() { if (noAmmoDeathTime > 0) { noAmmoDeathTime -= Time.deltaTime; noAmmoDeathSlider.value = noAmmoDeathTime; } else { noAmmoDeathTime = 5f; noAmmoDeathSlider.value = noAmmoDeathTime; PlayerManager.Instance.Player1.Die(); PlayerManager.Instance.Player2.Die(); } } void RoundEnded() { //Debug.Log("Round Ended!"); AddRoundToScoreboard(); GameManager.Instance.CurrentRound++; if (GameManager.Instance.CurrentRound == roundCount + 1) { //Debug.Log("[Round Manager] Loaded Scoreboard. " + GameManager.Instance.CurrentRound + " : " + RoundCount + ";"); GameManager.Instance.LoadScoreboard(); GameManager.Instance.CurrentRound = 1; } else if (GameManager.Instance.CurrentRound < roundCount + 1) { // Debug.Log("[Round Manager] Restarted Level. " + GameManager.Instance.CurrentRound + " : " + RoundCount + ";"); RestartRound(); FindObjectOfType<GameUI>().UpdateCurrentRoundText(); } } void AddRoundToScoreboard() { string scoreToSave = PlayerManager.Instance.Player1.Score + ";" + PlayerManager.Instance.Player2.Score + ";"; GameManager.Instance.ScoreBoard.Add(scoreToSave); } void RestartRound() { Player[] players = FindObjectsOfType<Player>(); for (int i = 0; i < 2; i++) { players[i].ResetPlayer(); } ResetGameUI(); StartCoroutine(WaitAndStartCountingTime(players[0], players[1])); } IEnumerator WaitAndStartCountingTime(Player player1, Player player2) { timeRunning = false; yield return new WaitForSeconds(5f); timeRunning = true; } void ResetGameUI() { PlayerManager.Instance.Player1.Score = 0; PlayerManager.Instance.Player2.Score = 0; PlayerManager.Instance.UpdateScoreBoard(); PlayerManager.Instance.ClearPlayersCombos(); } } <file_sep>/README.md # BattlingBalloons 2D PvP game made in Unity (Mostly done by now) <file_sep>/BattlingBaloons/Assets/Scripts/Core/AudioManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioManager : MonoBehaviour { public static AudioManager Instance; AudioSource mainAudioSource; [SerializeField] AudioClip[] menuClickSFX; [SerializeField] AudioClip[] particleCollideSFX; private void Awake() { if(Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } private void Start() { mainAudioSource = GetComponent<AudioSource>(); } public void PlayMenuClick() { mainAudioSource.PlayOneShot(menuClickSFX[Random.Range(0, menuClickSFX.Length)], mainAudioSource.volume * .5f); } public void PlayParticleColliding() { mainAudioSource.PlayOneShot(particleCollideSFX[Random.Range(0, particleCollideSFX.Length)], .008f); } public void SetVolumes(float value) { mainAudioSource.volume = value; } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/PvPMapSelection.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PvPMapSelection : MonoBehaviour { [SerializeField] Button returnButton; [SerializeField] Button _map1; [SerializeField] Button _map2; [SerializeField] Button _map3; [SerializeField] Button _map4; [SerializeField] GameObject gameModeSelection; [SerializeField] GameObject ground; private void Start() { returnButton.onClick.AddListener(HandleReturnClicked); _map1.onClick.AddListener(HandleMap1Clicked); _map2.onClick.AddListener(HandleMap2Clicked); _map3.onClick.AddListener(HandleMap3Clicked); _map4.onClick.AddListener(HandleMap4Clicked); } void HandleReturnClicked() { gameModeSelection.SetActive(true); gameObject.SetActive(false); ground.SetActive(true); AudioManager.Instance.PlayMenuClick(); } void HandleMap1Clicked() { GameManager.Instance.StartGame("Level 0"); AudioManager.Instance.PlayMenuClick(); } void HandleMap2Clicked() { GameManager.Instance.StartGame("Level 1"); AudioManager.Instance.PlayMenuClick(); } void HandleMap3Clicked() { GameManager.Instance.StartGame("Level 2"); AudioManager.Instance.PlayMenuClick(); } void HandleMap4Clicked() { GameManager.Instance.StartGame("Level 3"); AudioManager.Instance.PlayMenuClick(); } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/MainMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainMenu : MonoBehaviour { [SerializeField] Button _playButton; [SerializeField] Button _optionsButton; [SerializeField] Button _quitButton; [SerializeField] GameObject optionsMenu; [SerializeField] GameObject gameModeSelectionMenu; private void Start() { _playButton.onClick.AddListener(HandlePlayClicked); _optionsButton.onClick.AddListener(HandleOptionsClicked); _quitButton.onClick.AddListener(HandleQuitClicked); } void HandlePlayClicked() { gameModeSelectionMenu.SetActive(true); gameObject.SetActive(false); AudioManager.Instance.PlayMenuClick(); } void HandleOptionsClicked() { optionsMenu.SetActive(true); gameObject.SetActive(false); AudioManager.Instance.PlayMenuClick(); } void HandleQuitClicked() { AudioManager.Instance.PlayMenuClick(); Application.Quit(); } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/GameUI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameUI : MonoBehaviour { [SerializeField] Button pauseButton; [SerializeField] Button mainMenuButton; [SerializeField] Button quitButton; [SerializeField] Text currentRound; [SerializeField] GameObject pausedGameUI; private void Start() { pauseButton.onClick.AddListener(HandlePauseClicked); mainMenuButton.onClick.AddListener(HandleMainMenuClicked); quitButton.onClick.AddListener(HandleQuitClicked); GameManager.Instance.OnGameStateChanged.AddListener(HandleGameStateChanged); UpdateCurrentRoundText(); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape) && GameManager.Instance.CurrentGameState == GameManager.GameState.PLAYING) { TogglePauseGameUI(true); GameManager.Instance.UpdateGameState(GameManager.GameState.PAUSED); } } void HandlePauseClicked() { TogglePauseGameUI(true); GameManager.Instance.UpdateGameState(GameManager.GameState.PAUSED); } void HandleMainMenuClicked() { GameManager.Instance.UpdateGameState(GameManager.GameState.PREGAME); AudioManager.Instance.PlayMenuClick(); } void HandleQuitClicked() { AudioManager.Instance.PlayMenuClick(); Application.Quit(); } public void HandleGameStateChanged(GameManager.GameState current, GameManager.GameState previous) { if (current == GameManager.GameState.PREGAME && (previous == GameManager.GameState.PLAYING || previous == GameManager.GameState.PAUSED)) { GameManager.Instance.LoadMainMenu(); } } void TogglePauseGameUI(bool active) { gameObject.SetActive(!active); pausedGameUI.SetActive(active); } public void UpdateCurrentRoundText() { currentRound.text = GameManager.Instance.CurrentRound.ToString(); } } <file_sep>/BattlingBaloons/Assets/Scripts/Player/Player.cs using System.Collections; using UnityEngine; using UnityEngine.UI; using EZCameraShake; using UnityEngine.SceneManagement; using System.Numerics; public class Player : MonoBehaviour, IDamagable { #region Variables int score; public UnityEngine.Vector2 basePos; [Header("Health & Death")] [SerializeField] float health = 0f; [SerializeField] GameObject deathVFX; [SerializeField] float yOffset = .5f; public bool damagable { get; set; } [Header("Projectiles")] [SerializeField] float amountOfProjectiles = 100f; [SerializeField] float waterUsage = 20f; [SerializeField] float rewardWater = 10f; [SerializeField] bool outOfAmmo = false; public bool ableToShoot { get; set; } [Space] [SerializeField] int damage = 1; [SerializeReference] int damageFromDeathParticles = 2; [Space] [SerializeField] ParticleSystem water; [SerializeField] GameObject gun; [Header("Respawn")] [SerializeField] float respawnTime; [SerializeField] Transform[] spawnPoints; [Header("Sliders")] [SerializeField] Slider fillIndicator; [SerializeField] Slider ammoSlider; public GameObject Gun { get { return gun; } } public int Score { get { return score; } set { score = value; } } public bool OutOFAmmo { get { return outOfAmmo; } } PlayerAudio playerAudio; AudioSource playerAudioSource; #endregion #region Start&Update private void Start() { basePos = transform.position; playerAudio = GetComponent<PlayerAudio>(); playerAudioSource = GetComponent<AudioSource>(); if(gameObject.CompareTag("Player 1")) { PlayerManager.Instance.Player1Died += Die; } else { PlayerManager.Instance.Player2Died += Die; } } private void Update() { if(gameObject.CompareTag("Player 1")) { if (Input.GetButton("Player 1 Fire") && ableToShoot) { if (amountOfProjectiles <= 0) { water.enableEmission = false; playerAudio.StopPlayerShootSFX(); outOfAmmo = true; return; } outOfAmmo = false; water.enableEmission = true; UseWater(); } if(Input.GetButtonUp("Player 1 Fire")) { water.enableEmission = false; } if (Input.GetButtonDown("Player 1 Fire") && !outOfAmmo && ableToShoot) { playerAudio.PlayPlayerShootSFX(); } if (Input.GetButtonUp("Player 1 Fire") || outOfAmmo || SceneManager.GetActiveScene().name == "Scoreboard" || !ableToShoot) { playerAudio.StopPlayerShootSFX(); } } else if(gameObject.CompareTag("Player 2")) { if (Input.GetButton("Player 2 Fire") && ableToShoot) { if (amountOfProjectiles <= 0) { water.enableEmission = false; playerAudio.StopPlayerShootSFX(); outOfAmmo = true; return; } outOfAmmo = false; water.enableEmission = true; UseWater(); } if(Input.GetButtonUp("Player 2 Fire")) { water.enableEmission = false; } if (Input.GetButtonDown("Player 2 Fire") && !outOfAmmo && ableToShoot) { playerAudio.PlayPlayerShootSFX(); } if (Input.GetButtonUp("Player 2 Fire") || outOfAmmo || SceneManager.GetActiveScene().name == "Scoreboard" || !ableToShoot) { playerAudio.StopPlayerShootSFX(); } } } #endregion private void OnParticleCollision(GameObject other) { if(!other.gameObject.CompareTag("Player 1 Death Particles") && !other.gameObject.CompareTag("Player 2 Death Particles")) Damage(other.gameObject.GetComponentInParent<Player>().damage); else { //Debug.Log(gameObject.name + " got hit for " + damageFromDeathParticles + " dmg"); Damage(damageFromDeathParticles); } } public void Damage(int damage) { if (health + damage < 100f) { health += damage; //Debug.Log("[Player] name: " + gameObject.name + " now has " + health + " health"); UpdateFillIndicator(); } else if (health + damage >= 100f) { if (gameObject.CompareTag("Player 1")) PlayerManager.Instance.TriggerPlayer1Died(); else if (gameObject.CompareTag("Player 2")) PlayerManager.Instance.TriggerPlayer2Died(); } } public void Die() { GameObject death = Instantiate(deathVFX, transform.position, UnityEngine.Quaternion.identity); StartCoroutine(WaitAndDestroy(death)); CameraShaker.Instance.ShakeOnce(4f, 2f,.1f, 1f); playerAudio.PlayPlayerDeathSFX(); //Debug.Log(gameObject.name + " has died!"); Respawn(); if (gameObject.CompareTag("Player 1")) { PlayerManager.Instance.Player2AddPoint(); PlayerManager.Instance.Player2AddWater(); PlayerManager.Instance.IncreasePlayer2Combo(); }else if (gameObject.CompareTag("Player 2")) { PlayerManager.Instance.Player1AddPoint(); PlayerManager.Instance.Player1AddWater(); PlayerManager.Instance.IncreasePlayer1Combo(); } } IEnumerator WaitAndDestroy(GameObject obj) { yield return new WaitForSeconds(2f); Destroy(obj); } void Respawn() { health = 0f; amountOfProjectiles = 100f; outOfAmmo = false; UpdateFillIndicator(); UpdateAmmoCount(); transform.position = spawnPoints[Random.Range(0, spawnPoints.Length)].position; } public void ResetPlayer() { health = 0f; amountOfProjectiles = 100f; outOfAmmo = false; UpdateFillIndicator(); UpdateAmmoCount(); transform.position = basePos; } public void UpdateFillIndicator() { fillIndicator.value = health; } public void UpdateAmmoCount() { ammoSlider.value = amountOfProjectiles; } void UseWater() { amountOfProjectiles -= Time.deltaTime * waterUsage; UpdateAmmoCount(); } public void AddWater() { if(gameObject.CompareTag("Player 1")) { amountOfProjectiles = (amountOfProjectiles + rewardWater > 100f) ? 100f : amountOfProjectiles + rewardWater + (PlayerManager.Instance.Player1Combo - 1) * rewardWater * .3f; } else { amountOfProjectiles = (amountOfProjectiles + rewardWater > 100f) ? 100f : amountOfProjectiles + rewardWater + (PlayerManager.Instance.Player2Combo - 1) * rewardWater * .3f; } UpdateAmmoCount(); } } <file_sep>/BattlingBaloons/Assets/Scripts/WaterParticlesCollision.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaterParticlesCollision : MonoBehaviour { private void OnParticleCollision(GameObject other) { if(!other.CompareTag("Player 1") && !other.CompareTag("Player 2")) { AudioManager.Instance.PlayParticleColliding(); } } } <file_sep>/BattlingBaloons/Assets/Scripts/Player/PlayerAudio.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerAudio : MonoBehaviour { AudioSource playerAudioSource; [SerializeField] AudioClip playerShoot; [SerializeField] AudioClip[] playerDeathSFXs; [SerializeField] AudioClip[] playerJumpSFXs; [SerializeField] AudioClip[] playerLandSFXs; private void Start() { playerAudioSource = GetComponent<AudioSource>(); SetPlayerAudioVolume(); } public void SetPlayerAudioVolume() { playerAudioSource.volume = PlayerPrefsController.GetMasterVolume(); } public void PlayPlayerShootSFX() { if (playerAudioSource.clip != playerShoot) playerAudioSource.clip = playerShoot; playerAudioSource.Play(); } public void StopPlayerShootSFX() { if (playerAudioSource.clip == playerShoot) playerAudioSource.Stop(); } public void PlayPlayerDeathSFX() { SetPlayerAudioVolume(); playerAudioSource.PlayOneShot(playerDeathSFXs[Random.Range(0, playerDeathSFXs.Length)], playerAudioSource.volume); } public void PlayPlayerJumpSFX() { SetPlayerAudioVolume(); playerAudioSource.PlayOneShot(playerJumpSFXs[Random.Range(0, playerJumpSFXs.Length)], playerAudioSource.volume); } public void PlayPlayerLandSFX() { SetPlayerAudioVolume(); playerAudioSource.PlayOneShot(playerLandSFXs[Random.Range(0, playerLandSFXs.Length)], playerAudioSource.volume * .1f); } } <file_sep>/BattlingBaloons/Assets/Scripts/Core/PlayerPrefsController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerPrefsController { const float MIN_VOLUME = 0f; const float MAX_VOLUME = 1f; const int MIN_ROUND_COUNT = 1; const int MAX_ROUND_COUNT = 6; public static float GetMaxRoundCount { get { return MAX_ROUND_COUNT; } } public static float GetMinRoundCount { get { return MIN_ROUND_COUNT; } } const float MIN_ROUND_TIME = 30f; const float MAX_ROUND_TIME = 360f; public static float GetMaxRoundTime { get { return MAX_ROUND_TIME; } } public static float GetMinRoundTime { get { return MIN_ROUND_TIME; } } const string MASTER_VOLUME_KEY = "Master Volume"; const string ROUNDS_TO_PLAY_KEY = "Rounds Count"; const string ROUND_TIME_KEY = "Round Time"; #region Player 1 Keybinds const string PLAYER_1_MOVE_LEFT_KEY = "Player 1 Move Left"; const string PLAYER_1_MOVE_RIGHT_KEY = "Player 1 Move Right"; const string PLAYER_1_SHOOT_KEY = "Player 1 Shoot"; const string PLAYER_1_JUMP_KEY = "Player 1 Jump"; const string PLAYER_1_ROTATE_LEFT_KEY = "Player 1 Rotate Left"; const string PLAYER_1_ROTATE_RIGHT_KEY = "Player 1 Rotate Right"; #endregion #region Player 2 Keybinds const string PLAYER_2_MOVE_LEFT_KEY = "Player 2 Move Left"; const string PLAYER_2_MOVE_RIGHT_KEY = "Player 2 Move Right"; const string PLAYER_2_SHOOT_KEY = "Player 2 Shoot"; const string PLAYER_2_JUMP_KEY = "Player 2 Jump"; const string PLAYER_2_ROTATE_LEFT_KEY = "Player 2 Rotate Left"; const string PLAYER_2_ROTATE_RIGHT_KEY = "Player 2 Rotate Right"; #endregion #region Default Settings const float MASTER_VOLUME_DEFAULT = .6f; const int ROUNDS_TO_PLAY_DEFAULT = 3; const float ROUND_TIME_DEFAULT = 300f; #region Player 1 Keybinds const string PLAYER_1_MOVE_LEFT_DEFAULT = "a"; const string PLAYER_1_MOVE_RIGHT_DEFAULT = "d"; const string PLAYER_1_SHOOT_DEFAULT = "y"; const string PLAYER_1_JUMP_DEFAULT = "w"; const string PLAYER_1_ROTATE_LEFT_DEFAULT = "r"; const string PLAYER_1_ROTATE_RIGHT_DEFAULT = "t"; #endregion #region Player 2 Keybinds const string PLAYER_2_MOVE_LEFT_DEFAULT = "left"; const string PLAYER_2_MOVE_RIGHT_DEFAULT = "right"; const string PLAYER_2_SHOOT_DEFAULT = "l"; const string PLAYER_2_JUMP_DEFAULT = "up"; const string PLAYER_2_ROTATE_LEFT_DEFAULT = "j"; const string PLAYER_2_ROTATE_RIGHT_DEFAULT = "k"; #endregion #endregion #region 'Set' Methods public static void SetMasterVolume(float volume) { if (volume >= MIN_VOLUME && volume <= MAX_VOLUME) PlayerPrefs.SetFloat(MASTER_VOLUME_KEY, volume); else Debug.LogError("Master Volume not set properly!"); } public static void SetRoundsCount(int value) { if (value >= MIN_ROUND_COUNT && value <= MAX_ROUND_COUNT) PlayerPrefs.SetInt(ROUNDS_TO_PLAY_KEY, value); else Debug.LogError("Rounds count not set properly!"); } public static void SetRoundsTime(float value) { if (value >= MIN_ROUND_TIME && value <= MAX_ROUND_TIME) PlayerPrefs.SetFloat(ROUND_TIME_KEY, value); else Debug.LogError("Rounds time not set properly!"); } #endregion #region 'Get' Methods public static float GetMasterVolume() { return PlayerPrefs.GetFloat(MASTER_VOLUME_KEY); } public static float GetRoundTime() { return PlayerPrefs.GetFloat(ROUND_TIME_KEY); } public static int GetRoundsCount() { return PlayerPrefs.GetInt(ROUNDS_TO_PLAY_KEY); } #endregion #region Player 1 Keybinds public Methods #region Set Keybinds public static void SetPlayer1MoveLeft(string keybind) { PlayerPrefs.SetString(PLAYER_1_MOVE_LEFT_KEY, keybind); } public static void SetPlayer1MoveRight(string keybind) { PlayerPrefs.SetString(PLAYER_1_MOVE_RIGHT_KEY, keybind); } public static void SetPlayer1Jump(string keybind) { PlayerPrefs.SetString(PLAYER_1_JUMP_KEY, keybind); } public static void SetPlayer1Shoot(string keybind) { PlayerPrefs.SetString(PLAYER_1_SHOOT_KEY, keybind); } public static void SetPlayer1RotateLeft(string keybind) { PlayerPrefs.SetString(PLAYER_1_ROTATE_LEFT_KEY, keybind); } public static void SetPlayer1RotateRight(string keybind) { PlayerPrefs.SetString(PLAYER_1_ROTATE_RIGHT_KEY, keybind); } #endregion #region Get Keybinds public static string GetPlayer1MoveLeft() { return PlayerPrefs.GetString(PLAYER_1_MOVE_LEFT_KEY); } public static string GetPlayer1MoveRight() { return PlayerPrefs.GetString(PLAYER_1_MOVE_RIGHT_KEY); } public static string GetPlayer1Jump() { return PlayerPrefs.GetString(PLAYER_1_JUMP_KEY); } public static string GetPlayer1Shoot() { return PlayerPrefs.GetString(PLAYER_1_SHOOT_KEY); } public static string GetPlayer1RotateLeft() { return PlayerPrefs.GetString(PLAYER_1_ROTATE_LEFT_KEY); } public static string GetPlayer1RotateRight() { return PlayerPrefs.GetString(PLAYER_1_ROTATE_RIGHT_KEY); } #endregion #endregion #region Player 2 Keybinds public Methods #region Set Keybinds public static void SetPlayer2MoveLeft(string keybind) { PlayerPrefs.SetString(PLAYER_2_MOVE_LEFT_KEY, keybind); } public static void SetPlayer2MoveRight(string keybind) { PlayerPrefs.SetString(PLAYER_2_MOVE_RIGHT_KEY, keybind); } public static void SetPlayer2Jump(string keybind) { PlayerPrefs.SetString(PLAYER_2_JUMP_KEY, keybind); } public static void SetPlayer2Shoot(string keybind) { PlayerPrefs.SetString(PLAYER_2_SHOOT_KEY, keybind); } public static void SetPlayer2RotateLeft(string keybind) { PlayerPrefs.SetString(PLAYER_2_ROTATE_LEFT_KEY, keybind); } public static void SetPlayer2RotateRight(string keybind) { PlayerPrefs.SetString(PLAYER_2_ROTATE_RIGHT_KEY, keybind); } #endregion #region Get Keybinds public static string GetPlayer2MoveLeft() { return PlayerPrefs.GetString(PLAYER_2_MOVE_LEFT_KEY); } public static string GetPlayer2MoveRight() { return PlayerPrefs.GetString(PLAYER_2_MOVE_RIGHT_KEY); } public static string GetPlayer2Jump() { return PlayerPrefs.GetString(PLAYER_2_JUMP_KEY); } public static string GetPlayer2Shoot() { return PlayerPrefs.GetString(PLAYER_2_SHOOT_KEY); } public static string GetPlayer2RotateLeft() { return PlayerPrefs.GetString(PLAYER_2_ROTATE_LEFT_KEY); } public static string GetPlayer2RotateRight() { return PlayerPrefs.GetString(PLAYER_2_ROTATE_RIGHT_KEY); } #endregion #endregion public static void SetDefaultKeybinds() { SetPlayer1Jump(PLAYER_1_JUMP_DEFAULT); SetPlayer1MoveLeft(PLAYER_1_MOVE_LEFT_DEFAULT); SetPlayer1MoveRight(PLAYER_1_MOVE_RIGHT_DEFAULT); SetPlayer1RotateLeft(PLAYER_1_ROTATE_LEFT_DEFAULT); SetPlayer1RotateRight(PLAYER_1_ROTATE_RIGHT_DEFAULT); SetPlayer1Shoot(PLAYER_1_SHOOT_DEFAULT); SetPlayer2Jump(PLAYER_2_JUMP_DEFAULT); SetPlayer2MoveLeft(PLAYER_2_MOVE_LEFT_DEFAULT); SetPlayer2MoveRight(PLAYER_2_MOVE_RIGHT_DEFAULT); SetPlayer2RotateLeft(PLAYER_2_ROTATE_LEFT_DEFAULT); SetPlayer2RotateRight(PLAYER_2_ROTATE_RIGHT_DEFAULT); SetPlayer2Shoot(PLAYER_2_SHOOT_DEFAULT); } public static void SetDefaultSettings() { SetMasterVolume(MASTER_VOLUME_DEFAULT); SetRoundsCount(ROUNDS_TO_PLAY_DEFAULT); SetRoundsTime(ROUND_TIME_DEFAULT); } public static void SetDefaultVolume() { SetMasterVolume(MASTER_VOLUME_DEFAULT); } } <file_sep>/BattlingBaloons/Assets/Scripts/Keybind/KeybindsManager.cs using UnityEngine; using UnityEngine.UI; public class KeybindsManager : MonoBehaviour { #region Player1 Keybinds Placeholders [Header("Player 1 Keybind Input Fields")] [SerializeField] InputField Player1MoveLeft; [SerializeField] InputField Player1MoveRight; [SerializeField] InputField Player1Jump; [SerializeField] InputField Player1Shoot; [SerializeField] InputField Player1RotateLeft; [SerializeField] InputField Player1RotateRight; [Space] [SerializeField] Text Player1MoveLeftPlaceholder; [SerializeField] Text Player1MoveRightPlaceholder; [SerializeField] Text Player1JumpPlaceholder; [SerializeField] Text Player1ShootPlaceholder; [SerializeField] Text Player1RotateLeftPlaceholder; [SerializeField] Text Player1RotateRightPlaceholder; #endregion #region Player2 Keybinds Placeholders [Header("Player 2 Keybind Input Fields")] [SerializeField] InputField Player2MoveLeft; [SerializeField] InputField Player2MoveRight; [SerializeField] InputField Player2Jump; [SerializeField] InputField Player2Shoot; [SerializeField] InputField Player2RotateLeft; [SerializeField] InputField Player2RotateRight; [Space] [SerializeField] Text Player2MoveLeftPlaceholder; [SerializeField] Text Player2MoveRightPlaceholder; [SerializeField] Text Player2JumpPlaceholder; [SerializeField] Text Player2ShootPlaceholder; [SerializeField] Text Player2RotateLeftPlaceholder; [SerializeField] Text Player2RotateRightPlaceholder; #endregion public void SetPlaceholderTexts() { Player1JumpPlaceholder.text = PlayerPrefsController.GetPlayer1Jump(); Player1MoveLeftPlaceholder.text = PlayerPrefsController.GetPlayer1MoveLeft(); Player1MoveRightPlaceholder.text = PlayerPrefsController.GetPlayer1MoveRight(); Player1RotateLeftPlaceholder.text = PlayerPrefsController.GetPlayer1RotateLeft(); Player1RotateRightPlaceholder.text = PlayerPrefsController.GetPlayer1RotateRight(); Player1ShootPlaceholder.text = PlayerPrefsController.GetPlayer1Shoot(); Player2JumpPlaceholder.text = PlayerPrefsController.GetPlayer2Jump(); Player2MoveLeftPlaceholder.text = PlayerPrefsController.GetPlayer2MoveLeft(); Player2MoveRightPlaceholder.text = PlayerPrefsController.GetPlayer2MoveRight(); Player2RotateLeftPlaceholder.text = PlayerPrefsController.GetPlayer2RotateLeft(); Player2RotateRightPlaceholder.text = PlayerPrefsController.GetPlayer2RotateRight(); Player2ShootPlaceholder.text = PlayerPrefsController.GetPlayer2Shoot(); } public void SaveKeybinds() { PlayerPrefsController.SetPlayer1Jump(Player1Jump.text); PlayerPrefsController.SetPlayer1MoveLeft(Player1MoveLeft.text); PlayerPrefsController.SetPlayer1MoveRight(Player1MoveRight.text); PlayerPrefsController.SetPlayer1RotateLeft(Player1RotateLeft.text); PlayerPrefsController.SetPlayer1RotateRight(Player1RotateRight.text); PlayerPrefsController.SetPlayer1Shoot(Player1Shoot.text); PlayerPrefsController.SetPlayer2Jump(Player2Jump.text); PlayerPrefsController.SetPlayer2MoveLeft(Player2MoveLeft.text); PlayerPrefsController.SetPlayer2MoveRight(Player2MoveRight.text); PlayerPrefsController.SetPlayer2RotateLeft(Player2RotateLeft.text); PlayerPrefsController.SetPlayer2RotateRight(Player2RotateRight.text); PlayerPrefsController.SetPlayer2Shoot(Player2Shoot.text); } } <file_sep>/BattlingBaloons/Assets/Scripts/Core/GameManager.cs using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Events; using System.Collections.Generic; using UnityEngine.UI; [System.Serializable] public class EventGameState : UnityEvent<GameManager.GameState, GameManager.GameState> { } public class GameManager : MonoBehaviour { public static GameManager Instance { get; private set; } public enum GameState { PREGAME, PLAYING, PAUSED, DIALOGUE}; [SerializeField] GameState currentGameState = GameState.PREGAME; public GameState CurrentGameState { get { return currentGameState; } private set { currentGameState = value; } } GameState previousState; public GameState PreviousState { get { return previousState; } } [SerializeField] int currentLevel; public int CurrentLevel { get { return currentLevel; } } public EventGameState OnGameStateChanged; [SerializeField] List<string> scoreBoard; public List<string> ScoreBoard { get { return scoreBoard; } } [SerializeField] int currentRound = 1; public int CurrentRound { get { return currentRound; } set { currentRound = value; } } private void Awake() { if(Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } private void Start() { PlayerPrefsController.SetDefaultSettings(); UpdateGameState(GameState.PREGAME); } public void UpdateGameState(GameState gameState) { previousState = currentGameState; currentGameState = gameState; switch (currentGameState) { case GameState.PREGAME: Time.timeScale = 1f; break; case GameState.PLAYING: Time.timeScale = 1f; break; case GameState.PAUSED: Time.timeScale = 0f; break; case GameState.DIALOGUE: Time.timeScale = 1f; break; default: break; } OnGameStateChanged?.Invoke(currentGameState, previousState); } public void StartGame(string levelName) { SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Single); UpdateGameState(GameState.PLAYING); currentLevel = SceneManager.GetSceneByName(levelName).buildIndex; } public void LoadNextLevel() { currentLevel = SceneManager.GetActiveScene().buildIndex; currentLevel += 1; SceneManager.LoadSceneAsync(currentLevel, LoadSceneMode.Single); } public void LoadMainMenu() { AsyncOperation ao = SceneManager.LoadSceneAsync(0, LoadSceneMode.Single); UpdateGameState(GameState.PREGAME); } public void LoadScoreboard() { SceneManager.LoadSceneAsync("Scoreboard", LoadSceneMode.Single); } } <file_sep>/BattlingBaloons/Assets/Scripts/GameStartCountdown.cs using System.Collections; using UnityEngine; using UnityEngine.Experimental.Rendering.Universal; using UnityEngine.UI; public class GameStartCountdown : MonoBehaviour { [SerializeField] Light2D light; [SerializeField] Text _countdownText; [Space] [SerializeField] int startTime = 5; float timeLeft; bool RoundStarted = false; [Space] [SerializeField] Player Player1; [SerializeField] Player Player2; RoundManager roundManager; // Start is called before the first frame update void Start() { roundManager = FindObjectOfType<RoundManager>(); SetupRoundCountdown(); roundManager.OnRoundEnded += SetupRoundCountdown; } // Update is called once per frame void Update() { if(!RoundStarted) CountDown(); } void SetupRoundCountdown() { timeLeft = startTime; _countdownText.text = startTime.ToString(); roundManager.timeRunning = false; Player1.ableToShoot = false; Player2.ableToShoot = false; Player1.damagable = false; Player2.damagable = false; if (RoundStarted) { RoundStarted = false; light.gameObject.SetActive(true); _countdownText.gameObject.SetActive(true); } } public void CountDown() { if(timeLeft > 0) { timeLeft -= Time.deltaTime; _countdownText.text = Mathf.CeilToInt(timeLeft).ToString(); } else if (timeLeft <= 0) { Player1.ableToShoot = true; Player2.ableToShoot = true; Player1.damagable = true; Player2.damagable = true; roundManager.timeRunning = true; RoundStarted = true; StartCoroutine(WaitAndDestroy()); } } IEnumerator WaitAndDestroy() { _countdownText.text = "Start!"; yield return new WaitForSeconds(1.2f); light.gameObject.SetActive(false); _countdownText.gameObject.SetActive(false); } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/GameModeSelection.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameModeSelection : MonoBehaviour { [SerializeField] Button pvpButton; [SerializeField] Button returnButton; [SerializeField] Button tutorialButton; [SerializeField] GameObject pvpMapSelection; [SerializeField] GameObject mainMenu; [SerializeField] GameObject ground; private void Start() { pvpButton.onClick.AddListener(HandlePvPButtonClicked); returnButton.onClick.AddListener(HandleReturnClicked); tutorialButton.onClick.AddListener(HandleTutorialClicked); } void HandlePvPButtonClicked() { pvpMapSelection.SetActive(true); gameObject.SetActive(false); ground.SetActive(false); AudioManager.Instance.PlayMenuClick(); } void HandleReturnClicked() { mainMenu.SetActive(true); gameObject.SetActive(false); AudioManager.Instance.PlayMenuClick(); } void HandleTutorialClicked() { SceneManager.LoadSceneAsync("Tutorial", LoadSceneMode.Single); AudioManager.Instance.PlayMenuClick(); } } <file_sep>/BattlingBaloons/Assets/Scripts/Player/PlayerMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class PlayerMovement : MonoBehaviour { CharacterController2D controller; Player player; [SerializeField] float rotateSpeed; [SerializeField] float movementSpeed; float horizontalMove; float rotationChange; bool jump = false; private void Start() { controller = GetComponent<CharacterController2D>(); player = GetComponent<Player>(); } private void Update() { if(gameObject.CompareTag("Player 1")) { horizontalMove = Input.GetAxis("Player 1 Horizontal") * movementSpeed; rotationChange = Input.GetAxis("Player 1 Rotation") * rotateSpeed; if (Input.GetButtonDown("Player 1 Vertical")) { jump = true; } }else if (gameObject.CompareTag("Player 2")) { horizontalMove = Input.GetAxis("Player 2 Horizontal") * movementSpeed; rotationChange = Input.GetAxis("Player 2 Rotation") * rotateSpeed; if (Input.GetButtonDown("Player 2 Vertical")) { jump = true; } } } private void FixedUpdate() { controller.Move(horizontalMove * Time.deltaTime, false, jump); if(player) controller.Rotate(rotationChange * Time.deltaTime, player.Gun.transform); jump = false; } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/OptionsMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; using UnityEngine.UI; public class OptionsMenu : MonoBehaviour { [SerializeField] Button _keybindsButton; [SerializeField] Button _returnButton; [SerializeField] Button _defaultVolumeButton; [SerializeField] Slider _volumeSlider; [SerializeField] GameObject mainMenu; //[SerializeField] GameObject keybindsMenu; //[SerializeField] GameObject ground; private void Start() { //_keybindsButton.onClick.AddListener(HandleKeybindsClicked); _returnButton.onClick.AddListener(HandleReturnClicked); _defaultVolumeButton.onClick.AddListener(HandleDefaultVolumeClicked); } //void HandleKeybindsClicked() //{ // keybindsMenu.GetComponent<KeybindsManager>().SetPlaceholderTexts(); // gameObject.SetActive(false); // keybindsMenu.SetActive(true); // ground.SetActive(false); //} void HandleReturnClicked() { mainMenu.SetActive(true); gameObject.SetActive(false); AudioManager.Instance.PlayMenuClick(); } void HandleDefaultVolumeClicked() { PlayerPrefsController.SetDefaultVolume(); _volumeSlider.value = PlayerPrefsController.GetMasterVolume(); AudioManager.Instance.PlayMenuClick(); } } <file_sep>/BattlingBaloons/Assets/Scripts/Spikes.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spikes : MonoBehaviour { private void OnCollisionEnter2D(Collision2D collision) { if(collision.gameObject.CompareTag("Player 1") || collision.gameObject.CompareTag("Player 2")) { collision.gameObject.GetComponent<Player>().Die(); } } } <file_sep>/BattlingBaloons/Assets/Scripts/UI/FillBarFollow.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class FillBarFollow : MonoBehaviour { [SerializeField] Transform player; [SerializeField] float yOffset; private void Start() { transform.position = new Vector3(player.position.x, player.position.y + yOffset, player.position.z); } private void Update() { transform.position = new Vector3(player.position.x, player.position.y + yOffset, player.position.z); } } <file_sep>/BattlingBaloons/Assets/Scripts/Tutorial/TutorialSlider.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TutorialSlider : MonoBehaviour { [SerializeField] Slider slider; [SerializeField] Transform deathTransform; [SerializeField] GameObject deathVFX; private void Update() { if (slider.value < 100) slider.value += Time.deltaTime * 10; else { slider.value = 0f; StartCoroutine(SendWater()); } } IEnumerator SendWater() { GameObject go = Instantiate(deathVFX, deathTransform.position, Quaternion.identity); yield return new WaitForSeconds(2f); Destroy(go); } } <file_sep>/BattlingBaloons/Assets/Scripts/Core/PlayerManager.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PlayerManager : MonoBehaviour { public static PlayerManager Instance { get; private set; } [SerializeField] int player1Combo; [SerializeField] int player2Combo; public int Player1Combo { get { return player1Combo; } } public int Player2Combo { get { return player2Combo; } } [SerializeField] Text player1ComboText; [SerializeField] Text player2ComboText; [SerializeField] Text scoreBoardText; [SerializeField] Player player1; [SerializeField] Player player2; public Player Player1 { get { return player1; } } public Player Player2 { get { return player2; } } public Action Player1Died; public Action Player2Died; private void Awake() { if(Instance == null) { Instance = this; }else { Destroy(gameObject); } } public void Player1AddPoint() { player1.Score++; UpdateScoreBoard(); } public void Player2AddPoint() { player2.Score++; UpdateScoreBoard(); } public void Player1AddWater() { player1.AddWater(); } public void Player2AddWater() { player2.AddWater(); } public void UpdateScoreBoard() { scoreBoardText.text = player1.Score + ":" + player2.Score; } public void TriggerPlayer1Died() { Player1Died?.Invoke(); } public void TriggerPlayer2Died() { Player2Died?.Invoke(); } public void IncreasePlayer1Combo() { player2ComboText.gameObject.SetActive(false); player1ComboText.gameObject.SetActive(true); player2Combo = 0; player1Combo++; player1ComboText.text = "x" + player1Combo.ToString(); } public void IncreasePlayer2Combo() { player1ComboText.gameObject.SetActive(false); player2ComboText.gameObject.SetActive(true); player1Combo = 0; player2Combo++; player2ComboText.text = "x" + player2Combo.ToString(); } public void ClearPlayersCombos() { player1ComboText.gameObject.SetActive(false); player2ComboText.gameObject.SetActive(false); player1Combo = 0; player2Combo = 0; } }
b35cd8f00c329dd90e732f1e63b52924f0af959f
[ "Markdown", "C#" ]
26
C#
MJPB0/BattlingBalloons
1f4a6282c005c49390c7bf25be3deeb18018724c
5dfe4e5827f00cf4990d5d9fc4e8457d496f41c0
refs/heads/master
<file_sep><?php /*************************************************************** * Copyright notice * * (c) 2015 <EMAIL> <> * * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ namespace Ecentral\EcStyla\Hook; use TYPO3\CMS\Core\SingletonInterface; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\SignalSlot\Dispatcher; use TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility; /** * Class Realurl * @package Ecentral\EcStyla\Hook */ class Realurl implements SingletonInterface { /** @var \TYPO3\CMS\Extbase\Object\ObjectManager */ protected $objectManager; /** * @var array */ protected $valuedExtensionConfiguration; public function __construct() { $this->objectManager = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class); } /** * Set postVarSet_failureMode when a certain uri segment is present * * @param $parameters */ public function configure($parameters) { $uriSegments = array_map('trim', explode(',', $this->getExtensionConfiguration('rootPath'))); $signalSlotDispatcher = $this->objectManager->get(Dispatcher::class); foreach ($uriSegments as $uriSegment) { list($uriSegment) = $signalSlotDispatcher->dispatch(__CLASS__, 'beforeCheckingForRootPath', array($uriSegment)); if ($this->isStylaRequest($uriSegment)) { $parameters['configuration']['init']['postVarSet_failureMode'] = 'ignore'; } } } protected function isStylaRequest($uriSegment) { $pattern = sprintf('~/%s/~', trim($uriSegment, '/')); return (bool)preg_match($pattern, $_SERVER['REQUEST_URI']); } /** * @param string $key * @return mixed */ public function getExtensionConfiguration($key) { if (!is_array($this->valuedExtensionConfiguration)) { /** @var ConfigurationUtility $configurationUtility */ $configurationUtility = $this->objectManager->get(ConfigurationUtility::class); $extensionConfiguration = $configurationUtility->getCurrentConfiguration('ec_styla'); $this->valuedExtensionConfiguration = $configurationUtility->convertNestedToValuedConfiguration($extensionConfiguration); } $configKey = sprintf('%s.value', $key); if (array_key_exists($configKey, $this->valuedExtensionConfiguration)) { return $this->valuedExtensionConfiguration[$configKey]['value']; } else { return null; } } } <file_sep># TYPO3 Styla Extension Docker setup ## How to start In project's root folder, start with docker-compose up --build Access frontend: http://localhost Access backend: http://localhost/typo3 Credentials are `admin` / `password` (set in [./run.sh]) ## Example database There is a set of configured pages within the docker setup to test the extension behavior. ### How to create a new database dump Connect to docker instance: docker exec -it typo3_typo3_1 bash Execute database export: php /var/www/html/Packages/Libraries/bin/typo3cms database:export -c Default -e 'cf_*' -e 'cache_*' -e '[bf]e_sessions' -e sys_log > dump.sql Open dump.sql and copy to clipboard: cat dump.sql Replace content of `docker/dump.sql` and rebuild instance. <file_sep>FROM php:7.1-apache-jessie # Install TYPO3 RUN apt-get update && \ apt-get install -y --no-install-recommends \ wget \ git \ mysql-client \ unzip # Configure PHP RUN apt-get install -y --no-install-recommends \ libxml2-dev libfreetype6-dev \ libjpeg62-turbo-dev \ libmcrypt-dev \ libpng-dev \ zlib1g-dev RUN apt-get install -y zlib1g-dev libicu-dev g++ RUN docker-php-ext-configure intl RUN docker-php-ext-install intl # Install required 3rd party tools RUN apt-get install -y --no-install-recommends \ graphicsmagick # Configure extensions RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ && \ docker-php-ext-install -j$(nproc) mysqli soap gd zip opcache intl && \ echo 'always_populate_raw_post_data = -1\nmax_execution_time = 240\nmax_input_vars = 1500\nupload_max_filesize = 32M\npost_max_size = 32M' > /usr/local/etc/php/conf.d/typo3.ini # Configure Apache as needed RUN a2enmod rewrite && \ apt-get clean && \ apt-get -y purge \ libxml2-dev libfreetype6-dev \ libjpeg62-turbo-dev \ libmcrypt-dev \ libpng12-dev \ zlib1g-dev RUN rm -rf /var/lib/apt/lists/* /usr/src/* # Install composer RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer RUN a2enmod rewrite ADD ./docker/typo3.conf /etc/apache2/sites-enabled/000-default.conf # Adjust some php settings ADD ./docker/typo3.php.ini /etc/php5/conf.d/ ADD ./docker/AdditionalConfiguration.php /var/www/html/typo3conf/ # Expose environment variables ENV DB_HOST **LinkMe** ENV DB_PORT **LinkMe** ENV DB_NAME typo3 ENV DB_USER admin ENV DB_PASS **<PASSWORD>** ENV INSTALL_TOOL_PASSWORD <PASSWORD> ENV TYPO3_CONTEXT Development ADD ./docker/run.sh /run.sh RUN chmod 755 /*.sh # Configurate apache ADD ./docker/000-default.conf /etc/apache2/sites-available/000-default.conf # Install app WORKDIR /var/www/html/ # Install dependencies defined in composer.json ADD ./docker/composer.json . #ADD ./docker/composer.lock . RUN composer config extra.typo3/cms.cms-package-dir '{$vendor-dir}/typo3/cms' && \ composer config secure-http false && \ composer install # Install plugin RUN mkdir ./typo3conf/ext/ec_styla ADD . ./typo3conf/ext/ec_styla # Add other files WORKDIR /var/www/html/ ADD ./docker/dump.sql . # Configure volumes VOLUME /var/www/html/fileadmin VOLUME /var/www/html/typo3conf VOLUME /var/www/html/typo3temp VOLUME /var/www/html/uploads VOLUME /var/www/html/typo3conf/ext/ec-styla CMD ["/bin/bash", "-c", "/run.sh"] <file_sep><?php $GLOBALS['TYPO3_CONF_VARS']['DB']['host'] = getenv('DB_HOST'); $GLOBALS['TYPO3_CONF_VARS']['DB']['username'] = getenv('DB_USER'); $GLOBALS['TYPO3_CONF_VARS']['DB']['password'] = getenv('DB_PASS'); $GLOBALS['TYPO3_CONF_VARS']['DB']['port'] = getenv('DB_PORT'); $GLOBALS['TYPO3_CONF_VARS']['DB']['database'] = getenv('DB_NAME'); $GLOBALS['TYPO3_CONF_VARS']['BE']['installToolPassword'] = md5(getenv('INSTALL_TOOL_PASSWORD')); $GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'] = 1; $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'] = 'error_log'; $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] = '0'; $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_errorDLOG'] = '1'; $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_exceptionDLOG'] = '1'; $GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog'] = 'console'; <file_sep><?php namespace Ecentral\EcStyla\Controller; use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility; use TYPO3\CMS\Frontend\Page\PageRepository; /*************************************************************** * Copyright notice * * (c) 2015 <EMAIL> <> * * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * Class ContentHubController * @package Ecentral\EcStyla\Controller */ class ContentHubController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController { const API_URI_QUERYSTRING = '%s?url=/%s'; /** * @var \TYPO3\CMS\Core\Cache\CacheManager */ protected $cache; /** * @var array */ protected $disabledMetaTagsArray = []; /** * Default lifetime of cached data * @var int */ protected $cachePeriod = 3600; /** @var \TYPO3\CMS\Extbase\Object\ObjectManager */ protected $objectManager; /** * @var PageRepository */ protected $pageRepository; public function __construct() { $this->objectManager = GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Object\ObjectManager'); } /** * action show * * Add seo relevant elements to html body, either by fetching * the data from remote or using the cached data. * * @return void */ public function showAction() { if (!array_key_exists('api_url',$this->settings) || !array_key_exists('contenthub_segment',$this->settings)) { $pluginConfigFromSetup = ''; TypoScriptParser::includeFile('typo3conf/ext/ec_styla/Configuration/TypoScript/setup.ts' ,1 ,false,$pluginConfigFromSetup); /** @var TypoScriptParser $typoScriptParser */ $typoScriptParser = $this->objectManager->get(TypoScriptParser::class); $typoScriptParser->parse($pluginConfigFromSetup); $this->settings['api_url'] = $typoScriptParser->setup['plugin.']['tx_ecstyla_contenthub.']['settings.']['api_url']; } $this->cache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('ec_styla'); $cacheIdentifier = $this->getCacheIdentifier(); $cachedContent = $this->cache->get($cacheIdentifier); $pageUid = $this->configurationManager->getContentObject()->data['uid']; $autodetectContent = $this->getExtensionConfiguration('autodetectContent'); if ((!array_key_exists('stylaContent', $this->settings['contenthub']) || $this->settings['stylaContent'] === '') && $autodetectContent === '1') { $this->pageRepository = $this->objectManager->get(PageRepository::class); $page = $this->pageRepository->getPage($pageUid); $realurlPathSegment = $page['tx_realurl_pathsegment']; $this->view->assign('stylaContent', $realurlPathSegment); } else { $this->view->assign('stylaContent', $this->settings['contenthub']['stylaContent']); } if (false == $cachedContent) { $path = strtok(str_replace( $this->getControllerContext()->getRequest()->getBaseUri(), '', $this->getControllerContext()->getRequest()->getRequestUri() ), '?'); $url = sprintf( $this->settings['api_url'] . self::API_URI_QUERYSTRING, $this->settings['contenthub']['id'], $path ); $request = GeneralUtility::makeInstance(\Ecentral\EcStyla\Utility\StylaRequest::class); $content = $request->get($url); if (null !== $content) { $this->cachePeriod = $request->getCachePeriod(); $this->cacheContent( $content, array ( 'styla', $this->settings['contenthub']['id'] ) ); } } else { $content = $cachedContent; } $signalSlotDispatcher = $this->objectManager->get(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class); list($content) = $signalSlotDispatcher->dispatch(__CLASS__, 'beforeProcessingSeoContent', array($content)); if (!$content || $content->error) { $this->view->assign('seoHtml', ''); return; } $this->disabledMetaTagsArray = array_map('trim', explode(',', $this->settings['disabled_meta_tags'])); foreach ($content->tags as $item) { if ('' != ($headerElement = $this->getHtmlForTagItem($item))) { // If Cache-Control is set to no-cache upon request, the page renderer // may not add additional meta information for this request. Hence the // additional header elements are directly added to the header elements list. $GLOBALS['TSFE']->additionalHeaderData[] = $headerElement; } } $this->view->assign('seoHtml', $content->html->body); } /** * Cache serializable item * * @param $item * @param array $tags * @param int $cachePeriod */ protected function cacheContent($item, $tags = array('styla'), $cachePeriod = 3600) { $this->cache->set( $this->getCacheIdentifier(), $item, $tags, $cachePeriod ); } /** * Get cache identifier * * @return string */ protected function getCacheIdentifier() { $path = strtok($this->getControllerContext()->getRequest()->getRequestUri(), '?'); return 'styla-' . $this->settings['contenthub']['id'] . '-'. md5($path); } /** * Return html element for item * * TODO: Implement generic approach * * @param $item * @return string */ protected function getHtmlForTagItem($item) { switch ($item->tag) { case 'meta': if(null != $item->attributes->name && !in_array($item->attributes->name, $this->disabledMetaTagsArray)) { return '<meta name="' . $item->attributes->name . '" content="' . $item->attributes->content . '" />'; } if (!in_array($item->attributes->property, $this->disabledMetaTagsArray)) { return '<meta property="' . $item->attributes->property . '" content="' . $item->attributes->content . '" />'; } return ''; break; case 'link': return '<link rel="' . $item->attributes->rel . '" href="' . $item->attributes->href . '" />'; break; case 'title': return '<title>' . $item->content . '</title>'; break; default: return ''; } } protected function removeTYPO3MetaTags() { $metaTagManager = $this->objectManager->get(MetaManagrw::class)->getManagerForProperty('og:title'); } /** * @param string $key * @return mixed */ public function getExtensionConfiguration($key) { if (!is_array($this->valuedExtensionConfiguration)) { /** @var ConfigurationUtility $configurationUtility */ $configurationUtility = $this->objectManager->get(ConfigurationUtility::class); $extensionConfiguration = $configurationUtility->getCurrentConfiguration('ec_styla'); $this->valuedExtensionConfiguration = $configurationUtility->convertNestedToValuedConfiguration($extensionConfiguration); } $configKey = sprintf('%s.value', $key); if (array_key_exists($configKey, $this->valuedExtensionConfiguration)) { return $this->valuedExtensionConfiguration[$configKey]['value']; } else { return null; } } } <file_sep><?php /**************************************************************** * Copyright notice * * (c) 2015 <EMAIL> <<EMAIL>> * * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ namespace Ecentral\EcStyla\Compatiblity\_7_6\Utility; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Core\Http\HttpRequest; /** * Class StylaRequest * @package Ecentral\EcStyla\Compatiblity\_7_6\Utility */ class StylaRequest { protected $logger; protected $cachePeriod = 0; public function get($url) { /** @var \TYPO3\CMS\Core\Log\Logger $logger */ $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); /** @var HttpRequest $request */ $request = GeneralUtility::makeInstance(HttpRequest::class); try { $request->setUrl($url); $request->setConfig('follow_redirects', true); $request->setMethod(\HTTP_Request2::METHOD_GET); $response = $request->send(); if (true == isset($response) && 200 === $response->getStatus()) { $content = json_decode($response->getBody()); if (null !== $content && strtolower($content->code) === 'success') { $cacheControl = $response->getHeader('cache-control'); if (null !== $cacheControl) { $this->cachePeriod = $cacheControl; } return $content; } else { $this->logger->error( 'Styla api could not deliver requested content', array( 'code' => $content->code, ) ); } } else { throw new \HTTP_Request2_Exception("Unexpected response status: " . $response->getStatus()); } } catch (\HTTP_Request2_Exception $e) { $this->logger->error( 'Exception during communication with styla api', array( 'url' => $url, 'page' => $GLOBALS['TSFE']->id, 'message' => $e->getMessage() ) ); } return null; } /** * @return int */ public function getCachePeriod() { return $this->cachePeriod; } }
a0d45a5b14a0c401e22cc237258ce408dedf2cd4
[ "Markdown", "Dockerfile", "PHP" ]
6
PHP
ecentral/typo3
e804dfeec5f304af8973973c76953856abc309d9
16845ca519b81553e9d9fa1fde9c5a50895b7e59
refs/heads/master
<file_sep>const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const path = require('path'); app.use(express.static('public')); app.get('/', function (req, res){ res.sendFile(path.join(__dirname, '/public/index.html')); }); io.on('connection', function (socket) { io.sockets.emit('on connect', {userCount: io.engine.clientsCount}) socket.on('message', function (channel, message) { if(channel === 'user joined') { io.sockets.emit('user joined', message) } else { io.sockets.emit('chat', message) } }); socket.on('disconnect', function (channel, message) { io.sockets.emit('user left', {text: 'someone left the chat'}) io.sockets.emit('on connect', {userCount: io.engine.clientsCount}) }) }); http.listen(process.env.PORT || 3000, function(){ console.log('Your server is up and running on Port 3000. Good job!'); });
beb99fc8d5ac71a6c84e77f5ca80dc000695863d
[ "JavaScript" ]
1
JavaScript
Alex-Tideman/right-now
3287b7ad85993e84370c6ff193ccd31c9fb3444e
53ff180784dc17415c6ef1f8a9956531108ff92d
refs/heads/master
<repo_name>AiSRoV/prog<file_sep>/cmake-build-debug/CMakeFiles/Task16.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Task16.dir/Tasks/Task16/task16.cpp.o" "Task16" "Task16.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Task16.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/cmake-build-debug/Makefile # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.15 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/bin/cmake # The command to remove a file. RM = /home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/canned_dead/Документы/CLionProjects/prog # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/canned_dead/Документы/CLionProjects/prog/cmake-build-debug #============================================================================= # Targets provided globally by CMake. # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /home/canned_dead/Документы/CLionProjects/prog/cmake-build-debug/CMakeFiles /home/canned_dead/Документы/CLionProjects/prog/cmake-build-debug/CMakeFiles/progress.marks $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/canned_dead/Документы/CLionProjects/prog/cmake-build-debug/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named Lab3 # Build rule for target. Lab3: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Lab3 .PHONY : Lab3 # fast build rule for target. Lab3/fast: $(MAKE) -f CMakeFiles/Lab3.dir/build.make CMakeFiles/Lab3.dir/build .PHONY : Lab3/fast #============================================================================= # Target rules for targets named Lab4 # Build rule for target. Lab4: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Lab4 .PHONY : Lab4 # fast build rule for target. Lab4/fast: $(MAKE) -f CMakeFiles/Lab4.dir/build.make CMakeFiles/Lab4.dir/build .PHONY : Lab4/fast #============================================================================= # Target rules for targets named Tasks30 # Build rule for target. Tasks30: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Tasks30 .PHONY : Tasks30 # fast build rule for target. Tasks30/fast: $(MAKE) -f CMakeFiles/Tasks30.dir/build.make CMakeFiles/Tasks30.dir/build .PHONY : Tasks30/fast #============================================================================= # Target rules for targets named Task29 # Build rule for target. Task29: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task29 .PHONY : Task29 # fast build rule for target. Task29/fast: $(MAKE) -f CMakeFiles/Task29.dir/build.make CMakeFiles/Task29.dir/build .PHONY : Task29/fast #============================================================================= # Target rules for targets named Task26 # Build rule for target. Task26: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task26 .PHONY : Task26 # fast build rule for target. Task26/fast: $(MAKE) -f CMakeFiles/Task26.dir/build.make CMakeFiles/Task26.dir/build .PHONY : Task26/fast #============================================================================= # Target rules for targets named Lab2 # Build rule for target. Lab2: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Lab2 .PHONY : Lab2 # fast build rule for target. Lab2/fast: $(MAKE) -f CMakeFiles/Lab2.dir/build.make CMakeFiles/Lab2.dir/build .PHONY : Lab2/fast #============================================================================= # Target rules for targets named Task25 # Build rule for target. Task25: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task25 .PHONY : Task25 # fast build rule for target. Task25/fast: $(MAKE) -f CMakeFiles/Task25.dir/build.make CMakeFiles/Task25.dir/build .PHONY : Task25/fast #============================================================================= # Target rules for targets named Task23 # Build rule for target. Task23: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task23 .PHONY : Task23 # fast build rule for target. Task23/fast: $(MAKE) -f CMakeFiles/Task23.dir/build.make CMakeFiles/Task23.dir/build .PHONY : Task23/fast #============================================================================= # Target rules for targets named Task22 # Build rule for target. Task22: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task22 .PHONY : Task22 # fast build rule for target. Task22/fast: $(MAKE) -f CMakeFiles/Task22.dir/build.make CMakeFiles/Task22.dir/build .PHONY : Task22/fast #============================================================================= # Target rules for targets named Task21 # Build rule for target. Task21: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task21 .PHONY : Task21 # fast build rule for target. Task21/fast: $(MAKE) -f CMakeFiles/Task21.dir/build.make CMakeFiles/Task21.dir/build .PHONY : Task21/fast #============================================================================= # Target rules for targets named Task24 # Build rule for target. Task24: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task24 .PHONY : Task24 # fast build rule for target. Task24/fast: $(MAKE) -f CMakeFiles/Task24.dir/build.make CMakeFiles/Task24.dir/build .PHONY : Task24/fast #============================================================================= # Target rules for targets named Task9 # Build rule for target. Task9: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task9 .PHONY : Task9 # fast build rule for target. Task9/fast: $(MAKE) -f CMakeFiles/Task9.dir/build.make CMakeFiles/Task9.dir/build .PHONY : Task9/fast #============================================================================= # Target rules for targets named Task8 # Build rule for target. Task8: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task8 .PHONY : Task8 # fast build rule for target. Task8/fast: $(MAKE) -f CMakeFiles/Task8.dir/build.make CMakeFiles/Task8.dir/build .PHONY : Task8/fast #============================================================================= # Target rules for targets named Task7 # Build rule for target. Task7: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task7 .PHONY : Task7 # fast build rule for target. Task7/fast: $(MAKE) -f CMakeFiles/Task7.dir/build.make CMakeFiles/Task7.dir/build .PHONY : Task7/fast #============================================================================= # Target rules for targets named Task14 # Build rule for target. Task14: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task14 .PHONY : Task14 # fast build rule for target. Task14/fast: $(MAKE) -f CMakeFiles/Task14.dir/build.make CMakeFiles/Task14.dir/build .PHONY : Task14/fast #============================================================================= # Target rules for targets named Task10 # Build rule for target. Task10: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task10 .PHONY : Task10 # fast build rule for target. Task10/fast: $(MAKE) -f CMakeFiles/Task10.dir/build.make CMakeFiles/Task10.dir/build .PHONY : Task10/fast #============================================================================= # Target rules for targets named Task1-5 # Build rule for target. Task1-5: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task1-5 .PHONY : Task1-5 # fast build rule for target. Task1-5/fast: $(MAKE) -f CMakeFiles/Task1-5.dir/build.make CMakeFiles/Task1-5.dir/build .PHONY : Task1-5/fast #============================================================================= # Target rules for targets named Task6 # Build rule for target. Task6: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task6 .PHONY : Task6 # fast build rule for target. Task6/fast: $(MAKE) -f CMakeFiles/Task6.dir/build.make CMakeFiles/Task6.dir/build .PHONY : Task6/fast #============================================================================= # Target rules for targets named Lab1 # Build rule for target. Lab1: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Lab1 .PHONY : Lab1 # fast build rule for target. Lab1/fast: $(MAKE) -f CMakeFiles/Lab1.dir/build.make CMakeFiles/Lab1.dir/build .PHONY : Lab1/fast #============================================================================= # Target rules for targets named Task11 # Build rule for target. Task11: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task11 .PHONY : Task11 # fast build rule for target. Task11/fast: $(MAKE) -f CMakeFiles/Task11.dir/build.make CMakeFiles/Task11.dir/build .PHONY : Task11/fast #============================================================================= # Target rules for targets named Task16 # Build rule for target. Task16: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task16 .PHONY : Task16 # fast build rule for target. Task16/fast: $(MAKE) -f CMakeFiles/Task16.dir/build.make CMakeFiles/Task16.dir/build .PHONY : Task16/fast #============================================================================= # Target rules for targets named Task18 # Build rule for target. Task18: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task18 .PHONY : Task18 # fast build rule for target. Task18/fast: $(MAKE) -f CMakeFiles/Task18.dir/build.make CMakeFiles/Task18.dir/build .PHONY : Task18/fast #============================================================================= # Target rules for targets named Task12 # Build rule for target. Task12: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task12 .PHONY : Task12 # fast build rule for target. Task12/fast: $(MAKE) -f CMakeFiles/Task12.dir/build.make CMakeFiles/Task12.dir/build .PHONY : Task12/fast #============================================================================= # Target rules for targets named Task13 # Build rule for target. Task13: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task13 .PHONY : Task13 # fast build rule for target. Task13/fast: $(MAKE) -f CMakeFiles/Task13.dir/build.make CMakeFiles/Task13.dir/build .PHONY : Task13/fast #============================================================================= # Target rules for targets named Task15 # Build rule for target. Task15: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task15 .PHONY : Task15 # fast build rule for target. Task15/fast: $(MAKE) -f CMakeFiles/Task15.dir/build.make CMakeFiles/Task15.dir/build .PHONY : Task15/fast #============================================================================= # Target rules for targets named Task28 # Build rule for target. Task28: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task28 .PHONY : Task28 # fast build rule for target. Task28/fast: $(MAKE) -f CMakeFiles/Task28.dir/build.make CMakeFiles/Task28.dir/build .PHONY : Task28/fast #============================================================================= # Target rules for targets named Task27 # Build rule for target. Task27: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task27 .PHONY : Task27 # fast build rule for target. Task27/fast: $(MAKE) -f CMakeFiles/Task27.dir/build.make CMakeFiles/Task27.dir/build .PHONY : Task27/fast #============================================================================= # Target rules for targets named Task17 # Build rule for target. Task17: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task17 .PHONY : Task17 # fast build rule for target. Task17/fast: $(MAKE) -f CMakeFiles/Task17.dir/build.make CMakeFiles/Task17.dir/build .PHONY : Task17/fast #============================================================================= # Target rules for targets named Task19 # Build rule for target. Task19: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task19 .PHONY : Task19 # fast build rule for target. Task19/fast: $(MAKE) -f CMakeFiles/Task19.dir/build.make CMakeFiles/Task19.dir/build .PHONY : Task19/fast #============================================================================= # Target rules for targets named Task20 # Build rule for target. Task20: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 Task20 .PHONY : Task20 # fast build rule for target. Task20/fast: $(MAKE) -f CMakeFiles/Task20.dir/build.make CMakeFiles/Task20.dir/build .PHONY : Task20/fast Labs/Lab1/lab1.o: Labs/Lab1/lab1.cpp.o .PHONY : Labs/Lab1/lab1.o # target to build an object file Labs/Lab1/lab1.cpp.o: $(MAKE) -f CMakeFiles/Lab1.dir/build.make CMakeFiles/Lab1.dir/Labs/Lab1/lab1.cpp.o .PHONY : Labs/Lab1/lab1.cpp.o Labs/Lab1/lab1.i: Labs/Lab1/lab1.cpp.i .PHONY : Labs/Lab1/lab1.i # target to preprocess a source file Labs/Lab1/lab1.cpp.i: $(MAKE) -f CMakeFiles/Lab1.dir/build.make CMakeFiles/Lab1.dir/Labs/Lab1/lab1.cpp.i .PHONY : Labs/Lab1/lab1.cpp.i Labs/Lab1/lab1.s: Labs/Lab1/lab1.cpp.s .PHONY : Labs/Lab1/lab1.s # target to generate assembly for a file Labs/Lab1/lab1.cpp.s: $(MAKE) -f CMakeFiles/Lab1.dir/build.make CMakeFiles/Lab1.dir/Labs/Lab1/lab1.cpp.s .PHONY : Labs/Lab1/lab1.cpp.s Labs/Lab2/lab2.o: Labs/Lab2/lab2.cpp.o .PHONY : Labs/Lab2/lab2.o # target to build an object file Labs/Lab2/lab2.cpp.o: $(MAKE) -f CMakeFiles/Lab2.dir/build.make CMakeFiles/Lab2.dir/Labs/Lab2/lab2.cpp.o .PHONY : Labs/Lab2/lab2.cpp.o Labs/Lab2/lab2.i: Labs/Lab2/lab2.cpp.i .PHONY : Labs/Lab2/lab2.i # target to preprocess a source file Labs/Lab2/lab2.cpp.i: $(MAKE) -f CMakeFiles/Lab2.dir/build.make CMakeFiles/Lab2.dir/Labs/Lab2/lab2.cpp.i .PHONY : Labs/Lab2/lab2.cpp.i Labs/Lab2/lab2.s: Labs/Lab2/lab2.cpp.s .PHONY : Labs/Lab2/lab2.s # target to generate assembly for a file Labs/Lab2/lab2.cpp.s: $(MAKE) -f CMakeFiles/Lab2.dir/build.make CMakeFiles/Lab2.dir/Labs/Lab2/lab2.cpp.s .PHONY : Labs/Lab2/lab2.cpp.s Labs/Lab3/lab3.o: Labs/Lab3/lab3.cpp.o .PHONY : Labs/Lab3/lab3.o # target to build an object file Labs/Lab3/lab3.cpp.o: $(MAKE) -f CMakeFiles/Lab3.dir/build.make CMakeFiles/Lab3.dir/Labs/Lab3/lab3.cpp.o .PHONY : Labs/Lab3/lab3.cpp.o Labs/Lab3/lab3.i: Labs/Lab3/lab3.cpp.i .PHONY : Labs/Lab3/lab3.i # target to preprocess a source file Labs/Lab3/lab3.cpp.i: $(MAKE) -f CMakeFiles/Lab3.dir/build.make CMakeFiles/Lab3.dir/Labs/Lab3/lab3.cpp.i .PHONY : Labs/Lab3/lab3.cpp.i Labs/Lab3/lab3.s: Labs/Lab3/lab3.cpp.s .PHONY : Labs/Lab3/lab3.s # target to generate assembly for a file Labs/Lab3/lab3.cpp.s: $(MAKE) -f CMakeFiles/Lab3.dir/build.make CMakeFiles/Lab3.dir/Labs/Lab3/lab3.cpp.s .PHONY : Labs/Lab3/lab3.cpp.s Labs/Lab3/libbmp.o: Labs/Lab3/libbmp.cpp.o .PHONY : Labs/Lab3/libbmp.o # target to build an object file Labs/Lab3/libbmp.cpp.o: $(MAKE) -f CMakeFiles/Lab3.dir/build.make CMakeFiles/Lab3.dir/Labs/Lab3/libbmp.cpp.o .PHONY : Labs/Lab3/libbmp.cpp.o Labs/Lab3/libbmp.i: Labs/Lab3/libbmp.cpp.i .PHONY : Labs/Lab3/libbmp.i # target to preprocess a source file Labs/Lab3/libbmp.cpp.i: $(MAKE) -f CMakeFiles/Lab3.dir/build.make CMakeFiles/Lab3.dir/Labs/Lab3/libbmp.cpp.i .PHONY : Labs/Lab3/libbmp.cpp.i Labs/Lab3/libbmp.s: Labs/Lab3/libbmp.cpp.s .PHONY : Labs/Lab3/libbmp.s # target to generate assembly for a file Labs/Lab3/libbmp.cpp.s: $(MAKE) -f CMakeFiles/Lab3.dir/build.make CMakeFiles/Lab3.dir/Labs/Lab3/libbmp.cpp.s .PHONY : Labs/Lab3/libbmp.cpp.s Labs/Lab4/helper.o: Labs/Lab4/helper.cpp.o .PHONY : Labs/Lab4/helper.o # target to build an object file Labs/Lab4/helper.cpp.o: $(MAKE) -f CMakeFiles/Lab4.dir/build.make CMakeFiles/Lab4.dir/Labs/Lab4/helper.cpp.o .PHONY : Labs/Lab4/helper.cpp.o Labs/Lab4/helper.i: Labs/Lab4/helper.cpp.i .PHONY : Labs/Lab4/helper.i # target to preprocess a source file Labs/Lab4/helper.cpp.i: $(MAKE) -f CMakeFiles/Lab4.dir/build.make CMakeFiles/Lab4.dir/Labs/Lab4/helper.cpp.i .PHONY : Labs/Lab4/helper.cpp.i Labs/Lab4/helper.s: Labs/Lab4/helper.cpp.s .PHONY : Labs/Lab4/helper.s # target to generate assembly for a file Labs/Lab4/helper.cpp.s: $(MAKE) -f CMakeFiles/Lab4.dir/build.make CMakeFiles/Lab4.dir/Labs/Lab4/helper.cpp.s .PHONY : Labs/Lab4/helper.cpp.s Labs/Lab4/main.o: Labs/Lab4/main.cpp.o .PHONY : Labs/Lab4/main.o # target to build an object file Labs/Lab4/main.cpp.o: $(MAKE) -f CMakeFiles/Lab4.dir/build.make CMakeFiles/Lab4.dir/Labs/Lab4/main.cpp.o .PHONY : Labs/Lab4/main.cpp.o Labs/Lab4/main.i: Labs/Lab4/main.cpp.i .PHONY : Labs/Lab4/main.i # target to preprocess a source file Labs/Lab4/main.cpp.i: $(MAKE) -f CMakeFiles/Lab4.dir/build.make CMakeFiles/Lab4.dir/Labs/Lab4/main.cpp.i .PHONY : Labs/Lab4/main.cpp.i Labs/Lab4/main.s: Labs/Lab4/main.cpp.s .PHONY : Labs/Lab4/main.s # target to generate assembly for a file Labs/Lab4/main.cpp.s: $(MAKE) -f CMakeFiles/Lab4.dir/build.make CMakeFiles/Lab4.dir/Labs/Lab4/main.cpp.s .PHONY : Labs/Lab4/main.cpp.s Tasks/Task1-5/task1-5.o: Tasks/Task1-5/task1-5.cpp.o .PHONY : Tasks/Task1-5/task1-5.o # target to build an object file Tasks/Task1-5/task1-5.cpp.o: $(MAKE) -f CMakeFiles/Task1-5.dir/build.make CMakeFiles/Task1-5.dir/Tasks/Task1-5/task1-5.cpp.o .PHONY : Tasks/Task1-5/task1-5.cpp.o Tasks/Task1-5/task1-5.i: Tasks/Task1-5/task1-5.cpp.i .PHONY : Tasks/Task1-5/task1-5.i # target to preprocess a source file Tasks/Task1-5/task1-5.cpp.i: $(MAKE) -f CMakeFiles/Task1-5.dir/build.make CMakeFiles/Task1-5.dir/Tasks/Task1-5/task1-5.cpp.i .PHONY : Tasks/Task1-5/task1-5.cpp.i Tasks/Task1-5/task1-5.s: Tasks/Task1-5/task1-5.cpp.s .PHONY : Tasks/Task1-5/task1-5.s # target to generate assembly for a file Tasks/Task1-5/task1-5.cpp.s: $(MAKE) -f CMakeFiles/Task1-5.dir/build.make CMakeFiles/Task1-5.dir/Tasks/Task1-5/task1-5.cpp.s .PHONY : Tasks/Task1-5/task1-5.cpp.s Tasks/Task10/task10.o: Tasks/Task10/task10.cpp.o .PHONY : Tasks/Task10/task10.o # target to build an object file Tasks/Task10/task10.cpp.o: $(MAKE) -f CMakeFiles/Task10.dir/build.make CMakeFiles/Task10.dir/Tasks/Task10/task10.cpp.o .PHONY : Tasks/Task10/task10.cpp.o Tasks/Task10/task10.i: Tasks/Task10/task10.cpp.i .PHONY : Tasks/Task10/task10.i # target to preprocess a source file Tasks/Task10/task10.cpp.i: $(MAKE) -f CMakeFiles/Task10.dir/build.make CMakeFiles/Task10.dir/Tasks/Task10/task10.cpp.i .PHONY : Tasks/Task10/task10.cpp.i Tasks/Task10/task10.s: Tasks/Task10/task10.cpp.s .PHONY : Tasks/Task10/task10.s # target to generate assembly for a file Tasks/Task10/task10.cpp.s: $(MAKE) -f CMakeFiles/Task10.dir/build.make CMakeFiles/Task10.dir/Tasks/Task10/task10.cpp.s .PHONY : Tasks/Task10/task10.cpp.s Tasks/Task11/task11.o: Tasks/Task11/task11.cpp.o .PHONY : Tasks/Task11/task11.o # target to build an object file Tasks/Task11/task11.cpp.o: $(MAKE) -f CMakeFiles/Task11.dir/build.make CMakeFiles/Task11.dir/Tasks/Task11/task11.cpp.o .PHONY : Tasks/Task11/task11.cpp.o Tasks/Task11/task11.i: Tasks/Task11/task11.cpp.i .PHONY : Tasks/Task11/task11.i # target to preprocess a source file Tasks/Task11/task11.cpp.i: $(MAKE) -f CMakeFiles/Task11.dir/build.make CMakeFiles/Task11.dir/Tasks/Task11/task11.cpp.i .PHONY : Tasks/Task11/task11.cpp.i Tasks/Task11/task11.s: Tasks/Task11/task11.cpp.s .PHONY : Tasks/Task11/task11.s # target to generate assembly for a file Tasks/Task11/task11.cpp.s: $(MAKE) -f CMakeFiles/Task11.dir/build.make CMakeFiles/Task11.dir/Tasks/Task11/task11.cpp.s .PHONY : Tasks/Task11/task11.cpp.s Tasks/Task12/task12.o: Tasks/Task12/task12.cpp.o .PHONY : Tasks/Task12/task12.o # target to build an object file Tasks/Task12/task12.cpp.o: $(MAKE) -f CMakeFiles/Task12.dir/build.make CMakeFiles/Task12.dir/Tasks/Task12/task12.cpp.o .PHONY : Tasks/Task12/task12.cpp.o Tasks/Task12/task12.i: Tasks/Task12/task12.cpp.i .PHONY : Tasks/Task12/task12.i # target to preprocess a source file Tasks/Task12/task12.cpp.i: $(MAKE) -f CMakeFiles/Task12.dir/build.make CMakeFiles/Task12.dir/Tasks/Task12/task12.cpp.i .PHONY : Tasks/Task12/task12.cpp.i Tasks/Task12/task12.s: Tasks/Task12/task12.cpp.s .PHONY : Tasks/Task12/task12.s # target to generate assembly for a file Tasks/Task12/task12.cpp.s: $(MAKE) -f CMakeFiles/Task12.dir/build.make CMakeFiles/Task12.dir/Tasks/Task12/task12.cpp.s .PHONY : Tasks/Task12/task12.cpp.s Tasks/Task13/task13.o: Tasks/Task13/task13.cpp.o .PHONY : Tasks/Task13/task13.o # target to build an object file Tasks/Task13/task13.cpp.o: $(MAKE) -f CMakeFiles/Task13.dir/build.make CMakeFiles/Task13.dir/Tasks/Task13/task13.cpp.o .PHONY : Tasks/Task13/task13.cpp.o Tasks/Task13/task13.i: Tasks/Task13/task13.cpp.i .PHONY : Tasks/Task13/task13.i # target to preprocess a source file Tasks/Task13/task13.cpp.i: $(MAKE) -f CMakeFiles/Task13.dir/build.make CMakeFiles/Task13.dir/Tasks/Task13/task13.cpp.i .PHONY : Tasks/Task13/task13.cpp.i Tasks/Task13/task13.s: Tasks/Task13/task13.cpp.s .PHONY : Tasks/Task13/task13.s # target to generate assembly for a file Tasks/Task13/task13.cpp.s: $(MAKE) -f CMakeFiles/Task13.dir/build.make CMakeFiles/Task13.dir/Tasks/Task13/task13.cpp.s .PHONY : Tasks/Task13/task13.cpp.s Tasks/Task14/task14.o: Tasks/Task14/task14.cpp.o .PHONY : Tasks/Task14/task14.o # target to build an object file Tasks/Task14/task14.cpp.o: $(MAKE) -f CMakeFiles/Task14.dir/build.make CMakeFiles/Task14.dir/Tasks/Task14/task14.cpp.o .PHONY : Tasks/Task14/task14.cpp.o Tasks/Task14/task14.i: Tasks/Task14/task14.cpp.i .PHONY : Tasks/Task14/task14.i # target to preprocess a source file Tasks/Task14/task14.cpp.i: $(MAKE) -f CMakeFiles/Task14.dir/build.make CMakeFiles/Task14.dir/Tasks/Task14/task14.cpp.i .PHONY : Tasks/Task14/task14.cpp.i Tasks/Task14/task14.s: Tasks/Task14/task14.cpp.s .PHONY : Tasks/Task14/task14.s # target to generate assembly for a file Tasks/Task14/task14.cpp.s: $(MAKE) -f CMakeFiles/Task14.dir/build.make CMakeFiles/Task14.dir/Tasks/Task14/task14.cpp.s .PHONY : Tasks/Task14/task14.cpp.s Tasks/Task15/task15.o: Tasks/Task15/task15.cpp.o .PHONY : Tasks/Task15/task15.o # target to build an object file Tasks/Task15/task15.cpp.o: $(MAKE) -f CMakeFiles/Task15.dir/build.make CMakeFiles/Task15.dir/Tasks/Task15/task15.cpp.o .PHONY : Tasks/Task15/task15.cpp.o Tasks/Task15/task15.i: Tasks/Task15/task15.cpp.i .PHONY : Tasks/Task15/task15.i # target to preprocess a source file Tasks/Task15/task15.cpp.i: $(MAKE) -f CMakeFiles/Task15.dir/build.make CMakeFiles/Task15.dir/Tasks/Task15/task15.cpp.i .PHONY : Tasks/Task15/task15.cpp.i Tasks/Task15/task15.s: Tasks/Task15/task15.cpp.s .PHONY : Tasks/Task15/task15.s # target to generate assembly for a file Tasks/Task15/task15.cpp.s: $(MAKE) -f CMakeFiles/Task15.dir/build.make CMakeFiles/Task15.dir/Tasks/Task15/task15.cpp.s .PHONY : Tasks/Task15/task15.cpp.s Tasks/Task16/task16.o: Tasks/Task16/task16.cpp.o .PHONY : Tasks/Task16/task16.o # target to build an object file Tasks/Task16/task16.cpp.o: $(MAKE) -f CMakeFiles/Task16.dir/build.make CMakeFiles/Task16.dir/Tasks/Task16/task16.cpp.o .PHONY : Tasks/Task16/task16.cpp.o Tasks/Task16/task16.i: Tasks/Task16/task16.cpp.i .PHONY : Tasks/Task16/task16.i # target to preprocess a source file Tasks/Task16/task16.cpp.i: $(MAKE) -f CMakeFiles/Task16.dir/build.make CMakeFiles/Task16.dir/Tasks/Task16/task16.cpp.i .PHONY : Tasks/Task16/task16.cpp.i Tasks/Task16/task16.s: Tasks/Task16/task16.cpp.s .PHONY : Tasks/Task16/task16.s # target to generate assembly for a file Tasks/Task16/task16.cpp.s: $(MAKE) -f CMakeFiles/Task16.dir/build.make CMakeFiles/Task16.dir/Tasks/Task16/task16.cpp.s .PHONY : Tasks/Task16/task16.cpp.s Tasks/Task17/task17.o: Tasks/Task17/task17.cpp.o .PHONY : Tasks/Task17/task17.o # target to build an object file Tasks/Task17/task17.cpp.o: $(MAKE) -f CMakeFiles/Task17.dir/build.make CMakeFiles/Task17.dir/Tasks/Task17/task17.cpp.o .PHONY : Tasks/Task17/task17.cpp.o Tasks/Task17/task17.i: Tasks/Task17/task17.cpp.i .PHONY : Tasks/Task17/task17.i # target to preprocess a source file Tasks/Task17/task17.cpp.i: $(MAKE) -f CMakeFiles/Task17.dir/build.make CMakeFiles/Task17.dir/Tasks/Task17/task17.cpp.i .PHONY : Tasks/Task17/task17.cpp.i Tasks/Task17/task17.s: Tasks/Task17/task17.cpp.s .PHONY : Tasks/Task17/task17.s # target to generate assembly for a file Tasks/Task17/task17.cpp.s: $(MAKE) -f CMakeFiles/Task17.dir/build.make CMakeFiles/Task17.dir/Tasks/Task17/task17.cpp.s .PHONY : Tasks/Task17/task17.cpp.s Tasks/Task18/task18.o: Tasks/Task18/task18.cpp.o .PHONY : Tasks/Task18/task18.o # target to build an object file Tasks/Task18/task18.cpp.o: $(MAKE) -f CMakeFiles/Task18.dir/build.make CMakeFiles/Task18.dir/Tasks/Task18/task18.cpp.o .PHONY : Tasks/Task18/task18.cpp.o Tasks/Task18/task18.i: Tasks/Task18/task18.cpp.i .PHONY : Tasks/Task18/task18.i # target to preprocess a source file Tasks/Task18/task18.cpp.i: $(MAKE) -f CMakeFiles/Task18.dir/build.make CMakeFiles/Task18.dir/Tasks/Task18/task18.cpp.i .PHONY : Tasks/Task18/task18.cpp.i Tasks/Task18/task18.s: Tasks/Task18/task18.cpp.s .PHONY : Tasks/Task18/task18.s # target to generate assembly for a file Tasks/Task18/task18.cpp.s: $(MAKE) -f CMakeFiles/Task18.dir/build.make CMakeFiles/Task18.dir/Tasks/Task18/task18.cpp.s .PHONY : Tasks/Task18/task18.cpp.s Tasks/Task19/task19.o: Tasks/Task19/task19.cpp.o .PHONY : Tasks/Task19/task19.o # target to build an object file Tasks/Task19/task19.cpp.o: $(MAKE) -f CMakeFiles/Task19.dir/build.make CMakeFiles/Task19.dir/Tasks/Task19/task19.cpp.o .PHONY : Tasks/Task19/task19.cpp.o Tasks/Task19/task19.i: Tasks/Task19/task19.cpp.i .PHONY : Tasks/Task19/task19.i # target to preprocess a source file Tasks/Task19/task19.cpp.i: $(MAKE) -f CMakeFiles/Task19.dir/build.make CMakeFiles/Task19.dir/Tasks/Task19/task19.cpp.i .PHONY : Tasks/Task19/task19.cpp.i Tasks/Task19/task19.s: Tasks/Task19/task19.cpp.s .PHONY : Tasks/Task19/task19.s # target to generate assembly for a file Tasks/Task19/task19.cpp.s: $(MAKE) -f CMakeFiles/Task19.dir/build.make CMakeFiles/Task19.dir/Tasks/Task19/task19.cpp.s .PHONY : Tasks/Task19/task19.cpp.s Tasks/Task20/task20.o: Tasks/Task20/task20.cpp.o .PHONY : Tasks/Task20/task20.o # target to build an object file Tasks/Task20/task20.cpp.o: $(MAKE) -f CMakeFiles/Task20.dir/build.make CMakeFiles/Task20.dir/Tasks/Task20/task20.cpp.o .PHONY : Tasks/Task20/task20.cpp.o Tasks/Task20/task20.i: Tasks/Task20/task20.cpp.i .PHONY : Tasks/Task20/task20.i # target to preprocess a source file Tasks/Task20/task20.cpp.i: $(MAKE) -f CMakeFiles/Task20.dir/build.make CMakeFiles/Task20.dir/Tasks/Task20/task20.cpp.i .PHONY : Tasks/Task20/task20.cpp.i Tasks/Task20/task20.s: Tasks/Task20/task20.cpp.s .PHONY : Tasks/Task20/task20.s # target to generate assembly for a file Tasks/Task20/task20.cpp.s: $(MAKE) -f CMakeFiles/Task20.dir/build.make CMakeFiles/Task20.dir/Tasks/Task20/task20.cpp.s .PHONY : Tasks/Task20/task20.cpp.s Tasks/Task21/task21.o: Tasks/Task21/task21.cpp.o .PHONY : Tasks/Task21/task21.o # target to build an object file Tasks/Task21/task21.cpp.o: $(MAKE) -f CMakeFiles/Task21.dir/build.make CMakeFiles/Task21.dir/Tasks/Task21/task21.cpp.o .PHONY : Tasks/Task21/task21.cpp.o Tasks/Task21/task21.i: Tasks/Task21/task21.cpp.i .PHONY : Tasks/Task21/task21.i # target to preprocess a source file Tasks/Task21/task21.cpp.i: $(MAKE) -f CMakeFiles/Task21.dir/build.make CMakeFiles/Task21.dir/Tasks/Task21/task21.cpp.i .PHONY : Tasks/Task21/task21.cpp.i Tasks/Task21/task21.s: Tasks/Task21/task21.cpp.s .PHONY : Tasks/Task21/task21.s # target to generate assembly for a file Tasks/Task21/task21.cpp.s: $(MAKE) -f CMakeFiles/Task21.dir/build.make CMakeFiles/Task21.dir/Tasks/Task21/task21.cpp.s .PHONY : Tasks/Task21/task21.cpp.s Tasks/Task22/task22.o: Tasks/Task22/task22.cpp.o .PHONY : Tasks/Task22/task22.o # target to build an object file Tasks/Task22/task22.cpp.o: $(MAKE) -f CMakeFiles/Task22.dir/build.make CMakeFiles/Task22.dir/Tasks/Task22/task22.cpp.o .PHONY : Tasks/Task22/task22.cpp.o Tasks/Task22/task22.i: Tasks/Task22/task22.cpp.i .PHONY : Tasks/Task22/task22.i # target to preprocess a source file Tasks/Task22/task22.cpp.i: $(MAKE) -f CMakeFiles/Task22.dir/build.make CMakeFiles/Task22.dir/Tasks/Task22/task22.cpp.i .PHONY : Tasks/Task22/task22.cpp.i Tasks/Task22/task22.s: Tasks/Task22/task22.cpp.s .PHONY : Tasks/Task22/task22.s # target to generate assembly for a file Tasks/Task22/task22.cpp.s: $(MAKE) -f CMakeFiles/Task22.dir/build.make CMakeFiles/Task22.dir/Tasks/Task22/task22.cpp.s .PHONY : Tasks/Task22/task22.cpp.s Tasks/Task23/task23.o: Tasks/Task23/task23.cpp.o .PHONY : Tasks/Task23/task23.o # target to build an object file Tasks/Task23/task23.cpp.o: $(MAKE) -f CMakeFiles/Task23.dir/build.make CMakeFiles/Task23.dir/Tasks/Task23/task23.cpp.o .PHONY : Tasks/Task23/task23.cpp.o Tasks/Task23/task23.i: Tasks/Task23/task23.cpp.i .PHONY : Tasks/Task23/task23.i # target to preprocess a source file Tasks/Task23/task23.cpp.i: $(MAKE) -f CMakeFiles/Task23.dir/build.make CMakeFiles/Task23.dir/Tasks/Task23/task23.cpp.i .PHONY : Tasks/Task23/task23.cpp.i Tasks/Task23/task23.s: Tasks/Task23/task23.cpp.s .PHONY : Tasks/Task23/task23.s # target to generate assembly for a file Tasks/Task23/task23.cpp.s: $(MAKE) -f CMakeFiles/Task23.dir/build.make CMakeFiles/Task23.dir/Tasks/Task23/task23.cpp.s .PHONY : Tasks/Task23/task23.cpp.s Tasks/Task24/task24.o: Tasks/Task24/task24.cpp.o .PHONY : Tasks/Task24/task24.o # target to build an object file Tasks/Task24/task24.cpp.o: $(MAKE) -f CMakeFiles/Task24.dir/build.make CMakeFiles/Task24.dir/Tasks/Task24/task24.cpp.o .PHONY : Tasks/Task24/task24.cpp.o Tasks/Task24/task24.i: Tasks/Task24/task24.cpp.i .PHONY : Tasks/Task24/task24.i # target to preprocess a source file Tasks/Task24/task24.cpp.i: $(MAKE) -f CMakeFiles/Task24.dir/build.make CMakeFiles/Task24.dir/Tasks/Task24/task24.cpp.i .PHONY : Tasks/Task24/task24.cpp.i Tasks/Task24/task24.s: Tasks/Task24/task24.cpp.s .PHONY : Tasks/Task24/task24.s # target to generate assembly for a file Tasks/Task24/task24.cpp.s: $(MAKE) -f CMakeFiles/Task24.dir/build.make CMakeFiles/Task24.dir/Tasks/Task24/task24.cpp.s .PHONY : Tasks/Task24/task24.cpp.s Tasks/Task25/task25.o: Tasks/Task25/task25.cpp.o .PHONY : Tasks/Task25/task25.o # target to build an object file Tasks/Task25/task25.cpp.o: $(MAKE) -f CMakeFiles/Task25.dir/build.make CMakeFiles/Task25.dir/Tasks/Task25/task25.cpp.o .PHONY : Tasks/Task25/task25.cpp.o Tasks/Task25/task25.i: Tasks/Task25/task25.cpp.i .PHONY : Tasks/Task25/task25.i # target to preprocess a source file Tasks/Task25/task25.cpp.i: $(MAKE) -f CMakeFiles/Task25.dir/build.make CMakeFiles/Task25.dir/Tasks/Task25/task25.cpp.i .PHONY : Tasks/Task25/task25.cpp.i Tasks/Task25/task25.s: Tasks/Task25/task25.cpp.s .PHONY : Tasks/Task25/task25.s # target to generate assembly for a file Tasks/Task25/task25.cpp.s: $(MAKE) -f CMakeFiles/Task25.dir/build.make CMakeFiles/Task25.dir/Tasks/Task25/task25.cpp.s .PHONY : Tasks/Task25/task25.cpp.s Tasks/Task26/task26.o: Tasks/Task26/task26.cpp.o .PHONY : Tasks/Task26/task26.o # target to build an object file Tasks/Task26/task26.cpp.o: $(MAKE) -f CMakeFiles/Task26.dir/build.make CMakeFiles/Task26.dir/Tasks/Task26/task26.cpp.o .PHONY : Tasks/Task26/task26.cpp.o Tasks/Task26/task26.i: Tasks/Task26/task26.cpp.i .PHONY : Tasks/Task26/task26.i # target to preprocess a source file Tasks/Task26/task26.cpp.i: $(MAKE) -f CMakeFiles/Task26.dir/build.make CMakeFiles/Task26.dir/Tasks/Task26/task26.cpp.i .PHONY : Tasks/Task26/task26.cpp.i Tasks/Task26/task26.s: Tasks/Task26/task26.cpp.s .PHONY : Tasks/Task26/task26.s # target to generate assembly for a file Tasks/Task26/task26.cpp.s: $(MAKE) -f CMakeFiles/Task26.dir/build.make CMakeFiles/Task26.dir/Tasks/Task26/task26.cpp.s .PHONY : Tasks/Task26/task26.cpp.s Tasks/Task27/task27.o: Tasks/Task27/task27.cpp.o .PHONY : Tasks/Task27/task27.o # target to build an object file Tasks/Task27/task27.cpp.o: $(MAKE) -f CMakeFiles/Task27.dir/build.make CMakeFiles/Task27.dir/Tasks/Task27/task27.cpp.o .PHONY : Tasks/Task27/task27.cpp.o Tasks/Task27/task27.i: Tasks/Task27/task27.cpp.i .PHONY : Tasks/Task27/task27.i # target to preprocess a source file Tasks/Task27/task27.cpp.i: $(MAKE) -f CMakeFiles/Task27.dir/build.make CMakeFiles/Task27.dir/Tasks/Task27/task27.cpp.i .PHONY : Tasks/Task27/task27.cpp.i Tasks/Task27/task27.s: Tasks/Task27/task27.cpp.s .PHONY : Tasks/Task27/task27.s # target to generate assembly for a file Tasks/Task27/task27.cpp.s: $(MAKE) -f CMakeFiles/Task27.dir/build.make CMakeFiles/Task27.dir/Tasks/Task27/task27.cpp.s .PHONY : Tasks/Task27/task27.cpp.s Tasks/Task28/task28.o: Tasks/Task28/task28.cpp.o .PHONY : Tasks/Task28/task28.o # target to build an object file Tasks/Task28/task28.cpp.o: $(MAKE) -f CMakeFiles/Task28.dir/build.make CMakeFiles/Task28.dir/Tasks/Task28/task28.cpp.o .PHONY : Tasks/Task28/task28.cpp.o Tasks/Task28/task28.i: Tasks/Task28/task28.cpp.i .PHONY : Tasks/Task28/task28.i # target to preprocess a source file Tasks/Task28/task28.cpp.i: $(MAKE) -f CMakeFiles/Task28.dir/build.make CMakeFiles/Task28.dir/Tasks/Task28/task28.cpp.i .PHONY : Tasks/Task28/task28.cpp.i Tasks/Task28/task28.s: Tasks/Task28/task28.cpp.s .PHONY : Tasks/Task28/task28.s # target to generate assembly for a file Tasks/Task28/task28.cpp.s: $(MAKE) -f CMakeFiles/Task28.dir/build.make CMakeFiles/Task28.dir/Tasks/Task28/task28.cpp.s .PHONY : Tasks/Task28/task28.cpp.s Tasks/Task29/task29.o: Tasks/Task29/task29.cpp.o .PHONY : Tasks/Task29/task29.o # target to build an object file Tasks/Task29/task29.cpp.o: $(MAKE) -f CMakeFiles/Task29.dir/build.make CMakeFiles/Task29.dir/Tasks/Task29/task29.cpp.o .PHONY : Tasks/Task29/task29.cpp.o Tasks/Task29/task29.i: Tasks/Task29/task29.cpp.i .PHONY : Tasks/Task29/task29.i # target to preprocess a source file Tasks/Task29/task29.cpp.i: $(MAKE) -f CMakeFiles/Task29.dir/build.make CMakeFiles/Task29.dir/Tasks/Task29/task29.cpp.i .PHONY : Tasks/Task29/task29.cpp.i Tasks/Task29/task29.s: Tasks/Task29/task29.cpp.s .PHONY : Tasks/Task29/task29.s # target to generate assembly for a file Tasks/Task29/task29.cpp.s: $(MAKE) -f CMakeFiles/Task29.dir/build.make CMakeFiles/Task29.dir/Tasks/Task29/task29.cpp.s .PHONY : Tasks/Task29/task29.cpp.s Tasks/Task30/t30.o: Tasks/Task30/t30.cpp.o .PHONY : Tasks/Task30/t30.o # target to build an object file Tasks/Task30/t30.cpp.o: $(MAKE) -f CMakeFiles/Tasks30.dir/build.make CMakeFiles/Tasks30.dir/Tasks/Task30/t30.cpp.o .PHONY : Tasks/Task30/t30.cpp.o Tasks/Task30/t30.i: Tasks/Task30/t30.cpp.i .PHONY : Tasks/Task30/t30.i # target to preprocess a source file Tasks/Task30/t30.cpp.i: $(MAKE) -f CMakeFiles/Tasks30.dir/build.make CMakeFiles/Tasks30.dir/Tasks/Task30/t30.cpp.i .PHONY : Tasks/Task30/t30.cpp.i Tasks/Task30/t30.s: Tasks/Task30/t30.cpp.s .PHONY : Tasks/Task30/t30.s # target to generate assembly for a file Tasks/Task30/t30.cpp.s: $(MAKE) -f CMakeFiles/Tasks30.dir/build.make CMakeFiles/Tasks30.dir/Tasks/Task30/t30.cpp.s .PHONY : Tasks/Task30/t30.cpp.s Tasks/Task6/task6.o: Tasks/Task6/task6.cpp.o .PHONY : Tasks/Task6/task6.o # target to build an object file Tasks/Task6/task6.cpp.o: $(MAKE) -f CMakeFiles/Task6.dir/build.make CMakeFiles/Task6.dir/Tasks/Task6/task6.cpp.o .PHONY : Tasks/Task6/task6.cpp.o Tasks/Task6/task6.i: Tasks/Task6/task6.cpp.i .PHONY : Tasks/Task6/task6.i # target to preprocess a source file Tasks/Task6/task6.cpp.i: $(MAKE) -f CMakeFiles/Task6.dir/build.make CMakeFiles/Task6.dir/Tasks/Task6/task6.cpp.i .PHONY : Tasks/Task6/task6.cpp.i Tasks/Task6/task6.s: Tasks/Task6/task6.cpp.s .PHONY : Tasks/Task6/task6.s # target to generate assembly for a file Tasks/Task6/task6.cpp.s: $(MAKE) -f CMakeFiles/Task6.dir/build.make CMakeFiles/Task6.dir/Tasks/Task6/task6.cpp.s .PHONY : Tasks/Task6/task6.cpp.s Tasks/Task7/task7.o: Tasks/Task7/task7.cpp.o .PHONY : Tasks/Task7/task7.o # target to build an object file Tasks/Task7/task7.cpp.o: $(MAKE) -f CMakeFiles/Task7.dir/build.make CMakeFiles/Task7.dir/Tasks/Task7/task7.cpp.o .PHONY : Tasks/Task7/task7.cpp.o Tasks/Task7/task7.i: Tasks/Task7/task7.cpp.i .PHONY : Tasks/Task7/task7.i # target to preprocess a source file Tasks/Task7/task7.cpp.i: $(MAKE) -f CMakeFiles/Task7.dir/build.make CMakeFiles/Task7.dir/Tasks/Task7/task7.cpp.i .PHONY : Tasks/Task7/task7.cpp.i Tasks/Task7/task7.s: Tasks/Task7/task7.cpp.s .PHONY : Tasks/Task7/task7.s # target to generate assembly for a file Tasks/Task7/task7.cpp.s: $(MAKE) -f CMakeFiles/Task7.dir/build.make CMakeFiles/Task7.dir/Tasks/Task7/task7.cpp.s .PHONY : Tasks/Task7/task7.cpp.s Tasks/Task8/task8.o: Tasks/Task8/task8.cpp.o .PHONY : Tasks/Task8/task8.o # target to build an object file Tasks/Task8/task8.cpp.o: $(MAKE) -f CMakeFiles/Task8.dir/build.make CMakeFiles/Task8.dir/Tasks/Task8/task8.cpp.o .PHONY : Tasks/Task8/task8.cpp.o Tasks/Task8/task8.i: Tasks/Task8/task8.cpp.i .PHONY : Tasks/Task8/task8.i # target to preprocess a source file Tasks/Task8/task8.cpp.i: $(MAKE) -f CMakeFiles/Task8.dir/build.make CMakeFiles/Task8.dir/Tasks/Task8/task8.cpp.i .PHONY : Tasks/Task8/task8.cpp.i Tasks/Task8/task8.s: Tasks/Task8/task8.cpp.s .PHONY : Tasks/Task8/task8.s # target to generate assembly for a file Tasks/Task8/task8.cpp.s: $(MAKE) -f CMakeFiles/Task8.dir/build.make CMakeFiles/Task8.dir/Tasks/Task8/task8.cpp.s .PHONY : Tasks/Task8/task8.cpp.s Tasks/Task9/task9.o: Tasks/Task9/task9.cpp.o .PHONY : Tasks/Task9/task9.o # target to build an object file Tasks/Task9/task9.cpp.o: $(MAKE) -f CMakeFiles/Task9.dir/build.make CMakeFiles/Task9.dir/Tasks/Task9/task9.cpp.o .PHONY : Tasks/Task9/task9.cpp.o Tasks/Task9/task9.i: Tasks/Task9/task9.cpp.i .PHONY : Tasks/Task9/task9.i # target to preprocess a source file Tasks/Task9/task9.cpp.i: $(MAKE) -f CMakeFiles/Task9.dir/build.make CMakeFiles/Task9.dir/Tasks/Task9/task9.cpp.i .PHONY : Tasks/Task9/task9.cpp.i Tasks/Task9/task9.s: Tasks/Task9/task9.cpp.s .PHONY : Tasks/Task9/task9.s # target to generate assembly for a file Tasks/Task9/task9.cpp.s: $(MAKE) -f CMakeFiles/Task9.dir/build.make CMakeFiles/Task9.dir/Tasks/Task9/task9.cpp.s .PHONY : Tasks/Task9/task9.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... rebuild_cache" @echo "... edit_cache" @echo "... Lab3" @echo "... Lab4" @echo "... Tasks30" @echo "... Task29" @echo "... Task26" @echo "... Lab2" @echo "... Task25" @echo "... Task23" @echo "... Task22" @echo "... Task21" @echo "... Task24" @echo "... Task9" @echo "... Task8" @echo "... Task7" @echo "... Task14" @echo "... Task10" @echo "... Task1-5" @echo "... Task6" @echo "... Lab1" @echo "... Task11" @echo "... Task16" @echo "... Task18" @echo "... Task12" @echo "... Task13" @echo "... Task15" @echo "... Task28" @echo "... Task27" @echo "... Task17" @echo "... Task19" @echo "... Task20" @echo "... Labs/Lab1/lab1.o" @echo "... Labs/Lab1/lab1.i" @echo "... Labs/Lab1/lab1.s" @echo "... Labs/Lab2/lab2.o" @echo "... Labs/Lab2/lab2.i" @echo "... Labs/Lab2/lab2.s" @echo "... Labs/Lab3/lab3.o" @echo "... Labs/Lab3/lab3.i" @echo "... Labs/Lab3/lab3.s" @echo "... Labs/Lab3/libbmp.o" @echo "... Labs/Lab3/libbmp.i" @echo "... Labs/Lab3/libbmp.s" @echo "... Labs/Lab4/helper.o" @echo "... Labs/Lab4/helper.i" @echo "... Labs/Lab4/helper.s" @echo "... Labs/Lab4/main.o" @echo "... Labs/Lab4/main.i" @echo "... Labs/Lab4/main.s" @echo "... Tasks/Task1-5/task1-5.o" @echo "... Tasks/Task1-5/task1-5.i" @echo "... Tasks/Task1-5/task1-5.s" @echo "... Tasks/Task10/task10.o" @echo "... Tasks/Task10/task10.i" @echo "... Tasks/Task10/task10.s" @echo "... Tasks/Task11/task11.o" @echo "... Tasks/Task11/task11.i" @echo "... Tasks/Task11/task11.s" @echo "... Tasks/Task12/task12.o" @echo "... Tasks/Task12/task12.i" @echo "... Tasks/Task12/task12.s" @echo "... Tasks/Task13/task13.o" @echo "... Tasks/Task13/task13.i" @echo "... Tasks/Task13/task13.s" @echo "... Tasks/Task14/task14.o" @echo "... Tasks/Task14/task14.i" @echo "... Tasks/Task14/task14.s" @echo "... Tasks/Task15/task15.o" @echo "... Tasks/Task15/task15.i" @echo "... Tasks/Task15/task15.s" @echo "... Tasks/Task16/task16.o" @echo "... Tasks/Task16/task16.i" @echo "... Tasks/Task16/task16.s" @echo "... Tasks/Task17/task17.o" @echo "... Tasks/Task17/task17.i" @echo "... Tasks/Task17/task17.s" @echo "... Tasks/Task18/task18.o" @echo "... Tasks/Task18/task18.i" @echo "... Tasks/Task18/task18.s" @echo "... Tasks/Task19/task19.o" @echo "... Tasks/Task19/task19.i" @echo "... Tasks/Task19/task19.s" @echo "... Tasks/Task20/task20.o" @echo "... Tasks/Task20/task20.i" @echo "... Tasks/Task20/task20.s" @echo "... Tasks/Task21/task21.o" @echo "... Tasks/Task21/task21.i" @echo "... Tasks/Task21/task21.s" @echo "... Tasks/Task22/task22.o" @echo "... Tasks/Task22/task22.i" @echo "... Tasks/Task22/task22.s" @echo "... Tasks/Task23/task23.o" @echo "... Tasks/Task23/task23.i" @echo "... Tasks/Task23/task23.s" @echo "... Tasks/Task24/task24.o" @echo "... Tasks/Task24/task24.i" @echo "... Tasks/Task24/task24.s" @echo "... Tasks/Task25/task25.o" @echo "... Tasks/Task25/task25.i" @echo "... Tasks/Task25/task25.s" @echo "... Tasks/Task26/task26.o" @echo "... Tasks/Task26/task26.i" @echo "... Tasks/Task26/task26.s" @echo "... Tasks/Task27/task27.o" @echo "... Tasks/Task27/task27.i" @echo "... Tasks/Task27/task27.s" @echo "... Tasks/Task28/task28.o" @echo "... Tasks/Task28/task28.i" @echo "... Tasks/Task28/task28.s" @echo "... Tasks/Task29/task29.o" @echo "... Tasks/Task29/task29.i" @echo "... Tasks/Task29/task29.s" @echo "... Tasks/Task30/t30.o" @echo "... Tasks/Task30/t30.i" @echo "... Tasks/Task30/t30.s" @echo "... Tasks/Task6/task6.o" @echo "... Tasks/Task6/task6.i" @echo "... Tasks/Task6/task6.s" @echo "... Tasks/Task7/task7.o" @echo "... Tasks/Task7/task7.i" @echo "... Tasks/Task7/task7.s" @echo "... Tasks/Task8/task8.o" @echo "... Tasks/Task8/task8.i" @echo "... Tasks/Task8/task8.s" @echo "... Tasks/Task9/task9.o" @echo "... Tasks/Task9/task9.i" @echo "... Tasks/Task9/task9.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>/cmake-build-debug/CMakeFiles/Task21.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Task21.dir/Tasks/Task21/task21.cpp.o" "Task21" "Task21.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Task21.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/cmake-build-debug/CMakeFiles/Makefile.cmake # CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.15 # The generator used is: set(CMAKE_DEPENDS_GENERATOR "Unix Makefiles") # The top level Makefile was generated from the following files: set(CMAKE_MAKEFILE_DEPENDS "CMakeCache.txt" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeCInformation.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeCXXInformation.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeCommonLanguageInclude.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeExtraGeneratorDetermineCompilerMacrosAndIncludeDirs.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeFindCodeBlocks.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeGenericSystem.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeInitializeConfigs.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeLanguageInformation.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeSystemSpecificInformation.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/CMakeSystemSpecificInitialize.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Compiler/CMakeCommonCompilerMacros.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Compiler/GNU-C.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Compiler/GNU-CXX.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Compiler/GNU.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Internal/CMakeCheckCompilerFlag.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Platform/Linux-GNU-C.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Platform/Linux-GNU-CXX.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Platform/Linux-GNU.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Platform/Linux.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/Platform/UnixPaths.cmake" "/home/canned_dead/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/193.5233.144/bin/cmake/linux/share/cmake-3.15/Modules/ProcessorCount.cmake" "../CMakeLists.txt" "CMakeFiles/3.15.3/CMakeCCompiler.cmake" "CMakeFiles/3.15.3/CMakeCXXCompiler.cmake" "CMakeFiles/3.15.3/CMakeSystem.cmake" ) # The corresponding makefile is: set(CMAKE_MAKEFILE_OUTPUTS "Makefile" "CMakeFiles/cmake.check_cache" ) # Byproducts of CMake generate step: set(CMAKE_MAKEFILE_PRODUCTS "CMakeFiles/CMakeDirectoryInformation.cmake" ) # Dependency information for all targets: set(CMAKE_DEPEND_INFO_FILES "CMakeFiles/Lab3.dir/DependInfo.cmake" "CMakeFiles/Lab4.dir/DependInfo.cmake" "CMakeFiles/Tasks30.dir/DependInfo.cmake" "CMakeFiles/Task29.dir/DependInfo.cmake" "CMakeFiles/Task26.dir/DependInfo.cmake" "CMakeFiles/Lab2.dir/DependInfo.cmake" "CMakeFiles/Task25.dir/DependInfo.cmake" "CMakeFiles/Task23.dir/DependInfo.cmake" "CMakeFiles/Task22.dir/DependInfo.cmake" "CMakeFiles/Task21.dir/DependInfo.cmake" "CMakeFiles/Task24.dir/DependInfo.cmake" "CMakeFiles/Task9.dir/DependInfo.cmake" "CMakeFiles/Task8.dir/DependInfo.cmake" "CMakeFiles/Task7.dir/DependInfo.cmake" "CMakeFiles/Task14.dir/DependInfo.cmake" "CMakeFiles/Task10.dir/DependInfo.cmake" "CMakeFiles/Task1-5.dir/DependInfo.cmake" "CMakeFiles/Task6.dir/DependInfo.cmake" "CMakeFiles/Lab1.dir/DependInfo.cmake" "CMakeFiles/Task11.dir/DependInfo.cmake" "CMakeFiles/Task16.dir/DependInfo.cmake" "CMakeFiles/Task18.dir/DependInfo.cmake" "CMakeFiles/Task12.dir/DependInfo.cmake" "CMakeFiles/Task13.dir/DependInfo.cmake" "CMakeFiles/Task15.dir/DependInfo.cmake" "CMakeFiles/Task28.dir/DependInfo.cmake" "CMakeFiles/Task27.dir/DependInfo.cmake" "CMakeFiles/Task17.dir/DependInfo.cmake" "CMakeFiles/Task19.dir/DependInfo.cmake" "CMakeFiles/Task20.dir/DependInfo.cmake" ) <file_sep>/cmake-build-debug/CMakeFiles/Task20.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Task20.dir/Tasks/Task20/task20.cpp.o" "Task20" "Task20.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Task20.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/Tasks/Task30/t30.cpp // // Created by canned_dead on 09.12.2019. // #include <iostream> #include <cstring> using namespace std; bool is_ok(char ch, const char* arr, int len){ for (int i = 0; i < len; i ++){ if (ch == arr[i]) return true; } return false; } char* strtok2(char* string, const char* delim){ static int start = 0; static int end = 0; static char* str = string; static int leng = 0; if (string != nullptr){ start = 0; end = 0; str = string; int i = 0; while (string[i] != '\0'){ i ++; leng ++; } } while (is_ok(str[start], delim, strlen(delim)) && start < leng){ start ++; end ++; } if (start >= leng){ return nullptr; } else{ while (!is_ok(str[end], delim, strlen(delim)) && end < leng){ end ++; } int temp = start; str[end] = '\0'; end ++; start = end; return str+ temp; } } int main(){ char* str_buf= new char [100]; char* delim_buf = new char [100]; cin.getline(str_buf, 100); cin.getline(delim_buf, 100); char* temp = strtok2(str_buf, delim_buf); int words = 0; while (temp != nullptr) { cout << temp << endl; temp = strtok2(nullptr, delim_buf); words ++; } cout << "words:" << words << endl; return 0; }<file_sep>/cmake-build-debug/CMakeFiles/Task17.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Task17.dir/Tasks/Task17/task17.cpp.o" "Task17" "Task17.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Task17.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/cmake-build-debug/CMakeFiles/Task19.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Task19.dir/Tasks/Task19/task19.cpp.o" "Task19" "Task19.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Task19.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/cmake-build-debug/CMakeFiles/Task18.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/Task18.dir/Tasks/Task18/task18.cpp.o" "Task18" "Task18.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/Task18.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach()
c34f4eb0bd683689915940cf7f2d634d7a760746
[ "Makefile", "CMake", "C++" ]
9
CMake
AiSRoV/prog
5ef84a71907fe7bdb1a6711f738f58569a48f427
67ee3e22c0017a179cb4c8a0cd432c29355277dc
refs/heads/master
<file_sep>package com.example.andy.thankyoujames; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class ItemClass extends Activity implements View.OnClickListener{ private Button plusButton, minusButton, shoppingCartButton; private TextView nameTag, descriptionTag, counterText, priceTag; private ImageView ImageTag; private int counter1 = 1; private int finalFoodID; private boolean isOfferWitchDiscount = false; private String selectedMeal; public static ShoppingCart shoppingCart = new ShoppingCart(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_class); initViews(); getFinalID(); checkForOffer(); setTexts(); } private void getFinalID() { finalFoodID = getIntent().getExtras().getInt("finalFoodID"); } private void checkForOffer(){ if(finalFoodID == Constants.OFFER_ONE || finalFoodID == Constants.OFFER_TWO){ isOfferWitchDiscount = true; }else { isOfferWitchDiscount = false; } } private double getDiscount(double price){ double result = price*Constants.DISCOUNT; return result; } private void setTexts(){ new Thread(new Runnable() { @Override public void run() { Meal resultMeal; resultMeal = MainJames.mealDatabase.daoAccess().fetchOneMealbyMealID(finalFoodID); if (resultMeal != null){ final String mealName = resultMeal.getMealName(); selectedMeal = resultMeal.getMealName(); final String mealDes = resultMeal.getDescription(); double realPrice = resultMeal.getPrice(); if (isOfferWitchDiscount == true){ realPrice = getDiscount(realPrice); } final String mealPrice =""+ realPrice; final int mealImageID = resultMeal.getImageID(); final Drawable mealImage = getDrawable(mealImageID); runOnUiThread(new Runnable() { @Override public void run() { nameTag.setText(mealName); descriptionTag.setText(mealDes); priceTag.setText(mealPrice + "€"); ImageTag.setImageDrawable(mealImage); if (isOfferWitchDiscount){ priceTag.setTextColor(Color.GREEN); } } }); } } }).start(); } private void initViews(){ //Buttons plusButton = findViewById(R.id.counter_plus); minusButton = findViewById(R.id.counter_minus); shoppingCartButton = findViewById(R.id.shopping_button); plusButton.setOnClickListener(this); minusButton.setOnClickListener(this); shoppingCartButton.setOnClickListener(this); //TextView nameTag = findViewById(R.id.name_tag); descriptionTag = findViewById(R.id.description_tag); priceTag = findViewById(R.id.price_tag); counterText = findViewById(R.id.counter); counterText.setText("1"); //Image ImageTag = findViewById(R.id.meal_image); } private void updateCounter(int i ){ if (i ==1 ){ counter1++; String counterAsString = ""+counter1; counterText.setText(counterAsString); } else if( i == 0 && counter1 > 1){ counter1 --; String counterAsString = ""+counter1; counterText.setText(counterAsString); }else if (i == 0 && counter1 == 1){ String counterAsString = ""+counter1; counterText.setText(counterAsString); } } @Override public void onClick(View view) { switch(view.getId()){ case R.id.counter_plus: updateCounter(1); break; case R.id.counter_minus: updateCounter(0); break; case R.id.shopping_button: for (int i = 1; i <= counter1; i++){ shoppingCart.addShoppingItem(finalFoodID);} Toast.makeText(this, ""+ counter1 + " "+selectedMeal+" zum Warenkorb hinzugefügt", Toast.LENGTH_SHORT).show(); break; } } } <file_sep>package com.example.andy.thankyoujames; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class Menu_2 extends Activity implements View.OnClickListener{ private TextView headerText; private Button headerShopping, headerBurger, meal_no_1, meal_no_2, meal_no_3; private ImageView headerImage; private int menuID, foodID, id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_2); initViews(); getIds(); setTexts(menuID, foodID); } private void initViews(){ //TextViews headerText = findViewById(R.id.header_text_menu2); //Buttons headerBurger = findViewById(R.id.header_burger_button_menu2); headerShopping = findViewById(R.id.header_shopping_button_menu2); //ImageViews headerImage = findViewById(R.id.header_image_menu2); //Buttons meal_no_1 = findViewById(R.id.submeal_no1_menu2); meal_no_2 = findViewById(R.id.submeal_no2_menu2); meal_no_3 = findViewById(R.id.submeal_no3_menu2); meal_no_1.setOnClickListener(this); meal_no_2.setOnClickListener(this); meal_no_3.setOnClickListener(this); } private void getIds (){ menuID = getIntent().getExtras().getInt("MenuID"); foodID = getIntent().getExtras().getInt("FoodID"); } //in dieser Methode sollen die Texte und Bilder angepasst werden, jenachdem welches Menü ausgewählt worden ist private void setTexts (int menuIdentifier, int foodIdentifier){ id = menuIdentifier*10+foodIdentifier; switch (id){ case 11: meal_no_1.setText(R.string.coffee_1); meal_no_2.setText(R.string.coffee_2); meal_no_3.setText(R.string.coffee_3); break; case 12: meal_no_1.setText(R.string.muesli_1); meal_no_2.setText(R.string.muesli_2); meal_no_3.setText(R.string.muesli_3); break; case 13: meal_no_1.setText(R.string.bagel_1); meal_no_2.setText(R.string.bagel_2); meal_no_3.setText(R.string.bagel_3); break; case 21: meal_no_1.setText(R.string.soup_1); meal_no_2.setText(R.string.soup_2); meal_no_3.setText(R.string.soup_3); break; case 22: meal_no_1.setText(R.string.pasta_1); meal_no_2.setText(R.string.pasta_2); meal_no_3.setText(R.string.pasta_3); break; case 23: meal_no_1.setText(R.string.sandwich_1); meal_no_2.setText(R.string.sandwich_2); meal_no_3.setText(R.string.sandwich_3); break; case 31: meal_no_1.setText(R.string.pizza_1); meal_no_2.setText(R.string.pizza_2); meal_no_3.setText(R.string.pizza_3); break; case 32: meal_no_1.setText(R.string.meat_1); meal_no_2.setText(R.string.meat_2); meal_no_3.setText(R.string.meat_3); break; case 33: meal_no_1.setText(R.string.fish_1); meal_no_2.setText(R.string.fish_2); meal_no_3.setText(R.string.fish_3); break; } } private void finalMenuSelect(int i ){ int finalFoodID = id*10+i; Intent menuSelect = new Intent(Menu_2.this, ItemClass.class); menuSelect.putExtra("finalFoodID", finalFoodID); startActivity(menuSelect); } @Override public void onClick(View view) { // TODO: 30.07.2018 send intents machen, Auf die einzelnen Seiten der Gerichte kommen -> Vermutlich mit Datenbank switch (view.getId()){ case R.id.header_burger_button: break; case R.id.header_shopping_button: break; case R.id.submeal_no1_menu2: finalMenuSelect(1); break; case R.id.submeal_no2_menu2: finalMenuSelect(2); break; case R.id.submeal_no3_menu2: finalMenuSelect(3); break; } } } <file_sep>package com.example.andy.thankyoujames; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.ArrayList; public class Cart extends Activity implements View.OnClickListener{ private TextView cartHeader, textTotal, textSumPrice; private Button btnSendOrder, btnKeepShopping; private ListView itemList; private MealListAdapter adapter; private double sumPrices = 0; private ArrayList<Integer> shoppingItems; private ArrayList<Meal> shoppedMeals = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cart); initViews(); getShoppingItems(); setUpListView(); //setTexts(); } private void initViews(){ //TextViews cartHeader = findViewById(R.id.cartHeader); textTotal = findViewById(R.id.textTotal); textSumPrice = findViewById(R.id.textSumPrice); //Buttons btnSendOrder = findViewById(R.id.btnSendOrder); btnKeepShopping = findViewById(R.id.btnContinueShopping); btnKeepShopping.setOnClickListener(this); btnSendOrder.setOnClickListener(this); } private void getShoppingItems(){ shoppingItems = ItemClass.shoppingCart.getShoppingItems(); getShoppedMeals(); } private void getShoppedMeals(){ new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < shoppingItems.size(); i ++){ Meal newShoppedMeal; newShoppedMeal = MainJames.mealDatabase.daoAccess().fetchOneMealbyMealID(shoppingItems.get(i)); sumPrices += newShoppedMeal.getPrice(); System.out.println(sumPrices); //getSumPrice(newShoppedMeal.getPrice()); shoppedMeals.add(newShoppedMeal); } } }).start(); } // private void getSumPrice(double newPrice){ // sumPrices += newPrice; //} private void setUpListView(){ //ListView itemList = findViewById(R.id.itemView); adapter = new MealListAdapter(getApplicationContext(), shoppedMeals); itemList.setAdapter(adapter); itemList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { itemLongClicked(position); return false; } }); } /*public void setTexts(){ String result = ""+ sumPrices; textSumPrice.setText(result); }*/ private void clearShoppingCart(){ ItemClass.shoppingCart.clearShoppingCart(); shoppingItems.clear(); shoppedMeals.clear(); adapter.notifyDataSetChanged(); } private void itemLongClicked(int position){ shoppingItems.remove(position); shoppedMeals.remove(position); ItemClass.shoppingCart.removeSingleItem(position); adapter.notifyDataSetChanged(); } @Override public void onClick(View view) { switch(view.getId()){ case R.id.btnContinueShopping: Intent intent = new Intent(Cart.this, MainJames.class); startActivity(intent); break; case R.id.btnSendOrder: Toast.makeText(this, "Ihre Bestellung wurde abgeschickt", Toast.LENGTH_SHORT).show(); break; case R.id.btnClearCart: clearShoppingCart(); Toast.makeText(this, "Warenkorb geleert", Toast.LENGTH_SHORT).show(); } } }
ff820a2ad1753576908621a142f470324789bdc4
[ "Java" ]
3
Java
RosalieSchmid/ThankYouJames
8740733a97b95d8d79802ea6575f61f0f9c7f25d
dc190bee1b0df305f95223dd1ff5cf0005b9c446
refs/heads/master
<repo_name>radvc/dragonpay-payment<file_sep>/lib/dragonpay_payment/merchant.rb require 'securerandom' module DragonpayPayment class Merchant attr_accessor :merchant_id, :txn_id, :amount, :ccy, :description, :email, :digest URL = 'https://gw.dragonpay.ph/Pay.aspx' def initialize(options = {}) @amount = options[:amount] @ccy = options[:ccy] @description = options[:description] @email = options[:email] end def pay generate_url end private def generate_url merchant_id = DragonpayPayment.configuration.merchant_id secret_key = DragonpayPayment.configuration.secret_key txn_id = SecureRandom.urlsafe_base64 12 details = [ merchant_id, txn_id, amount, ccy, description, email, secret_key] digest = Digest::SHA1.hexdigest details.join(':') parameters = { merchantid: merchant_id, txnid: txn_id, amount: amount, ccy: ccy, description: description, email: email, digest: digest, mode: 7 } query_string = parameters.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&") url = URL + "?#{query_string}" end end end <file_sep>/lib/dragonpay_payment/configuration.rb module DragonpayPayment class Configuration attr_accessor :merchant_id, :secret_key def initialize @merchant_id @secret_key end end end <file_sep>/lib/dragonpay_payment.rb require 'dragonpay_payment/configuration' require 'dragonpay_payment/merchant' require 'dragonpay_payment/version' module DragonpayPayment class << self attr_accessor :configuration end def self.configuration @configuration ||= Configuration.new end def self.configure yield configuration end end <file_sep>/spec/dragonpay_payment_spec.rb require "spec_helper" RSpec.describe DragonpayPayment do before do DragonpayPayment.configure do |config| config.merchant_id = 'your_merchant_id' config.secret_key = 'your_secret_key' end @transaction = DragonpayPayment::Merchant.new( amount: '500.00', ccy: 'PHP', description: 'Test payment', email: '<EMAIL>' ) end it "has a version number" do expect(DragonpayPayment::VERSION).not_to be nil end describe 'configure method' do it 'will set configuration' do config = DragonpayPayment.configuration expect(config.merchant_id).to eq 'your_merchant_id' expect(config.secret_key).to eq 'your_secret_key' end end describe 'initializing' do it 'will set payment details' do expect(@transaction.amount).to eq '500.00' expect(@transaction.ccy).to eq 'PHP' expect(@transaction.description).to eq 'Test payment' expect(@transaction.email).to eq '<EMAIL>' end end describe 'sending payment' do it 'will generate payment url' do expect(@transaction.pay).to include 'merchantid=your_merchant_id' expect(@transaction.pay).to include 'amount=500.00' expect(@transaction.pay).to include 'ccy=PHP' expect(@transaction.pay).to include 'description=Test payment' expect(@transaction.pay).to include 'email=<EMAIL>' end end end <file_sep>/README.md # DragonpayPayment Dragonpay API payment integration. ## Installation Add this line to your application's Gemfile: ```ruby gem 'dragonpay_payment' ``` And then execute: $ bundle Or install it yourself as: $ gem install dragonpay_payment ## Configuration ```ruby # config/initializers/dragonpay_payment.rb DragonpayPayment.configure do |config| config.merchant_id = 'your_merchant_id' config.secret_key = 'your_secret_key' end ``` ## Usage ```ruby @process_payment = DragonpayPayment::Merchant.new( amount: '500.00', ccy: 'PHP', description: 'Test Payment', email: '<EMAIL>' ) @process_payment.pay ``` The ```pay``` method will generate the dragonpay url it will not redirect you to the dragonpay website. ## Important Note This gem uses the dragonpay production environment url (https://gw.dragonpay.ph/Pay.aspx) for generating the payment url, I am currently working on the test environment of the dragonpay because as of the moment dragonpay returns an invalid digest error when using test url. ## Contributing Bug reports and pull requests are welcome. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). ## Code of Conduct Everyone interacting in the DragonpayPayment project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/dragonpay_payment/blob/master/CODE_OF_CONDUCT.md).
067c691e811010b10ec07beab986c9da2e353d21
[ "Markdown", "Ruby" ]
5
Ruby
radvc/dragonpay-payment
e35d28256f3913b2b11ed06bc7d97d99be341b30
37ae657b647dcef56ad863be07517a75b3fd23d2
refs/heads/master
<repo_name>mawroos/Angular<file_sep>/productManagement/common/services/productResourceMock.js (function () { "use strict"; var app = angular .module("productResourceMock", ["ngMockE2E"]); app.run(function ($httpBackend) { var products = [ { "productId": 1, "productName": "Laptop", "productCode": "LKP-223", "releaseDate": "March 10, 2014", "description": "14inch Laptop.", "cost": 1500.00, "price": 2200, "category": "computers", "tags": ["laptop", "pc"], "imageUrl": "https://openclipart.org/image/300px/svg_to_png/243109/1457105843.png" }, { "productId": 2, "productName": "Desktop", "productCode": "LKP-213", "releaseDate": "March 10, 2010", "description": "Gaming Desktop.", "cost": 1000.00, "price": 1200, "category": "computers", "tags": ["desktop", "pc"], "imageUrl": "https://openclipart.org/image/300px/svg_to_png/241121/Minimal-Desktop-Computer-With-Optical-Drive-and-Power-Button.png" } ]; var productUrl = "/api/products" $httpBackend.whenGET(productUrl).respond(products); var editingRegex = new RegExp(productUrl + "/[0-9][0-9]*", ''); $httpBackend.whenGET(editingRegex).respond(function (method, url, data) { var product = {"productId": 0}; var parameters = url.split('/'); var length = parameters.length; var id = parameters[length - 1]; if (id > 0) { for (var i = 0; i < products.length; i++) { if (products[i].productId == id) { product = products[i]; break; } }; } return [200, product, {}]; }); $httpBackend.whenPOST(productUrl).respond(function (method, url, data) { var product = angular.fromJson(data); if (!product.productId) { // new product Id product.productId = products[products.length - 1].productId + 1; products.push(product); } else { // Updated product for (var i = 0; i < products.length; i++) { if (products[i].productId == product.productId) { products[i] = product; break; } }; } return [200, product, {}]; }); // Pass through any requests for application files $httpBackend.whenGET(/app/).passThrough(); }) }());
8f05393afd0222c64998e4e194d0197cd4f96fcd
[ "JavaScript" ]
1
JavaScript
mawroos/Angular
bc5bed82dea7a60d6e592ac9dddb3daa7541ea8b
d6df0eb629e9a3108135cca4ee8fc5c20e2e88d7
refs/heads/master
<repo_name>wfei3/carshop<file_sep>/shop/src/cn/itcast/shop/product/adminaction/AdminProductAction.java package cn.itcast.shop.product.adminaction; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import cn.itcast.shop.adminuser.vo.AdminUser; import cn.itcast.shop.categorysecond.service.CategorySecondService; import cn.itcast.shop.categorysecond.vo.CategorySecond; import cn.itcast.shop.order.vo.Order; import cn.itcast.shop.product.service.ProductService; import cn.itcast.shop.product.vo.Product; import cn.itcast.shop.utils.ChineseToEnglish; import cn.itcast.shop.utils.PageBean; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * 后台商品管理的Action * * 项目名称:shop00 类名称:AdminProductAction 类描述: 创建人:Teemo 创建时间:2017年5月19日 下午1:45:52 * 修改人:Teemo 修改时间:2017年5月19日 下午1:45:52 修改备注: * * @version * */ public class AdminProductAction extends ActionSupport implements ModelDriven<Product> { // 模型驱动使用的对象 private Product product = new Product(); public Product getModel() { return product; } // 接收page参数 private Integer page; public void setPage(Integer page) { this.page = page; } // 注入ProductService private ProductService productService; public void setProductService(ProductService productService) { this.productService = productService; } // 注入CategorySecondService private CategorySecondService categorySecondService; public void setCategorySecondService( CategorySecondService categorySecondService) { this.categorySecondService = categorySecondService; } // 文件上传需要的三个属性: private File[] upload;// s上传的文件,与上传input的name一致 private String[] uploadFileName;// 接收文件上传的文件名 private String[] uploadContentType;// 接收文件类型 public void setUpload(File[] upload) { this.upload = upload; } public void setUploadFileName(String[] uploadFileName) { this.uploadFileName = uploadFileName; } public void setUploadContentType(String[] uploadContentType) { this.uploadContentType = uploadContentType; } // 查询所有的商品: public String findAll() { PageBean<Product> pageBean = productService.findByPage(page); // 将PageBean数据存入到值栈中. ActionContext.getContext().getValueStack().set("pageBean", pageBean); // 页面跳转 return "findAll"; } // 查询所有的待审核商品: public String findcheck() { PageBean<Product> pageBean = productService.findBycheck(page); // 将PageBean数据存入到值栈中. ActionContext.getContext().getValueStack().set("pageBean", pageBean); // 页面跳转 return "findcheck"; } // 查询当前经销商所提供的所有汽车信息 @SuppressWarnings("unused") public String findagent() { AdminUser existAdminUser = (AdminUser) ServletActionContext .getRequest().getSession().getAttribute("existAdminUser"); if (existAdminUser == null) { this.addActionMessage("亲!您还没有登录!"); return "msg"; } if (existAdminUser.getState() == 4 || existAdminUser.getState() == 1) { PageBean<Product> pageBean = productService.findByagent( existAdminUser.getUsername(), page); // 将PageBean数据存入到值栈中. ActionContext.getContext().getValueStack() .set("pageBean", pageBean); // 页面跳转 return "findagent"; } else { this.addActionMessage("亲!您还没有此权限!"); return "msg"; } } // 搜索汽车 public String search() throws UnsupportedEncodingException { PageBean<Product> pageBean = productService.searchCar( product.getPname(), page); ActionContext.getContext().getValueStack().set("pageBean", pageBean); return "search"; } // 跳转到添加页面的方法: public String addPage() { // 查询所有的二级分类: List<CategorySecond> csList = categorySecondService.findAll(); // 将二级分类的数据显示到页面上 ActionContext.getContext().getValueStack().set("csList", csList); // 页面跳转 return "addPageSuccess"; } // 保存商品的方法: public String save() throws IOException { // 将提交的数据添加到数据库中. product.setPdate(new Date());// 系统当前时间 AdminUser existAdminUser = (AdminUser) ServletActionContext .getRequest().getSession().getAttribute("existAdminUser"); if (existAdminUser == null) { this.addActionMessage("亲!您还没有登录!"); return "msg"; } product.setState(1); product.setUploadingservername(existAdminUser.getUsername()); // 对中文车名进行拼音改写 String pybrand = product.getBrand(); if (isContainChinese(pybrand)) { product.setPybrand(ChineseToEnglish.getPingYin(pybrand)); } else { product.setPybrand(pybrand); } String pycarseries = product.getCarSeries(); if (isContainChinese(pycarseries)) { product.setPycarSeries(ChineseToEnglish.getPingYin(pycarseries)); } else { product.setPycarSeries(pycarseries); } // product.setImage(image); if (upload != null) { // 将商品图片上传到服务器上.获得磁盘的绝对路径 // 文件重名也只是个问题 // 获得上传图片的服务器端路径. String path = ServletActionContext.getServletContext().getRealPath( "/products"); for (int i = 0; i < upload.length; i++) { // 创建文件类型对象: File diskFile = new File(path + "//" + uploadFileName[i]); // 文件上传: FileUtils.copyFile(upload[i], diskFile); if (null != uploadFileName[0]) { product.setImage("products/" + uploadFileName[0]); } if (null != uploadFileName[1]) { product.setImageFront("products/" + uploadFileName[1]); } if (null != uploadFileName[2]) { product.setImageBehind("products/" + uploadFileName[2]); } if (null != uploadFileName[3]) { product.setImageLeft("products/" + uploadFileName[3]); } if (null != uploadFileName[4]) { product.setImageRight("products/" + uploadFileName[4]); } if (null != uploadFileName[5]) { product.setImageInterior1("products/" + uploadFileName[5]); } if (null != uploadFileName[6]) { product.setImageInterior2("products/" + uploadFileName[6]); } if (null != uploadFileName[7]) { product.setImageEngine_compartment("products/" + uploadFileName[7]); } if (null != uploadFileName[8]) { product.setImageRoof("products/" + uploadFileName[8]); } if (null != uploadFileName[9]) { product.setImageTrunk("products/" + uploadFileName[9]); } if (null != uploadFileName[10]) { product.setImageChassis("products/" + uploadFileName[10]); } } } productService.save(product); if (existAdminUser.getState() == 1) { return "saveSuccess"; } else { return "agentsaveSuccess"; } } // 删除商品的方法: public String delete() { // 根据id查询商品信息 AdminUser existAdminUser = (AdminUser) ServletActionContext .getRequest().getSession().getAttribute("existAdminUser"); if (existAdminUser == null) { this.addActionMessage("亲!您还没有登录!"); return "msg"; } product = productService.findByPid(product.getPid()); product.setState(5); // 在商品表中告知是哪位管理员删除的 product.setDeletename(existAdminUser.getUsername()); // 删除商品的图片: // String oldpath = product.getImage(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath); // File file = new File(path); // file.delete(); // } // String oldpath1 = product.getImageFront(); // if (oldpath1 != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath1); // File file = new File(path); // file.delete(); // } // String oldpath2 = product.getImageBehind(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath2); // File file = new File(path); // file.delete(); // } // String oldpath3 = product.getImageLeft(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath2); // File file = new File(path); // file.delete(); // } // String oldpath4 = product.getImageRight(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath4); // File file = new File(path); // file.delete(); // } // String oldpath5 = product.getImageInterior1(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath5); // File file = new File(path); // file.delete(); // } // String oldpath6 = product.getImageInterior2(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath6); // File file = new File(path); // file.delete(); // } // String oldpath7 = product.getImageEngine_compartment(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath7); // File file = new File(path); // file.delete(); // } // String oldpath8 = product.getImageRoof(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath8); // File file = new File(path); // file.delete(); // } // String oldpath9 = product.getImageTrunk(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath9); // File file = new File(path); // file.delete(); // } // String oldpath10 = product.getImageChassis(); // if (oldpath != null) { // String path = ServletActionContext.getServletContext().getRealPath( // "/" + oldpath10); // File file = new File(path); // file.delete(); // } // 删除数据库中商品记录: productService.update(product); // 页面跳转 return "deleteSuccess"; } // 编辑商品的方法 public String edit() { // 根据商品id查询商品信息 product = productService.findByPid(product.getPid()); // 查询所有二级分类 List<CategorySecond> csList = categorySecondService.findAll(); ActionContext.getContext().getValueStack().set("csList", csList); // 页面跳转到编辑页面: return "editSuccess"; } // 修改商品的方法 public String update() throws IOException { // 将信息修改到数据库 product.setPdate(new Date()); AdminUser existAdminUser = (AdminUser) ServletActionContext .getRequest().getSession().getAttribute("existAdminUser"); if (existAdminUser == null) { this.addActionMessage("亲!您还没有登录!"); return "msg"; } product.setState(1); product.setUploadingservername(existAdminUser.getUsername()); // 对中文车名进行拼音改写 String pybrand = product.getBrand(); System.out.println("action:---------------"+pybrand); if (isContainChinese(pybrand)) { product.setPybrand(ChineseToEnglish.getPingYin(pybrand)); } else { product.setPybrand(pybrand); } String pycarseries = product.getCarSeries(); if (isContainChinese(pycarseries)) { product.setPycarSeries(ChineseToEnglish.getPingYin(pycarseries)); } else { product.setPycarSeries(pycarseries); } // 上传: if (upload != null) { String delPath = ServletActionContext.getServletContext() .getRealPath("/" + product.getImage()); File file = new File(delPath); file.delete(); // 获得上传图片的服务器端路径. String path = ServletActionContext.getServletContext().getRealPath( "/products"); // // 创建文件类型对象: // File diskFile = new File(path + "//" + uploadFileName); // // 文件上传: // FileUtils.copyFile(upload, diskFile); // // product.setImage("products/" + uploadFileName); for (int i = 0; i < upload.length; i++) { // 创建文件类型对象: File diskFile = new File(path + "//" + uploadFileName[i]); // 文件上传: FileUtils.copyFile(upload[i], diskFile); if (uploadFileName.length >= 1 && null != uploadFileName[0]) { product.setImage("products/" + uploadFileName[0]); } if (uploadFileName.length >= 2 && null != uploadFileName[1]) { product.setImageFront("products/" + uploadFileName[1]); } if (uploadFileName.length >= 3 && null != uploadFileName[2]) { product.setImageBehind("products/" + uploadFileName[2]); } if (uploadFileName.length >= 4 && null != uploadFileName[3]) { product.setImageLeft("products/" + uploadFileName[3]); } if (uploadFileName.length >= 5 && null != uploadFileName[4]) { product.setImageRight("products/" + uploadFileName[4]); } if (uploadFileName.length >= 6 && null != uploadFileName[5]) { product.setImageInterior1("products/" + uploadFileName[5]); } if (uploadFileName.length >= 7 && null != uploadFileName[6]) { product.setImageInterior2("products/" + uploadFileName[6]); } if (uploadFileName.length >= 8 && null != uploadFileName[7]) { product.setImageEngine_compartment("products/" + uploadFileName[7]); } if (uploadFileName.length >= 9 && null != uploadFileName[8]) { product.setImageRoof("products/" + uploadFileName[8]); } if (uploadFileName.length >= 10 && null != uploadFileName[9]) { product.setImageTrunk("products/" + uploadFileName[9]); } if (uploadFileName.length >= 11 && null != uploadFileName[10]) { product.setImageChassis("products/" + uploadFileName[10]); } } } productService.update(product); // 页面跳转 if (existAdminUser.getState() == 1) { return "updateSuccess"; } else { return "agentupdateSuccess"; } } // 审核商品的方法:通过 public String checkpass() { AdminUser existAdminUser = (AdminUser) ServletActionContext .getRequest().getSession().getAttribute("existAdminUser"); if (existAdminUser == null) { this.addActionMessage("亲!您还没有登录!"); return "msg"; } // 根据id查询订单 // 根据商品id查询商品信息 product = productService.findByPid(product.getPid()); product.setState(3); product.setCheckname(existAdminUser.getUsername()); productService.update(product); // 页面跳转 return "checkpass"; } // 审核商品的方法:不通过 public String checknopass() { AdminUser existAdminUser = (AdminUser) ServletActionContext .getRequest().getSession().getAttribute("existAdminUser"); if (existAdminUser == null) { this.addActionMessage("亲!您还没有登录!"); return "msg"; } // 根据id查询订单 // 根据商品id查询商品信息 product = productService.findByPid(product.getPid()); product.setState(2); product.setCheckname(existAdminUser.getUsername()); productService.update(product); // 页面跳转 return "checknopass"; } // 判断字符串是否包含中文 public static boolean isContainChinese(String str) { Pattern p = Pattern.compile("[\u4e00-\u9fa5]"); Matcher m = p.matcher(str); if (m.find()) { return true; } return false; } } <file_sep>/shop/.svn/pristine/7d/7d8ec92c34934cff666b830f95a9b128793e1785.svn-base package cn.itcast.shop.adminuser.vo; /** * 后台用户登录实体 * * 项目名称:shop00 * 类名称:AdminUser * 类描述: * 创建人:Teemo * 创建时间:2017年5月18日 上午11:25:50 * 修改人:Teemo * 修改时间:2017年5月18日 上午11:25:50 * 修改备注: * @version * */ public class AdminUser { private Integer uid; private String username; private String password; //用户权限状态:1.超级用户;2.审核;3.客服;4.经销商; private Integer state; public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } } <file_sep>/shop/.svn/pristine/1e/1e5fba8396b2d704c2f7b974e1ef54413492a713.svn-base package cn.itcast.shop.index.action; import java.util.List; import cn.itcast.shop.advertisement.service.AdvertisementService; import cn.itcast.shop.advertisement.vo.Advertisement; import cn.itcast.shop.category.service.CategoryService; import cn.itcast.shop.category.vo.Category; import cn.itcast.shop.product.service.ProductService; import cn.itcast.shop.product.vo.Product; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * 首页访问的Action * * 项目名称:shop00 类名称:IndexAction 类描述: 创建人:Teemo 创建时间:2017年4月14日 下午2:43:35 * 修改人:Teemo 修改时间:2017年4月14日 下午2:43:35 修改备注: * * @version * */ public class IndexAction extends ActionSupport implements ModelDriven<Advertisement> { // 注入一级分类的Service: private CategoryService categoryService; // 注入商品的Service private ProductService productService; // 注入广告的Service private AdvertisementService advertisementService; private Advertisement advertisement = new Advertisement(); public void setCategoryService(CategoryService categoryService) { this.categoryService = categoryService; } public void setProductService(ProductService productService) { this.productService = productService; } public void setAdvertisementService( AdvertisementService advertisementService) { this.advertisementService = advertisementService; } public Advertisement getModel() { return advertisement; } /** * 执行的访问首页的方法: */ public String execute() { // 查询所有一级分类集合 List<Category> cList = categoryService.findAll(); // 将一级分类存入到Session的范围: ActionContext.getContext().getSession().put("cList", cList); // 查询热门商品: List<Product> hList = productService.findHot(); // 保存到值栈中: ActionContext.getContext().getValueStack().set("hList", hList); // 查询最新商品: List<Product> nList = productService.findNew(); // 保存到值栈中: ActionContext.getContext().getValueStack().set("nList", nList); // 查询到广告图片 advertisement = advertisementService.findpic(); // 保存到值栈 return "index"; } }
ba11bb920b6d9dab88fbdd0199e5cd62ea94bb1e
[ "Java" ]
3
Java
wfei3/carshop
734bb4eab3c249f9df58c6590568199a9edd2d99
3e342040df52ddae3e4ed245da464e3d66e4aab6
refs/heads/master
<file_sep>package com.samuraism.javatraining.fizzbuzz; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @org.springframework.stereotype.Controller public class FizzBuzzController { @Autowired private FizzBuzz fizzbuzz; @GetMapping("/fizzbuzz") String fizzbuzz(Model model) { var fizzBuzz = fizzbuzz.fizzBuzz(); model.addAttribute("fizzBuzz", fizzBuzz); return "fizzbuzz"; } } <file_sep>package com.samuraism.javatraining.todo; import javax.persistence.*; @Entity @Table(name = "Task") public class Task { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Integer id; private String text; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String firstName) { this.text = firstName; } }<file_sep>spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:tcp://localhost:9092/./h2/javatraining spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=update spring.sql.init.mode=always <file_sep>package com.samuraism.javatraining; import org.h2.tools.Server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.sql.SQLException; @SpringBootApplication public class Main { public static void main(String[] args) throws SQLException{ // H2をサーバモードで起動 Server.main( // tcpリスナを有効化 "-tcp", // 存在しないDBへの接続を試みたら作る "-ifNotExists" ); SpringApplication.run(Main.class, args); } }
fd0bbd4ce2888334c91d73ebf7af3d47c4d08d21
[ "Java", "INI" ]
4
Java
Samuraism/java-training
f39ccf350b82f0ecbc9600edcc80166a91c2cb1e
b69c8ef26ed8aab292f2fb2260d1b6fa171833d1
refs/heads/master
<repo_name>expovin/enigma.js<file_sep>/test/unit/intercept.spec.js import Promise from 'bluebird'; import Intercept from '../../src/intercept'; import ApiCache from '../../src/api-cache'; describe('Intercept', () => { let JSONPatch; let intercept; let apis; const createApi = () => ({ on: () => {}, emit: () => {}, removeAllListeners: () => {}, }); beforeEach(() => { JSONPatch = { apply() {} }; apis = new ApiCache(); intercept = new Intercept({ Promise, JSONPatch, apis, delta: true }); }); describe('getPatchee', () => { it('should get an existing patchee', () => { const patchee = {}; apis.add(-1, createApi()); apis.addPatchee(-1, 'Foo', patchee); expect(intercept.getPatchee(-1, [], 'Foo')).to.equal(patchee); expect(intercept.getPatchee(-1, [], 'Foo')).to.equal(patchee); }); it('should apply and return a patchee', () => { const JSONPatchStub = sinon.stub(JSONPatch, 'apply'); apis.add(-1, createApi()); apis.addPatchee(-1, 'Foo', {}); intercept.getPatchee(-1, [{ op: 'add', path: '/', value: {} }], 'Foo'); expect(JSONPatchStub).to.have.been.calledWith({}, [{ op: 'add', path: '/', value: {} }]); JSONPatchStub.reset(); apis.addPatchee(-1, 'Bar', []); intercept.getPatchee(-1, [{ op: 'add', path: '/', value: [] }], 'Bar'); expect(JSONPatchStub).to.have.been.calledWith([], [{ op: 'add', path: '/', value: [] }]); JSONPatchStub.reset(); // primitive apis.addPatchee(-1, 'Baz', 'my folder'); intercept.getPatchee(-1, [{ op: 'add', path: '/', value: ['my documents'] }], 'Baz'); expect(JSONPatchStub.callCount).to.equal(0); }); describe('primitive patch', () => { let value; beforeEach(() => { apis.add(-1, createApi()); }); describe('add', () => { const op = 'add'; it('should return a string', () => { value = intercept.getPatchee(-1, [{ op, path: '/', value: 'A string' }], 'Foo'); expect(value).to.equal('A string'); }); it('should return a boolean', () => { value = intercept.getPatchee(-1, [{ op, path: '/', value: true }], 'Foo'); expect(value).to.equal(true); }); it('should return a number', () => { value = intercept.getPatchee(-1, [{ op, path: '/', value: 123 }], 'Foo'); expect(value).to.equal(123); }); }); describe('replace', () => { const op = 'replace'; it('should return a string', () => { value = intercept.getPatchee(-1, [{ op, path: '/', value: 'A string' }], 'Foo'); expect(value).to.equal('A string'); }); it('should return a boolean', () => { value = intercept.getPatchee(-1, [{ op, path: '/', value: true }], 'Foo'); expect(value).to.equal(true); }); it('should return a number', () => { value = intercept.getPatchee(-1, [{ op, path: '/', value: 123 }], 'Foo'); expect(value).to.equal(123); }); }); it('should cache primitive patches', () => { value = intercept.getPatchee(-1, [{ op: 'add', path: '/', value: 'A string' }], 'Foo'); expect(value).to.equal('A string'); expect(intercept.getPatchee(-1, [], 'Foo')).to.equal(value); }); it('should not throw if primitive patch already exists', () => { intercept.getPatchee(-1, [{ op: 'add', path: '/', value: 'A string' }], 'Foo'); expect(intercept.getPatchee(-1, [{ op: 'replace', path: '/', value: 'Bar' }], 'Foo')).to.equal('Bar'); }); }); }); describe('intercept', () => { it('should call interceptors onFulfilled', () => { intercept.interceptors = [{ onFulfilled: sinon.stub().returns({ bar: {} }) }]; return expect(intercept.execute({}, Promise.resolve({ foo: {} }))) .to.eventually.deep.equal({ bar: {} }); }); it('should reject and stop the interceptor chain', () => { const spyFulFilled = sinon.spy(); intercept.interceptors = [{ onFulfilled() { return Promise.reject('foo'); } }, { onFulfilled: spyFulFilled }]; return expect(intercept.execute({}, Promise.resolve()).then(() => {}, (err) => { expect(spyFulFilled.callCount).to.equal(0); return Promise.reject(err); })).to.eventually.be.rejectedWith('foo'); }); it('should call interceptors onRejected', () => { const onRejected = sinon.stub().returns('foo'); intercept.interceptors = [{ onFulfilled() { return Promise.reject('foo'); } }, { onFulfilled() {}, onRejected }]; return expect(intercept.execute({}, Promise.resolve(), {})).to.eventually.equal('foo'); }); }); describe('processErrorInterceptor', () => { it('should reject and emit if the response contains an error', () => intercept.processErrorInterceptor({}, {}, { error: { code: 2, parameter: 'param', message: 'msg' } }).then(null, (err) => { expect(err instanceof Error).to.equal(true); expect(err.code).to.equal(2); expect(err.parameter).to.equal('param'); expect(err.message).to.equal('msg'); expect(err.stack).to.be.a('string'); // check if the test file is included in the stack trace: expect(err.stack.indexOf('intercept.spec.js')).to.not.equal(-1); })); it('should not reject if the response does not contain any error', () => { const response = {}; expect(intercept.processErrorInterceptor({}, {}, response)).to.equal(response); }); }); describe('processDeltaInterceptor', () => { let response = { result: { foo: {} } }; it('should call getPatchee', () => { response = { result: { qReturn: [{ foo: {} }] }, delta: true }; const stub = sinon.stub(intercept, 'getPatchee').returns(response.result.qReturn); intercept.processDeltaInterceptor({}, { handle: 1, method: 'Foo', outKey: -1 }, response); expect(stub).to.have.been.calledWith(1, response.result.qReturn, 'Foo-qReturn'); }); it('should reject when response is not an array of patches', () => { response = { result: { qReturn: { foo: {} } }, delta: true }; return expect(intercept.processDeltaInterceptor({}, { handle: 1, method: 'Foo', outKey: -1 }, response)).to.eventually.be.rejectedWith('Unexpected rpc response, expected array of patches'); }); it('should return response if delta is falsy', () => { response = { result: { qReturn: [{ foo: {} }] }, delta: false }; expect(intercept.processDeltaInterceptor({}, { handle: 1, method: 'Foo', outKey: -1 }, response)).to.equal(response); }); }); describe('processResultInterceptor', () => { const response = { result: { foo: {} } }; it('should return result', () => { expect(intercept.processResultInterceptor({}, { outKey: -1 }, response)) .to.be.equal(response.result); }); }); describe('processMultipleOutParamInterceptor', () => { it('should append missing qGenericId for CreateSessionApp', () => { const result = { qReturn: { qHandle: 1, qType: 'Doc' }, qSessionAppId: 'test' }; const out = intercept.processMultipleOutParamInterceptor({}, { method: 'CreateSessionApp' }, result); expect(out.qReturn.qGenericId).to.be.equal(result.qSessionAppId); }); it('should remove errenous qReturn from GetInteract', () => { const result = { qReturn: false, qDef: 'test' }; const out = intercept.processMultipleOutParamInterceptor({}, { method: 'GetInteract' }, result); expect(out.qReturn).to.be.equal(undefined); }); }); describe('processOutInterceptor', () => { it('should return result with out key', () => { const result = { foo: { bar: {} } }; expect(intercept.processOutInterceptor({}, { outKey: 'foo' }, result)).to.be.equal(result.foo); }); it('should return result with return key', () => { const result = { qReturn: { foo: {} } }; expect(intercept.processOutInterceptor( {}, { outKey: -1 }, result, )).to.be.equal(result.qReturn); }); it('should return result if neither out key or return key is specified', () => { const result = { foo: {} }; expect(intercept.processOutInterceptor({}, { outKey: -1 }, result)).to.be.equal(result); }); }); }); <file_sep>/src/intercept.js const RETURN_KEY = 'qReturn'; class Intercept { /** * Create a new Intercept instance. * @param {Object} options The configuration options for this class. * @param {Promise} options.Promise The promise constructor to use. * @param {ApiCache} options.apis The ApiCache instance to use. * @param {Boolean} options.delta Whether to use the delta protocol. * @param {Array} [options.interceptors] Additional interceptors to use. * @param {JSONPatch} [options.JSONPatch] The JSONPatch implementation to use (for testing). */ constructor(options) { Object.assign(this, options); this.interceptors = [{ onFulfilled: this.processErrorInterceptor, }, { onFulfilled: this.processDeltaInterceptor, }, { onFulfilled: this.processResultInterceptor, }, { onFulfilled: this.processMultipleOutParamInterceptor, }, { onFulfilled: this.processOutInterceptor, }, ...this.interceptors || []]; } /** * Function used to determine if it is a primitive patch. * @param {Array} patches Patches from engine. * @return {Boolean} Returns true if it is a primitive patch. */ isPrimitivePatch(patches) { // It's only `add` and `replace` that has a // value property according to the jsonpatch spec return patches.length === 1 && ['add', 'replace'].indexOf(patches[0].op) !== -1 && this.isPrimitiveValue(patches[0].value) && patches[0].path === '/'; } /** * Function used to determine if it is a primitive value. * @param {Any} value. * @return {Boolean} Returns true if it is a primitive value. */ isPrimitiveValue(value) { return typeof value !== 'undefined' && value !== null && typeof value !== 'object' && !Array.isArray(value); } /** * Function used to get a patchee. * @param {Number} handle - The handle. * @param {Array} patches - The patches. * @param {String} cacheId - The cacheId. * @returns {Object} Returns the patchee. */ getPatchee(handle, patches, cacheId) { // handle primitive types, e.g. string, int, bool if (this.isPrimitivePatch(patches)) { const value = patches[0].value; this.apis.setPatchee(handle, cacheId, value); return value; } let patchee = this.apis.getPatchee(handle, cacheId); if (!this.isPrimitiveValue(patchee)) { patchee = patchee || (patches.length && Array.isArray(patches[0].value) ? [] : {}); this.applyPatch(patchee, patches); } this.apis.setPatchee(handle, cacheId, patchee); return patchee; } /** * Function used to apply a patch. * @param {Object} patchee - The object to patch. * @param {Array} patches - The list of patches to apply. */ applyPatch(patchee, patches) { this.JSONPatch.apply(patchee, patches); } /** * Process error interceptor. * @param {Object} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the defined error for an error, else the response. */ processErrorInterceptor(session, request, response) { if (typeof response.error !== 'undefined') { const data = response.error; const error = new Error(data.message); error.code = data.code; error.parameter = data.parameter; return this.Promise.reject(error); } return response; } /** * Process delta interceptor. * @param {Object} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the patched response */ processDeltaInterceptor(session, request, response) { const result = response.result; if (response.delta) { // when delta is on the response data is expected to be an array of patches const keys = Object.keys(result); for (let i = 0, cnt = keys.length; i < cnt; i += 1) { const key = keys[i]; const patches = result[key]; if (!Array.isArray(patches)) { return this.Promise.reject(new Error('Unexpected rpc response, expected array of patches')); } result[key] = this.getPatchee(request.handle, patches, `${request.method}-${key}`); } // return a cloned response object to avoid patched object references: return JSON.parse(JSON.stringify(response)); } return response; } /** * Process result interceptor. * @param {Object} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the result property on the response */ processResultInterceptor(session, request, response) { return response.result; } /** * Processes specific QIX methods that are breaking the protocol specification * and normalizes the response. * @param {Object} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the result property on the response */ processMultipleOutParamInterceptor(session, request, response) { if (request.method === 'CreateSessionApp' || request.method === 'CreateSessionAppFromApp') { // this method returns multiple out params that we need // to normalize before processing the response further: response[RETURN_KEY].qGenericId = response[RETURN_KEY].qGenericId || response.qSessionAppId; } else if (request.method === 'GetInteract') { // this method returns a qReturn value when it should only return // meta.outKey: delete response[RETURN_KEY]; } return response; } /** * Process out interceptor. * @param {Object} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The result. * @returns {Object} - Returns the out property on result */ processOutInterceptor(session, request, response) { if (hasOwnProperty.call(response, RETURN_KEY)) { return response[RETURN_KEY]; } else if (request.outKey !== -1) { return response[request.outKey]; } return response; } /** * Execute the interceptor queue, each interceptor will get the result from * the previous interceptor. * @param {Object} session The session instance to execute against. * @param {Promise} promise The promise to chain on to. * @param {Object} request The JSONRPC request object for the intercepted response. * @returns {Promise} */ execute(session, promise, request) { return this.interceptors.reduce((interception, interceptor) => interception.then( interceptor.onFulfilled && interceptor.onFulfilled.bind(this, session, request), interceptor.onRejected && interceptor.onRejected.bind(this, session, request)) , promise, ); } } export default Intercept;
9998062fd7c583edb8f2c859469dc7b8b2190506
[ "JavaScript" ]
2
JavaScript
expovin/enigma.js
c78162e46ed293e5b30c091812d1c9614eb7edaa
65117e34cc1ce69d5da73e0e36498eac689573d3
refs/heads/main
<repo_name>TooPositive/CardGame<file_sep>/PersonSpaceshipsGame/Models/Database/CardGameContext.cs using Microsoft.EntityFrameworkCore; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Services.CardGameService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Models.Database { public class CardGameContext : DbContext { public CardGameContext(DbContextOptions<CardGameContext> options) : base(options) { this.Database.Migrate(); } public DbSet<PersonCard> PersonCards { get; set; } public DbSet<SpaceshipCard> SpaceshipCards { get; set; } public DbSet<Player> Players { get; set; } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/Dtos/PlayerDto.ts export class PlayerDto { Id: string; Points: number; } <file_sep>/PersonSpaceshipsGame/Factories/GameServiceFactory.cs using PersonSpaceshipsGame.Services; using PersonSpaceshipsGame.Services.CardGameService; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using System; namespace PersonSpaceshipsGame.Factories { public class GameServiceFactory { public static T Create<T>() { if (typeof(T) == typeof(IPersonCardGameService)) { return (T)(IPersonCardGameService)new PersonCardGameService(); } else if (typeof(T) == typeof(ISpaceshipCardGameService)) { return (T)(ISpaceshipCardGameService)new SpaceshipCardGameService(); } else { throw new NotImplementedException(String.Format("Creation of {0} interface is not supported yet.", typeof(T))); } } } } <file_sep>/PersonSpaceshipsGame/CQRS/Responses/Persons/GetStartPersonsCardResponseModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Requests.Persons; using PersonSpaceshipsGame.Models.Cards.Person; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Responses.Persons { public class GetStartPersonsCardResponseModel : IRequest<GetStartPersonsCardRequestModel> { public IEnumerable<PersonCard> Cards { get; set; } } } <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/QueriesHandlers/Cards/GetCardTypesQueryHandler.cs using MediatR; using PersonSpaceshipsGame.CQRS.Requests.Cards; using PersonSpaceshipsGame.CQRS.Responses.Cards; using PersonSpaceshipsGame.Dtos; using PersonSpaceshipsGame.Models.Cards; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.QueriesHandlers.Cards { public class GetCardTypesQueryHandler : IRequestHandler<GetCardTypesRequestModel, GetCardTypesResponseModel> { public async Task<GetCardTypesResponseModel> Handle(GetCardTypesRequestModel request, CancellationToken cancellationToken) { List<CardTypeDto> cardTypes = new List<CardTypeDto>(); Enum.GetValues(typeof(Enums.CardType)).Cast<Enums.CardType>().ToList().ForEach(x => cardTypes.Add(new CardTypeDto { Name = x.ToString()})); return new GetCardTypesResponseModel() { CardTypes = cardTypes }; } } }<file_sep>/PersonSpaceshipsGame/CQRS/Responses/Players/PostPlayerChangesResponseModel.cs using MediatR; using PersonSpaceshipsGame.Models.Cards.Person; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Responses.Persons { public class PostPlayerChangesResponseModel { public bool IsSuccess { get; set; } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/models/cards/CardType.ts //TODO: maybe just string instead of two places to edit this enums? export enum CardType { Persons, Spaceship } export enum CardResponseResult{ Win, Draw, NotEnoughCards, TooMuchCards } <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Persons/AddPersonCardsRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.Models.Cards.Person; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Persons { public class AddPersonCardsRequestModel : IRequest<AddPersonCardsResponseModel> { public IEnumerable<IPersonCard> PersonCards { get; set; } } } <file_sep>/PersonSpaceshipsGame.Tests/Services/CardGameServiceTests.cs using NUnit.Framework; using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Factories; using PersonSpaceshipsGame.Models.Cards; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using PersonSpaceshipsGame.Tests.TestCaseSources.Services.Cards; using System.Collections.Generic; namespace PersonSpaceshipsGame.Tests.Services { public class CardGameServiceTests { private IPersonCardGameService personCardGameService; private ISpaceshipCardGameService spaceshipCardGameService; [SetUp] public void Setup() { this.personCardGameService = GameServiceFactory.Create<IPersonCardGameService>(); this.spaceshipCardGameService = GameServiceFactory.Create<ISpaceshipCardGameService>(); } [TestCaseSource(typeof(ChooseWinnerTestCases), nameof(ChooseWinnerTestCases.PersonTestCases))] public void ChooseWinnerPersonCard(List<IPersonCard> cards, ICardsPlayedResponse desiredResponse) { ICardsPlayedResponse cardsPlayedResponse = personCardGameService.ChooseWinnerCard(cards); Assert.AreEqual(cardsPlayedResponse, desiredResponse); } [TestCaseSource(typeof(ChooseWinnerTestCases), nameof(ChooseWinnerTestCases.SpaceshipsTestCases))] public void ChooseWinnerSpaceshipCard(List<ISpaceshipCard> cards, ICardsPlayedResponse desiredResponse) { ICardsPlayedResponse winnerCardfromService = spaceshipCardGameService.ChooseWinnerCard(cards); Assert.AreEqual(winnerCardfromService, desiredResponse); } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/models/players/Player.ts import { PlayableCard } from "../cards/PlayableCard"; export class Player { id: string; points: number; cards: PlayableCard[]; hasWon: boolean; constructor(id: string, points: number, cards: PlayableCard[]) { this.id = id; this.points = points; this.cards = cards; this.hasWon = false; } } <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/CommandHandlers/Players/PostPlayerChangesCommandHandler.cs using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using PersonSpaceshipsGame.CQRS.Requests.Players; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Database; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.CommandHandlers.Players { public class PostPlayerChangesCommandHandler : IRequestHandler<PostPlayerChangesRequestModel, PostPlayerChangesResponseModel> { private readonly CardGameContext _context; private readonly IServiceScopeFactory _serviceScopeFactory; public PostPlayerChangesCommandHandler(CardGameContext context, IServiceScopeFactory serviceScopeFactory) { _context = context; _serviceScopeFactory = serviceScopeFactory; } //TODO: better error handling public async Task<PostPlayerChangesResponseModel> Handle(PostPlayerChangesRequestModel request, CancellationToken cancellationToken) { using (var scope = _serviceScopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetService<CardGameContext>(); Player player = await _context.Players.FirstOrDefaultAsync(x => x.Id == request.Player.Id); if (player == null) return new PostPlayerChangesResponseModel { IsSuccess = false }; try { if (player.Points != request.Player.Points) { player.Points = request.Player.Points; await _context.SaveChangesAsync(); } } catch (Exception) { return new PostPlayerChangesResponseModel { IsSuccess = false }; } return new PostPlayerChangesResponseModel { IsSuccess = true }; } } } } <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/QueriesHandlers/Spaceships/GetStartSpaceshipCardsQueryHandler.cs using MediatR; using Microsoft.EntityFrameworkCore; using PersonSpaceshipsGame.CQRS.Requests.Spaceships; using PersonSpaceshipsGame.CQRS.Responses.Spaceships; using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Models.Database; using PersonSpaceshipsGame.Models.Players; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.QueriesHandlers.Spaceships { //TODO: this should be one query with Persons query handler public class GetStartSpaceshipCardsQueryHandler : IRequestHandler<GetStartSpaceshipCardRequestModel, GetStartSpaceshipCardResponseModel> { private readonly CardGameContext _context; public GetStartSpaceshipCardsQueryHandler(CardGameContext context) { _context = context; } public async Task<GetStartSpaceshipCardResponseModel> Handle(GetStartSpaceshipCardRequestModel request, CancellationToken cancellationToken) { List<SpaceshipCard> cards = new List<SpaceshipCard>(); var allSpaceShipCards = await _context.SpaceshipCards.ToListAsync(); //TODO: This has so low performance, figure out other way to choose random cards for players; stored procedure will be better IEnumerable<Player> thePlayers = await _context.Players.Take(request.PlayersCount).ToListAsync(); for (int i = 0; i < request.PlayersCount; i++) { var spaceshipCards = allSpaceShipCards.OrderBy(x => Guid.NewGuid()).Take(PlayerStatics.MaxHandCards).ToList(); spaceshipCards.ForEach(x => cards.Add(new SpaceshipCard { Id = x.Id, CardType = x.CardType, CrewCount = x.CrewCount, Name = x.Name, Player = thePlayers.ElementAt(i) })); } return new GetStartSpaceshipCardResponseModel { Cards = cards }; } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/cardGame/cardGameService.ts import { HttpClient, HttpHeaders } from '@angular/common/http'; import { CardTypeDto } from '../Dtos/CardTypeDto' import { CardType, CardResponseResult } from '../models/cards/CardType'; import { PersonCard } from '../models/cards/PersonCard'; import { SpaceshipCard } from '../models/cards/SpaceshipCard'; import { PlayableCard } from '../models/cards/PlayableCard'; import { PersonCardDto } from '../Dtos/PersonCardDto'; import { Player } from '../models/players/Player'; import { Observable } from 'rxjs'; import { CardsPlayedResponseDto } from '../Dtos/CardsPlayedResponseDto'; import { Injectable } from '@angular/core'; @Injectable() export class CardGameService { url: string = "https://localhost:44306/api"; selectedStartCardType: CardTypeDto; cardTypes: CardTypeDto[]; // cards player1Cards: PlayableCard[] = []; player2Cards: PlayableCard[] = []; player1: Player; player2: Player; //TODO: Implement to allow more users firstPlayedCard: PlayableCard; secondPlayedCard: PlayableCard; //TODO: better user move tracking isPlayer1Move = true; presentingRoundResult = false; endRoundDecision: string; isPlaying = false; isGameEnded = false; constructor(private http: HttpClient) { } initCardTypes() { let cardTypes: CardTypeDto[]; this.http.get(`${this.url}/Game/GetCardTypes`).subscribe((data: CardTypeDto[]) => { this.cardTypes = data; }); this.cardTypes = cardTypes; } async getStartingGameCards(selectedCardType: string): Promise<any[]> { let data = await this.http.get(`${this.url}/Game/GetStartingGamesCards/${selectedCardType}`).toPromise(); let dataToReturn = []; //TODO: think about open/close principle switch (selectedCardType.trim()) { case "Person": let personCardData = data as PersonCard[]; personCardData.forEach(x => { dataToReturn.push(new PersonCard(x.id, x.name, x.player, x.mass)); }); return dataToReturn as PersonCard[]; case "Spaceship": let spaceshipCardData = data as SpaceshipCard[]; spaceshipCardData.forEach(x => { dataToReturn.push(new SpaceshipCard(x.id, x.name, x.player, x.crewCount)); }); return dataToReturn as SpaceshipCard[]; default: console.log(`Wrong selected card type.`); // TODO: better error handling return []; } } getGroupedPlayerCards(cards: PlayableCard[]) { let players = cards.map(x => x.player.id).filter((value, index, array) => array.indexOf(value) === index); var dataToReturnGroupedByPlayer = []; for (var i = 0; i < players.length; i++) { dataToReturnGroupedByPlayer.push(cards.filter(x => x.player.id === players[i])); } return dataToReturnGroupedByPlayer; } async postRoundPlayedCards(cards: PlayableCard[]): Promise<CardsPlayedResponseDto> { let player: Player; var headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post<CardsPlayedResponseDto>(`${this.url}/Game/PostRoundPlayedCards`, JSON.stringify(cards), { headers: headers }).toPromise(); } async startGameClicked() { let response = await this.getStartingGameCards(this.selectedStartCardType.name); if (response.length > 0) { //TODO: Better handling more users + refactor assigining users this.assignCardsToPlayers(response); } } public assignCardsToPlayers(cardResponse: any[]) { let playersCards = this.getGroupedPlayerCards(cardResponse); this.player1Cards = playersCards[0]; this.player1 = this.player1Cards[0].player; this.player2Cards = playersCards[1]; this.player2 = this.player2Cards[0].player; this.isPlaying = true; } public initGameServiceState() { this.selectedStartCardType = null; this.isPlaying = false; this.endRoundDecision = ""; this.isPlayer1Move = true; this.firstPlayedCard = null; this.secondPlayedCard = null; this.presentingRoundResult = false; this.isGameEnded = false; this.player1Cards = []; this.player2Cards = []; } //TODO: create better logic for rounds async cardPlayed(cardClicked: PlayableCard) { let card = this.getAllPlayingCards().filter(x => x.id === cardClicked.id && x.player.id === cardClicked.player.id)[0]; //TODO: better error handling if (!card) { console.log(`error didn't find clicked card in players hand.`) return; } if (this.isPlayer1Move) this.firstPlayedCard = card; else this.secondPlayedCard = card; this.removeCardFromHand(card); await this.endMove(); } getAllPlayingCards(): PlayableCard[] { return this.player1Cards.concat(this.player2Cards); } removeCardFromHand(card: PlayableCard) { if (this.isPlayer1Move) this.player1Cards = this.player1Cards.filter(x => x.id !== card.id); else this.player2Cards = this.player2Cards.filter(x => x.id !== card.id); } async endMove() { //TODO: figure out better move logic if (this.isPlayer1Move && this.firstPlayedCard) { this.isPlayer1Move = !this.isPlayer1Move; console.log(`end of player 1 move`); } else if (!this.isPlayer1Move && this.secondPlayedCard) { console.log(`end of player 2 move`); await this.endRound(); } else console.log(`One of the players didn't place their card!`) } async endRound() { let roundCards: PlayableCard[] = [this.firstPlayedCard, this.secondPlayedCard]; let roundResult = await this.postRoundPlayedCards(roundCards) as CardsPlayedResponseDto; this.addPointsToWinnerPlayer(roundResult); this.presentingRoundResult = true; } //TODO: refactor addPointsToWinnerPlayer(roundResult: CardsPlayedResponseDto) { if (!roundResult.winner) { this.endRoundDecision = CardResponseResult[roundResult.result]; return; } if (this.player1.id === roundResult.winner.id) { this.player1.points = roundResult.winner.points; this.player1.hasWon = true; this.endRoundDecision = `Player 1 Won`; } else if (this.player2.id === roundResult.winner.id) { this.player2.points = roundResult.winner.points; this.player2.hasWon = true; this.endRoundDecision = `Player 2 Won`; } else console.log(`Cannot add points to player. Didn't find player with id ${roundResult.winner.id}`); } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/models/cards/SpaceshipCard.ts import { PlayableCard } from './PlayableCard'; import { Player } from '../players/Player'; import { CardType } from './CardType'; export class SpaceshipCard extends PlayableCard { cardType = CardType.Spaceship; id: string; name: string; player: Player; crewCount: number; constructor(id: string, name: string, player: Player, crewCount: number) { super(id, name, player); this.crewCount = crewCount; } getPower() { return this.crewCount; } } <file_sep>/PersonSpaceshipsGame.Tests/TestCaseSources/Services/Cards/ChooseWinnerTestCases.cs using NUnit.Framework; using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Tests.TestCaseSources.Services.Cards { public class ChooseWinnerTestCases { public static IEnumerable<TestCaseData> PersonTestCases { get { IPersonCard mass10PersonCard = new PersonCard { Id = new Guid(), Mass = 10, Name = "<NAME>0", Player = new Player() }; IPersonCard mass15PersonCard = new PersonCard { Id = new Guid(), Mass = 15, Name = "Mass 15", Player = new Player() }; List<IPersonCard> mass15CardWin = new List<IPersonCard>() { mass15PersonCard, mass10PersonCard }; List<IPersonCard> mass15CardWinDifferentOrder = new List<IPersonCard>() { mass10PersonCard, mass15PersonCard }; List<IPersonCard> drawCards = new List<IPersonCard>() { mass15PersonCard, mass15PersonCard }; List<IPersonCard> oneCard = new List<IPersonCard>() { mass15PersonCard }; yield return new TestCaseData(mass15CardWin, new CardsPlayedResponse() { Players = mass15CardWin.Select(x => x.Player), Winner = mass15PersonCard.Player, Result = Models.Cards.Enums.CardResponseResult.Win }); yield return new TestCaseData(mass15CardWinDifferentOrder, new CardsPlayedResponse() { Players = mass15CardWinDifferentOrder.Select(x => x.Player), Winner = mass15PersonCard.Player, Result = Models.Cards.Enums.CardResponseResult.Win }); yield return new TestCaseData(drawCards, new CardsPlayedResponse() { Players = drawCards.Select(x => x.Player), Result = Models.Cards.Enums.CardResponseResult.Draw }); yield return new TestCaseData(oneCard, new CardsPlayedResponse() { Players = oneCard.Select(x => x.Player), Result = Models.Cards.Enums.CardResponseResult.NotEnoughCards }); } } public static IEnumerable<TestCaseData> SpaceshipsTestCases { get { ISpaceshipCard crewCount10PersonCard = new SpaceshipCard { Id = new Guid(), CrewCount = 10, Name = "CrewCount 10", Player = new Player() }; ISpaceshipCard crewCount15PersonCard = new SpaceshipCard { Id = new Guid(), CrewCount = 15, Name = "CrewCount 15", Player = new Player() }; List<ISpaceshipCard> crew15WinCards = new List<ISpaceshipCard>() { crewCount15PersonCard, crewCount10PersonCard }; List<ISpaceshipCard> crew15WinCardsDifferentOrder = new List<ISpaceshipCard>() { crewCount10PersonCard, crewCount15PersonCard }; List<ISpaceshipCard> drawCards = new List<ISpaceshipCard>() { crewCount15PersonCard, crewCount15PersonCard }; List<ISpaceshipCard> oneCard = new List<ISpaceshipCard>() { crewCount15PersonCard }; yield return new TestCaseData(crew15WinCards, new CardsPlayedResponse() { Players = crew15WinCards.Select(x => x.Player), Winner = crewCount15PersonCard.Player, Result = Models.Cards.Enums.CardResponseResult.Win }); yield return new TestCaseData(crew15WinCardsDifferentOrder, new CardsPlayedResponse() { Players = crew15WinCardsDifferentOrder.Select(x => x.Player), Winner = crewCount15PersonCard.Player, Result = Models.Cards.Enums.CardResponseResult.Win }); yield return new TestCaseData(drawCards, new CardsPlayedResponse() { Players = drawCards.Select(x => x.Player), Result = Models.Cards.Enums.CardResponseResult.Draw }); yield return new TestCaseData(oneCard, new CardsPlayedResponse() { Players = oneCard.Select(x => x.Player), Result = Models.Cards.Enums.CardResponseResult.NotEnoughCards }); } } } } <file_sep>/PersonSpaceshipsGame/Controllers/CardGame/ICardGameController.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Controllers.CardGame { public interface ICardGameController : IDefaultCardGameController, IPersonsPlayedCardGameController, ISpaceShipsPlayedCardGameController { } } <file_sep>/PersonSpaceshipsGame/CQRS/Responses/Spaceships/GetSpaceshipResponseModel.cs using PersonSpaceshipsGame.Models.Cards.Spaceships; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Responses.Spaceships { public class GetSpaceshipResponseModel { public IEnumerable<ISpaceshipCard> SpaceshipCards { get; set; } } } <file_sep>/PersonSpaceshipsGame/Models/Players/Player.cs using PersonSpaceshipsGame.Models.Players; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Models { public class Player : BasePlayer { public Player() : base() { } } } <file_sep>/PersonSpaceshipsGame/CQRS/Responses/Cards/GetCardTypesResponseModel.cs using PersonSpaceshipsGame.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Responses.Cards { public class GetCardTypesResponseModel { public IEnumerable<CardTypeDto> CardTypes { get; set; } } } <file_sep>/PersonSpaceshipsGame/CQRS/Responses/Players/GetPlayersResponseModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Responses.Players { public class GetPlayersResponseModel { public IEnumerable<PersonSpaceshipsGame.Models.Player> Players { get; set; } } } <file_sep>/PersonSpaceshipsGame/Models/Players/PlayerStatics.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Models.Players { public static class PlayerStatics { public static int MaxPlayersCount = 2; public static int MaxHandCards = 3; } } <file_sep>/PersonSpaceshipsGame/CQRS/Responses/Persons/GetPersonsResponseModel.cs using MediatR; using PersonSpaceshipsGame.Models.Cards.Person; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Responses.Persons { public class GetPersonsResponseModel { public IEnumerable<IPersonCard> PersonCards { get; set; } } } <file_sep>/PersonSpaceshipsGame/Dtos/CardsPlayedResponseDto.cs using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Cards; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Dtos { public class CardsPlayedResponseDto { public Player? Winner { get; set; } public Enums.CardResponseResult Result { get; set; } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/templates/cards/playingCard/playingCard.template.component.ts import { Component, ViewEncapsulation, Input, ContentChild, TemplateRef } from '@angular/core'; import { PlayableCard } from '../../../models/cards/PlayableCard'; import { PersonCard } from '../../../models/cards/PersonCard'; import { SpaceshipCard } from '../../../models/cards/SpaceshipCard'; import { CardType } from '../../../models/cards/CardType'; @Component({ selector: 'app-playingCard', templateUrl: './playingCard.template.html', styleUrls: ['./playingCard.template.css'] }) export class PlayingCardComponent { @Input() inputPlayingCard: PlayableCard; personPlayingCard: PersonCard; spaceShipPlayingCard: SpaceshipCard; ngOnChanges(changePlayableCard: any) { //TODO: Better object creation, abstraction/factories/different components ? this.inputPlayingCard = changePlayableCard.inputPlayingCard.currentValue; switch (this.inputPlayingCard.cardType) { case CardType.Persons: this.personPlayingCard = this.inputPlayingCard as PersonCard; break; case CardType.Spaceship: this.spaceShipPlayingCard = this.inputPlayingCard as SpaceshipCard; break; default: console.log(`Card type not implemented ${this.inputPlayingCard.cardType}`); // TODO: Better exception handling } } } <file_sep>/PersonSpaceshipsGame/Dtos/PlayableCardDto.cs using PersonSpaceshipsGame.Models; using static PersonSpaceshipsGame.Models.Cards.Enums; namespace PersonSpaceshipsGame.Dtos { public class PlayableCardDto { public CardType CardType { get; set; } public string id { get; set; } public string name { get; set; } public Player player { get; set; } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/home/home.component.ts import { Component } from '@angular/core'; import { CardTypeDto } from '../Dtos/CardTypeDto' import { CardGameService } from '../cardGame/cardGameService' import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { PlayableCard } from '../models/cards/PlayableCard'; import { Player } from '../models/players/Player'; import { trigger, state, style, transition, animate } from '@angular/animations'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], animations: [ trigger('playerWon', [ state('true', style({ 'font-size': '1.5em' })), state('false', style({ 'font-size': '1em' })), transition('false <=> true', animate(500)) ]) ] }) @Injectable() export class HomeComponent { cardGameService: CardGameService; constructor(private http: HttpClient) { this.cardGameService = new CardGameService(http); } initCardsDropdown() { this.cardGameService.initCardTypes(); } async startGameClicked() { await this.cardGameService.startGameClicked(); } // TODO: move logic to api, create rounds, every move should be approve by api instead of just js receiveCardClickedMessage($event) { let cardObject = JSON.parse($event) as PlayableCard; this.cardGameService.cardPlayed(cardObject); } } <file_sep>/PersonSpaceshipsGame/Controllers/CardGame/Responses/CardsPlayedResponse.cs using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Cards; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Controllers.CardGame.Responses { public class CardsPlayedResponse : ICardsPlayedResponse { public Player? Winner { get; set; } public Enums.CardResponseResult Result { get; set; } public IEnumerable<Player> Players { get; set; } public override bool Equals(object obj) { ICardsPlayedResponse cardResponseObject = obj as ICardsPlayedResponse; if (cardResponseObject == null) return false; return Winner == cardResponseObject.Winner && Result == cardResponseObject.Result; } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/Dtos/CardsPlayedResponseDto.ts import { Player } from "../models/players/Player"; import { CardResponseResult } from "../models/cards/CardType"; export interface CardsPlayedResponseDto { winner: Player; result: CardResponseResult; } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/Dtos/PersonCardDto.ts import { PlayerDto } from './PlayerDto'; export class PersonCardDto { CardType: string; Id: string; Name: string; Player: PlayerDto; Mass: number; } <file_sep>/PersonSpaceshipsGame/CQRS/Responses/Spaceships/GetStartSpaceshipCardResponseModel.cs using PersonSpaceshipsGame.Models.Cards.Spaceships; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Responses.Spaceships { public class GetStartSpaceshipCardResponseModel { public IEnumerable<SpaceshipCard> Cards { get; set; } } } <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Cards/GetCardTypesRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Responses.Cards; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Cards { public class GetCardTypesRequestModel : IRequest<GetCardTypesResponseModel> { } } <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/QueriesHandlers/Persons/GetStartPersonsCardQueryHandler.cs using MediatR; using Microsoft.EntityFrameworkCore; using PersonSpaceshipsGame.CQRS.Requests.Persons; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Database; using PersonSpaceshipsGame.Models.Players; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.QueriesHandlers.Persons { //TODO: this should be one query with Spaceships query handler public class GetStartPersonsCardQueryHandler : IRequestHandler<GetStartPersonsCardRequestModel, GetStartPersonsCardResponseModel> { private readonly CardGameContext _context; public GetStartPersonsCardQueryHandler(CardGameContext context) { _context = context; } public async Task<GetStartPersonsCardResponseModel> Handle(GetStartPersonsCardRequestModel request, CancellationToken cancellationToken) { List<PersonCard> cards = new List<PersonCard>(); List<PersonCard> allPersonCards = await _context.PersonCards.ToListAsync(); //TODO: This has so low performance, figure out other way to choose random cards for players; stored procedure will be better IEnumerable<Player> thePlayers = await _context.Players.Take(request.PlayersCount).ToListAsync(); for (int i = 0; i < request.PlayersCount; i++) { var personCards = allPersonCards.OrderBy(x => Guid.NewGuid()).Take(PlayerStatics.MaxHandCards).ToList(); var thePlayer = thePlayers.ElementAt(i); personCards.ForEach(x => cards.Add(new PersonCard {Id = x.Id, CardType = x.CardType, Mass = x.Mass, Name = x.Name , Player = thePlayers.ElementAt(i) })); //TODO: store players in DB } return new GetStartPersonsCardResponseModel { Cards = cards }; } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/models/cards/PersonCard.ts import { PlayableCard } from './PlayableCard'; import { Player } from '../players/Player'; import { CardType } from './CardType'; export class PersonCard extends PlayableCard { cardType: CardType; id: string; name: string; player: Player; mass: number; constructor(id: string, name: string, player: Player, mass: number) { super(id, name, player); this.mass = mass; } getPower() { return this.mass; } } <file_sep>/PersonSpaceshipsGame/Controllers/CardGame/IDefaultCardGameController.cs namespace PersonSpaceshipsGame.Controllers.CardGame { public interface IDefaultCardGameController { int MaxPlayersCount { get; set; } } } <file_sep>/PersonSpaceshipsGame/Controllers/CardGame/ISpaceShipsPlayedCardGameController.cs using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using System.Collections.Generic; namespace PersonSpaceshipsGame.Controllers.CardGame { public interface ISpaceShipsPlayedCardGameController { ISpaceshipCardGameService spaceshipCardGameService { get; set; } ICardsPlayedResponse SpaceShipCardsPlayed(IEnumerable<ISpaceshipCard> playedCards); } } <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Players/GetPlayersRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Requests.Cards; using PersonSpaceshipsGame.CQRS.Responses.Players; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Players { public class GetPlayersRequestModel : IRequest<GetPlayersResponseModel> { public IEnumerable<Guid> Guids { get; set; } } } <file_sep>/PersonSpaceshipsGame.Tests/TestCaseSources/Controllers/Cards/PlayedCardsTestCases.cs using NUnit.Framework; using PersonSpaceshipsGame.Dtos; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; using System.Text.Json; using System.Text.Json.Serialization; using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models.Players; namespace PersonSpaceshipsGame.Tests.TestCaseSources.Controllers.Cards { public class PlayedCardsTestCases { public static IEnumerable<TestCaseData> PersonsPlayedCard { get { List<Player> players = GetPlayers(2); IPersonCard mass10PersonCard = new PersonCard { Id = new Guid(), Mass = 10, Name = "Mass 10", Player = players[0] }; IPersonCard mass15PersonCard = new PersonCard { Id = new Guid(), Mass = 15, Name = "Mass 15", Player = players[1] }; List<IPersonCard> person1WonCards = new List<IPersonCard>() { mass15PersonCard, mass10PersonCard }; List<IPersonCard> drawCards = new List<IPersonCard>() { mass15PersonCard, mass15PersonCard }; List<IPersonCard> justOneCard = new List<IPersonCard>() { mass15PersonCard }; yield return new TestCaseData(person1WonCards, new CardsPlayedResponse() { Winner = mass15PersonCard.Player, Players = players, Result = Models.Cards.Enums.CardResponseResult.Win }); yield return new TestCaseData(drawCards, new CardsPlayedResponse() { Players = players, Result = Models.Cards.Enums.CardResponseResult.Draw }); yield return new TestCaseData(justOneCard, new CardsPlayedResponse() { Players = players, Result = Models.Cards.Enums.CardResponseResult.NotEnoughCards }); } } public static IEnumerable<TestCaseData> SpaceshipsPlayedCards { get { List<Player> players = GetPlayers(2); ISpaceshipCard crew10PersonCard = new SpaceshipCard { Id = new Guid(), CrewCount = 10, Name = "<NAME>", Player = players[0] }; ISpaceshipCard crew15PersonCard = new SpaceshipCard { Id = new Guid(), CrewCount = 15, Name = "<NAME>", Player = players[1] }; List<ISpaceshipCard> spaceship1Won = new List<ISpaceshipCard>() { crew15PersonCard, crew10PersonCard }; List<ISpaceshipCard> drawCards = new List<ISpaceshipCard>() { crew15PersonCard, crew15PersonCard }; List<ISpaceshipCard> justOneCard = new List<ISpaceshipCard>() { crew15PersonCard }; yield return new TestCaseData(spaceship1Won, new CardsPlayedResponse() { Winner = crew15PersonCard.Player, Players = players, Result = Models.Cards.Enums.CardResponseResult.Win }); yield return new TestCaseData(drawCards, new CardsPlayedResponse() { Players = players, Result = Models.Cards.Enums.CardResponseResult.Draw }); yield return new TestCaseData(justOneCard, new CardsPlayedResponse() { Players = players, Result = Models.Cards.Enums.CardResponseResult.NotEnoughCards }); } } static List<Player> GetPlayers(int count) { List<Player> players = new List<Player>(); for (int i = 0; i < count; i++) players.Add(new Player()); return players; } } } <file_sep>/PersonSpaceshipsGame/Controllers/API/GameController.cs using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using PersonSpaceshipsGame.Controllers.CardGame; using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.CQRS.Requests.Cards; using PersonSpaceshipsGame.CQRS.Requests.Persons; using PersonSpaceshipsGame.CQRS.Requests.Players; using PersonSpaceshipsGame.CQRS.Requests.Spaceships; using PersonSpaceshipsGame.Dtos; using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Cards; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; namespace PersonSpaceshipsGame.Controllers.API { [ApiController] [Route("api/[controller]")] public class GameController : ControllerBase { private readonly ILogger<GameController> _logger; private readonly ICardGameController _cardGameController; private readonly IMediator _mediator; private readonly IMapper _mapper; public GameController(ILogger<GameController> logger, IMediator mediator, IMapper mapper) { _logger = logger; _cardGameController = new CardGameController(); // change to factory _mediator = mediator; _mapper = mapper; } /// <summary> /// Get all card types /// </summary> /// <returns>The list of CardTypeDto's</returns> /// <remarks> /// Sample output: /// /// [ /// { /// "name": "Person" /// }, /// { /// "name": "Spaceship" /// } /// ] /// </remarks> [HttpGet] [Route("[action]")] public IEnumerable<CardTypeDto> GetCardTypes() { var response = _mediator.Send(request: new GetCardTypesRequestModel()); return response.Result.CardTypes; } /// <summary> /// Gets starting cards acording to send CardType ( Person or Spaceship ) /// </summary> /// <remarks> /// Sample response like: /// /// [ /// { /// "id": "32dc22ed-c7c1-4d69-9b05-667484824ab4", /// "mass": 70, /// "name": "<NAME>", /// "cardTypeString": "Person", /// "cardType": 0, /// "player": { /// "id": "09d9b6ee-03d8-4d92-b974-44c8c2189a7c", /// "points": 23, /// "cards": null /// } /// }, /// { /// "id": "b5378c90-caa6-41e1-ab4d-1dd624fc401e", /// "mass": 35, /// "name": "<NAME>", /// "cardTypeString": "Person", /// "cardType": 0, /// "player": { /// "id": "09d9b6ee-03d8-4d92-b974-44c8c2189a7c", /// "points": 23, /// "cards": null /// } /// }, /// { /// "id": "fca28765-d903-4ced-9453-904aa02be26a", /// "mass": 55, /// "name": "<NAME>", /// "cardTypeString": "Person", /// "cardType": 0, /// "player": { /// "id": "09d9b6ee-03d8-4d92-b974-44c8c2189a7c", /// "points": 23, /// "cards": null /// } /// }, /// { /// "id": "083faa7b-1fda-4dac-ba09-14a63857f1d9", /// "mass": 1, /// "name": "<NAME>", /// "cardTypeString": "Person", /// "cardType": 0, /// "player": { /// "id": "2dd5aae4-7fb3-4d6a-a679-7c971466f1bb", /// "points": 17, /// "cards": null /// } /// }, /// { /// "id": "fca28765-d903-4ced-9453-904aa02be26a", /// "mass": 55, /// "name": "<NAME>", /// "cardTypeString": "Person", /// "cardType": 0, /// "player": { /// "id": "2dd5aae4-7fb3-4d6a-a679-7c971466f1bb", /// "points": 17, /// "cards": null /// } /// }, /// { /// "id": "58e9c1f8-6017-49cb-a07f-0cdf82efa01d", /// "mass": 25, /// "name": "<NAME>", /// "cardTypeString": "Person", /// "cardType": 0, /// "player": { /// "id": "2dd5aae4-7fb3-4d6a-a679-7c971466f1bb", /// "points": 17, /// "cards": null /// } /// } /// ] /// </remarks> /// <param name="cardType"></param> /// <returns>List of playable cards</returns> [HttpGet] [Route("[action]/{cardType}")] public IEnumerable<IPlayableCard> GetStartingGamesCards(Enums.CardType cardType) { //TODO: change to factory query method switch (cardType) { case Enums.CardType.Person: var personResponse = _mediator.Send(request: new GetStartPersonsCardRequestModel()); return personResponse.Result.Cards; case Enums.CardType.Spaceship: var spaceshipResponse = _mediator.Send(request: new GetStartSpaceshipCardRequestModel()); return spaceshipResponse.Result.Cards; default: throw new NotImplementedException($"{cardType} is not implemented for starting game."); } } /// <summary> /// Posting players round cards /// </summary> /// <remarks> /// Sample respone like: /// /// { /// "winner": { /// "id": "09d9b6ee-03d8-4d92-b974-44c8c2189a7c", /// "points": 1, /// "cards": null /// }, /// "result": 0 /// } /// </remarks> /// <param name="cards"></param> /// <returns>CardsPlayedResponseDto which has round result and winner player object</returns> [HttpPost] [Route("[action]")] public CardsPlayedResponseDto PostRoundPlayedCards([FromBody] PlayableCardDto[] cards) { //TODO: better error handling if (cards.Select(x => x.CardType).Distinct().Count() != 1) return null; IEnumerable<Player> players = _mediator.Send(request: new GetPlayersRequestModel { Guids = cards.Select(x => x.player.Id).ToList() }).Result.Players; ICardsPlayedResponse response; //TODO: Move logic to cardController and follow open/close principle switch (cards.First().CardType) { case Enums.CardType.Person: response = GetPersonsCardPlayedResponse(cards, players); break; case Enums.CardType.Spaceship: response = GetSpaceShipPlayedResponse(cards, players); break; default: return null;//TODO: Better error handling } if (response.Winner != null) _mediator.Send(request: new PostPlayerChangesRequestModel { Player = response.Winner }); return _mapper.Map<CardsPlayedResponseDto>(response); } //TODO: move this with mediator call to cardgame controller private ICardsPlayedResponse GetSpaceShipPlayedResponse(PlayableCardDto[] cards, IEnumerable<Player> players) { ICardsPlayedResponse response; List<ISpaceshipCard> spaceShipCards = new List<ISpaceshipCard>(); for (int i = 0; i < cards.Length; i++) { var spaceshipCardsResponse = _mediator.Send(request: new GetSpaceshipRequestModel { SpaceshipIds = new List<Guid> { Guid.Parse(cards[i].id) } }).Result.SpaceshipCards; spaceshipCardsResponse.ToList().ForEach(x => x.Player = players.ElementAt(i)); spaceShipCards.AddRange(spaceshipCardsResponse); } response = _cardGameController.SpaceShipCardsPlayed(spaceShipCards); return response; } //TODO: move this with mediator call to cardgame controller private ICardsPlayedResponse GetPersonsCardPlayedResponse(PlayableCardDto[] cards, IEnumerable<Player> players) { ICardsPlayedResponse response; List<IPersonCard> personCards = new List<IPersonCard>(); for (int i = 0; i < cards.Length; i++) { var personCardsResponse = _mediator.Send(request: new GetPersonsRequestModel { PersonIds = new List<Guid> { Guid.Parse(cards[i].id) } }).Result.PersonCards; personCardsResponse.ToList().ForEach(x => x.Player = players.ElementAt(i)); personCards.AddRange(personCardsResponse); } response = _cardGameController.PersonsCardsPlayed(personCards); return response; } } } <file_sep>/PersonSpaceshipsGame/Services/CardGameService/SpaceshipCardGameService.cs using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models.Cards; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Models.Players; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Services.CardGameService { public class SpaceshipCardGameService : ISpaceshipCardGameService { //TODO: Think about merging this method to one with custom comparer as parameter public ICardsPlayedResponse ChooseWinnerCard(IEnumerable<ISpaceshipCard> cards) { List<ISpaceshipCard> sortedCardsList = cards.ToList().OrderByDescending(x => x.CrewCount).ToList(); if (sortedCardsList.Count <= 1) return new CardsPlayedResponse() { Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.NotEnoughCards }; if (sortedCardsList.Count > PlayerStatics.MaxPlayersCount) return new CardsPlayedResponse() { Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.TooMuchCards }; // if there is just one card with same amount of CrewCount as first one call a draw on a round if (sortedCardsList.First().CrewCount.Equals(sortedCardsList[1].CrewCount)) return new CardsPlayedResponse() { Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.Draw }; return new CardsPlayedResponse() { Winner = sortedCardsList.First().Player, Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.Win }; } } } <file_sep>/PersonSpaceshipsGame/Services/CardGameService/Interfaces/ISpaceshipCardGameService.cs using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models.Cards.Spaceships; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Services.CardGameService.Interfaces { public interface ISpaceshipCardGameService { ICardsPlayedResponse ChooseWinnerCard(IEnumerable<ISpaceshipCard> cards); } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/templates/cards/handCard/handCards.template.componnent.spec.ts import { TestBed, ComponentFixture } from '@angular/core/testing'; import { HandCardsComponent } from './handCards.template.component'; import { ComponentFactory, Component, DebugElement } from '@angular/core'; import { FixedSizeVirtualScrollStrategy } from '@angular/cdk/scrolling'; describe('HandCardsTemplate', () => { let componnent: HandCardsComponent; let fixture: ComponentFixture<HandCardsComponent>; let de: DebugElement; beforeEach(async() => { TestBed.configureTestingModule({ declarations: [HandCardsComponent], // your component here imports: [], }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(HandCardsComponent); componnent = fixture.componentInstance; de = fixture.debugElement; }); it('componnent be created', () => { expect(componnent).toBeTruthy(); }); }); <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Persons/GetPersonsRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Responses.Persons; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Persons { public class GetPersonsRequestModel : IRequest<GetPersonsResponseModel> { public IEnumerable<Guid> PersonIds { get; set; } } } <file_sep>/PersonSpaceshipsGame.Tests/Controllers/CardGameControllerTests.cs using NUnit.Framework; using PersonSpaceshipsGame.Controllers.CardGame; using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Dtos; using PersonSpaceshipsGame.Factories; using PersonSpaceshipsGame.Models.Cards; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using PersonSpaceshipsGame.Tests.TestCaseSources.Controllers.Cards; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Tests.Controllers { public class CardGameControllerTests { private CardGameController _cardGameController; [SetUp] public void Setup() { _cardGameController = new CardGameController(); } [TestCaseSource(typeof(PlayedCardsTestCases), nameof(PlayedCardsTestCases.PersonsPlayedCard))] public void PersonsCardsPlayed(List<IPersonCard> cards, ICardsPlayedResponse desiredResponse) { //TODO: Validate points var response = _cardGameController.PersonsCardsPlayed(cards); Assert.IsTrue(response.Equals(desiredResponse)); } [TestCaseSource(typeof(PlayedCardsTestCases), nameof(PlayedCardsTestCases.SpaceshipsPlayedCards))] public void SpaceShipsCardsPlayed(List<ISpaceshipCard> cards, ICardsPlayedResponse desiredResponse) { //TODO: Validate points var response = _cardGameController.SpaceShipCardsPlayed(cards); Assert.IsTrue(response.Equals(desiredResponse)); } } } <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/QueriesHandlers/Persons/GetAllPersonsQueryHandler.cs using MediatR; using Microsoft.EntityFrameworkCore; using PersonSpaceshipsGame.CQRS.Requests.Persons; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Database; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.QueriesHandlers.Persons { public class GetAllPersonsQueryHandler : IRequestHandler<GetPersonsRequestModel, GetPersonsResponseModel> { private readonly CardGameContext _context; public GetAllPersonsQueryHandler(CardGameContext context) { _context = context; } public async Task<GetPersonsResponseModel> Handle(GetPersonsRequestModel request, CancellationToken cancellationToken) { IQueryable<PersonCard> query; if (request.PersonIds.Any()) query = _context.PersonCards.Where(x => request.PersonIds.Contains(x.Id)); else query = _context.PersonCards; List<PersonCard> cards = await query.ToListAsync(); return new GetPersonsResponseModel { PersonCards = cards}; } } } <file_sep>/PersonSpaceshipsGame/Models/Players/BasePlayer.cs using PersonSpaceshipsGame.Models.Cards; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Models.Players { public abstract class BasePlayer { public Guid Id { get; set; } public int Points { get; set; } [NotMapped] public IEnumerable<IPlayableCard> Cards { get; set; } public BasePlayer() { Id = Guid.NewGuid(); Points = 0; } } } <file_sep>/PersonSpaceshipsGame/Models/Cards/Person/IPersonCard.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Models.Cards.Person { public interface IPersonCard : IPlayableCard { public float Mass { get; set; } } } <file_sep>/PersonSpaceshipsGame/Models/Cards/IPlayableCard.cs using PersonSpaceshipsGame.Models.Players; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; using static PersonSpaceshipsGame.Models.Cards.Enums; namespace PersonSpaceshipsGame.Models.Cards { public interface IPlayableCard { Guid Id { get; set; } string Name { get; set; } [NotMapped] public Player Player { get; set; } [Column("CardType")] public string CardTypeString { get { return CardType.ToString(); } private set { CardType = Enums.ParseEnum<CardType>(value); } } [NotMapped] public Enums.CardType CardType { get; set; } } } <file_sep>/PersonSpaceshipsGame/Services/CardGameService/Interfaces/IPersonCardGameService.cs using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models.Cards.Person; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Services.CardGameService.Interfaces { public interface IPersonCardGameService { ICardsPlayedResponse ChooseWinnerCard(IEnumerable<IPersonCard> cards); } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/home/home.component.spec.ts import { of, Observable } from 'rxjs'; import { TestBed, ComponentFixture } from '@angular/core/testing'; import { ComponentFactory, Component, DebugElement, Type } from '@angular/core'; import { FixedSizeVirtualScrollStrategy } from '@angular/cdk/scrolling'; import { CardGameService } from '../cardGame/cardGameService'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { PersonCard } from '../models/cards/PersonCard'; import { Player } from '../models/players/Player'; import { SpaceshipCard } from '../models/cards/SpaceshipCard'; import { HomeComponent } from './home.component'; import { CardTypeDto } from '../Dtos/CardTypeDto'; import { CardType } from '../models/cards/CardType'; import { PlayableCard } from '../models/cards/PlayableCard'; //TODO: add UI tests describe('CardGameService', () => { let service: CardGameService; let component: HomeComponent; let fixture: ComponentFixture<HomeComponent>; let de: DebugElement; let httpMock: HttpTestingController; beforeEach(async () => { TestBed.configureTestingModule({ declarations: [HomeComponent], imports: [HttpClientTestingModule], providers: [CardGameService] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(HomeComponent); component = fixture.componentInstance; service = TestBed.get(CardGameService); de = fixture.debugElement; httpMock = fixture.debugElement.injector.get<HttpTestingController>(HttpTestingController as Type<HttpTestingController>); let expectedResponse = [{ "name": "Persons" } as CardTypeDto, { "name": "Spaceships" } as CardTypeDto]; service.cardTypes = expectedResponse; }); afterEach(() => { httpMock.verify(); }); it('service be created', () => { expect(component).toBeTruthy(); }); it('assign player cards woks', async () => { let player1 = new Player('aaa', 0, []); let player2 = new Player('aaab', 0, []); const player1Cards = [ new PersonCard('11', 'Card 1', player1, 15), new PersonCard('115', 'Card 2', player1, 10), ]; let player2Cards = [ new PersonCard('112', 'Card 3', player2, 10), new PersonCard('1125', 'Card 4', player2, 19), ]; const peopleCardResponse = player1Cards.concat(player2Cards); service.assignCardsToPlayers(peopleCardResponse); expect(service.player1Cards).toEqual(player1Cards); expect(service.player2Cards).toEqual(player2Cards); expect(service.player1).toEqual(player1); expect(service.player2).toEqual(player2); expect(service.isPlaying).toBeTruthy(); }); it(`init game start game service state works`, () => { service.initGameServiceState(); expect(service.selectedStartCardType).toBeNull(); expect(service.firstPlayedCard).toBeNull(); expect(service.secondPlayedCard).toBeNull(); expect(service.isPlaying).toBeFalsy(); expect(service.presentingRoundResult).toBeFalsy(); expect(service.isGameEnded).toBeFalsy(); expect(service.isPlayer1Move).toBeTruthy(); expect(service.endRoundDecision).toEqual(""); expect(service.player1Cards).toEqual([]); expect(service.player2Cards).toEqual([]); }); it(`init game start works`, () => { service.initGameServiceState(); expect(service.selectedStartCardType).toBeNull(); expect(service.firstPlayedCard).toBeNull(); expect(service.secondPlayedCard).toBeNull(); expect(service.isPlaying).toBeFalsy(); expect(service.presentingRoundResult).toBeFalsy(); expect(service.isGameEnded).toBeFalsy(); expect(service.isPlayer1Move).toBeTruthy(); expect(service.endRoundDecision).toEqual(""); expect(service.player1Cards).toEqual([]); expect(service.player2Cards).toEqual([]); }); it(`start game click works`, async () => { let player1 = new Player('aaa', 0, []); let player2 = new Player('aaab', 0, []); const player1Cards = [ new PersonCard('11', 'Card 1', player1, 15), new PersonCard('115', 'Card 2', player1, 10), ]; let player2Cards = [ new PersonCard('112', 'Card 3', player2, 10), new PersonCard('1125', 'Card 4', player2, 19), ]; const peopleCardResponse = player1Cards.concat(player2Cards); service.selectedStartCardType = { "name": "Persons" } as CardTypeDto; spyOn(service, `getStartingGameCards`).and.returnValue(Promise.resolve<PlayableCard[]>(peopleCardResponse)); await service.startGameClicked(); // duplicated expect(service.player1Cards).toEqual(player1Cards); expect(service.player2Cards).toEqual(player2Cards); expect(service.player1).toEqual(player1); expect(service.player2).toEqual(player2); expect(service.isPlaying).toBeTruthy(); }); }); <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/QueriesHandlers/Spaceships/GetAllSpaceshipsQueryHandler.cs using MediatR; using Microsoft.EntityFrameworkCore; using PersonSpaceshipsGame.CQRS.Requests.Persons; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.CQRS.Responses.Spaceships; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Models.Database; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.QueriesHandlers.Persons { public class GetAllSpaceshipsQueryHandler : IRequestHandler<GetSpaceshipRequestModel, GetSpaceshipResponseModel> { private readonly CardGameContext _context; public GetAllSpaceshipsQueryHandler(CardGameContext context) { _context = context; } public async Task<GetSpaceshipResponseModel> Handle(GetSpaceshipRequestModel request, CancellationToken cancellationToken) { IQueryable<SpaceshipCard> query; if (request.SpaceshipIds.Any()) query = _context.SpaceshipCards.Where(x => request.SpaceshipIds.Contains(x.Id)); else query = _context.SpaceshipCards; List<SpaceshipCard> cards = await query.ToListAsync(); return new GetSpaceshipResponseModel { SpaceshipCards = cards}; } } } <file_sep>/PersonSpaceshipsGame/Controllers/CardGame/Responses/ICardsPlayedResponse.cs using PersonSpaceshipsGame.Models; using PersonSpaceshipsGame.Models.Cards; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Controllers.CardGame.Responses { public interface ICardsPlayedResponse { Player? Winner { get; set; } IEnumerable<Player> Players { get; set; } Enums.CardResponseResult Result { get; set; } } } <file_sep>/PersonSpaceshipsGame/Controllers/CardGame/IPersonsPlayedCardGameController.cs using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using System.Collections.Generic; namespace PersonSpaceshipsGame.Controllers.CardGame { public interface IPersonsPlayedCardGameController { IPersonCardGameService personCardGameService { get; set; } ICardsPlayedResponse PersonsCardsPlayed(IEnumerable<IPersonCard> playedCards); } } <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Spaceships/GetPersonsRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.CQRS.Responses.Spaceships; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Persons { public class GetSpaceshipRequestModel : IRequest<GetSpaceshipResponseModel> { public IEnumerable<Guid> SpaceshipIds { get; set; } } } <file_sep>/PersonSpaceshipsGame/Migrations/20201108160838_addData.cs using Microsoft.EntityFrameworkCore.Migrations; namespace PersonSpaceshipsGame.Migrations { public partial class addData : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(@"INSERT [dbo].[PersonCards] ([Id], [Mass], [Name], [CardType]) VALUES (N'58e9c1f8-6017-49cb-a07f-0cdf82efa01d', 25, N'Brave Person', N'Person') GO INSERT[dbo].[PersonCards]([Id], [Mass], [Name], [CardType]) VALUES(N'083faa7b-1fda-4dac-ba09-14a63857f1d9', 1, N'Funny Person', N'Person') GO INSERT[dbo].[PersonCards] ([Id], [Mass], [Name], [CardType]) VALUES(N'b5378c90-caa6-41e1-ab4d-1dd624fc401e', 35, N'Popular Person', N'Person') GO INSERT[dbo].[PersonCards] ([Id], [Mass], [Name], [CardType]) VALUES(N'baaed6d4-eba1-46f1-945e-5eab629b9ee4', 2, N'Nice Person', N'Person') GO INSERT[dbo].[PersonCards] ([Id], [Mass], [Name], [CardType]) VALUES(N'32dc22ed-c7c1-4d69-9b05-667484824ab4', 70, N'Loud Person', N'Person') GO INSERT[dbo].[PersonCards] ([Id], [Mass], [Name], [CardType]) VALUES(N'e70c09e6-8f1f-40f9-8e1d-739e81d7fca8', 20, N'Shy Person', N'Person') GO INSERT[dbo].[PersonCards] ([Id], [Mass], [Name], [CardType]) VALUES(N'fca28765-d903-4ced-9453-904aa02be26a', 55, N'Pretty Person', N'Person') GO INSERT[dbo].[Players] ([Id], [Points]) VALUES(N'09d9b6ee-03d8-4d92-b974-44c8c2189a7c', 0) GO INSERT[dbo].[Players] ([Id], [Points]) VALUES(N'2dd5aae4-7fb3-4d6a-a679-7c971466f1bb', 0) GO INSERT[dbo].[Players] ([Id], [Points]) VALUES(N'2be4b52a-e8b4-4183-86cd-7e000e3361d0', 0) GO INSERT[dbo].[Players] ([Id], [Points]) VALUES(N'9996f7c3-adeb-40b1-bb22-a04fe47bb9cd', 0) GO INSERT[dbo].[SpaceshipCards] ([Id], [CrewCount], [Name], [CardType]) VALUES(N'9eba4d17-da9f-4a74-aa57-1f2f5c19fc6e', 8, N'Large Spaceship', N'Spaceship') GO INSERT[dbo].[SpaceshipCards] ([Id], [CrewCount], [Name], [CardType]) VALUES(N'01e91ca7-8645-49a2-9703-1ff9df819dfa', 4, N'Smaller Spaceship', N'Spaceship') GO INSERT[dbo].[SpaceshipCards] ([Id], [CrewCount], [Name], [CardType]) VALUES(N'27e3fdcd-2a90-471e-8ed6-5608f3ac9ec4', 15, N'The Spaceship', N'Spaceship') GO INSERT[dbo].[SpaceshipCards] ([Id], [CrewCount], [Name], [CardType]) VALUES(N'9aba8921-29a6-4cff-9110-5de4966a36b5', 30, N'Just Spaceship', N'Spaceship') GO INSERT[dbo].[SpaceshipCards] ([Id], [CrewCount], [Name], [CardType]) VALUES(N'a7cb6d5c-2f0b-4cf8-974e-c0000a9a186c', 80, N'Huge Spaceship', N'Spaceship') GO INSERT[dbo].[SpaceshipCards] ([Id], [CrewCount], [Name], [CardType]) VALUES(N'1ddb3a27-18fd-4462-84e4-c108fae1422a', 1, N'Small Spaceship', N'Spaceship') GO "); } protected override void Down(MigrationBuilder migrationBuilder) { } } } <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Persons/GetStartPersonsCardRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.Models.Players; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Persons { public class GetStartPersonsCardRequestModel : IRequest<GetStartPersonsCardResponseModel> { public int PlayersCount { get; set; } = PlayerStatics.MaxPlayersCount; } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/templates/cards/handCard/handCards.template.component.ts import { Component, ViewEncapsulation, Input, Output, ContentChild, TemplateRef, EventEmitter } from '@angular/core'; import { PlayableCard } from '../../../models/cards/PlayableCard'; @Component({ selector: 'app-handCards', templateUrl: './handCards.template.html', styleUrls: ['./handCards.template.css'] }) export class HandCardsComponent { @Input() inputPlayingCards: PlayableCard[]; @Output() messageEvent = new EventEmitter<string>(); ngOnChanges(changePlayableCard: any) { let value = changePlayableCard.inputPlayingCards.currentValue as PlayableCard[]; this.inputPlayingCards = value; } cardClicked(card: PlayableCard) { this.messageEvent.emit(JSON.stringify(card)); } } <file_sep>/PersonSpaceshipsGame/Models/Cards/Spaceships/SpaceshipCard.cs using PersonSpaceshipsGame.Models.Players; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using static PersonSpaceshipsGame.Models.Cards.Enums; namespace PersonSpaceshipsGame.Models.Cards.Spaceships { public class SpaceshipCard : ISpaceshipCard { [Column("CardType")] public string CardTypeString { get { return CardType.ToString(); } private set { CardType = Enums.ParseEnum<CardType>(value); } } [NotMapped] public CardType CardType { get; set; } = CardType.Spaceship; public Guid Id { get; set; } public int CrewCount { get; set; } public string Name { get; set; } [NotMapped] public Player Player { get; set; } } } <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Players/PostPlayerChangesRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Players { public class PostPlayerChangesRequestModel : IRequest<PostPlayerChangesResponseModel> { public Player Player { get; set; } } } <file_sep>/PersonSpaceshipsGame/Models/Mapping/MappingProfile.cs using AutoMapper; using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Models.Mapping { public class MappingProfile : Profile { public MappingProfile() { CreateMap<CardsPlayedResponse, CardsPlayedResponseDto>(); } } } <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/CommandHandlers/Persons/AddPersonCommandHandler.cs using MediatR; using PersonSpaceshipsGame.CQRS.Requests; using PersonSpaceshipsGame.CQRS.Requests.Persons; using PersonSpaceshipsGame.CQRS.Responses; using PersonSpaceshipsGame.CQRS.Responses.Persons; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Database; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.CommandHandlers.Persons { public class AddPersonCommandHandler : IRequestHandler<AddPersonCardsRequestModel, AddPersonCardsResponseModel> { private readonly CardGameContext _context; public AddPersonCommandHandler(CardGameContext context) { _context = context; } public async Task<AddPersonCardsResponseModel> Handle(AddPersonCardsRequestModel request, CancellationToken cancellationToken) { IEnumerable<PersonCard> personCardInstances = request.PersonCards.Select(x => (PersonCard)x); try { await _context.AddRangeAsync(personCardInstances); await _context.SaveChangesAsync(); return new AddPersonCardsResponseModel { IsSuccess = true }; } catch (Exception) { return new AddPersonCardsResponseModel { IsSuccess = false }; } } } } <file_sep>/PersonSpaceshipsGame.Tests/CQRS/PersonsTests.cs using MediatR; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using PersonSpaceshipsGame.Controllers.API; using PersonSpaceshipsGame.Controllers.CardGame; using PersonSpaceshipsGame.CQRS.Requests.Persons; using PersonSpaceshipsGame.CQRS.Responses.Persons; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Tests.CQRS { public class PersonsTests { private Mock<IMediator> _mediator; public PersonsTests() { _mediator = new Mock<IMediator>(); } [TestCase] public void GetAllPersons_Success() { //TODO: add mocked tests var getAllRequestModel = new GetPersonsRequestModel { PersonIds = new List<Guid> {new Guid()} }; _mediator.Setup(x => x.Send(It.IsAny<GetPersonsResponseModel>(), new System.Threading.CancellationToken())).ReturnsAsync(new GetPersonsResponseModel()); //var cardGameController = new GameApiController(null,null,_mediator.Object); //var result = cardGameController.CardsPlayed(getAllRequestModel); //Assert.IsTrue(result is OkObjectResult); } } } <file_sep>/PersonSpaceshipsGame/Models/Cards/Enums.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.Models.Cards { public class Enums { public enum CardType { Person, Spaceship } public enum CardResponseResult { Win, Draw, NotEnoughCards, TooMuchCards } public static T ParseEnum<T>(string value) { return (T)Enum.Parse(typeof(T), value, true); } } } <file_sep>/PersonSpaceshipsGame/Services/CardGameService/PersonCardGameService.cs using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Models.Cards; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Players; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using System.Collections.Generic; using System.Linq; namespace PersonSpaceshipsGame.Services { public class PersonCardGameService : IPersonCardGameService { //TODO: Think about merging this method to one with custom comparer as parameter public ICardsPlayedResponse ChooseWinnerCard(IEnumerable<IPersonCard> cards) { List<IPersonCard> sortedCardsList = cards.OrderByDescending(x => x.Mass).ToList(); if (sortedCardsList.Count <= 1) return new CardsPlayedResponse() { Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.NotEnoughCards }; if (sortedCardsList.Count > PlayerStatics.MaxPlayersCount) return new CardsPlayedResponse() { Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.TooMuchCards }; // if there is just one card with same amount of mass as first one call a draw on a round if (sortedCardsList.First().Mass.Equals(sortedCardsList[1].Mass)) return new CardsPlayedResponse() { Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.Draw }; return new CardsPlayedResponse() { Winner = sortedCardsList.First().Player, Players = sortedCardsList.Select(x => x.Player), Result = Enums.CardResponseResult.Win }; } } } <file_sep>/PersonSpaceshipsGame/CQRS/Handlers/QueriesHandlers/Players/GetAllPlayersQueryHandler.cs using MediatR; using Microsoft.EntityFrameworkCore; using PersonSpaceshipsGame.CQRS.Requests.Players; using PersonSpaceshipsGame.CQRS.Responses.Players; using PersonSpaceshipsGame.Models.Database; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Handlers.QueriesHandlers.Players { public class GetAllPlayersQueryHandler : IRequestHandler<GetPlayersRequestModel, GetPlayersResponseModel> { private readonly CardGameContext _context; public GetAllPlayersQueryHandler(CardGameContext context) { _context = context; } public async Task<GetPlayersResponseModel> Handle(GetPlayersRequestModel request, CancellationToken cancellationToken) { System.Collections.Generic.List<Models.Player> players = await _context.Players.Where(x => request.Guids.Contains(x.Id)).ToListAsync(); return new GetPlayersResponseModel { Players = players }; } } } <file_sep>/PersonSpaceshipsGame/Migrations/20201108160133_addedCardType4.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace PersonSpaceshipsGame.Migrations { public partial class addedCardType4 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_PersonCards_Players_PlayerId", table: "PersonCards"); migrationBuilder.DropForeignKey( name: "FK_SpaceshipCards_Players_PlayerId", table: "SpaceshipCards"); migrationBuilder.DropIndex( name: "IX_SpaceshipCards_PlayerId", table: "SpaceshipCards"); migrationBuilder.DropIndex( name: "IX_PersonCards_PlayerId", table: "PersonCards"); migrationBuilder.DropColumn( name: "PlayerId", table: "SpaceshipCards"); migrationBuilder.DropColumn( name: "PlayerId", table: "PersonCards"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<Guid>( name: "PlayerId", table: "SpaceshipCards", type: "uniqueidentifier", nullable: true); migrationBuilder.AddColumn<Guid>( name: "PlayerId", table: "PersonCards", type: "uniqueidentifier", nullable: true); migrationBuilder.CreateIndex( name: "IX_SpaceshipCards_PlayerId", table: "SpaceshipCards", column: "PlayerId"); migrationBuilder.CreateIndex( name: "IX_PersonCards_PlayerId", table: "PersonCards", column: "PlayerId"); migrationBuilder.AddForeignKey( name: "FK_PersonCards_Players_PlayerId", table: "PersonCards", column: "PlayerId", principalTable: "Players", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_SpaceshipCards_Players_PlayerId", table: "SpaceshipCards", column: "PlayerId", principalTable: "Players", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } } <file_sep>/PersonSpaceshipsGame/ClientApp/src/app/models/cards/PlayableCard.ts import { Player } from "../players/Player"; import { CardType } from "./CardType"; export abstract class PlayableCard { cardType: CardType; id: string; name: string; player: Player; constructor(id: string, name: string, player: Player) { this.id = id; this.name = name; this.player = player; } getName() { return this.name; } getCardType() { return CardType[this.cardType] }; abstract getPower(); } <file_sep>/PersonSpaceshipsGame/CQRS/Requests/Spaceships/GetStartSpaceshipCardRequestModel.cs using MediatR; using PersonSpaceshipsGame.CQRS.Responses.Spaceships; using PersonSpaceshipsGame.Models.Players; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonSpaceshipsGame.CQRS.Requests.Spaceships { public class GetStartSpaceshipCardRequestModel : IRequest<GetStartSpaceshipCardResponseModel> { public int PlayersCount { get; set; } = PlayerStatics.MaxPlayersCount; } } <file_sep>/PersonSpaceshipsGame/Controllers/CardGame/CardGameController.cs using PersonSpaceshipsGame.Controllers.CardGame.Responses; using PersonSpaceshipsGame.Factories; using PersonSpaceshipsGame.Models.Cards; using PersonSpaceshipsGame.Models.Cards.Person; using PersonSpaceshipsGame.Models.Cards.Spaceships; using PersonSpaceshipsGame.Services.CardGameService.Interfaces; using System; using System.Collections.Generic; namespace PersonSpaceshipsGame.Controllers.CardGame { public class CardGameController : ICardGameController { public IPersonCardGameService personCardGameService { get; set; } public ISpaceshipCardGameService spaceshipCardGameService { get; set; } public int MaxPlayersCount { get; set; } = Models.Players.PlayerStatics.MaxPlayersCount; public CardGameController() { personCardGameService = GameServiceFactory.Create<IPersonCardGameService>(); spaceshipCardGameService = GameServiceFactory.Create<ISpaceshipCardGameService>(); } public ICardsPlayedResponse PersonsCardsPlayed(IEnumerable<IPersonCard> cards) { ICardsPlayedResponse cardsPlayedResponse = personCardGameService.ChooseWinnerCard(cards); AddPointsToWinner(cardsPlayedResponse); return cardsPlayedResponse; } public ICardsPlayedResponse SpaceShipCardsPlayed(IEnumerable<ISpaceshipCard> cards) { ICardsPlayedResponse cardsPlayedResponse = spaceshipCardGameService.ChooseWinnerCard(cards); AddPointsToWinner(cardsPlayedResponse); return cardsPlayedResponse; } private void AddPointsToWinner(ICardsPlayedResponse cardsPlayedResponse) { if (cardsPlayedResponse.Result == Enums.CardResponseResult.Win) cardsPlayedResponse.Winner.Points++; } } }
234c29c07c094ff9487273693ecd19b988d3fe04
[ "C#", "TypeScript" ]
68
C#
TooPositive/CardGame
cb5343d8dda0a4ef8fc98fce7cb1f42feddbcdaf
e526f99fba3302fd8a286daf99e5eb59f4471c63
refs/heads/master
<file_sep>// // ViewController.swift // LCAnimationPosition // // Created by 呆仔~林枫 on 2017/8/29. // Copyright © 2017年 Lin_Crazy. All rights reserved. // import UIKit class ViewController: UIViewController { let screen_w = UIScreen.main.bounds.width let screen_h = UIScreen.main.bounds.height let layerW : CGFloat = 200 let layerH : CGFloat = 150 override func viewDidLoad() { super.viewDidLoad() print(layer) } lazy var layer : CALayer = { let layer = CALayer() layer.bounds = CGRect.init(x: 0.0, y: 0.0, width: self.layerW, height: self.layerH) layer.position = self.view.center layer.backgroundColor = UIColor.orange.cgColor self.view.layer.addSublayer(layer) return layer }() override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let animation = CABasicAnimation.init(keyPath: "position") animation.toValue = CGRect.init(x: 110, y: 100, width: layerW, height: layerH) animation.duration = 1.5 animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = false animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear) layer.add(animation, forKey: "linear") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep># LCAnimationPosition 核心动画-Position ![image](https://github.com/CrazyDaiDai/LCAnimationPosition/blob/master/LCAnimationPosition.gif)
89ffb8d43d4cbb4182d30477059e8e334e44e67a
[ "Swift", "Markdown" ]
2
Swift
CrazyDaiDai/LCAnimationPosition
d966db27e6de8a2eed0e5dde7caddc41635edf84
6cb7fbcbb57ffdbf58ea0ce68ec76bc6c7bd4dfd
refs/heads/main
<file_sep>import colors from './colors' const startBtnRef = document.querySelector('[data-action="start"]') const stopBtnRef = document.querySelector('[data-action="stop"]') const TIME_INTERVAL = 1000; let intervalId = null const randomIntegerFromInterval = (min, max) => { return Math.floor(Math.random() * (max - min + 1) + min); }; startBtnRef.addEventListener('click', onStartBtnClick) stopBtnRef.addEventListener('click', onStopBtnClick) function onStartBtnClick() { intervalId = setInterval(changeBodyBgC, TIME_INTERVAL) startBtnRef.setAttribute('disabled', true) } function onStopBtnClick() { clearInterval(intervalId); startBtnRef.removeAttribute('disabled') document.body.removeAttribute('style') } function changeBodyBgC() { const colorBodyBgr = randomIntegerFromInterval(0, colors.length - 1) document.body.setAttribute('style', `background-color:${colors[colorBodyBgr]}`) }
66c4422ad7beae41f974773204bc9e15d7664041
[ "JavaScript" ]
1
JavaScript
andrii-telishko/goit-js-hw-11-color-switch
ce334bfaa497534336139cf44ef1318ea49d8faa
663e6117fd4744d240fe68f2bcf1635ff2401fa9
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityStandardAssets.ImageEffects; public class AVToggleHandler : MonoBehaviour { public float darknessLevel, blurLevel; public bool startBlind; private bool blind; private BlurOptimized blurryVision; private Transform blindnessSprite; // The GoDeaf event fires an alert to the GameController when the player turns on vision public delegate void GoDeaf(); public static event GoDeaf goDeaf; // The GoBlind event fires an alert to the GameController when the player turns on hearing public delegate void GoBlind(); public static event GoBlind goBlind; void Start () { blurryVision = Camera.main.GetComponent<BlurOptimized> (); blindnessSprite = Camera.main.transform.FindChild ("BlindnessSprite"); // If startBlind is checked, start blind with normal audio if (startBlind) { StartBlind (); StartNormalAudio (); blind = true; } // Else if startBlind is not checked, start deaf with normal vision else { StartNormalVision (); StartDeaf (); blind = false; } } void Update () { // If input is AV toggle button ... if (Input.GetMouseButtonDown (0)) { // If already blind, make deaf with normal vision if (blind) { StartNormalVision (); StartDeaf (); blind = false; } // Else if not already blind, make blind with normal audio else { StartBlind (); StartNormalAudio (); blind = true; } } } private void StartNormalVision() { blindnessSprite.GetComponent<SpriteRenderer> ().color = new Color (1f, 1f, 1f, 0); blurryVision.enabled = false; } public void StartBlind() { blindnessSprite.GetComponent<SpriteRenderer> ().color = new Color (1f, 1f, 1f, darknessLevel); blurryVision.enabled = true; blurryVision.downsample = (int)blurLevel * 2; blurryVision.blurSize = blurLevel * 10; blurryVision.blurIterations = (int)blurLevel * 4; } public void StartNormalAudio() { goBlind (); } public void StartDeaf() { goDeaf (); } }<file_sep>using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { public AudioSource soundtrack, ambientFactory; public float volume; // The game controller subscribes to these events from other classes void OnEnable() { AVToggleHandler.goDeaf += Deaf; AVToggleHandler.goBlind += Blind; } void OnDisable() { AVToggleHandler.goDeaf -= Deaf; AVToggleHandler.goBlind -= Blind; } void Start () { soundtrack.Play (); } void Deaf() { if (ambientFactory.isPlaying) { ambientFactory.volume = 0; } } void Blind() { if (!ambientFactory.isPlaying || ambientFactory.volume == 0) { ambientFactory.Play(); ambientFactory.volume = volume; } } }
228b253fcbab85d49493b90c3294bf43d2700e21
[ "C#" ]
2
C#
nellid/SensoryOverload
fb270d5245851d78ec7525ff4bad35b2b6d17e2c
073f40b599e5aecac4fe97f8827bcefa93406b6a
refs/heads/master
<repo_name>daviesjamie/comp3004-cw3<file_sep>/shader.hpp #ifndef SHADER_HPP_INCLUDED #define SHADER_HPP_INCLUDED GLint createShader( const char* filename, GLenum type ); #endif // SHADER_HPP_INCLUDED <file_sep>/Camera.hpp #ifndef CAMERA_HPP_INCLUDED #define CAMERA_HPP_INCLUDED #include <glm/glm.hpp> class Camera { private: glm::vec3 position; glm::vec3 direction; float speed; glm::mat4 projection; glm::mat4 view; public: Camera(); void adjustElevation( float amount ); void adjustSpeed( float amount ); void move(); void stop(); void pitch( float angle ); void yaw( float angle ); glm::vec3 getPosition(); void setPosition( glm::vec3 pos ); glm::vec3 getDirection(); void setDirection( glm::vec3 dir ); glm::mat4 getMVP( glm::mat4 model ); void status(); void reset(); }; #endif // CAMERA_HPP_INCLUDED <file_sep>/utils/filetobuffer.hpp #ifndef FILETOBUFFER_HPP_INCLUDED #define FILETOBUFFER_HPP_INCLUDED char* fileToBuffer( const char* filename ); #endif // FILETOBUFFER_HPP_INCLUDED <file_sep>/shader.cpp // This code was largely adopted from // http://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_02 #include <cstdio> #include <cstdlib> #include <GL/glew.h> #include <vector> #include "utils/filetobuffer.hpp" #include "shader.hpp" void printLog( GLuint object ) { GLint log_length = 0; if( glIsShader( object ) ) glGetShaderiv( object, GL_INFO_LOG_LENGTH, &log_length ); else if( glIsProgram( object ) ) glGetProgramiv( object, GL_INFO_LOG_LENGTH, &log_length ); else { fprintf( stderr, "printlog: Not a shader or a program\n" ); return; } char* log = ( char* )malloc( log_length ); if( glIsShader( object ) ) glGetShaderInfoLog( object, log_length, NULL, log ); else if( glIsProgram( object ) ) glGetProgramInfoLog( object, log_length, NULL, log ); fprintf( stderr, "%s", log ); free( log ); } GLint createShader( const char* filename, GLenum type ) { fprintf( stdout, "Loading %s...\n", filename ); const GLchar* source = fileToBuffer( filename ); if( source == NULL ) { fprintf( stderr, "Error opening %s: ", filename ); perror( "" ); return 0; } GLuint res = glCreateShader( type ); glShaderSource( res, 1, &source, NULL ); free( ( void* )source ); glCompileShader( res ); GLint compile_ok = GL_FALSE; glGetShaderiv( res, GL_COMPILE_STATUS, &compile_ok ); if( compile_ok == GL_FALSE ) { fprintf( stderr, "%s:", filename ); printLog( res ); glDeleteShader( res ); return 0; } return res; } <file_sep>/README.md # COMP3004 CW3 This is the coursework for the COMP3004 Computer Graphics module at School of Electronics and Computer Science, University of Southampton.<file_sep>/main.cpp #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/string_cast.hpp> #include <iostream> #include <vector> #include "Camera.hpp" #include "Model.hpp" #include "shader.hpp" int screen_width = 800; int screen_height = 600; bool running = true; Camera camera = Camera(); const char* HELP_TEXT = "COMP3004 Coursework 3, by <NAME> (jagd1g11)\n\n" "|-----------|---------------------------------------------------|\n" "| Key | Action |\n" "|-----------|---------------------------------------------------|\n" "| Q, ESC | Quit the program |\n" "| P | Move camera to location screenshot was taken from |\n" "| T | Start the tour |\n" "| E | End the tour |\n" "| LEFT | Turn camera left |\n" "| RIGHT | Turn camera right |\n" "| W | Tilt camera up |\n" "| S | Tilt camera down |\n" "| PAGE UP | Raise camera |\n" "| PAGE DOWN | Lower camera |\n" "| UP | Speed up camera |\n" "| DOWN | Slow down camera |\n" "| SPACE | Stop camera |\n" "| BACKSPACE | Reset camera position |\n" "| . | Print camera position to console |\n" "| H, ? | Print this help message |\n" "|-----------|---------------------------------------------------|\n"; static void keyHandler( GLFWwindow* window, int key, int scancode, int action, int mods ) { if( action == GLFW_PRESS ) { switch( key ) { // Quit case GLFW_KEY_Q: case GLFW_KEY_ESCAPE: running = false; break; // Screenshot location case GLFW_KEY_P: break; // Start tour case GLFW_KEY_T: break; // End tour case GLFW_KEY_E: break; // Turn camera left case GLFW_KEY_LEFT: camera.yaw( 2 ); break; // Turn camera right case GLFW_KEY_RIGHT: camera.yaw( -2 ); break; // Tilt camera up case GLFW_KEY_W: camera.pitch( 2 ); break; // Tilt camera down case GLFW_KEY_S: camera.pitch( -2 ); break; // Raise camera case GLFW_KEY_PAGE_UP: camera.adjustElevation( 0.5 ); break; // Lower camera case GLFW_KEY_PAGE_DOWN: camera.adjustElevation( -0.5 ); break; // Speed up camera case GLFW_KEY_UP: camera.adjustSpeed( 0.01 ); break; // Slow down camera case GLFW_KEY_DOWN: camera.adjustSpeed( -0.01 ); break; // Stop camera case GLFW_KEY_SPACE: camera.stop(); break; // Reset camera case GLFW_KEY_BACKSPACE: camera.reset(); break; // Log camera position to console case GLFW_KEY_PERIOD: camera.status(); break; // Display help on console case GLFW_KEY_H: case GLFW_KEY_SLASH: std::cout << HELP_TEXT << std::endl; break; } } } static void resizeHandler( GLFWwindow* window, int width, int height ) { screen_width = width; screen_height = height; glViewport( 0, 0, width, height ); } GLint linkShaders( const std::vector<GLint> &shaders ) { GLuint program = glCreateProgram(); for( GLuint i = 0; i < shaders.size(); i++ ) glAttachShader( program, shaders[ i ] ); glLinkProgram( program ); return program; } int main( int argc, char* argv[] ) { // Initialise GLFW fprintf( stdout, "Initialising GLFW...\n" ); if( !glfwInit() ) { fprintf( stderr, "Failed to start GLFW\n" ); exit( EXIT_FAILURE ); } // Create a window and OpenGL context GLFWwindow* window = glfwCreateWindow( screen_width, screen_height, "COMP3004 CW 3 -- <NAME> (jagd1g11)", NULL, NULL ); if( !window ) { fprintf( stderr, "Failed to create a window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } // Make that context the current one glfwMakeContextCurrent( window ); // Initialise GLEW fprintf( stdout, "Initialising GLEW...\n" ); glewExperimental = GL_TRUE; int err = glewInit(); if( err != GLEW_OK ) { fprintf( stderr, "Failed to start GLEW\n" ); glfwDestroyWindow( window ); glfwTerminate(); exit( EXIT_FAILURE ); } // Set key/resize callback functions glfwSetKeyCallback( window, keyHandler ); glfwSetWindowSizeCallback( window, resizeHandler ); // Load the shaders GLuint vertex_shader = createShader( "vertex.glsl", GL_VERTEX_SHADER ); GLuint fragment_shader = createShader( "fragment.glsl", GL_FRAGMENT_SHADER ); // Create the shader program std::vector<GLint> shaders; shaders.push_back( vertex_shader ); shaders.push_back( fragment_shader ); GLuint shader_program = linkShaders( shaders ); // Load models Model terrain( "models/terrain2.obj" ); terrain.load(); terrain.scale( glm::vec3( 100.0f, 100.0f, 100.0f ) ); Model clanger1( "models/clanger.obj" ); clanger1.load(); Model clanger2 = clanger1; clanger2.translate( glm::vec3( -3.0f, 0.0f, 0.0f ) ); Model clanger3 = clanger1; clanger3.translate( glm::vec3( 3.0f, 0.0f, 0.0f ) ); Model asteroid( "models/asteroid.obj" ); asteroid.load(); asteroid.translate( glm::vec3( 20.0f, 5.0f, 0.0f ) ); Model hole1( "models/hole.obj" ); hole1.load(); hole1.scale( glm::vec3( 1.5f, 1.5f, 1.5f ) ); Model hole2 = hole1; hole2.translate( glm::vec3( -3.0f, -0.5f, 6.0f ) ); hole1.translate( glm::vec3( 0.0f, -0.3f, 0.0f ) ); Model lid1( "models/dustbinlid.obj" ); lid1.load(); Model lid2 = lid1; lid2.translate( glm::vec3( -3.0f, -0.5f, 6.0f ) ); lid1.translate( glm::vec3( -1.0f, -0.5f, -3.5f ) ); // Set up uniform variables for GLSL glUseProgram( shader_program ); GLuint mvp_id = glGetUniformLocation( shader_program, "mvp" ); GLuint enable_shading_id = glGetUniformLocation( shader_program, "enable_shading" ); float ambient_intensity = 0.2f; GLuint ambient_intensity_id = glGetUniformLocation( shader_program, "ambient_intensity" ); glUniform1f( ambient_intensity_id, ambient_intensity ); glm::vec3 light_direction = glm::vec3( -10.0f, -10.0f, 10.0f ); GLuint light_direction_id = glGetUniformLocation( shader_program, "light_direction" ); glUniform3fv( light_direction_id, 1, &light_direction[ 0 ] ); glm::vec3 light_color; GLuint light_color_id = glGetUniformLocation( shader_program, "light_color" ); light_color = glm::vec3( 0.5f, 0.5f, 0.5f ); glUniform3fv( light_color_id, 1, &light_color[ 0 ] ); glm::vec3 object_color; GLuint object_color_id = glGetUniformLocation( shader_program, "object_color" ); glEnable( GL_DEPTH_TEST ); // Loop variables float currentTime = 0; float lastTime = 0; float timeDiff = 0; while( running ) { // Calculate time difference between this frame and the last currentTime = glfwGetTime(); timeDiff = currentTime - lastTime; lastTime = currentTime; /////////////////////////////////////////////////////////////////////// // EVENTS glfwPollEvents(); // Exit on window close if( glfwWindowShouldClose( window ) ) running = false; /////////////////////////////////////////////////////////////////////// // LOGIC camera.move(); asteroid.translate( glm::vec3( -20.0f, -5.0f, 0.0f ) ); asteroid.rotate( -timeDiff * 45, glm::vec3( 0.2f, 1.0f, 0.0f ) ); asteroid.translate( glm::vec3( 20.0f, 5.0f, 0.0f ) ); /////////////////////////////////////////////////////////////////////// // RENDERING glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Enable lighting glUniform1i( enable_shading_id, GL_TRUE ); // Terrain object_color = glm::vec3( 0.8f, 0.8f, 0.9f ); glUniform3fv( object_color_id, 1, &object_color[ 0 ] ); glm::mat4 mvp = camera.getMVP( terrain.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); terrain.render(); // Clanger 1 object_color = glm::vec3( 1.0f, 0.6f, 0.6f ); glUniform3fv( object_color_id, 1, &object_color[ 0 ] ); mvp = camera.getMVP( clanger1.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); clanger1.render(); // Clanger 2 mvp = camera.getMVP( clanger2.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); clanger2.render(); // Clanger 3 mvp = camera.getMVP( clanger3.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); clanger3.render(); // Asteroid object_color = glm::vec3( 0.9f, 0.85f, 0.8f ); glUniform3fv( object_color_id, 1, &object_color[ 0 ] ); mvp = camera.getMVP( asteroid.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); asteroid.render(); // Hole 1 object_color = glm::vec3( 0.6f, 0.6f, 0.6f ); glUniform3fv( object_color_id, 1, &object_color[ 0 ] ); mvp = camera.getMVP( hole1.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); hole1.render(); // Hole 2 mvp = camera.getMVP( hole2.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); hole2.render(); // Lid 1 mvp = camera.getMVP( lid1.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); lid1.render(); // Lid 2 mvp = camera.getMVP( lid2.getModel() ); glUniformMatrix4fv( mvp_id, 1, GL_FALSE, &mvp[ 0 ][ 0 ] ); lid2.render(); glfwSwapBuffers( window ); } // Clean up glfwDestroyWindow( window ); glfwTerminate(); return 0; } <file_sep>/utils/objloader.cpp #include <cstdio> #include <cstdlib> #include <fstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <sstream> #include <stdio.h> #include <string> #include "objloader.hpp" using namespace std; /* * Splits a string on a given delimiter, and puts the parts * into the supplied elements vector. */ vector<string> &split( const string &str, char delimiter, vector<string> &elements ) { elements.clear(); stringstream ss( str ); string item; while( getline( ss, item, delimiter ) ) elements.push_back( item ); return elements; } /* * Splits a string on a given delimiter, and returns a * new vector containing the separate parts. */ vector<string> split( const string &str, char delimiter ) { vector<string> elements; split( str, delimiter, elements ); return elements; } /* * A simple, rudimentary OBJ file loader. Returns true if successful. * Loads vertex, normal and texture coordinates from the file into the given vectors. * Adopted from http://www.opengl-tutorial.org/beginners-tutorials/tutorial-7-model-loading */ bool loadObj( string path, vector<glm::vec3> &vertices, vector<glm::vec3> &normals ) { vector<glm::vec3> temp_vertices; vector<glm::vec3> temp_normals; vector<unsigned int> vert_indices; vector<unsigned int> norm_indices; fstream file; file.open( path.c_str() ); if( file.is_open() ) { // Stores the current line of the file string line; // Stores the parts of a line when splitting vector<string> parts; // Stores the parts of a face index when splitting vector<string> faceparts; std::cout << "Loading " << path << "..." << std::endl; while( file.good() ) { getline( file, line ); // Ignore Comment size_t match = line.find( "#", 0 ); if( match != string::npos ) continue; // Ignore materials match = line.find( "mtllib", 0 ); if( match != string::npos ) continue; match = line.find( "usemtl", 0 ); if( match != string::npos ) continue; // Ignore Object match = line.find( "o", 0 ); if( match != string::npos ) continue; // Ignore Texture Coordinates match = line.find( "vt", 0 ); if( match != string::npos ) continue; // Normal Coordinates match = line.find( "vn", 0 ); if( match != string::npos ) { split( line, ' ', parts ); double x = atof( parts[ 1 ].c_str() ); double y = atof( parts[ 2 ].c_str() ); double z = atof( parts[ 3 ].c_str() ); temp_normals.push_back( glm::vec3( x, y, z ) ); continue; } // Vertex Coordinates match = line.find( "v", 0 ); if( match != string::npos ) { split( line, ' ', parts ); double x = atof( parts[ 1 ].c_str() ); double y = atof( parts[ 2 ].c_str() ); double z = atof( parts[ 3 ].c_str() ); temp_vertices.push_back( glm::vec3( x, y, z ) ); continue; } // Face Indices match = line.find( "f", 0 ); if( match != string::npos ) { split( line, ' ', parts ); for( int i = 1; i < parts.size(); i++ ) { split( parts[ i ], '/', faceparts ); if( faceparts.size() != 3 ) { fprintf( stderr, "Invalid face declaration: %s", parts[ i ].c_str() ); return false; } vert_indices.push_back( atoi( faceparts[ 0 ].c_str() ) ); norm_indices.push_back( atoi( faceparts[ 2 ].c_str() ) ); } } continue; } } for( int i = 0; i < vert_indices.size(); i++ ) { int vert_index = vert_indices[ i ]; glm::vec3 vertex = temp_vertices[ vert_index - 1 ]; vertices.push_back( vertex ); int norm_index = norm_indices[ i ]; glm::vec3 norm = temp_normals[ norm_index - 1 ]; normals.push_back( norm ); } return true; } <file_sep>/Model.hpp #ifndef MODEL_HPP_INCLUDED #define MODEL_HPP_INCLUDED #include <glm/glm.hpp> #include <string> #include <vector> using namespace std; class Model { private: GLuint vao[ 1 ]; GLuint vbo[ 2 ]; string model_path; vector<glm::vec3> vertices; vector<glm::vec3> normals; glm::mat4 model; public: Model( string file ); void load(); void rotate( float amount, glm::vec3 axes ); void scale( glm::vec3 amounts ); void translate( glm::vec3 amounts ); void render(); glm::mat4 getModel(); }; #endif // MODEL_HPP_INCLUDED <file_sep>/Camera.cpp #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include "Camera.hpp" Camera::Camera() { reset(); } void Camera::adjustElevation( float amount ) { if( position.y + amount >= 0.5 ) { position = glm::vec3( position.x, position.y + amount, position.z ); view = glm::lookAt( position, position + direction, glm::vec3( 0.0f, 1.0f, 0.0f ) ); } else { position = glm::vec3( position.x, 0.5, position.z ); view = glm::lookAt( position, position + direction, glm::vec3( 0.0f, 1.0f, 0.0f ) ); } } void Camera::adjustSpeed( float amount ) { speed += amount; //if( speed < 0.0f ) // speed = 0.0f; } void Camera::move() { //if( speed > 0.0f ) //{ position = position + glm::vec3( direction.x * speed, direction.y * speed, direction.z * speed ); view = glm::lookAt( position, position + direction, glm::vec3( 0.0f, 1.0f, 0.0f ) ); //} } void Camera::stop() { speed = 0.0f; } void Camera::pitch( float angle ) { direction = glm::rotateX( direction, angle ); view = glm::lookAt( position, position + direction, glm::vec3( 0.0f, 1.0f, 0.0f ) ); } void Camera::yaw( float angle ) { direction = glm::rotateY( direction, angle ); view = glm::lookAt( position, position + direction, glm::vec3( 0.0f, 1.0f, 0.0f ) ); } glm::vec3 Camera::getPosition() { return position; } void Camera::setPosition( glm::vec3 pos ) { position = pos; } glm::vec3 Camera::getDirection() { return direction; } void Camera::setDirection( glm::vec3 dir ) { direction = dir; } glm::mat4 Camera::getMVP( glm::mat4 model ) { return projection * view * model; } void Camera::status() { fprintf( stdout, "Position: ( %f, %f, %f )\n", position.x, position.y, position.z ); fprintf( stdout, "Looking at: ( %f, %f, %f )\n", direction.x, direction.y, direction.z ); } void Camera::reset() { position = glm::vec3( 0.0f, 2.0f, 10.0f ); direction = glm::vec3( 0.0f, 1.0f, -10.0f ); speed = 0.0f; // perspective( field of view, aspect ratio, near clip, far clip ) projection = glm::perspective( 45.0f, 4.0f / 3.0f, 0.1f, 500.0f ); // lookAt( camera position, target position, up direction ) view = glm::lookAt( position, position + direction, glm::vec3( 0.0f, 1.0f, 0.0f ) ); } <file_sep>/Model.cpp #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glimg/glimg.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/string_cast.hpp> #include <iostream> #include <memory> #include <stdio.h> #include "Model.hpp" #include "utils/objloader.hpp" Model::Model( string file ) { model_path = file; model = glm::mat4( 1.0f ); } void Model::load() { loadObj( model_path, vertices, normals ); glGenBuffers( 2, vbo ); glGenVertexArrays( 1, vao ); glBindBuffer( GL_ARRAY_BUFFER, vbo[ 0 ] ); glBufferData( GL_ARRAY_BUFFER, vertices.size() * sizeof( glm::vec3 ), &vertices[ 0 ], GL_STATIC_DRAW ); glBindVertexArray( vao[ 0 ] ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof( glm::vec3 ), (const GLvoid*) 0 ); glBindBuffer( GL_ARRAY_BUFFER, vbo[ 1 ] ); glBufferData( GL_ARRAY_BUFFER, normals.size() * sizeof( glm::vec3 ), &normals[ 0 ], GL_STATIC_DRAW ); glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, sizeof( glm::vec3 ), (const GLvoid*) 0 ); glEnableVertexAttribArray( 1 ); } void Model::rotate( float amount, glm::vec3 axes ) { model = glm::rotate( model, amount, axes ); } void Model::scale( glm::vec3 amounts ) { model = glm::scale( model, amounts ); } void Model::translate( glm::vec3 amounts ) { model = glm::translate( model, amounts ); } void Model::render() { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glBindVertexArray( vao[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vbo[ 0 ] ); glDrawArrays( GL_TRIANGLES, 0, vertices.size() ); } glm::mat4 Model::getModel() { return model; } <file_sep>/utils/filetobuffer.cpp #include "filetobuffer.hpp" #include <cstdio> #include <cstdlib> char* fileToBuffer( const char* filename ) { FILE* in = fopen( filename, "rb" ); if( in == NULL ) return NULL; int res_size = BUFSIZ; char* res = ( char* )std::malloc( res_size ); int nb_read_total = 0; while( !feof( in ) && !ferror( in ) ) { if( nb_read_total + BUFSIZ > res_size ) { if( res_size > 10 * 1024 * 1024 ) break; res_size = res_size * 2; res = ( char* )std::realloc( res, res_size ); } char* p_res = res + nb_read_total; nb_read_total += fread( p_res, 1, BUFSIZ, in ); } fclose( in ); res = ( char* )realloc( res, nb_read_total + 1 ); res[nb_read_total] = '\0'; return res; } <file_sep>/utils/objloader.hpp #ifndef OBJLOADER_HPP_INCLUDED #define OBJLOADER_HPP_INCLUDED #include <glm/glm.hpp> #include <vector> using namespace std; bool loadObj( string path, std::vector<glm::vec3> &vertices, std::vector<glm::vec3> &normals ); #endif // OBJLOADER_HPP_INCLUDED
761e554815a5f3268a736747ee875c6ead78e677
[ "Markdown", "C++" ]
12
C++
daviesjamie/comp3004-cw3
52ea577745c8b4d4ffc48fe7f602ee888d7a96ef
7419194c9269dde287db2535b0cab88f2ab8a131
refs/heads/master
<repo_name>PhoenixFate/angular5<file_sep>/angularViewChild/src/app/components/product/product.component.ts import { Component, OnInit ,ViewChild} from '@angular/core'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { @ViewChild('cart') cart;//定义子组件, 和#name对应起来 constructor() { } ngOnInit() { } getChildData(){ //通过cart执行子组件的方法 // this.cart.run(); //通过cart获取子组件的数据 alert(this.cart.msg); this.cart.name='我是父组件改变子组件后的name'; } } <file_sep>/angularRouting/src/app/app-routing.module.ts //新建项目时 ng new projectName --routing //路由配置文件 import { NgModule, Component } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; //引入组件 import {HomeComponent} from './components/home/home.component'; import {NewsComponent} from './components/news/news.component'; import {UserComponent} from './components/user/user.component'; //配置路由 const routes: Routes = [ { path:'home', component:HomeComponent }, { path:'news', component:NewsComponent }, { path:'user', component:UserComponent }, //默认跳转的路由 { path:'', redirectTo:'home', pathMatch:'full' }, //匹配不到路由的时候加载的组件 { path:'**',//任意的路由 // component:NewsComponent redirectTo:'home', } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/angularHttp/src/app/components/news/news.component.ts import { Component, OnInit } from '@angular/core'; import {Http,Jsonp,Headers} from '@angular/http';//引入http,jsonp //引入rxjs // import {Observable} from 'rxjs'; // import 'rxjs/Rx'; // import { map } from"rxjs/operators"; // import 'rxjs/add/operator/map'; // import 'rxjs/Rx' // // import {Observable} from 'rxjs/Observable'; // import 'rxjs/add/operator/map'; import {Observable} from 'rxjs'; import {map} from 'rxjs/operators'; @Component({ selector: 'app-news', templateUrl: './news.component.html', styleUrls: ['./news.component.css'] }) export class NewsComponent implements OnInit { private headers=new Headers({'Content-Type':'application/json;charset=utf-8'}); public list:any=[]; constructor(private http:Http,private jsonp:Jsonp) { } ngOnInit() { } requestData(){ var that=this; console.log("begin requesting data"); var url="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1"; console.log(url); this.http.get(url).subscribe(function(data){ console.log(data); console.log("success"); that.list=JSON.parse(data["_body"]); console.log(that.list); },function(err){ console.log("failure"); console.log(err); }); } requestJsonpData(){ var that=this; console.log("begin jsonp requesting data"); var url="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK"; console.log(url); this.jsonp.get(url).subscribe(function(data){ console.log("success"); console.log(data); that.list=data["_body"]; },function(err){ console.log("failure"); console.log(err); }) } postData(){ //headers定义请求头 //1.引入headers,import {Http,Jsonp,Headers} from '@angular/http';//引入http,jsonp //2.实例化headers private headers=new Headers({'Content-Type':'application/json'}); //3.post提交数据 var url="http://127.0.0.1:3000/dologin"; this.http.post(url, JSON.stringify({username:"张三"}), {headers:this.headers}).subscribe(function(data){ console.log("success"); console.log(data); },function(err){ console.log("failure"); console.log(err); }) } requestDataRxjs(){ var that=this; console.log("begin requesting data using rxjs"); var url="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1"; this.http.get(url).pipe( map(res=> res.json()) ).subscribe(function(data){ console.log("success"); console.log(data); that.list=data; },function(err){ console.log("failure"); console.log(err); }); } requestJsonpDataRxjs(){ var that=this; console.log("begin jsonp requesting data"); var url="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK"; console.log(url); this.jsonp.get(url).pipe( map(res=>res.json()) ).subscribe(function(data){ console.log("success"); console.log(data); that.list=data; },function(err){ console.log("failure"); console.log(err); }) } } <file_sep>/angularInputOutput/src/app/components/home/home.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { public msg="home组件"; public list; constructor() { } ngOnInit() { } run(){ console.log("home run function"); } getDataFromChild(childData){ alert(childData); } runParent(event){ console.log("run parent"); console.log(event); this.list=event; } } <file_sep>/angularToDoList/src/app/components/todolist/todolist.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-todolist', templateUrl: './todolist.component.html', styleUrls: ['./todolist.component.css'] }) export class TodolistComponent implements OnInit { public username:any; public list=[]; constructor() { this.username=''; } ngOnInit() { } addData(e){ // alert(this.username);//双向数据绑定,获取文本框的值 if(e.keyCode==13){ var obj={ "username":this.username, "status":0 } this.list.push(obj); this.username=''; } // console.log(e); } deleteData(key){ // alert(key); this.list.splice(key,1); } changeData(key){ this.list[key].status=1; } } <file_sep>/angularInputOutput/src/app/components/footer/footer.component.ts import { Component, OnInit,Input,Output,EventEmitter} from '@angular/core'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.css'] }) export class FooterComponent implements OnInit { @Input() msg:string; @Input() run:Function;//接收父组件传递过来的run方法 @Input() getDataFromChild:any; public list=['111','222','333']; //EventEmitter实现子组件给父组件传值 @Output() private outer1=new EventEmitter<any>(); constructor() { } public childMsg="这是子组件的数据"; ngOnInit() { } footerRun(){ console.log("footerRun"); this.run(); } sendToParent(){//子组件自己的方法 this.getDataFromChild(this.childMsg);//子组件调用父组件的方法并传值 } sendDataByEventEmitter(){ console.log("sendDataByEventEmitter"); this.outer1.emit(this.list); } } <file_sep>/angularService/src/app/app.module.ts // 这个根模块会告诉angular如何组装该应用 //引入模块 import { BrowserModule } from '@angular/platform-browser';//browser模块 import{FormsModule}from'@angular/forms'; import { NgModule } from '@angular/core';//angular核心模块 import { AppComponent } from './app.component';//引入自定义组件 import { TodolistComponent } from './components/todolist/todolist.component'; import { StorageService } from './services/storage.service';//引入服务 //@NgModule装饰器将angular标记为Angular模块类(也叫NgModule类) //@NgModule接收一个元数据对象,告诉angular如何编辑和启动 @NgModule({ declarations: [//引入当前项目运行的组件 自定义组件都需要引入并在这个里面配置 AppComponent,TodolistComponent ], imports: [//当前项目依赖哪些模块 BrowserModule,FormsModule ], providers: [StorageService],//定义的服务,放在这个里面 bootstrap: [AppComponent]//默认启动的组件 }) export class AppModule { } <file_sep>/angularRoutingManual/src/app/app-routing.module.ts import { NgModule, Component } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {HomeComponent} from './components/home/home.component'; import {NewsComponent} from './components/news/news.component'; import {NewsContentComponent} from './components/news-content/news-content.component'; //配置路由 const routes: Routes = [ { path:'home', component:HomeComponent }, { path:'news', component:NewsComponent }, { path:'newsContent/:id', //路由传值(动态路由) component:NewsContentComponent }, //默认跳转的路由 { path:'', redirectTo:'home', pathMatch:'full' }, //匹配不到路由的时候加载的组件 { path:'**',//任意的路由 // component:NewsComponent redirectTo:'home', } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/README.md # angular 5 <file_sep>/angularRoutingManual/src/app/components/news-content/news-content.component.ts import { Component, OnInit } from '@angular/core'; //引入Router,ActivatedRoute,Params import {Router,ActivatedRoute,Params} from '@angular/router'; @Component({ selector: 'app-news-content', templateUrl: './news-content.component.html', styleUrls: ['./news-content.component.css'] }) export class NewsContentComponent implements OnInit { constructor(private route:ActivatedRoute) { } ngOnInit() { console.log(this.route.params); console.log(this.route.params['_value'].id); //获取动态路由的传值 this.route.params.subscribe(function(data){ console.log(data); console.log(data.id); }) } } <file_sep>/angularService/src/app/components/todolist/todolist.component.ts import { Component, OnInit } from '@angular/core'; import { StorageService } from '../../services/storage.service';//引入自定义服务 @Component({ selector: 'app-todolist', templateUrl: './todolist.component.html', styleUrls: ['./todolist.component.css'] }) export class TodolistComponent implements OnInit { //使用storageservice服务 //private storage=new StorageService();//可以这样引入和使用服务,但官方不推荐这样的方法 public username: any; public list = []; //官方推荐的引用和使用服务的方式:依赖注入服务 constructor(private storage: StorageService) { console.log("consturctor"); this.username = ''; console.log(this.storage); this.storage.setItem('userInfo', 'zhangsan'); // alert(storage.getItem('userInfo')); } ngOnInit() { console.log("ngOnInit"); //每次刷新,获取storage的值 var todolist=this.storage.getItem("todolist"); if(todolist){ this.list=todolist; } } addData(e) { //1.从storage获取todolist数据 //2.如果有数据,拿到这个数据然后把这个数据和新数据拼接,重新写入 //3.如果没有数据,直接给storage写入数据 // alert(this.username);//双向数据绑定,获取文本框的值 if (e.keyCode == 13) { var obj = { "username": this.username, "status": 0 } var todolist = this.storage.getItem("todolist"); //如果有数据,拿到这个数据,然后把新数据和这个storage数据拼接,并重新写入。 if (todolist) { todolist.push(obj); this.storage.setItem("todolist",todolist); }else{ //如果没有数据,直接给storage写入数据 var arr=[]; arr.push(obj); this.storage.setItem("todolist",arr); } this.list.push(obj); this.username = ''; } // console.log(e); } deleteData(key) { // alert(key); this.list.splice(key, 1); this.storage.setItem("todolist",this.list); } changeData(key,status) { this.list[key].status = status; this.storage.setItem("todolist",this.list); } }
2b10c33ca3dc868e26659d27001e839ae01f199c
[ "Markdown", "TypeScript" ]
11
TypeScript
PhoenixFate/angular5
14b12f2996a333966996f76300edb04213dfb93f
75434372e775c6da58ca24bd75927dbabc3a4570
refs/heads/master
<file_sep><?php namespace BookStack\Http\Controllers; use Activity; use BookStack\Entities\EntityRepo; use Illuminate\Http\Response; use Views; class ApiController extends Controller { protected $entityRepo; /** * HomeController constructor. * @param EntityRepo $entityRepo */ public function __construct(EntityRepo $entityRepo) { $this->entityRepo = $entityRepo; parent::__construct(); } /** * Display the homepage. * @return Response */ public function latestPages($apikey) { $latest = array(); $apikeyConfig = env('API_KEY', ''); if(!$apikeyConfig || $apikeyConfig != $apikey) { return response()->json([ 'name' => 'error' ]); } $recentlyUpdatedPages = $this->entityRepo->getRecentlyUpdated('page', 10); $books = $this->entityRepo->getAll('book'); foreach($recentlyUpdatedPages as $page) { $pageInfo = array( 'name' => $page->name, 'slug' => $page->slug, 'updated_at' => $page->updated_at ); foreach($books as $book) { if($book->id == $page->book_id) { $pageInfo['book_slug'] = $book->slug; } } array_push($latest, $pageInfo); } return response()->json($latest); } }
1b6a938e7737df4c7c9b787d36d5b1714041214b
[ "PHP" ]
1
PHP
enrollmentresources/BookStack
9ac4f8611d2690ed8033d2b9214c7f7653af39f1
d89b03b58595530cc300bbc28d9bb1b3f3803338
refs/heads/master
<repo_name>vnseattle/talktome<file_sep>/server/clients.js /******************************************************* * Clients control ******************************************************/ class Clients { constructor() { this.clientList = []; this.clientWaitList = []; this.len = 0; } add(id){ this.clientList.push(id); this.len++; } remove(id){ this.clientList.splice(this.clientList.indexOf(id), 1 ); this.len--; } get(id){ return this.clientList.find(client => client.id === id); } addWaitList(id){ this.clientWaitList.push(id); } setPartner(id,partner){ if(id){ this.get(id).partner = partner; } } stopFinding(id){ this.clientWaitList.splice(this.clientWaitList.indexOf(id), 1 ); let partner = this.get(id).partner; this.setPartner(partner,null); this.setPartner(id,null); } findPartner(id){ if(this.clientWaitList.length === 0){ this.clientWaitList.push(id); return 0; // not yet }else{ // remove let partner = this.clientWaitList.pop(); // set partner this.setPartner(id,partner); this.setPartner(partner,id); // match //console.log(partner," : ",id); return 1; } } getPartner(id){ var myClient = this.clientList.find(client => client.id === id); if(myClient){ //console.log(myClient); return myClient.partner; } } getAll(){ return this.clientList; } getSize(){ return this.len; } } module.exports = Clients <file_sep>/server/index.js /******************************************************* * Author: <NAME> * Setup the server * Using express, socket.io ******************************************************/ const Clients = require('./clients.js') var express = require("express"); var app = express(); var server = require("http").Server(app); var io = require("socket.io")(server); server.listen(1000); /******************************************************* * Clients management ******************************************************/ let clients = new Clients; /******************************************************* * Start listening ******************************************************/ io.on("connection", onConnect); /******************************************************* * A client connects to the server * @param {socket} socket ******************************************************/ function onConnect(socket){ console.log("Someone is connected"+socket.id); // Catch disconnect event socket.on("disconnect", onDisconnect); // Add client to client list var client = { id: socket.id, partner: null } clients.add(client); // Notify to all clients io.sockets.emit("size",clients.getSize()); socket.emit("id",socket.id); socket.on("find", ()=>{ var result = clients.findPartner(socket.id); if(result == 1){ io.to(clients.getPartner(socket.id)).emit('msg', 'Tim duoc roi' ); io.to(socket.id).emit('msg', 'Tim duoc roi' ); } //console.log("find : "+socket.id); //console.log(clients.getAll()); }); socket.on("stop", ()=>{ clients.stopFinding(socket.id); console.log("stop : "+socket.id); console.log(clients.getAll()); }); socket.on("send", (msg)=>{ console.log(socket.id+": ",msg," to "+clients.getPartner(socket.id)); io.to(clients.getPartner(socket.id)).emit('msg', msg ); io.to(socket.id).emit('msg', msg ); }) } /******************************************************* * A client disconnects to the server * @param {socket} socket ******************************************************/ function onDisconnect(socket){ console.log("Someone disconnect") // Remove the client to client list clients.remove(socket.id); // Notify to all clients io.sockets.emit("size",clients.getSize()); } /** * * Users.push(socket.id); io.sockets.emit("yourID",Users); socket.on("client-send-username", (data) => { if(Users.indexOf(data)>=0){ socket.emit("register-fail"); }else{ socket.Username = data; Users.push(data); socket.emit("register-ok",data); io.sockets.emit("send-all-users", Users); } }); */
0f346d488c52bf2269e74e78b1585d85b90b760e
[ "JavaScript" ]
2
JavaScript
vnseattle/talktome
5c7df3750e929d054793e52f3c45cf513a15d07b
0c27df16aefa185dc67e3d7653710b96fc83524b
refs/heads/master
<repo_name>ramarajugunturu/AAD-POC<file_sep>/Podfile # Uncomment the next line to define a global platform for your project platform :ios, '11.0' target '7Eleven' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for 7Eleven pod 'ADALiOS' #pod 'ADALiOS', :git => 'https://github.com/AzureAD/azure-activedirectory-library-for-objc.git', :branch=> 'convergence' pod 'NXOAuth2Client' pod 'Alamofire' target '7ElevenTests' do inherit! :search_paths # Pods for testing end target '7ElevenUITests' do inherit! :search_paths # Pods for testing end end
f6d31bae685e77d44ba83eb4848e13bae65be868
[ "Ruby" ]
1
Ruby
ramarajugunturu/AAD-POC
216ae674e4c25b106d07454eb12282aa185ce355
a8dde7575aef946dd67aee32c7b022dcddfd0b5a
refs/heads/master
<file_sep>exports.login = (req, res) => { console.log(req.body); res.send("form submitted"); }<file_sep><body> <?php $connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server $db = mysql_select_db("shopping cart", $connection); // Selecting Database from Server if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL $ID = $_POST['ID']; $ITEM = $_POST['ITEM']; $PRICE= $_POST['PRICE']; $QUANTITY = $_POST['$QUANTITY']; if($ITEM !='1'||$ !=''){ //Insert Query of SQL $query = mysql_query("insert into items(id, Item, Quantity, price ) values ('$ID', '$ITEM', '$PRICE', '$QUANTITY')"); echo "<br/><br/><span>Data Inserted successfully...!!</span>"; } else{ echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>"; } } mysql_close($connection); // Closing Connection with Server ?> </body> <file_sep>var http = require('http'); var fs = require('fs'); var express = require('express'); var app = express(); var mysql = require("mysql"); var path = require('path'); var url = require('url') const { login } = require('./controller/auth'); var db = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'shopping cart', }) function onRequest(req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); fs.readFile('index.html', function(error, data) { if (error) { res.writehead(404); res.write('file not found'); } else { res.write(data); } res.end(); }); } db.connect((error) => { if (error) { console.log(error) } else { console.log("mysql is connected") } }) http.createServer(onRequest).listen(8000);<file_sep># shopping-cart A basic shopping cart Framework- express, Languages-HTML,MY-sql,PHP,Node js,Javascript. Php for storing the data through submit button tp phpmyadmin database. Javascript and Html to create the shopping cart and functionalities of add to cart, remove item . use my sql to connect the database so to fetch data from cart to the localhostDatabase.
e96c4088aa37d8de916cd9a3b317092ab141c759
[ "JavaScript", "Markdown", "PHP" ]
4
JavaScript
Rituparnam-386/shopping-cart
53ac7ed6a6e4050d29a7f6f1c82bca7a4fed77fb
b8274de69f34d887f9efc63806664a916b2d47e9
refs/heads/master
<file_sep>import { test } from "tap"; import Fastify from "fastify"; import fastifyBcrypt from "../index"; const pwdHash = "$2b$10$8Es/etqSEcWH4SQsxQzKdO8eobWvi70PXGyr48v.Ia21MBcOA76i2"; const buildApp = async (t: Tap.Test) => { const fastify = Fastify({ logger: { level: "error", }, }); t.teardown(() => { fastify.close(); }); return fastify; }; test("fastify-bcrypt-plugin", async (t) => { t.test("without options", async (t) => { t.plan(1); const fastify = await buildApp(t); try { await fastify.register(fastifyBcrypt); t.ok("bcrypt" in fastify, "should not throw any error"); } catch (err) { console.log(err); t.error(err, "should not throw any error"); } }); t.test('with "saltWorkFactor" option', async (t) => { t.plan(1); const fastify = await buildApp(t); try { await fastify.register(fastifyBcrypt, { saltOrRounds: 8, }); t.ok("bcrypt" in fastify, "should not throw any error"); } catch (err) { console.log(err); t.error(err, "should not throw any error"); } }); t.test("hash", async (t) => { t.plan(2); const fastify = await buildApp(t); try { await fastify.register(fastifyBcrypt); const hash = await fastify.bcrypt.hash("password"); t.equal(typeof hash, "string", "should generate a hash"); t.not(hash, "password", "should generate a hash"); } catch (err) { console.log(err); t.error(err, "should not throw any error"); } }); t.test("compare two not matching claims", async (t) => { t.plan(1); const fastify = await buildApp(t); try { await fastify.register(fastifyBcrypt); const match = await fastify.bcrypt.compare("<PASSWORD>", <PASSWORD>); t.equal(match, false, "should return false"); } catch (err) { console.log(err); t.error(err, "should not throw any error"); } }); t.test("compare two matching claims", async (t) => { t.plan(1); const fastify = await buildApp(t); try { await fastify.register(fastifyBcrypt); const match = await fastify.bcrypt.compare("password", <PASSWORD>); t.equal(match, true, "should return true"); } catch (err) { console.log(err); t.error(err, "should not throw any error"); } }); }); <file_sep># fastify-bcrypt-plugin [![Version](https://img.shields.io/npm/v/fastify-bcrypt-plugin.svg)](https://www.npmjs.com/package/fastify-bcrypt-plugin) A Bcrypt hash generator & checker for Fastify ## Installation ```bash yarn add fastify-bcrypt-plugin or npm install fastify-bcrypt-plugin ``` ## Usage Register plugin ```js import fastifyBcrypt from "fastify-bcrypt-plugin"; fastify.register(fastifyBcrypt); ``` If you use with TypeScript , you have to give this type to avoid error ```js import Fastify, { FastifyInstance } from "fastify"; const fastify: FastifyInstance = Fastify(); ``` If you want to change the salt work factor ```js fastify.register(fastifyBcrypt, { saltOrRounds: 15 }); // The salt work factor for the bcrypt algorithm. The default value is 10. ``` Use with fastify decorate ```js fastify.get("/", async (request, reply) => { const hashedPassword = await fastify.bcrypt.hash(request.body.password); const isPasswordCompared = await fastify.bcrypt.compare( request.body.password, hashedPassword ); return { hashedPassword, isPasswordCompared }; }); ``` Use with request decorate ```js fastify.get("/", async (request, reply) => { const hashedPassword = await request.bcrypt.hash(request.body.password); const isPasswordCompared = await request.bcrypt.compare( request.body.password, hashedPassword ); return { hashedPassword, isPasswordCompared }; }); ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [MIT](https://choosealicense.com/licenses/mit/) <file_sep>import { FastifyPluginCallback } from "fastify"; import fp from "fastify-plugin"; import bcrypt from "bcrypt"; export type BcryptOptions = { saltOrRounds?: string | number }; type BcryptPlugin = { hash: { (data: string | Buffer): Promise<string>; ( data: string | Buffer, callback: (err: Error | undefined, encrypted: string) => any ): void; }; compare: typeof bcrypt.compare; }; const bcryptPlugin: FastifyPluginCallback<Partial<BcryptOptions>> = ( fastify, options, done ) => { if (fastify.bcrypt) return done(new Error("fastify-bcrypt-plugin has been defined before")); const hash: BcryptPlugin["hash"] = (data) => bcrypt.hash(data, options.saltOrRounds || 10); const compare: BcryptPlugin["compare"] = (data, encrypted) => bcrypt.compare(data, encrypted); fastify .decorate("bcrypt", { hash, compare }) .decorateRequest("bcrypt", { hash, compare }); done(); }; const fastifyBcrypt = fp(bcryptPlugin, { fastify: "3.x", name: "fastify-bcrypt,plugin", }); export default fastifyBcrypt; declare module "fastify" { interface FastifyRequest { bcrypt: BcryptPlugin; } interface FastifyInstance { bcrypt: BcryptPlugin; } }
eb4a4cbc4a1bd3da510ba00b659e165c10f2efee
[ "Markdown", "TypeScript" ]
3
TypeScript
balcieren/fastify-bcrypt-plugin
b5041585823c867dece70da52d7edd14a461ddd8
ecaee33a99ddab2883f8413173094209fab31107
HEAD
<repo_name>KyleMit/otIntJS<file_sep>/README.md Answering Interview Questions ======= OpenTempo interview learning JavaScript I'm supposed to answer some interview questions with JavaScript. Trying to use best practices by learning to use GitHub for doing this. Also I've been going crazy doing stuff locally. Haha. If you want to see what I've done to answer the question, check out * [The HTML Code](https://github.com/KyleMit/otIntJS/blob/gh-pages/just_array_please.html) * [Preview HTML](http://kylemit.github.io/otIntJS/just_array_please.html) <file_sep>/scripts/ArrayFuntions.js  function getArrayWithNumberOfInstances(myArray) { var numberOfInstancesArray = []; // find min / max values var minValue = Math.min.apply(null, myArray); var maxValue = Math.max.apply(null, myArray); // go though lowest to highest number for (var i = minValue; i <= maxValue; i++) { var numberOfInstances = 0; // get number of instances for (var j = 0; j < myArray.length; j++) { if (myArray[j] === i) { numberOfInstances += 1; } } // add number and count to array numberOfInstancesArray.push({ number: i, instances: numberOfInstances }); } return numberOfInstancesArray; }; function buildPrintMyArray(myArray) { // create elements var list = document.createElement('ul'); list.className = "unstyled"; // build list for (var i = 0; i < myArray.length; i++) { var listItem = document.createElement("li"); listItem.innerHTML = myArray[i]; list.appendChild(listItem); } return list; } function buildPrintArray(numberOfInstancesArray) { // create elements var howTable = document.createElement("table"); var tbody = document.createElement("tbody"); var thead = document.createElement("thead"); var rHead = document.createElement("tr"); var thL = document.createElement("th"); var thR = document.createElement("th"); // build table head thL.textContent = "Number"; thR.textContent = "How Many"; rHead.appendChild(thL); rHead.appendChild(thR); thead.appendChild(rHead); howTable.appendChild(thead); // build table body for (var i = 0; i < numberOfInstancesArray.length; i++) { var row = document.createElement("tr"); var cellL = document.createElement("td"); var cellR = document.createElement("td"); // build first column cellL.textContent = numberOfInstancesArray[i].number; row.appendChild(cellL); // buid second column cellR.textContent = numberOfInstancesArray[i].instances; row.appendChild(cellR); // add row to table body tbody.appendChild(row); } howTable.appendChild(tbody); return howTable; }; function getNumberOfEvenElementsInArray(numberOfInstancesArray) { var numEven = 0; for (var i = 0; i < numberOfInstancesArray.length; i++) { if ((numberOfInstancesArray[i].number % 2) === 0) { numEven += numberOfInstancesArray[i].instances; } } return numEven; }; function getNumberOfOddElementsInArray(numberOfInstancesArray) { var numOdd = 0; for (var i = 0; i < numberOfInstancesArray.length; i++) { if ((numberOfInstancesArray[i].number) % 2 === 1) { numOdd += numberOfInstancesArray[i].instances; } } return numOdd; }; function getNumberWithMostInstances(numberOfInstancesArray) { var currentValue, currentNumber, maxValue, maxNumber; for (var i = 0; i < numberOfInstancesArray.length; i++) { currentNumber = numberOfInstancesArray[i].number; currentValue = numberOfInstancesArray[i].instances; // get first instance or most value if (typeof maxValue === 'undefined' || currentValue > maxValue) { maxValue = currentValue; maxNumber = currentNumber; } } return maxNumber; }; function getNumberWithFewestInstances(numberOfInstancesArray) { var currentValue, currentNumber, minValue, minNumber; for (var i = 0; i < numberOfInstancesArray.length; i++) { currentNumber = numberOfInstancesArray[i].number; currentValue = numberOfInstancesArray[i].instances; // get first or least value if (typeof minValue === 'undefined' || currentValue < minValue) { minValue = currentValue; minNumber = currentNumber; } } return minNumber; }; <file_sep>/scripts/just_array_please_script.js window.onload = function () { var myArray = [1, 1, 3, 3, 3, 2, 5]; // build array with count of instances var numberOfInstancesArray = getArrayWithNumberOfInstances(myArray); // update DOM document.getElementById("arrayTableContainer").appendChild(buildPrintMyArray(myArray)); document.getElementById("howTableContainer").appendChild(buildPrintArray(numberOfInstancesArray)); document.getElementById("evens").innerHTML = getNumberOfEvenElementsInArray(numberOfInstancesArray); document.getElementById("odds").innerHTML = getNumberOfOddElementsInArray(numberOfInstancesArray); document.getElementById("most").innerHTML = getNumberWithMostInstances(numberOfInstancesArray); document.getElementById("few").innerHTML = getNumberWithFewestInstances(numberOfInstancesArray); } <file_sep>/scripts/array_practice.js // add listeners on page load window.onload = function () { document.getElementById("NumberOfRandomElements").addEventListener("keyup", GenerateNumbers); document.getElementById("NumberOfRandomElements").addEventListener("mouseup", GenerateNumbers); } function GenerateNumbers() { var myArray = getRandomArray(this.value); // build array with count of instances var numberOfInstancesArray = getArrayWithNumberOfInstances(myArray); // update DOM document.getElementById("arrayTableContainer").innerHTML = buildPrintMyArray(myArray).outerHTML; document.getElementById("numTable").innerHTML = buildPrintArray(numberOfInstancesArray).outerHTML; document.getElementById("even").innerHTML = getNumberOfEvenElementsInArray(numberOfInstancesArray); document.getElementById("odd").innerHTML = getNumberOfOddElementsInArray(numberOfInstancesArray); document.getElementById("most").innerHTML = getNumberWithMostInstances(numberOfInstancesArray); document.getElementById("few").innerHTML = getNumberWithFewestInstances(numberOfInstancesArray); }; function getRandomArray(numberOfRandom) { var myArray = []; numberOfRandom = Math.round(numberOfRandom); for (var i = 0; i < numberOfRandom; i++) { myArray[i] = getRandomNumber(); } return myArray; }; function getRandomNumber() { var max = 10; var rnd = Math.random() * max; var fin = Math.floor((rnd) + 1); return fin; }
6c6c2b98d69c97602811f18977a43952c0a7a0c0
[ "Markdown", "JavaScript" ]
4
Markdown
KyleMit/otIntJS
0a808bdadc6f664cde3f71d757a0df12e118637f
8eeb57b0af0f176fbfabe4adea119e3d6760b3ed
refs/heads/master
<file_sep>console.log("came to the feature-b");
92b4dc992d1795497b8928f2fc4b621f09aa676f
[ "JavaScript" ]
1
JavaScript
AjayKannuri/testing_proj
89f09ba6eee0ee28165dcf613d45c28ca0dc42ca
51ae0ce6648eb1e89c15ebfcfeb548d30a796aa2
refs/heads/main
<repo_name>SudheerBeerala/Flappy_Game<file_sep>/Flappy_Bird_Neat_AI.py import pygame import sys import os import random import neat pygame.font.init() # Global variables SCREEN_WIDTH = 600 SCREEN_HEIGHT = 700 FLOOR = 630 BIRD_X = 230 BIRD_Y = 350 STAT_FONT = pygame.font.SysFont("comicsans", 50) GRAVITY = 1 DRAW_LINES = False gen = 0 # Screen pygame.init() SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Flappy Bird") # Load Images # Background bg_img = pygame.image.load('resources/background-night.png').convert() bg_img = pygame.transform.scale(bg_img, (SCREEN_WIDTH, SCREEN_HEIGHT)) # Pipes pipe_image_bottom = pygame.image.load('resources/pipe-green.png').convert() pipe_image_top = pygame.transform.flip(pipe_image_bottom, False, True) # Bird bird_image_downflap = pygame.image.load('resources/redbird-downflap.png').convert_alpha() bird_image_midflap = pygame.image.load('resources/redbird-midflap.png').convert_alpha() bird_image_upflap = pygame.image.load('resources/redbird-upflap.png').convert_alpha() bird_images = [bird_image_downflap, bird_image_midflap, bird_image_upflap] base_img = pygame.image.load('resources/base.png').convert() class Bird: IMGS = bird_images ANIMATION_COUNT = 5 # for every ANIMATION_COUNT frames, next image is picked. def __init__(self, x, y): self.x = x self.y = y self.movement = 0 self.img_tick = 0 self.img = self.IMGS[0] self.rect = self.img.get_rect(center=(self.x, self.y)) def jump(self): self.movement = 0 self.movement -= 6 self.rect.centery += self.movement def move(self): self.movement += GRAVITY self.rect.centery += self.movement def rotate(self): self.img = pygame.transform.rotozoom(self.img, self.movement * 3, 1) def draw(self, screen): self.img_tick += 1 if self.img_tick <= self.ANIMATION_COUNT: self.img = self.IMGS[0] elif self.img_tick <= self.ANIMATION_COUNT * 2: self.img = self.IMGS[1] elif self.img_tick <= self.ANIMATION_COUNT * 3: self.img = self.IMGS[2] elif self.img_tick <= self.ANIMATION_COUNT * 4: self.img = self.IMGS[1] else: self.img = self.IMGS[0] self.img_tick = 0 self.rotate() screen.blit(self.img, self.rect) class Pipe(): GAP = 200 MOVE_COUNT = 5 def __init__(self, x): self.x = x self.height = 0 self.top = 0 self.bottom = 0 self.img_pipe_top = pipe_image_top self.img_pipe_bottom = pipe_image_bottom self.passed = False self.set_height() self.add_rect() def set_height(self): self.height = random.randrange(350, 480) self.top = self.height self.bottom = self.height - self.GAP def add_rect(self): self.rect_pipe_top = self.img_pipe_top.get_rect(midbottom=(self.x, self.bottom)) self.rect_pipe_bottom = self.img_pipe_bottom.get_rect(midtop=(self.x, self.top)) def move(self): self.rect_pipe_bottom.centerx -= self.MOVE_COUNT self.rect_pipe_top.centerx -= self.MOVE_COUNT def draw(self, screen): screen.blit(self.img_pipe_top, self.rect_pipe_top) screen.blit(self.img_pipe_bottom, self.rect_pipe_bottom) class Floor: MOVE_COUNT = 1 IMG = base_img WIDTH = base_img.get_width() THRESHOLD = 300 def __init__(self, y): self.y = y self.x = 0 self.img = self.IMG def move(self): self.x -= self.MOVE_COUNT if self.x <= self.THRESHOLD: self.x = 0 def draw(self, screen): screen.blit(self.img, (self.x, self.y)) screen.blit(self.img, (self.x + self.WIDTH, self.y)) def check_collission(pipe, bird): if pipe.rect_pipe_top.colliderect(bird.rect) or pipe.rect_pipe_bottom.colliderect(bird.rect): return True if bird.rect.top <= -50 or bird.rect.bottom >= FLOOR: return True return False def update_screen(screen, birds, pipes, floor, score, gen, pipe_ind): if gen == 0: gen = 1 screen.blit(bg_img, (0, 0)) for pipe in pipes: pipe.draw(screen) floor.draw(screen) for bird in birds: bird.draw(screen) if DRAW_LINES: try: pygame.draw.line(screen, (255, 0, 0), bird.rect.midtop, pipe.rect_pipe_top.midbottom, 5) pygame.draw.line(screen, (255, 0, 0), bird.rect.midbottom, pipe.rect_pipe_bottom.midtop, 5) except: pass score_label = STAT_FONT.render("Score: " + str(score), 1, (255, 255, 255)) screen.blit(score_label, (SCREEN_WIDTH - score_label.get_width() - 15, 10)) gen_label = STAT_FONT.render("Gens: " + str(gen - 1), 1, (255, 255, 255)) screen.blit(gen_label, (10, 10)) alive_label = STAT_FONT.render("Alive: " + str(len(birds)), 1, (255, 255, 255)) screen.blit(alive_label, (10, 50)) pygame.display.update() def evaluate_genomes(genomes, config): global SCREEN, gen gen += 1 nets = [] ge = [] birds = [] pipes = [] for genome_id, genome in genomes: genome.fitness = 0 net = neat.nn.FeedForwardNetwork.create(genome, config) nets.append(net) birds.append(Bird(BIRD_X, BIRD_Y)) ge.append(genome) pipes.append(Pipe(700)) floor = Floor(FLOOR) score = 0 clock = pygame.time.Clock() running = True while running and len(birds): clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() sys.exit() pipe_ind = 0 if len(pipes) > 1 and birds[0].rect.left > pipes[0].rect_pipe_bottom.right: pipe_ind = 1 for x, bird in enumerate(birds): ge[x].fitness += 0.1 bird.move() output = nets[x].activate((bird.rect.centery, abs(bird.rect.centery - pipes[pipe_ind].rect_pipe_bottom.top), abs(bird.rect.centery - pipes[pipe_ind].rect_pipe_top.bottom))) if output[0] > 0.5: bird.jump() rem = [] add_pipe = False for pipe in pipes: pipe.move() for x, bird in enumerate(birds): if check_collission(pipe, bird): ge[x].fitness -= 1 nets.pop(x) ge.pop(x) birds.pop(x) if pipe.rect_pipe_top.right < 0: rem.append(pipe) if not pipe.passed and pipe.rect_pipe_top.centerx < bird.rect.centerx: pipe.passed = True add_pipe = True if add_pipe: score += 1 for genome in ge: genome.fitness += 5 pipes.append(Pipe(SCREEN_WIDTH)) for r in rem: pipes.remove(r) floor.move() update_screen(SCREEN, birds, pipes, floor, score, gen, pipe_ind) def neat_run(config_file): config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file) # Population p = neat.Population(config) # Stats p.add_reporter(neat.StdOutReporter(True)) stats = neat.StatisticsReporter() p.add_reporter(stats) # Run upto 50 generations winner = p.run(evaluate_genomes, 50) # Show Final stats print('\nBest genome:\n{!s}'.format(winner)) if __name__ == '__main__': local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, 'config-feedforward.txt') neat_run(config_path) <file_sep>/README.md # Flappy_Game Flappy Bird Game_Python Arcade style game coded in Python using Pygame library. Run game.py <file_sep>/game.py import pygame as pg import sys import random def bottom_move(): screen.blit(bottom_image, (bottom_image_x, 540)) screen.blit(bottom_image, (bottom_image_x + 336, 540)) def create_pipe_rect(): pipe_height = random.choice([230, 330, 430]) pipe_rect_bottom = pipe_image_bottom.get_rect(midtop=(350, pipe_height)) pipe_rect_top = pipe_image_bottom.get_rect(midbottom=(350, pipe_height - 150)) return pipe_rect_bottom, pipe_rect_top def move_pipes(pipe_rect_list): for pipe_rect in pipe_rect_list: pipe_rect.centerx -= 2 visible_pipes = [pipe_rect for pipe_rect in pipe_rect_list if pipe_rect.right > -10] return visible_pipes def draw_pipes(pipe_rect_list): for pipe_rect in pipe_rect_list: if pipe_rect.bottom >= 550: screen.blit(pipe_image_bottom, pipe_rect) else: screen.blit(pipe_image_top, pipe_rect) def check_collision(pipe_rect_list): global score_deactive_period for pipe_rect in pipe_rect_list: if bird_rect.colliderect(pipe_rect): death_sound.play() score_deactive_period = False return False if bird_rect.top <= -100 or bird_rect.bottom >= 540: score_deactive_period = False return False return True def rotate_bird(bird_image): new_bird_image = pg.transform.rotozoom(bird_image, bird_movement * 3, 1) return new_bird_image def bird_animation(): new_bird_image = bird_image_list[bird_image_index] new_bird_rect = bird_image.get_rect(center=(100, bird_rect.centery)) return new_bird_image, new_bird_rect def score_display(game_status): if game_status == 'main_game': score_surface = game_font.render(f'Score: {int(score)}', True, (255, 255, 255)) score_rect = score_surface.get_rect(center=(180, 50)) screen.blit(score_surface, score_rect) elif game_status == 'game_over': score_surface = game_font.render(f'Score: {int(score)}', True, (255, 255, 255)) score_rect = score_surface.get_rect(center=(180, 50)) screen.blit(score_surface, score_rect) high_score_surface = game_font.render(f'High score: {int(high_score)}', True, (255, 255, 255)) high_score_rect = high_score_surface.get_rect(center=(180, 500)) screen.blit(high_score_surface, high_score_rect) def score_check(): global score, score_deactive_period if pipe_rect_list: for pipe_rect in pipe_rect_list: if 97 < pipe_rect.centerx < 103 and not score_deactive_period: score += 1 score_sound.play() score_deactive_period = True if pipe_rect.centerx < 0: score_deactive_period = False pg.init() # Game variables gravity = 0.2 bird_movement = 0 game_active = True game_font = pg.font.Font('04B_19.ttf', 30) score = 0 high_score = 0 score_count = 100 score_deactive_period = False running = True screen = pg.display.set_mode((360, 640)) clock = pg.time.Clock() background_image = pg.image.load('resources/background-day.png').convert() background_image = pg.transform.scale(background_image, (360, 640)) bottom_image = pg.image.load('resources/base.png').convert() bottom_image_x = 0 # bird_image = pg.image.load('resources/bluebird-midflap.png').convert_alpha() bird_image_downflap = pg.image.load('resources/bluebird-downflap.png').convert_alpha() bird_image_midflap = pg.image.load('resources/bluebird-midflap.png').convert_alpha() bird_image_upflap = pg.image.load('resources/bluebird-upflap.png').convert_alpha() bird_image_list = [bird_image_downflap, bird_image_midflap, bird_image_upflap] bird_image_index = 0 bird_image = bird_image_list[bird_image_index] bird_rect = bird_image.get_rect(center=(100, 320)) pipe_image_bottom = pg.image.load('resources/pipe-green.png').convert() pipe_image_top = pg.transform.flip(pipe_image_bottom, False, True) pipe_rect_list = [] game_over_image = pg.image.load('resources/message.png').convert_alpha() game_over_rect = game_over_image.get_rect(center=(180, 300)) # Sounds flap_sound = pg.mixer.Sound('audio/sfx_wing.wav') death_sound = pg.mixer.Sound('audio/sfx_die.wav') score_sound = pg.mixer.Sound('audio/sfx_point.wav') SPAWNPIPE = pg.USEREVENT pg.time.set_timer(SPAWNPIPE, 1200) BIRDFLAP = pg.USEREVENT + 1 pg.time.set_timer(BIRDFLAP, 200) while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False pg.quit() sys.exit() if event.type == pg.KEYDOWN: if event.key == pg.K_SPACE and game_active: bird_movement = 0 bird_movement -= 6 flap_sound.play() if event.key == pg.K_SPACE and not(game_active): game_active = True bird_movement = 0 bird_rect = bird_image.get_rect(center=(100, 320)) pipe_rect_list.clear() score = 0 if event.type == SPAWNPIPE and game_active: pipe_rect_list.extend(create_pipe_rect()) print(pipe_rect_list) if event.type == BIRDFLAP and game_active: if bird_image_index >= 2: bird_image_index = 0 else: bird_image_index += 1 bird_image, bird_rect = bird_animation() # Background screen.blit(background_image, (0, 0)) if(game_active): # Bird bird_movement += gravity bird_rect.centery += bird_movement rotated_bird = rotate_bird(bird_image) screen.blit(rotated_bird, bird_rect) game_active = check_collision(pipe_rect_list) # Pipes pipe_rect_list = move_pipes(pipe_rect_list) draw_pipes(pipe_rect_list) # Score score_check() score_display('main_game') else: # High Score if score > high_score: high_score = score screen.blit(game_over_image, game_over_rect) score_display('game_over') # Floor bottom_image_x -= 1 bottom_move() if bottom_image_x < -235: bottom_image_x = 0 pg.display.update() clock.tick(120)
c485db3b0a0ba34103e6d46ba85e21f08f80bb8b
[ "Markdown", "Python" ]
3
Python
SudheerBeerala/Flappy_Game
bd3294b6754fb9880b5f591cf42152d4585721d7
bc9a79e73ed8719379c04a58219af34d5489dda2
refs/heads/master
<repo_name>odaliz/programacion3<file_sep>/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SQLite; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Nomina { public partial class maestro_nomina : Form { public maestro_nomina() { InitializeComponent(); } public void consultarnomina() { //declaramos la clase operacion //luego nos conectamos a la db //hacemos un select con un where en idnominana operacion oper = new operacion(); SQLiteConnection cnx = new SQLiteConnection("Data Source=C:\\sistema\\tarea2.db;Version=3;"); cnx.Open(); string consultanomina = ("select * from detalle_nomina WHERE idnomina ='" + idnomina + "'"); SQLiteDataAdapter co = new SQLiteDataAdapter(consultanomina, cnx); DataSet ds = new DataSet(); ds.Reset(); DataTable dt = new DataTable(); co.Fill(ds); dt = ds.Tables[0]; dataGridView1.DataSource = dt; cnx.Close(); } private void btndetalle_factura_Click(object sender, EventArgs e) { vernomina(); } private void btnGenerar_Click(object sender, EventArgs e) { operacion oper = new operacion(); SQLiteConnection cnx = new SQLiteConnection("Data Source=C:\\sistema\\tarea2.db;Version=3;"); SQLiteCommand su1 = new SQLiteCommand("SELECT SUM(sueldo_emple) FROM empleados;", cnx); SQLiteCommand su2 = new SQLiteCommand("SELECT SUM(sueldo_emple*0.08) FROM empleados;", cnx); SQLiteCommand su3 = new SQLiteCommand("SELECT SUM(sueldo_emple*0.04) FROM empleados;", cnx); SQLiteCommand su4 = new SQLiteCommand("SELECT SUM(sueldo_emple)-SUM(sueldo*0.14) FROM empleados;", cnx); SQLiteCommand su5 = new SQLiteCommand("SELECT SUM(sueldo_empleo*0.02) FROM empleados;", cnx); SQLiteCommand su6 = new SQLiteCommand("SELECT SUM(sueldo_emple*0.14) FROM empleados;", cnx); cnx.Open(); string generaciondenomina = ("SELECT idempleado, nombre, apellido, sueldo,*0.08 AS ISR, sueldo*0.04 AS ss, sueldo*0.02 AS otros_desceunto, sueldo*0.14 AS total_descuentos, sueldo-(sueldo*0.14) AS total_sueldo_Neto FROM empleados"); SQLiteDataAdapter db = new SQLiteDataAdapter(generarnomina, cnx); DataSet ds = new DataSet(); ds.Reset(); DataTable dt = new DataTable(); db.Fill(ds); dt = ds.Tables[0]; dataGridView1.DataSource = dt; sueldoTotal.Text = cmd1.ExecuteScalar().ToString(); isrTotal.Text = cmd2.ExecuteScalar().ToString(); ssTotal.Text = cmd3.ExecuteScalar().ToString(); netoTotal.Text = cmd4.ExecuteScalar().ToString(); otrosDesc.Text = cmd5.ExecuteScalar().ToString(); deduccTotal.Text = cmd6.ExecuteScalar().ToString(); idNomina.Enabled = true; cnx.Close(); } private void btir_Click(object sender, EventArgs e) { operacion oper = new operacion(); SQLiteConnection cnx = new SQLiteConnection("Data Source=C:\\sistema\\tarea2.db;Version=3;"); oper.ConsultaSinResultado("insert into cabeza_nomina (fecha_ini, fecha_fin, sueldo_total, isr, ss, otros, total_dedu, total_sueldo_neto) vALUES('" + fechaini.text + "','" + FechaFin.Text + "','" + SueldoTotal + "','" + irs.Text + "','" + ss.Text + "','" + otrosDecu.Text + "','" + totalDeduc.Text + "','" + sueldo_Neto.Text + "')"); string idNomina; DataSet ds; ds = oper.ConsultaConResultado("select max(idnomina) from cabeza_nomina;"); idNomina = ds.Tables[0].Rows[0][0].ToString(); int filas = dataGridView1.RowCount; string idempleado, sueldo, isr, ss, otros, neto; for (int i = 0; i < (CantidaddDeFilas - 1); i++) { idempleado = dataGridView1.Rows[i].Cells[0].Value.ToString(); sueldo = dataGridView1.Rows[i].Cells[3].Value.ToString(); isr = dataGridView1.Rows[i].Cells[4].Value.ToString(); ss = dataGridView1.Rows[i].Cells[5].Value.ToString(); otros = dataGridView1.Rows[i].Cells[6].Value.ToString(); neto = dataGridView1.Rows[i].Cells[8].Value.ToString(); oper.ConsultaSinResultado("insert into detalle_nomina VALUES (" + NumNomina + "," + idempleado + "," + sueldo + "," + isr + "," + ss + "," + otros + "," + neto + ");"); } DataTable dt = null; dataGridView1.DataSource = dt; dataGridView1.Refresh(); Dedu.Clear(); irsTotal.Clear(); netoTotal.Clear(); numNomina.Clear(); otrosDesc.Clear(); ss.Clear(); sueldoTotal.Clear(); fechaIni.Value = DateTime.Now; fechaIni.Value = DateTime.Now; dataGridView1 = null; MessageBox.Show("exitoso!"); } } }
310733519c941bdb8d7866643ab30f840fab1e7f
[ "C#" ]
1
C#
odaliz/programacion3
54f704bbc753081245535efb3177a1f42e48d469
d5b9c05ecedbeebe8837205f8582a2a1d8ff27bc
refs/heads/master
<file_sep>#include<conio.h> #include<stdio.h> #include<iomanip.h> main() { int i; char nama[5][20]; float nilai1[5]; float nilai2[5]; float hasil[5]; clrscr(); for(i=1;i<=2;i++) { cout<<"Data ke-"<<i<<endl; cout<<"Nama Siswa :";gets(nama[i]); cout<<"Nilai MidTest :";cin>>nilai1[i]; cout<<"Nilai Final :";cin>>nilai2[i]; hasil[i]=(nilai1[i]*0.40)+(nilai2[i]*0.60); cout<<endl; } cout<<"___________________________________"<<endl; cout<<"No.Nama Siswa Nilai Nilai Hasil"<<endl; cout<<" MidTest Final Ujian"<<endl; cout<<"___________________________________"<<endl; for(i=1;i<=2;i++) { cout<<setiosflags(ios::left)<<setw(4)<<i; cout<<setiosflags(ios::left)<<setw(10)<<nama[i]; cout<<setprecision(5)<<" "<<nilai1[i]; cout<<setprecision(5)<<" "<<nilai2[i]; cout<<setprecision(5)<<" "<<hasil[i]<<endl; } cout<<"___________________________________"<<endl; getch(); } <file_sep> #include<conio.h> #include<iostream.h> main() { cout<<"********************PERKENALAN******************** \n"; cout<<"================================================== \n"; cout<<" Nama Saya :HAMID \n"; cout<<" NIM :12174410 \n"; cout<<" Alamat :Desa Cibadung RT01/02 Kec.Gunung sindur Kab.Bogor \n"; cout<<" =====Kampus BINA SARANA INFORMATIKA,BSD=====\n"; getch(); } <file_sep>#include<stdio.h> #include<conio.h> #include<iostream> main() { int jumbar=150,jumbar2=23; clrscr(); cout<<"Jumlah Barang 1;"<<jumbar1; cout<<"Jumlah Barang 2;"<<jumbar2; getch(); }
5861240e61dfe34c81769eb89886b04e7427be94
[ "C++" ]
3
C++
hamid97/hamid97
49699f8b33e8f9b75c3f1ed9b8faf68c4287fd65
7aa3af5f5eb694ec80d9530357e166ed3d561539
refs/heads/master
<repo_name>cmdIrelia/LearnGit<file_sep>/lala.cpp //asdfasdfasdf void gogogo();<file_sep>/modify.cpp void temp(); void pull_back(); //qwerqwer<file_sep>/ReadMe.md My Project about Learning How To Use Git 2019/01/05
fed7df35d5e17f4faa651ca295f2d2237edf8ae1
[ "Markdown", "C++" ]
3
C++
cmdIrelia/LearnGit
86bb240c26d0b6c4a0c69b79a624d4b364d1972f
0234567664cf182a18e3ef7bda20a5ec2296eb47
refs/heads/master
<repo_name>caroleco/ReactApp<file_sep>/README.md # React App OKR <file_sep>/App.js import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { createStackNavigator, createAppContainer} from 'react-navigation'; import Home from './components/Home' import Principal from './components/Principal' const RootStack = createStackNavigator({ Home: { screen: Home }, Principal: { screen: Principal } }); const App = createAppContainer(RootStack); export default App;
44e9f68d19888aaabb19417425002af0a44c3e86
[ "Markdown", "JavaScript" ]
2
Markdown
caroleco/ReactApp
025db68556e8f33717ff4d3078ad410c323e797d
79bc1e7edd365e5bd1e1c6311d34ff846b38d295
refs/heads/master
<repo_name>mrpaulphan/mrpaulphan<file_sep>/assets/js/modules/hr.js var $ = require('jquery'); module.exports = (function() { return { init: function() { $('a[href="#hr"]').text('').addClass('hr'); $('a[href="#hr"]').on('click', function(event) { event.preventDefault(); }); }, }; })(); <file_sep>/assets/js/modules/shortCode.js var $ = require('jquery'); module.exports = (function() { return { init: function() { } }; })(); <file_sep>/.env.example APP_ENV= APP_URL= DB_CONNECTION= DB_HOST= DB_PORT= DB_DATABASE= DB_USERNAME= DB_PASSWORD= DB_BACKUP_NAME= WEBSERVER_HOST= WEBSERVER_PORT= ARG_DIR= S3_KEY= S3_SECRET= S3_REGION= S3_BUCKET= S3_BACKUP_BUCKET= <file_sep>/assets/js/modules/scrollFix.js var $ = require('jquery'); module.exports = { init: function () { // window.addEventListener("hashchange", function() { // console.debug('foo'); // }, false); // var originalHash = window.location.hash; // if (originalHash) { // setTimeout(function () { // var el = $('[data-url-id="'+originalHash.substring(1)+'"]'); // if (el[1]) { // $(document.body).scrollTop($(el[1]).offset().top); // } // }, 1500); // } } }<file_sep>/assets/js/script.js var $ = require('jquery'); // Modules Dependencies var toggle = require('./modules/toggle'); var g = require('./modules/g'); var skipLink = require('./modules/skipLink'); /*------------------------------------------- DOCUMENT READY FUNCTIONS All functions to be called on doc ready -------------------------------------------*/ $(document).ready(function() { skipLink.init(); toggle.init(); toggle.successStories(); toggle.map(); toggle.grid(); toggle.story(); toggle.videoSwap(); g.init(); }); <file_sep>/assets/js/modules/toggle.js var $ = require('jquery'); module.exports = (function() { return { init: function() { var trigger = $('[data-toggle-trigger]'); var target = $('[data-toggle-target]'); var settings = { duration: 200, easing: 'swing' }; trigger.click(function() { var triggerId = $(this).attr('data-toggle-trigger'); var thisTarget = $('[data-toggle-target*="' + triggerId + '"]'); var el = $(this); switch (triggerId) { case 'form': thisTarget.toggle(); if ($('body').hasClass('no-scroll')) { $('body').removeClass('no-scroll'); } else { $('body').addClass('no-scroll'); } break; default: thisTarget.toggle(); } }); }, grid: function() { var trigger = $('[data-grid-trigger]'); var target = $('[data-grid-target]'); var settings = { duration: 200, easing: 'swing' }; trigger.click(function() { var triggerId = $(this).attr('data-grid-trigger'); var thisTarget = $('[data-grid-target*="' + triggerId + '"]'); var el = $(this); // Remove all active classes $('[data-grid-trigger]').each(function() { $(this).removeClass('active'); }); // Add active class to curent trigger el.addClass('active'); var id = $(this).attr('data-grid-trigger'); target.each(function() { var targetID = $(this).attr('data-grid-target'); var el = $(this); if (targetID != id) { $(this).removeClass('active'); $(this).addClass('hide'); } else { $(this).removeClass('hide'); $(this).addClass('active'); } }); }); }, story: function() { var trigger = $('[data-story-trigger]'); var target = $('[data-story-target]'); var settings = { duration: 200, easing: 'swing' }; trigger.click(function(e) { e.stopPropagation; var triggerId = $(this).attr('data-story-trigger'); var thisTarget = $('[data-story-target*="' + triggerId + '"]'); var el = $(this); var currentText = $(this).html(); if (currentText == 'Close') { trigger.each(function() { var el = $(this); var matchingID = $(this).attr('data-story-trigger'); if (triggerId === matchingID) { thisTarget.slideUp(); el.text('Read More'); el.removeClass('active') } }); } else { target.each(function() { $(this).hide(); var el = $(this); var matchingID = $(this).attr('data-story-trigger'); if (triggerId != matchingID) {} }); trigger.each(function() { var el = $(this); var matchingID = $(this).attr('data-story-trigger'); if (triggerId === matchingID) { el.html('Close'); el.addClass('active'); thisTarget.slideDown(); } else { el.text('Read More'); } }); } }); }, successStories: function() { var trigger = $('[data-story-trigger]'); var target = $('[data-story-target]'); var settings = { duration: 200, easing: 'swing' }; trigger.click(function() { var triggerId = $(this).attr('data-story-trigger'); var thisTarget = $('[data-story-target*="' + triggerId + '"]'); var el = $(this); // Remove all active classes $('[data-story-trigger]').each(function() { $(this).removeClass('active'); }); // Add active class to curent trigger el.addClass('active'); var id = $(this).attr('data-story-trigger'); target.each(function() { var targetID = $(this).attr('data-story-target'); var el = $(this); if (targetID != id) { $(this).removeClass('active'); $(this).addClass('hide'); } else { $(this).removeClass('hide'); $(this).addClass('active'); } }); }); }, map: function() { var trigger = $('[data-map-trigger]'); var target = $('[data-map-target]'); trigger.on('click', function() { var el = $(this); var triggerId = el.attr('data-map-trigger'); // Remove all active classes $('[data-map-trigger]').removeClass('active'); // Remove current open read more sections $('[data-story-target]').hide(); // Add active class to curent trigger el.addClass('active'); target.each(function() { var target = $(this); var targetID = target.attr('data-map-target'); if (targetID != triggerId) { target.removeClass('active').addClass('hide'); } else { target.removeClass('hide').addClass('active'); } }); }); }, videoSwap: function() { // User clicks on play button $('[data-video-button]').on('click', function() { // Play buttons ID var id = $(this).attr('data-video-button'); var video = '<div class="video-wrapper"><iframe src="https://player.vimeo.com/video/185717440?autoplay=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>'; $('[data-video-swap-container]').each(function() { var parentContainer = $(this); var parentContainerId = $(this).attr('data-video-swap-container'); if (id === parentContainerId) { // Empty out div parentContainer.before(video); parentContainer.detach(); } }) }); } }; })();
29a81bfe182c7a42d9c93e4951c7fe5d62979a55
[ "JavaScript", "Shell" ]
6
JavaScript
mrpaulphan/mrpaulphan
13f55955fe449a0efff9fc921b583af81f9f9694
005bb86c6f41b86f88873e3c4ef0216cd04400d8
refs/heads/master
<repo_name>pmd98/arduinolabs-lyceum<file_sep>/README.md # arduinolabs-lyceum Arduino labs for lyceum students "Οπθβες" ======= Arduino labs for NSTU lyceum students ИспользованиС Git ===== Установка для Windows ----- 1. По ссылкС http://git-scm.com/downloads ΡΠΊΠ°Ρ‡Π°Ρ‚ΡŒ послСдний Ρ€Π΅Π»ΠΈΠ· - Π½Π°ΠΆΠ°Ρ‚ΡŒ Π½Π° ΠΊΠ½ΠΎΠΏΠΊΡƒ Download for Windows/ 2. Π—Π°ΠΏΡƒΡΡ‚ΠΈΡ‚ΡŒ скачанный exe-Ρ„Π°ΠΉΠ». 3. Π’ ΠΎΠΊΠ½Π΅ **Welcome to the Git Setup Wizard** ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚ΡŒ **Next** 4. Π’ ΠΎΠΊΠ½Π΅ **Information** ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚ΡŒ **Next** 5. Π’ ΠΎΠΊΠ½Π΅ **Select components** ΡƒΠ±Ρ€Π°Ρ‚ΡŒ Π³Π°Π»ΠΊΡƒ Π² ΠΏΡƒΠ½ΠΊΡ‚Π΅ *Windows Explorer intergation* ΠΈ ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚ΡŒ **Next** 6. Π’ ΠΎΠΊΠ½Π΅ **Adjusting you PATH environment** ΠΎΡΡ‚Π°Π²ΠΈΡ‚ΡŒ Ρ€Π°Π΄ΠΈΠΎΡ‡Π΅ΠΊ Π½Π° ΠΏΠ΅Ρ€Π²ΠΎΠΌ ΠΏΡƒΠ½ΠΊΡ‚Π΅ ΠΈ ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚ΡŒ **Next** 7. Π’ ΠΎΠΊΠ½Π΅ **Configuring the line endings conversions** ΠΎΡΡ‚Π°Π²ΠΈΡ‚ΡŒ Ρ€Π°Π΄ΠΈΠΎΡ‡Π΅ΠΊ Π½Π° ΠΏΠ΅Ρ€Π²ΠΎΠΌ ΠΏΡƒΠ½ΠΊΡ‚Π΅ ΠΈ ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚ΡŒ **Next** 8. Π”ΠΎΠΆΠ΄Π°Ρ‚ΡŒΡΡ окончания установки 9. Π’ ΠΎΠΊΠ½Π΅ **Compliting the Git Setup Wizard** ΡƒΠ±Ρ€Π°Ρ‚ΡŒ Π³Π°Π»ΠΊΡƒ с *View ReleaseNotes.rtf* ΠΈ ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚ΡŒ **Finish** Запуск ΠΎΠ±ΠΎΠ»ΠΎΡ‡ΠΊΠΈ git ----- НайдитС Π² ΠŸΡƒΡΠΊΠ΅ ΠΏΡ€ΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ Git Bash ΠΈ запуститС Π΅Π³ΠΎ. ΠžΡ‚ΠΊΡ€ΠΎΠ΅Ρ‚ΡΡ консоль с ΠΏΡ€ΠΈΠ³Π»Π°ΡˆΠ΅Π½ΠΈΠ΅ΠΌ ΠΊ Π²Π²ΠΎΠ΄Ρƒ. ΠšΠ»ΠΎΠ½ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ рСпозитория с сСрвСра Π½Π° ПК ----- ΠŸΠ΅Ρ€Π΅ΠΉΠ΄ΠΈΡ‚Π΅ Π½Π° диск C: ΠΊΠΎΠΌΠ°Π½Π΄ΠΎΠΉ cd c: Если Ρƒ вас Π½Π΅Ρ‚ ΠΏΠ°ΠΏΠΊΠΈ `devel`, создайтС Π΅Ρ‘: mkdir devel ΠŸΠ΅Ρ€Π΅ΠΉΠ΄ΠΈΡ‚Π΅ Π² ΠΏΠ°ΠΏΠΊΡƒ `devel`: cd devel Π‘ΠΊΠ»ΠΎΠ½ΠΈΡ€ΡƒΠΉΡ‚Π΅ Ρ€Π΅ΠΏΠΎΠ·ΠΈΡ‚ΠΎΡ€ΠΈΠΉ с сСрвСра сСбС Π½Π° ПК: git clone http://github.com/%ВАШ_НИК%/arduinolabs-lyceum ΠŸΠ΅Ρ€Π΅ΠΉΠ΄ΠΈΡ‚Π΅ Π² ΠΏΠ°ΠΏΠΊΡƒ `arduinolabs-lyceum`: cd arduinolabs-lyceum НастройтС ΠΎΡ€ΠΈΠ³ΠΈΠ½Π°Π»ΡŒΠ½Ρ‹ΠΉ Ρ€Π΅ΠΏΠΎΠ·ΠΈΡ‚ΠΎΡ€ΠΈΠΉ, с ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ³ΠΎ Π²Ρ‹ сдСлали Ρ„ΠΎΡ€ΠΊ, ΠΊΠ°ΠΊ *ΡƒΠ΄Π°Π»Π΅Π½Π½Ρ‹ΠΉ Ρ€Π΅ΠΏΠΎΠ·ΠΈΡ‚ΠΎΡ€ΠΈΠΉ (remote)*: git remote add main http://github.com/dubkov/arduinolabs-lyceum master ΠŸΠΎΠ»ΡƒΡ‡ΠΈΡ‚Π΅ послСдниС измСнСния ΠΈΠ· ΠΎΡ€ΠΈΠ³ΠΈΠ½Π°Π»ΡŒΠ½ΠΎΠ³ΠΎ рСпозитория: git pull main НастройтС своС имя ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ: git config user.name "%ВАШ_НИК%" ΠΊΠ°Π²Ρ‹Ρ‡ΠΊΠΈ ΠΏΡ€ΠΈ этом Π΄ΠΎΠ»ΠΆΠ½Ρ‹ ΠΎΡΡ‚Π°Ρ‚ΡŒΡΡ. НастройтС свой e-mail: git config user.email "%ВАШ_EMAIL%" Π—Π°Π³Ρ€ΡƒΠ·ΠΊΠ° ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΉ Π½Π° сСрвСр ----- ПослС внСсСния Π² Ρ„Π°ΠΉΠ»Ρ‹ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΉ, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ Π²Ρ‹ Π±Ρ‹ Ρ…ΠΎΡ‚Π΅Π»ΠΈ ΡΠΎΡ…Ρ€Π°Π½ΠΈΡ‚ΡŒ, слСдуСт Π΄Π΅Π»Π°Ρ‚ΡŒ ΠΈΠ· Π½ΠΈΡ… ΠΊΠΎΠΌΠΌΠΈΡ‚. Π‘Π½Π°Ρ‡Π°Π»Π° Π΄ΠΎΠ±Π°Π²ΡŒΡ‚Π΅ всС ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠ΅ Π² `staging`: git add . Π’Π΅ΠΏΠ΅Ρ€ΡŒ создайтС ΠΊΠΎΠΌΠΌΠΈΡ‚: git commit -m "ΠΊΡ€Π°Ρ‚ΠΊΠΎ ΠΎΠΏΠΈΡˆΠΈΡ‚Π΅ измСнСния здСсь" НаконСц, ΠΌΠΎΠΆΠ½ΠΎ Π·Π°Π³Ρ€ΡƒΠΆΠ°Ρ‚ΡŒ измСнСния Π½Π° сСрвСр, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΎΠ½ΠΈ Π±Ρ‹Π»ΠΈ Π²ΠΈΠ΄Π½Ρ‹ всСм: git push Π£ вас спросят сначала ваш Π½ΠΈΠΊ Π½Π° сайтС github.com, Π° ΠΏΠΎΡ‚ΠΎΠΌ ΠΏΠ°Ρ€ΠΎΠ»ΡŒ. ΠŸΡ€ΠΈ Π²Π²ΠΎΠ΄Π΅ пароля Π½ΠΈΠΊΠ°ΠΊΠΈΠ΅ символы Π½Π΅ ΠΎΡ‚ΠΎΠ±Ρ€Π°ΠΆΠ°ΡŽΡ‚ΡΡ. > По сути, Π²Ρ‹ создаСтС ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ»ΡŒΠ½ΡƒΡŽ Ρ‚ΠΎΡ‡ΠΊΡƒ, ΠΊΠΎΡ‚ΠΎΡ€ΡƒΡŽ смоТСтС ΠΏΡ€ΠΎΡΠΌΠΎΡ‚Ρ€Π΅Ρ‚ΡŒ Π² любой ΠΌΠΎΠΌΠ΅Π½Ρ‚. Π­Ρ‚ΠΎ слСпок состояния вашСго ΠΏΡ€ΠΎΠ΅ΠΊΡ‚Π°. Π’Ρ‹ всСгда ΠΌΠΎΠΆΠ΅Ρ‚Π΅ Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒΡΡ ΠΊ любой вСрсии вашСго ΠΏΡ€ΠΎΠ΅ΠΊΡ‚Π° ΠΈ ΠΏΠΎΡΠΌΠΎΡ‚Ρ€Π΅Ρ‚ΡŒ, ΠΊΠ°ΠΊ Π±Ρ‹Π» Ρ€Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ Ρ‚ΠΎΡ‚ ΠΈΠ»ΠΈ ΠΈΠ½ΠΎΠΉ Π΅Π³ΠΎ кусок. <file_sep>/lab1/lab1.ino /* * Лабораторная работа 1 * "Счетчик нажатий" * Автор:<NAME> * Дата создания:04.03.2015 #define PIN_A 2 #define PIN_B 3 #define PIN_C 4 #define PIN_D 5 #define PIN_E 6 #define PIN_F 7 #define PIN_G 8 #define PIN_P 9 int number=0; byte digit[11] = { 0b00111111, 0b00000110, 0b01011011, 0b01001111, 0b01100110, 0b01101101, 0b01111101, 0b00000111, 0b01111111, 0b01101111, 0 }; void setup() { pinMode(PIN_A,OUTPUT); pinMode(PIN_B,OUTPUT); pinMode(PIN_C,OUTPUT); pinMode(PIN_D,OUTPUT); pinMode(PIN_E,OUTPUT); pinMode(PIN_F,OUTPUT); pinMode(PIN_G,OUTPUT); pinMode(PIN_P,OUTPUT); } void loop() { showDigit(number); delay(1000); number++; if (number == 10) number=0; } void showDigit(int i){ digitalWrite (PIN_A, digit[i]&(1<<0)); digitalWrite (PIN_B, digit[i]&(1<<1)); digitalWrite (PIN_C, digit[i]&(1<<2)); digitalWrite (PIN_D, digit[i]&(1<<3)); digitalWrite (PIN_E, digit[i]&(1<<4)); digitalWrite (PIN_F, digit[i]&(1<<5)); digitalWrite (PIN_G, digit[i]&(1<<6)); digitalWrite (PIN_P, digit[i]&(1<<7)); }
1bdd8ccddd4be400742aa9a782f4e452bf4ffa58
[ "Markdown", "C++" ]
2
Markdown
pmd98/arduinolabs-lyceum
47b0cc0a0d321f7ab0b7abb0b74a5c33b5428b8c
862fb9ef0ac0389f55bb827827f136d962492ed4
refs/heads/main
<file_sep>import os import glob import pandas as pd import numpy as np home_vcf_annot = '..' # CHANGE THIS TO THE FOLDER CONTAINING YOUR VCF AND ANNOTATION FILES vcf_suffix = 'eur.rehead.normID.GTflt.AB.noChrM' # CHANGE THIS TO THE SUFFIX OF YOUR VCF FILE, in my case files are named: ../chr*.eur.rehead.normID.GTflt.AB.noChrM.vcf.gz annot_prefix = 'finalAnnot.SortByGene' # CHANGE THIS TO THE PREFIX OF YOUR VEP ANNOTATIONS, in my case the files are named: ../finalAnnot.SortByGene.chr*.txt def update_variants_per_gene(data, bool_single, bool_multi, samples, gene): gene_with = np.any(data, axis = 0).astype(int) bool_single[gene] = {sample:gt for sample, gt in zip(samples, gene_with)} gene_with_multi = (np.sum(data, axis = 0) > 1).astype(int) bool_multi[gene_old] = {sample:gt for sample, gt in zip(samples, gene_with_multi)} def update_gc_per_gene(data, infos, hetero_homo, bool_aplo, fout, samples, gene): n_rows_gene = 0 n_samples_poli_rare = 0 if hetero_homo == 'hetero': gts_bool = data.astype(bool) elif hetero_homo == 'homo': gts_bool = (data > 1).astype(bool) else: raise ValueError('ERROR: wrong value for hetero_homo parameter') is_mut = np.any(gts_bool, axis = 0).astype(int) poli, poli_inv, counts = np.unique(gts_bool, axis = 1, return_inverse = True, return_counts= True) freq = counts / np.sum(counts) bool_aplo['{}_{}'.format(gene,0)] = {sample:0 for sample in samples} for i_poli in range(poli.shape[1]): if not np.any(poli[:,i_poli]): continue if freq[i_poli] < frequency_common: for i_sample, sample in enumerate(samples): if poli_inv[i_sample] == i_poli: bool_aplo['{}_{}'.format(gene,0)][sample] = 1 n_samples_poli_rare += 1 else: n_rows_gene += 1 row_name = '' for index, variant in infos[poli[:,i_poli]].iterrows(): row_name += '{}:{}-{}:{}-{}_,'.format(variant['chrom'], variant['start'], variant['end'], variant['ref'], variant['alt']) row_name = row_name[:-1] bool_aplo['{}_{}'.format(gene, n_rows_gene)] = {sample:0 for sample in samples} n_samples_this_poli = 0 for i_sample, sample in enumerate(samples): if poli_inv[i_sample] == i_poli: bool_aplo['{}_{}'.format(gene, n_rows_gene)][sample] = 1 n_samples_this_poli += 1 fout.write('{}_{} = '.format(gene, n_rows_gene)) fout.write('{} = {}\n'.format(row_name, n_samples_this_poli)) fout.flush() #--- Initialization bool_single_rare = {} bool_multi_rare = {} bool_gc_unique_homo = {} bool_gc_unique_hetero = {} fout_gc_unique_homo = open('bool_gc_unique_homo.txt','wt') fout_gc_unique_hetero = open('bool_gc_unique_hetero.txt','wt') contigs = ['chr{}'.format(ind) for ind in range(1,23)] + ['chrX', 'chrY'] contigs = ['chrX', 'chrY'] frequency_rare = 0.01 frequency_common = 0.05 ens2name = pd.read_csv('ensemblid_names.csv') n_genes = 0 for contig in contigs: vcf = '{}/{}.{}.vcf.gz'.format(home_vcf_annot, contig, vcf_suffix) if not os.path.exists(vcf): raise ValueError('ERROR: missing file {}'.format(vcf)) if not os.path.exists(vcf+'.tbi'): raise ValueError('ERROR: missing file {}'.format(vcf+'.tbi')) ann = '{}/{}.{}.txt'.format(home_vcf_annot, annot_prefix, contig) if not os.path.exists(ann): raise ValueError('ERROR: missing file {}'.format(ann)) cmd = 'bcftools view -h ./{} > header.txt'.format(vcf) os.system(cmd) samples = None with open('./header.txt','rt') as fin: for l in fin.readlines(): l = l.strip().split() if l[0] == '#CHROM': samples = l[9:] if samples is None: raise ValueError('ERROR: wrong format in {}'.format(vcf)) print('Number of samples for chrom {}: {}'.format(contig, len(samples))) fin_ann = open(ann) l = fin_ann.readline() gene_old = None gene_data = [] while l: l = l.strip() if l: if l[0] != '#': l = l.split() idd = l[0] chrom = l[0].split(':')[0] ref = l[0].split(':')[2] alt = l[0].split(':')[3] pos = l[1].split(':')[1] start = int(pos.split('-')[0]) if '-' in pos: end = int(pos.split('-')[1]) else: end = start gene = l[3] feat_type = l[5] cons = l[6] extra = l[13] if 'gnomAD_NFE_AF' in extra: ind = extra.index('gnomAD_NFE_AF=') af = float(extra[ind:].split(';')[0].split('=')[1]) elif 'EUR_AF' in extra: ind = extra.index('EUR_AF=') af = float(extra[ind:].split(';')[0].split('=')[1]) else: af = 1.0 if 'CLIN_SIG' in extra: ind = extra.index('CLIN_SIG=') clin_sig = extra[ind:].split(';')[0].split('=')[1] else: clin_sig = '' if (gene != gene_old): if (gene_old is not None) and ('ENSG' in gene_old): info = pd.DataFrame(gene_data, columns = ['id', 'chrom', 'start', 'end', 'ref', 'alt', 'gene', 'feat_type', 'cons', 'af', 'clin_sig']) info.drop_duplicates(subset = 'id', inplace = True) info.sort_values(by = 'id', axis = 0, inplace = True) with open('ids.txt','wt') as fout: for i in info['id']: fout.write(i+'\n') cmd = 'bcftools filter -r {}:{}-{} -Ou ./{} | bcftools view -i "%ID=@./ids.txt" -Ou | bcftools query -f "%ID [ %GT] \n" > ./variants.txt'.format(chrom, min(info['start']), max(info['start']), vcf) os.system(cmd) gts = [] with open('variants.txt','rt') as fin: for l in fin.readlines(): l = l.strip() if l: l = l.split() row = [l[0],] for gt in l[1:]: if (gt == '1/1') or (gt == '1|1'): row.append(2) elif (gt == '0/1') or (gt == '0|1') or (gt == '1/0') or (gt == '1|0'): row.append(1) elif (gt == '0/0') or (gt == '0|0') or (gt == './.') or (gt == '.|.'): row.append(0) else: raise ValueError('ERROR: unexpected genotype {}'.format(gt)) gts.append(row) gts = pd.DataFrame(gts, columns = ['id',]+samples) gts.sort_values(by = 'id', axis = 0, inplace = True) if gts.shape[0] != info.shape[0]: raise ValueError('ERROR: wrong dimensions in info {} or gts {}'.format(info.shape, gts.shape)) data = info.merge(gts, left_on = 'id', right_on = 'id') keep = np.logical_or.reduce( [data['cons'].str.contains(variant_type) for variant_type in ['transcript_ablation', 'splice_acceptor_variant', 'splice_donor_variant', 'stop_gained', 'frameshift_variant', 'stop_lost', 'start_lost', 'transcript_amplification', 'inframe_insertion', 'inframe_deletion', 'missense_variant', 'protein_altering_variant']] ) same_len = data['ref'].str.len() == data['alt'].str.len() unique = np.sum(data[samples].astype(int), axis = 1).astype(int) == 1 pat = data['clin_sig'].str.contains('athogenic') var1 = np.logical_and.reduce( ( keep, same_len, np.logical_or(data['af'] < frequency_rare, data['af'] == 1.0) ) ) var2 = np.logical_and.reduce( ( keep, np.logical_not(same_len), np.logical_or(data['af'] < frequency_rare, np.logical_and(data['af'] == 1.0, unique)) ) ) # indels that are not-unique without frequency are discarded var3 = np.logical_and( pat, data['af'] < frequency_common ) rare = np.logical_or.reduce( (var1, var2, var3) ) common = np.logical_and.reduce( ( keep, data['af'] >= frequency_common ) ) gene_name = np.unique(ens2name['Gene name'].loc[(ens2name['Gene stable ID'] == gene_old)].values)[0] if np.any(rare): update_variants_per_gene(data[samples].loc[rare], bool_single_rare, bool_multi_rare, samples, gene_name) if np.any(common): update_gc_per_gene(data[samples].loc[common], data[['id','chrom','ref','alt','start','end']].loc[common], 'homo', bool_gc_unique_homo, fout_gc_unique_homo, samples, gene_name) update_gc_per_gene(data[samples].loc[common], data[['id','chrom','ref','alt','start','end']].loc[common], 'hetero', bool_gc_unique_hetero, fout_gc_unique_hetero, samples, gene_name) n_genes += 1 print('Gene {}; number of genes: {}'.format(gene_old, n_genes)) gene_data = [] gene_old = gene gene_data.append([idd, chrom, start, end, ref, alt, gene, feat_type, cons, af, clin_sig]) l = fin_ann.readline() data = pd.DataFrame(bool_single_rare) data.to_csv('data_al1_rare.csv') data = pd.DataFrame(bool_multi_rare) data.to_csv('data_al2_rare.csv') data = pd.DataFrame(bool_gc_unique_homo) data.to_csv('data_gc_unique_homo.csv') data = pd.DataFrame(bool_gc_unique_hetero) data.to_csv('data_gc_unique_hetero.csv') fout_gc_unique_homo.close() fout_gc_unique_hetero.close() <file_sep>#!/bin/bash # sorting the annotation files by gene for chr in {1..22} X Y; do grep -v \# ../finalAnnot.chr${chr}.txt | sort -k 4 > ../finalAnnot.SortByGene.chr${chr}.txt done exit <file_sep># Boolean Test Analysis pipeline in https://docs.google.com/document/d/1n-J9JCxGNnsJ26eVI-tEl4pFy85wu6ZAMv1X7zdOhBk/ The code was tested using: * python 3.7 * pandas 0.24.2 * numpy 1.17.0 * mord 0.6 * matplotlib 3.1.0 * seaborn 0.10.1
03fb2c82c97661ef82d042ccd93c5f2074a027da
[ "Markdown", "Python", "Shell" ]
3
Python
nicolapicchiotti/covid_pmm
d9e43254913a29ee38626496b82c2b75aeac41f4
05e750aa4fa08e5b42ab2112d9ba0d81ce492cf6
refs/heads/master
<repo_name>GNSSNews/TingClass<file_sep>/README.md # TingClass 批量下载TingClass的MP3文件,简化手动下载模式。 用户手册 Note: TingClass采用了Python3的标准库urllib,引用了BeautifulSoup4,需要提前安装。 Windows下可以直接用pip install bs4指令进行安装; mp3_spider函数的参数说明: 参数1: 本地目录,请自行创建; 参数2: 节目目录地址,请去掉最后的"1.html"; 参数3: 节目目录页码,下图中就下载第1页; 参数4: 节目目录页码超出值,小于该值的会搜索; 参数5: 节目名称; import TingClass; TingClass.mp3_spider("H:\\english\\9695-科学一刻", "http://www.tingclass.net/list-9695-", 3, 5, "科学一刻"); TingClass.mp3_spider("H:\\english\\201605-VOA慢速英语", "http://www.tingclass.net/list-8335-", 1, 2, "VOA慢速英语"); TingClass.mp3_spider("H:\\english\\201604-VOA常速英语", "http://www.tingclass.net/list-9768-", 1, 3, "VOA常速英语"); <file_sep>/TingClass.py #!/usr/bin/paython # file name: TingClass.py __version__ = "ver 3.3"; ''' Author: GNSSNews Email: <EMAIL> ''' import os; import urllib.request; import re; from urllib.error import URLError, HTTPError; from bs4 import BeautifulSoup; def mp3_download(dirPath, name, url) : try: fout = urllib.request.urlopen(url); except HTTPError as e: print('%s, HTTPError: %s' %(name, e.code)); except URLError as e: print('%s, URLError: %s' %(name, e.reason)); except UnicodeEncodeError as e: print('%s, UnicodeEncodeError: %s' %(name, e.reason)); else: resp = fout.read(); fPath = dirPath + '\\' + name; try: with open(fPath, 'wb') as f: f.write(resp); f.close(); print("%s" %(name)); except IOError as err: print("File Error: %s" %(str(err))); # End of { try: } # End of { try: } # End of function mp3_download def mp3_searchItem(localDir, sidx, sName, url) : sName = sName.replace(u":", ""); sName = sName.replace(u":", " "); sName = sName.replace(u"?", " "); sName = sName.lstrip(); sName = sName.rstrip(); url = url.replace(u"show", u"down"); # print("%s,%s,%s" %(sidx, sName, url)); try: fo1 = urllib.request.urlopen(url); except HTTPError as e: print('%s, HTTPError: %s' % (sName, e.code)); except URLError as e: print('%s, URLError: %s' % (sName, e.reason)); else: '''<a rel="external nofollow" href="http://down010702.tingclass.net/lesson/shi0529/0009/9695/2016_03_24_apes_and_movies.mp3" class="lrc f16 botton" onclick="_hmt.push(['_trackEvent', 'mp3_download', 'click', 'mp3_download'])">MP3普通下载</a>''' bsO1 = BeautifulSoup(fo1, "html.parser"); urldest = bsO1.find("a", text="MP3普通下载"); sName = sidx + '-' + sName + '.mp3'; # print('%s' % (urldest.attrs['href'])); if os.path.exists(sName) : print('---skip,%s' % (sName)); else : mp3_download(localDir, sName, urldest.attrs['href']); # End of { if os.path.exists(sfName1) } # End of { try: } # End of function mp3_searchItem ''' <li class="clearfix"> <em class="fr">浏览:19</em> <span class="fl class_num">第4课:</span> <a class="ell" href="http://www.tingclass.net/show-9695-359947-1.html" target="_blank" title="科学一刻 猿和电影">科学一刻 猿和电影</a> </li> ''' ''' <dl class="list-1-con clearfix"> <dt><span class="data-in fr">2016-03-31</span> <a href="http://www.tingclass.net/show-9735-360719-1.html" target="_blank">VOA常速英语:工人阶级的不满使特朗普在威斯康辛州人气大增</a> </dt> </dl> ''' def mp3_search(localDir, fout, sTyName) : bsObj = BeautifulSoup(fout, "html.parser"); nameList = bsObj.findAll("li", {"class":"clearfix"}); # print("search li<clearfix>"); number=0; for ss in nameList: number = number + 1; sidx = ss.span.get_text(); sidx = sidx.replace(u"第", ""); sidx = sidx.replace(u"课", ""); sidx = sidx.replace(u":", ""); sName = ss.a.get_text(); sName = sName.replace(sTyName, ""); mp3_searchItem(localDir, sidx, sName, ss.a['href']); # End of { for ss in nameList } if (number == 0) : nameList = bsObj.findAll("dl", {"class":"list-1-con clearfix"}); # print("search dl<clearfix>"); for ss in nameList: number = number + 1; sidx = ss.span.get_text(); sName = ss.a.get_text(); sName = sName.replace(sTyName, ""); mp3_searchItem(localDir, sidx, sName, ss.a['href']); if (number == 0) : nameList = bsObj.findAll("ul", {"class":"list-unit"}); # print("search ul<unit>"); for ss in nameList: liList = ss.findAll("li"); for s1 in liList: number = number + 1; sidx = s1.em.get_text(); s1a = s1.find("a", {"class":"ell"}); sName = s1a.get_text(); sName = sName.replace(sTyName, ""); mp3_searchItem(localDir, sidx, sName, s1a.attrs['href']); # End of { for s1 in liList } # End of { for ss in nameList } # End of { if (0 == number) } # End of function mp3_search def mp3_spider(localDir, urlDir, idxMin, idxMax, sTyName): '''os.chdir(r'H:\english\9785'); urlDir = 'http://www.tingclass.net/list-8703-1.html'; idxMin = 1; idxMax = 10; ''' suffix = ".html"; os.chdir(localDir); tl = len(sTyName); for i in range(idxMin, idxMax, 1): fileName = str(i) + suffix; url = urlDir + fileName; print('%s' % (url)); req = urllib.request.Request(url); req.add_header('User-Agent', 'Mozilla/6.0'); try: fout = urllib.request.urlopen(url); except HTTPError as e: print('%s, HTTPError: %s' % (fileName, e.code)); except URLError as e: print('%s, URLError: %s' % (fileName, e.reason)); else: mp3_search(localDir, fout, sTyName); # End of { try: } # End of {for i in range( ...)} # End of function mp3_spider #mp3_spider("H:\english\9695-科学一刻", "http://www.tingclass.net/list-9695-", 1, 5, "科学一刻");
e53485cdf5a4a10c4e6ecdfde4db73aed59a3c64
[ "Markdown", "Python" ]
2
Markdown
GNSSNews/TingClass
fbbcdfc363daa5b3e78a78561466784eac46afc4
1120797e2a777d934071ab9a76a53db1c2a4208c
refs/heads/master
<repo_name>morettic2015/SmartcitiesMobileClient<file_sep>/.gradle/2.8/taskArtifacts/cache.properties #Wed Feb 24 18:59:48 BRT 2016 <file_sep>/app/src/main/java/view/infoseg/morettic/com/br/infosegapp/actions/AssyncUploadURLlink.java package view.infoseg.morettic.com.br.infosegapp.actions; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import org.json.JSONObject; import view.infoseg.morettic.com.br.infosegapp.util.HttpFileUpload; import view.infoseg.morettic.com.br.infosegapp.util.HttpUtil; import view.infoseg.morettic.com.br.infosegapp.util.ValueObject; import view.infoseg.morettic.com.br.infosegapp.view.InfosegMain; /** * Created by LuisAugusto on 24/02/2016. */ public class AssyncUploadURLlink extends AsyncTask<JSONObject, Void, String> { public static final String UPLOAD_URL = "http://gaeloginendpoint.appspot.com/upload.exec"; private ProgressDialog dialog; private Activity a1; private Bitmap bitmapM; private boolean origemIsOcorrencia = false; public void setOrigemOcorrencia(boolean isIt) { this.origemIsOcorrencia = isIt; } @Override protected void onPreExecute() { dialog.setMessage("Fazendo upload..."); dialog.show(); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (dialog.isShowing()) { dialog.dismiss(); } } public AssyncUploadURLlink(InfosegMain activity, Bitmap b1) { this.dialog = new ProgressDialog(activity); this.a1 = activity; this.bitmapM = b1; } protected String doInBackground(JSONObject... urls) { JSONObject js = null; // Creating new JSON Parser try { js = HttpUtil.getJSONFromUrl(UPLOAD_URL); ValueObject.URL_SUBMIT_UPLOAD = js.getString("uploadPath"); // CALL THIS METHOD TO GET THE URI FROM THE BITMAP Uri tempUri = HttpUtil.getImageUri(a1.getApplicationContext(), this.bitmapM); // CALL THIS METHOD TO GET THE ACTUAL PATH String realPathInSO = HttpUtil.getRealPathFromURI(tempUri, this.a1); String fTYpe = realPathInSO.substring(realPathInSO.length() - 3, realPathInSO.length()); if (ValueObject.URL_SUBMIT_UPLOAD != null) { js = HttpFileUpload.uploadFile(realPathInSO, ValueObject.URL_SUBMIT_UPLOAD, fTYpe); js = HttpUtil.getJSONFromUrl(HttpUtil.getSaveImagePath(js.getString("fName"), js.getString("token"))); //Salva em lugares distintos if (origemIsOcorrencia) { ValueObject.UPLOAD_PIC_OCORRENCIA = js.getString("key"); ValueObject.UPLOAD_PIC_OCORRENCIA_TOKEN = js.getString("token"); } else { ValueObject.UPLOAD_AVATAR = js.getString("key"); ValueObject.UPLOAD_AVATAR_TOKEN = js.getString("token"); } } //Salva a imagem no banco e retorna seus parametros } catch (Exception e) { js = new JSONObject(); ValueObject.URL_SUBMIT_UPLOAD = null; //e.printStackTrace(); } finally { return js.toString(); } } }<file_sep>/app/src/main/java/view/infoseg/morettic/com/br/infosegapp/util/HttpUtil.java package view.infoseg.morettic.com.br.infosegapp.util; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.provider.MediaStore; import org.json.JSONObject; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import static java.net.URLEncoder.encode; /** * Created by LuisAugusto on 24/02/2016. * * http://gaeloginendpoint.appspot.com/upload.exec */ public class HttpUtil { public static String getText(String url) throws Exception { StringBuilder response = new StringBuilder(); try { URL website = new URL(url); URLConnection connection = website.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); }catch(Exception e){ e.printStackTrace(); }finally { return response.toString(); } } public static JSONObject getJSONFromUrl(String url) throws Exception { String json = getText(url); return new JSONObject(json); } public static Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); return Uri.parse(path); } public static String getRealPathFromURI(Uri uri,Activity a) { Cursor cursor = a.getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); return cursor.getString(idx); } public static final String getSaveImagePath(String image, String token){ return "http://gaeloginendpoint.appspot.com/infosegcontroller.exec?action=2&iName"+image+"&iToken="+token; } public static final String getSaveUpdateProfile(String email,String avatar,String nome,String cpfCnpj,String cep,String passwd, String complemento, boolean pjf,String nasc,String id) throws UnsupportedEncodingException { return "http://gaeloginendpoint.appspot.com/infosegcontroller.exec?action=3&" + "email="+email+ "&avatar="+avatar+ "&nome="+ encode(nome, "UTF-8")+ "&cpfCnpj="+cpfCnpj+ "&cep="+cep+ "&passwd="+passwd+ "&complemento="+ encode(complemento)+ "&pjf="+Boolean.toString(pjf)+ "&nasc="+nasc+ "&id="+id; } public static final String getSaveOcorrenciaPath(String tit,double lat, double lon, String desc, String idPic, String tipo, String idProfile,String address){ return "http://gaeloginendpoint.appspot.com/infosegcontroller.exec?action=1&" + "titulo=" + encode(tit) + "&lat=" + lat + "&lon=" + lon + "&desc=" + encode(desc) + "&idPic=" + idPic + "&tipo=" + tipo + "&address=" + encode(address) + "&idProfile="+ idProfile; } public static final String getOcorrenciasPath(String pId,String pLat, String pMine, String distance, String types){ String r = "http://gaeloginendpoint.appspot.com/infosegcontroller.exec?action=6" + "&id=" + pId + "&lat=" + pLat + "&d="+ distance + "&type="+types ; if(pMine!=null) r+= "&mine"; return r; } public static Bitmap getBitmapFromURLBlobKey(String src) throws IOException { String urlImage = "http://gaeloginendpoint.appspot.com/infosegcontroller.exec?action=8&id="+encode(src); URL url = new URL(urlImage); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } public static final String getPathLoginRegister(String login,String senha){ return "http://gaeloginendpoint.appspot.com/infosegcontroller.exec?action=7&email="+encode(login)+"&pass="+encode(senha); } public static final Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // create a matrix for the manipulation Matrix matrix = new Matrix(); // resize the bit map matrix.postScale(scaleWidth, scaleHeight); // recreate the new Bitmap Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); return resizedBitmap; } public static final String getTokenImagemById(String id){ return "http://gaeloginendpoint.appspot.com/infosegcontroller.exec?action=8&id="+encode(id); } public static final String getTokenImagemById(){ return "http://gaeloginendpoint.appspot.com/infosegcontroller.exec"; } public static final String getGeocodingUrl(String lat,String lon){ return "https://maps.googleapis.com/maps/api/geocode/json?key=<KEY>&latlng="+lat+","+lon+"&sensor=true"; } } <file_sep>/app/src/main/java/view/infoseg/morettic/com/br/infosegapp/view/ActivityConfig.java package view.infoseg.morettic.com.br.infosegapp.view; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import static view.infoseg.morettic.com.br.infosegapp.util.ValueObject.*; import view.infoseg.morettic.com.br.infosegapp.R; import view.infoseg.morettic.com.br.infosegapp.util.ValueObject; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ActivityConfig.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ActivityConfig#newInstance} factory method to * create an instance of this fragment. */ public class ActivityConfig extends Fragment { private CheckBox ehMeu, eMeuEstado,ehMinhaCidade, ehMeuPais, saude,transporte,meioAmbiente, educacao, seguranca, politica; private Button bt; private View v; private SharedPreferences.Editor editor; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment InfosegMain.setTitleToolbar("Configurações", container); editor = ValueObject.MY_PREFERENCES.edit(); v = inflater.inflate(R.layout.activity_config, container, false); bt = (Button) v.findViewById(R.id.btSalvarPreferencias); ehMeu = (CheckBox) v.findViewById(R.id.chkMine); eMeuEstado = (CheckBox) v.findViewById(R.id.chkEstado); ehMinhaCidade = (CheckBox) v.findViewById(R.id.chkCity); ehMeuPais = (CheckBox) v.findViewById(R.id.chkPais); saude = (CheckBox) v.findViewById(R.id.chkSaude); transporte = (CheckBox) v.findViewById(R.id.chkTransporte); meioAmbiente = (CheckBox) v.findViewById(R.id.chkMeioAmbiente); educacao = (CheckBox) v.findViewById(R.id.chkEducacao); seguranca = (CheckBox) v.findViewById(R.id.chkSeguranca); politica = (CheckBox) v.findViewById(R.id.chkPolitica); bt.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { editor.putBoolean("ehMeu",ehMeu.isChecked()).commit(); editor.putBoolean("eMeuEstado",eMeuEstado.isChecked()).commit(); editor.putBoolean("ehMinhaCidade",ehMinhaCidade.isChecked()).commit(); editor.putBoolean("ehMeuPais",ehMeuPais.isChecked()).commit(); editor.putBoolean("saude",saude.isChecked()).commit(); editor.putBoolean("transporte",transporte.isChecked()).commit(); editor.putBoolean("meioAmbiente",meioAmbiente.isChecked()).commit(); editor.putBoolean("educacao",educacao.isChecked()).commit(); editor.putBoolean("seguranca",seguranca.isChecked()).commit(); editor.putBoolean("politica",politica.isChecked()).commit() ; } }); //Init values from pref commited ehMeu.setChecked(MY_PREFERENCES.getBoolean("ehMeu",false)); eMeuEstado.setChecked(MY_PREFERENCES.getBoolean("eMeuEstado",false)); ehMinhaCidade.setChecked(MY_PREFERENCES.getBoolean("ehMinhaCidade",false)); ehMeuPais.setChecked(MY_PREFERENCES.getBoolean("ehMeuPais",false)); saude.setChecked(MY_PREFERENCES.getBoolean("saude",false)); transporte.setChecked(MY_PREFERENCES.getBoolean("transporte",false)); meioAmbiente.setChecked(MY_PREFERENCES.getBoolean("meioAmbiente",false)); educacao.setChecked(MY_PREFERENCES.getBoolean("educacao",false)); seguranca.setChecked(MY_PREFERENCES.getBoolean("seguranca",false)); politica.setChecked(MY_PREFERENCES.getBoolean("politica",false)); return v; } } <file_sep>/app/src/main/java/view/infoseg/morettic/com/br/infosegapp/view/LoginFragment.java package view.infoseg.morettic.com.br.infosegapp.view; import android.app.Activity; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import view.infoseg.morettic.com.br.infosegapp.R; import view.infoseg.morettic.com.br.infosegapp.actions.AssyncLoginRegister; import view.infoseg.morettic.com.br.infosegapp.util.ValueObject; import static view.infoseg.morettic.com.br.infosegapp.util.ValueObject.MY_PREFERENCES; /** * Created by LuisAugusto on 02/03/2016. */ public class LoginFragment extends DialogFragment { private Button btLogin; private EditText email, senha; static LoginFragment newInstance() { return new LoginFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, R.style.MyDialog); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.dialog_login, container, false); btLogin = (Button) v.findViewById(R.id.btLoginRegister1); email = (EditText) v.findViewById(R.id.txtEmailLG); senha = (EditText) v.findViewById(R.id.txtSenhaLG); email.setText(MY_PREFERENCES.getString("email", "")); senha.setText(MY_PREFERENCES.getString("passwd", "")); btLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (email.getText().toString() == null || email.getText().toString().equals("")) { email.setFocusable(true); } else if (senha.getText().toString() == null || senha.getText().toString().equals("")) { senha.setFocusable(true); } else { AssyncLoginRegister assyncLoginRegister = new AssyncLoginRegister(v, email.getText().toString(), senha.getText().toString()); assyncLoginRegister.execute(); } } }); return v; } public void onDismiss(final DialogInterface dialog) { //final Activity activity = getActivity(); if (!ValueObject.AUTENTICADO) { LoginFragment loginFragment = LoginFragment.newInstance(); loginFragment.show(getFragmentManager(), "dialog"); } else { this.dismiss(); } } public void onStart() { super.onStart(); // safety check if (getDialog() == null) return; int width = getResources().getDimensionPixelSize(R.dimen.popup_width); int height = getResources().getDimensionPixelSize(R.dimen.popup_height); getDialog().getWindow().setLayout(width, height); getDialog().getWindow().setLayout(width, height); // ... other stuff you want to do in your onStart() method } }<file_sep>/app/src/main/java/view/infoseg/morettic/com/br/infosegapp/actions/AssyncLoginRegister.java package view.infoseg.morettic.com.br.infosegapp.actions; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.view.View; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; import java.net.URLEncoder; import view.infoseg.morettic.com.br.infosegapp.util.HttpFileUpload; import view.infoseg.morettic.com.br.infosegapp.util.HttpUtil; import view.infoseg.morettic.com.br.infosegapp.util.ValueObject; import view.infoseg.morettic.com.br.infosegapp.view.InfosegMain; import static java.net.URLEncoder.*; /** * Created by LuisAugusto on 24/02/2016. */ public class AssyncLoginRegister extends AsyncTask<JSONObject, Void, String> { public static final String LOGIN_URL = "http://gaeloginendpoint.appspot.com/upload.exec"; private ProgressDialog dialog; private View a1; private String email, senha; private SharedPreferences.Editor editor = ValueObject.MY_PREFERENCES.edit(); @Override protected void onPreExecute() { dialog.setMessage("Autenticando..."); dialog.show(); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (dialog.isShowing()) { dialog.dismiss(); } if (ValueObject.AUTENTICADO) { ValueObject.LOGIN.dismiss(); } } public AssyncLoginRegister(View activity, String login, String senha) { this.dialog = new ProgressDialog(activity.getContext()); this.a1 = activity; this.email = login; this.senha = senha; //builder = new AlertDialog.Builder(this.a1.getContext()); } protected String doInBackground(JSONObject... urls) { JSONObject js = null; // Creating new JSON Parser public static final String getSaveUpdateProfile(String email,String avatar,String nome,String cpfCnpj,String cep,String passwd, String complemento, boolean pjf,String nasc,String id){ try { //Validacao @TODO //URL PARA SALVAR O PERFIL. String url = HttpUtil.getPathLoginRegister(email, senha); //url = js = HttpUtil.getJSONFromUrl(url); if (js.has("erro")) { ValueObject.AUTENTICADO = false; } else { /** * { nasc: "18/2/2016", cpfCnpj: "028.903.629-14", complemento: "Jsnsns", cep: "88020100", email: "<EMAIL>", nome: "<NAME>", avatar: 5464390522372096, key: 6272386882076672, pass: "<PASSWORD> } * */ ValueObject.ID_PROFILE = js.getString("key"); ValueObject.UPLOAD_AVATAR = js.getString("avatar"); this.editor.putString("nome", js.getString("nome")).commit(); this.editor.putString("cpfCnpj", js.getString("cpfCnpj")).commit(); this.editor.putString("cep", js.getString("cep")).commit(); this.editor.putString("passwd", js.getString("pass")).commit(); this.editor.putString("complemento", js.getString("complemento")).commit(); this.editor.putBoolean("pjf", Boolean.getBoolean(js.getString("pjf"))).commit(); this.editor.putString("nasc", js.getString("nasc")).commit(); this.editor.putString("email", js.getString("email")).commit(); this.editor.putString("id", ValueObject.ID_PROFILE).commit(); this.editor.putString("avatar", ValueObject.UPLOAD_AVATAR).commit(); ValueObject.AUTENTICADO = true; try { // url = HttpUtil.getTokenImagemById(ValueObject.UPLOAD_AVATAR); // js = HttpUtil.getJSONFromUrl(url); ValueObject.AVATAR_BITMAP = HttpUtil.getBitmapFromURLBlobKey(js.getString("avatar")); ValueObject.AVATAR_BITMAP = HttpUtil.getResizedBitmap(ValueObject.AVATAR_BITMAP, 96, 96); } catch (Exception e) { e.printStackTrace(); } //ValueObject.LOGIN.dismiss(); } } catch (Exception e) { js = new JSONObject(); // ValueObject.URL_SUBMIT_UPLOAD = null; //e.printStackTrace(); } finally { return js.toString(); } } }
971e398e43f62c4eba87927ecf01a969a08ad086
[ "Java", "INI" ]
6
INI
morettic2015/SmartcitiesMobileClient
5f6f5e5469dabc48d19761ad454de0e70939fa08
efa36ec323daafc9169a0a3b7d11aaade7b385e3
refs/heads/master
<repo_name>firearthur/fullstack-review<file_sep>/server/index.js const express = require('express'); let app = express(); const db = require('../database'); const bodyParser = require('body-parser'); const githubAPI = require('../helpers/github'); // UNCOMMENT FOR ANGULARJS // app.use(express.static(__dirname + '/../angular-client')); // app.use(express.static(__dirname + '/../node_modules/angular')); app.use(express.static(__dirname + '/../react-client/dist')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true})); app.post('/repos', function (req, res) { githubAPI.getReposByUsername(req.body.username, (err, data)=>{ if(err) { res.send(err); } if(data) { res.send(201); } }); }); app.get('/repos', function (req, res) { db.getRepos((err, repos)=>{ res.send(repos); }); }); let port = 1128; app.listen(port, function() { console.log(`listening on port ${port}`); }); <file_sep>/react-client/src/components/RepoList.jsx import React from 'react'; const RepoList = (props) => ( <div> <h4> Repo List Component </h4> There are {props.repos.length} repos. {props.repos.map((repo, key)=>( <div key = {key}> <h3>Repo name: {repo.name}</h3> <small>ID: {repo.id}</small> <h5>Owner: {repo.owner}</h5> <strong>Stars: {repo.starsCount}</strong> </div> ))} </div> ) export default RepoList;<file_sep>/database/index.js const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/fetcher'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { // we're connected! }); let repoSchema = mongoose.Schema({ // TODO: your schema here! id: { type: Number, unique: true, dropDups: true }, name: String, starsCount: Number, owner: String, ownersGithubId: Number, ownersUrl: String }); let Repo = mongoose.model('Repo', repoSchema); // Repo.remove({}, (err, success)=> { //dropping the database // if(err) { // console.log(err); // } else { // console.log('Repos dropped'); // } // }) let save = (repos, callback) => { // console.log('repos from database index.js', repos); console.log('im about to save the repos that i got from git hub api'); if (repos){ let mappedRepos = repos.map((repo) => { return { id: repo.id, name: repo.name, starsCount: repo.stargazers_count, owner: repo.owner.login, ownersGithubId: repo.owner.id, ownersUrl: repo.owner.url, }; }); Repo.insertMany(mappedRepos,(err, data)=>{ if(err) { callback(err, null); } callback(null, data); }); } else { console.log('I got empty repos at index js in database'); } } let getRepos = (callback) => { Repo. find(). limit(25). sort('-starsCount'). select(''). exec(callback); // Repo.find(function (err, repos) { // if (err) return console.log(err); // callback(repos); // }) }; module.exports.getRepos = getRepos; module.exports.save = save; <file_sep>/helpers/github.js const request = require('request'); const config = require('../config.js'); const db = require('../database'); let getReposByUsername = (username, callback) => { let options = { method: "GET", url: `https://api.github.com/users/${username}/repos`, headers: { 'User-Agent': 'request', 'Authorization': `token ${config.TOKEN}`, } }; request(options, function(err, res){ if(err) console.log('error ', err); console.log('I just got the repos back from Github API'); let data = JSON.parse(res.body) db.save(data, callback); // console.log('ARE WE DOING ANYTHING!?', data); }) } module.exports.getReposByUsername = getReposByUsername;
5bf25624fd870c4f802a575ace559fb705bfb8f9
[ "JavaScript" ]
4
JavaScript
firearthur/fullstack-review
4145128da071ff129727b1378697ff123f95e980
b9c3866d84915d087b73eff020ac9abd4859c043
refs/heads/master
<repo_name>thedangerreaganzone/Project9<file_sep>/src/Orchestra/Project9.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Orchestra; import java.util.ArrayList; /** * * @author michael */ public class Project9 { /** * @param args the command line arguments */ public static void main(String[] args) { Instrument kazoo = new Kazoo(); Instrument electricguitar = new ElectricGuitar(); Instrument triangle = new Triangle(); //add your new instrument to this list ArrayList<Instrument> orchestra = new ArrayList<Instrument>(); orchestra.add(kazoo); orchestra.add(electricguitar); orchestra.add(triangle); System.out.println("Welcome to the orchestra, please sit back... relax and enjoy!\n"); System.out.println("We will be playing the following instruments.\n"); for(int i = 0; i < orchestra.size(); i++) { Instrument current_instrument = orchestra.get(i); System.out.println(current_instrument); } System.out.println("\nLet us begin!"); for(int i = 0; i < orchestra.size(); i++) { Instrument current_instrument = orchestra.get(i); for(int j = 0; j < current_instrument.numberOfMoments(); j++){ System.out.println(current_instrument.getSoundOne()); System.out.println(current_instrument.getSoundTwo()); System.out.println(current_instrument.getSoundThree()); } System.out.println(""); } } }<file_sep>/src/Orchestra/ElectricGuitar.java package Orchestra; public class ElectricGuitar extends Instrument{ public String getName() { return "Electric Guitar"; } public String getDescription() { return "Like a regular guitar except it uses that zappy stuff"; } public int numberOfMoments() { return 1; } public String getSoundOne() { return "WAAAAAHHHHHHHH"; } public String getSoundTwo() { return "*shredding*"; } public String getSoundThree() { return "Don't Fear The Reaper riff"; } public String toString() { return this.getName() + "\n" + this.getDescription(); } } <file_sep>/README.md # Project9 We will be using this project to explore Git, AbstractClasses and Interfaces. Instructions. 1. Fork this repository to your own Account. 2. Clone the repository down to your own computer into your NetBeansProjects diretory. Where all the rest of your projets are stored. 3. Add the remote of the master project through the interface or through the command line. git remote add origin <EMAIL>:JDCHS-AP-CompSci-A/Project9.git 4. Add a new subclass of Insturment of whatever instrument you would like as long as it is different from your classmates. We will make a list. 5. Implement all of the functions in the Playable interface and override the methods in the Abstract Class Instrument. 6. Instantiate one of your new instruments in the main function and add it to the orchestra like seen with the Kazoo. 7. Run the program and ensure its working without errors. 8. Push your code up to your fork of Project9 with a good commit message. 9. Open a pull request against the master branch of Project 9 with your instrument as the title. <file_sep>/src/Orchestra/Instrument.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Orchestra; /** * * @author michael */ public abstract class Instrument implements Playable { /** * Returns an String representing the name of the instrument. */ public String getName() { return "Basic Instrument"; } /** * Returns a String representing the description of the instrument. */ public String getDescription() { return "Basic Instrument Description"; } } <file_sep>/nbproject/private/private.properties compile.on.save=true user.properties.file=/home/nicholasreagan/Library/Application Support/NetBeans/8.2/build.properties
a7cd741e806070653b9b6d83ad950cfef4c6f3a4
[ "Markdown", "Java", "INI" ]
5
Java
thedangerreaganzone/Project9
36c801aec5f982dfdcb677cb0753111f08973d1d
a3f6e3c8cd33b630351efd4a67f79f39cd678646
refs/heads/master
<file_sep>impl Solution { pub fn get_no_zero_integers(n: i32) -> Vec<i32> { fn contains_zero(i: i32) -> bool { let s = i.to_string(); s.contains('0') } for i in 1..=n / 2 { if contains_zero(i) || contains_zero(n - i) { continue; } else { return vec![i, n - i]; } } vec![0, 0] //unreachable!() } }<file_sep>impl Solution { pub fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> { let n = n as usize; let mut shuffled= vec![0; 2*n]; for i in 0..n { shuffled[i*2] = nums[i]; shuffled[i*2 + 1] = nums[n+i]; } shuffled } }<file_sep>impl Solution { pub fn maximum69_number (num: i32) -> i32 { let s = num.to_string(); let mut c = String::new(); let mut d = false; for i in s.chars() { if i=='6' && !d { c.push('9'); d=true; } else { c.push(i); } } c.parse::<i32>().unwrap() } }<file_sep>impl Solution { pub fn reorder_spaces(text: String) -> String { let mut s = String::new(); let t = text.len(); let mut v:Vec<&str> = text.split_whitespace().collect(); let mut l=0; for i in &v { l += i.len(); } if v.len()==1 { s = v[0].to_string(); if l<t { s = s+ &" ".repeat(t-l) } return s; } let words = (t-l)/( v.len()-1 ); let spaces=" ".repeat(words); let words = v.len() -1; let mut j=0; for j in 0..words { s = s + v[j] + &spaces; } s =s + v[v.len()-1]; l = s.len(); if l<t { s = s + &" ".repeat(t-l); } s } }<file_sep>impl Solution { pub fn generate(num_rows: i32) -> Vec<Vec<i32>> { let mut ret: Vec<Vec<i32>> = Vec::new(); for i in 0..num_rows as usize { ret.push((1..i).fold(vec![1; i + 1], |mut acc, j| { acc[j] = ret[i-1][j-1] + ret[i-1][j]; acc })); } ret } }<file_sep>impl Solution { pub fn thousand_separator(mut n: i32) -> String { let mut ans = String::new(); let mut count = 0; while n > 0 { ans.insert(0, (b'0' + (n % 10) as u8) as char); n /= 10; count += 1; if count == 3 && n > 0 { ans.insert(0, '.'); count = 0; } } if ans.is_empty() { ans.push('0') } ans } }<file_sep>impl Solution { pub fn is_prefix_of_word(sentence: String, search_word: String) -> i32 { let mut string_set:Vec<&str> = sentence.split(" ").collect(); for i in 0..string_set.len() { if string_set[i].starts_with(&search_word) { return i as i32 + 1; } } -1 } }<file_sep>use std::collections::HashSet; impl Solution { pub fn is_path_crossing(path: String) -> bool { let mut visited:HashSet<i32> = HashSet::new(); let mut cur = 0; visited.insert(0); for i in path.chars() { if i=='N' { cur += 10_000; } else if i=='E' { cur += 1; } else if i=='S' { cur -= 10_000; } else if i=='W' { cur-=1; } if visited.contains(&cur) { return true; } visited.insert(cur); } false } }<file_sep>impl Solution { pub fn max_product(nums: Vec<i32>) -> i32 { let mut m1 = 0; let mut m2 = 0; for i in nums.iter() { if m1<*i { m2 = m1; m1 = *i; } else if m2<*i { m2 = *i; } } (m1-1)*(m2-1) } }<file_sep>All files are in src. <file_sep>impl Solution { pub fn balanced_string_split(s: String) -> i32 { let mut x:i32=0; let mut count=0; for c in s.chars(){ if c=='L'{ x+=1; } else{ x-=1; } if(x==0){ count+=1; } } count } }<file_sep>impl Solution { pub fn min_start_value(nums: Vec<i32>) -> i32 { let mut sum=0; let mut min=0; for i in nums.iter() { sum+=i; if sum<min { min=sum; } } if min>=0 { return 1; } min*(-1)+1 } }<file_sep>use std::io; fn main() { let mut arr = String::new(); let mut vec1: Vec<i64> = Vec::new(); io::stdin() .read_line(&mut arr) .expect("Error"); let mut arr: Vec<&str> = arr.trim().split_whitespace().collect(); for i in &arr { vec1.push( i.parse().unwrap() ); } println!("{:?}", vec1); }<file_sep>impl Solution { pub fn average(salary: Vec<i32>) -> f64 { let mut maxs = salary[0]; let mut mins = salary[0]; let mut sum = 0; for i in &salary { sum += i; if(*i>maxs) { maxs=*i; } else if(*i<mins) { mins=*i; } } (sum-maxs-mins) as f64/(salary.len()-2) as f64 } }<file_sep>impl Solution { pub fn freq_alphabets(s: String) -> String { let mut ans = String::new(); if s.is_empty() { return ans; } let mut v = s.chars().collect::<Vec<char>>(); while !v.is_empty() { let ch = v.pop().unwrap(); if ch == '#' { let mut ch2 = v.pop().unwrap(); let mut u = ch2 as u8 - '0' as u8; ch2 = v.pop().unwrap(); u += (ch2 as u8 - '1' as u8) * 10; ans.insert(0, (u + 'j' as u8) as char); } else { ans.insert(0, (ch as u8 - '1' as u8 + 'a' as u8) as char) } } ans } }<file_sep>impl Solution { pub fn restore_string(s: String, indices: Vec<i32>) -> String { let mut ch:Vec<char> = s.chars().collect(); let mut res:Vec<char> = s.chars().collect(); let mut j:usize = 0; for i in indices { res[i as usize] = ch[j]; j+=1; } res.into_iter().collect() } }<file_sep>impl Solution { pub fn sum_zero(n: i32) -> Vec<i32> { std::iter::once(-n * (n - 1) / 2).chain(1..n).collect() } }<file_sep>impl Solution { pub fn running_sum(nums: Vec<i32>) -> Vec<i32> { let mut sum = 0; let mut run_sum:Vec<i32> = Vec::new(); for i in nums.iter() { sum += i; run_sum.push(sum); } run_sum } }<file_sep>impl Solution { pub fn three_consecutive_odds(arr: Vec<i32>) -> bool { let mut count = 0; for i in arr { if i&1 == 1 { count += 1; if count>2 { return true; } } else { count = 0; } } false } }<file_sep>use std::collections::HashSet; impl Solution { pub fn dest_city(paths: Vec<Vec<String>>) -> String { let source: HashSet<String> = paths.iter().map(|v| v[0].clone()).collect(); let destination: HashSet<String> = paths.iter().map(|v| v[1].clone()).collect(); destination.difference(&source).collect::<Vec<&String>>()[0].to_string() } }<file_sep>impl Solution { pub fn max_power(s: String) -> i32 { let mut count=0; let mut max=0; let mut cur=']'; for ch in s.chars() { if ch!=cur { cur=ch; if max<count { max = count; } count=1; } else { count+=1; } } if count>max { return count; } max } }<file_sep>impl Solution { pub fn can_be_equal(mut target: Vec<i32>, mut arr: Vec<i32>) -> bool { target.sort(); arr.sort(); target == arr } }<file_sep>impl Solution { pub fn num_identical_pairs(nums: Vec<i32>) -> i32 { let mut count:i32 = 0; let mut n=nums.len(); for i in 0..&n - 1 as usize{ for j in &i + 1..n { if nums[i]==nums[j] { count += 1; } } } count } }<file_sep>impl Solution { pub fn count_odds(low: i32, high: i32) -> i32 { high/2 + (high&1) - low/2 } }<file_sep>impl Solution { pub fn reformat(s: String) -> String { let mut t = String::new(); let mut l:Vec<char> = Vec::new(); let mut d:Vec<char> = Vec::new(); for ch in s.chars() { if ch>='a' && ch<='z' { l.push(ch); } else { d.push(ch); } } if l.len() as i32 -d.len() as i32 >=2 || d.len() as i32 - l.len() as i32 >=2 { return t; } let mut m = d.len(); let mut n = l.len(); if m>n { while m>0 { t.push(d[m-1]); m-=1; if n>0 { t.push(l[n-1]); n-=1; } } } else { while n>0 { t.push(l[n-1]); n-=1; if m>0 { t.push(d[m-1]); m-=1; } } } t } }<file_sep>use std::collections::VecDeque; impl Solution { pub fn final_prices(ref mut ns: Vec<i32>) -> Vec<i32> { let n = ns.len(); let mut s = VecDeque::new(); for i in 0..n { let p = ns[i]; while !s.is_empty() && ns[*s.back().unwrap()] >= p { ns[s.pop_back().unwrap()] -= p; } s.push_back(i); } ns.to_vec() } }<file_sep>impl Solution { pub fn decompress_rl_elist(nums: Vec<i32>) -> Vec<i32> { let mut v:Vec<i32> = Vec::new(); let mut n; let mut m; let mut i=0; while i<nums.len() { n=nums[i]; i+=1; m=nums[i]; for j in 0..n{ v.push(m); } i+=1 } v } }<file_sep>impl Solution { pub fn kids_with_candies(candies: Vec<i32>, extra_candies: i32) -> Vec<bool> { let mut x = 0; let mut count:Vec<bool> = Vec::new(); for i in candies.iter() { if *i>x { x=*i; } } for i in candies { count.push(i+extra_candies >= x); } count } }
b86076b761cc853a32acad6c5952326a54e49bc5
[ "Markdown", "Rust" ]
28
Rust
VaibhavDS19/RustforLeetCode
5e92e66b317a558802c86da272b9832a5fa60a39
6fc668bd97ac86dd71abaa26ac6adf8d63492555
refs/heads/master
<repo_name>burt/sentinel<file_sep>/lib/sentinel/sentinel.rb module Sentinel class Sentinel def initialize(*args) attributes = args.extract_options! attributes.keys.each do |key| create_accessor_for_attribute(key) self.send("#{key}=", attributes[key]) if self.respond_to?("#{key}=") end end def [](temporary_overrides) temporary_overrides.keys.each do |key| create_accessor_for_attribute(key) end returning self.clone do |duplicate| temporary_overrides.keys.each do |key| if self.respond_to?("#{key}=") duplicate.send("#{key}=", temporary_overrides[key]) end end end end # Adds an authorisation scope to the associated model def self.auth_scope(name, block) model_class = self.name.demodulize.gsub("Sentinel", "").constantize model_class.send :named_scope, name.to_sym, block end # TODO: move this helper to class # source: http://blog.jayfields.com/2008/02/ruby-dynamically-define-method.html def self.def_each(*method_names, &block) method_names.each do |method_name| define_method method_name do instance_exec method_name, &block end end end # Adds rest methods, returning false in each case def_each :index, :create, :read, :update, :destroy do |method_name| false end private def create_accessor_for_attribute(attribute) unless self.respond_to?(attribute) || self.respond_to?("#{attribute}=") self.class_eval { attr_accessor attribute } end end end end <file_sep>/lib/sentinel/controller.rb module Sentinel module Controller def self.included(base) base.class_inheritable_writer :sentinel, :instance_writer => false base.class_inheritable_accessor :access_denied, :access_granted base.send :include, InstanceMethods base.extend ClassMethods base.class_eval do helper_method :sentinel end base.on_denied_with do respond_to do |format| format.html do render :text => "You do not have the proper privileges to access this page.", :status => :unauthorized end format.any { head :unauthorized } end end base.with_access do true end end module InstanceMethods def sentinel self.instance_eval(&self.class.sentinel) end end module ClassMethods # Macro to add restful access control by convention def restful_access_control model_name = self.name.demodulize.gsub("Controller", "").singularize.downcase.to_sym controls_access_with do model = instance_variable_get "@#{model_name}" "#{model_name.to_s.capitalize}Sentinel".constantize.new :current_user => current_user, model_name => model end self.grants_access_to :index, :only => [:index] self.grants_access_to :create, :only => [:new, :create] self.grants_access_to :read, :only => [:show] self.grants_access_to :update, :only => [:edit, :update] self.grants_access_to :destroy, :only => [:destroy] end def controls_access_with(&block) self.sentinel = block end def sentinel read_inheritable_attribute(:sentinel) end def on_denied_with(name = :default, &block) self.access_denied ||= {} self.access_denied[name] = block end def with_access(&block) self.access_granted = block end def grants_access_to(*args, &block) options = args.extract_options! block = args.shift if args.first.respond_to?(:call) sentinel_method = args.first denied_handler = options.delete(:denies_with) || :default before_filter(options) do |controller| if block if (block.arity == 1 ? controller.sentinel : controller).instance_eval(&block) controller.instance_eval(&controller.class.access_granted) else controller.instance_eval(&controller.class.access_denied[denied_handler]) end elsif sentinel_method && controller.sentinel && controller.sentinel.send(sentinel_method) controller.instance_eval(&controller.class.access_granted) else controller.instance_eval(&controller.class.access_denied[denied_handler]) end end end end end end <file_sep>/lib/sentinel/view_helper.rb module Sentinel module ViewHelper # Adds a permitted_to? helper to dry up views def permitted_to?(action, opts) sentinel[opts].send action end end end<file_sep>/lib/sentinel.rb %w{ controller sentinel view_helper }.each do |f| require File.join(File.dirname(__FILE__), "sentinel", f) end ActionController::Base.send :include, Sentinel::Controller ActionView::Base.send :include, Sentinel::ViewHelper
834ee7a0af82e9bc4ed5f2351b96d78e963a6441
[ "Ruby" ]
4
Ruby
burt/sentinel
a84cb60ddb7f307f21f9e4a1bb1bd24ac7123f30
38d193ec29da92d827208b579a40e9ae21d89d29
refs/heads/master
<file_sep>package com.tech.self.samples.flow; import org.springframework.context.annotation.Bean; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; @EnableIntegration @IntegrationComponentScan public class SimpleFlow { @MessagingGateway public interface MainFlow{ @Gateway(requestChannel="requestChannel") String hello(String name); } @Bean public IntegrationFlow firstFlow() { return IntegrationFlows.from("requestChannel") .transform("Hello "::concat) .get(); } } <file_sep># spring-integration spring integration dsl samples. Ref: https://github.com/spring-projects/spring-integration-java-dsl/wiki/spring-integration-java-dsl-reference <file_sep>package com.tech.self.samples.flow; import org.springframework.context.annotation.Bean; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.messaging.Message; import com.tech.self.samples.pojo.User; @EnableIntegration @IntegrationComponentScan public class EnrichFlow { @MessagingGateway public interface MainFlow{ @Gateway(requestChannel="requestChannel") Message<User> enrich(User user); } /** * header enricher - same way as payload (many implementation to add header) * payload enricher. * @return */ @Bean public IntegrationFlow firstFlow() { return IntegrationFlows.from("requestChannel") .enrichHeaders(h->h.header("key1", "value1") .header("key2", "value2")) .enrich(p->p.property("gender", "M")) .enrich(p->p.propertyExpression("fullName", "payload.firstName+' '+payload.lastName")) .enrich(p->p.propertyFunction("salary", f->addSalary())) .get(); } private double addSalary() { return 100.00; } } <file_sep>package com.tech.self.samples.flow; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.tech.self.samples.flow.SimpleFlow.MainFlow; @ContextConfiguration(classes= {SimpleFlow.class}) @RunWith(SpringJUnit4ClassRunner.class) public class SimpleFlowTest { @Autowired MainFlow flow; @Test public void testSimpleFlow() { System.out.println(flow.hello("saravanan")); } }
dbcda1ea3adfab9ff03cde4548c2b98a1c907968
[ "Markdown", "Java" ]
4
Java
saravanan84/spring-integration
9b2b14d750cbc1dca11af43de7f63b6996198249
451311df10f1e9ca970e14cf00e81145a075c14f
refs/heads/master
<repo_name>Slashxdd/task8<file_sep>/main.js "use sctrict"; class Pizza { constructor(img, name, consist, calories, price){ this.img = img; this.name = name; this.consist = consist; this.calories = calories; this.price = price; } } const Margarita = new Pizza("img/margarita.png", "Маргарита", "Соус маринара, помидоры, сыр моцарелла, соус песто", "460 ккал", "85 грн"); const Carbonara = new Pizza("img/carbonara.png", "Карбонара", "Сыр моцарелла, ветчина, грудинка, шампиньоны, пармезан, помидоры черри", "500 ккал", "159 грн"); const Pollo = new Pizza("img/pollo.png", "Полло", "Сыр моцарелла, соус маринара, соус ВВQ, чеснок, ананас, филе куриное sous-vide, перец болгарский", "550 ккал", "129 грн"); const Americano = new Pizza("img/americano.png", "Американо", "Соус BBQ, соус маринара, сыр моцарелла, горчица, филе куриное sous-vide, колбаски охотничьи, пепперони, конфитюр из лука, кукуруза, перец болгарский", "580 г", "149 грн"); const Calzone = new Pizza("img/calzone.png", "Кальцоне", "Соус маринара, сыр моцарелла, шампиньоны, сыр дор-блю, помидоры, ветчина, соус песто", "500 ккал", "115 грн"); const Diablo = new Pizza("img/diablo.png", "Диабло", "Сыр моцарелла, пепперони, перец чили, перец болгарский, лук репчатый, соус ВВQ,соус чили, петрушка", "530 ккал", "159 грн"); const Vegetable = new Pizza("img/vegetable.png", "Овощная", "Баклажан, вешенки, перец болгарский, помидоры, соус песто, соус маринара", "520 ккал", "89 грн"); const Berlusconi = new Pizza("img/berlusconi.png", "Берлускони", "Сливочный соус из белых грибов, сыр моцарелла, сыр дор-блю, пармезан, шампиньоны, вешенки, соус чесночный, масло трюфельное, петрушка", "530 ккал", "145 грн"); const Gourmeo = new Pizza("img/gourmeo.png", "Гурмео", "Соус BBQ, филе куриное sous-vide, ветчина, колбаски охотничьи, пеперони, сыр моцарелла, шампиньоны, лук репчатый, петрушка", "580 ккал", "165 грн"); const Hunting = new Pizza("img/hunting.png", "Охотничья", "Сыр моцарелла, сыр черный камамбер, соус из тунца, цуккини", "450 ккал", "149 грн"); const Bavarian = new Pizza("img/bavarian.png", "Баварская", "Сыр моцарелла, соус маринара, колбаски мюнхенские, колбаски охотничьи, огурец соленый, горчица, лук репчатый, лук зеленый", "620 ккал", "139 грн"); const Cheeses = new Pizza("img/cheeses.png", "Четыре сыра", "Сливочный соус, сыр моцарелла, сыр дор-блю, сыр чеддер, груша, сыр пармезан, орех грецкий", "430 ккал", "145 грн"); var array = []; // localStorage.setItem("basket", 0); // var basket = parseInt(localStorage.getItem("basket")); let count = document.getElementById("count"); count.innerText = localStorage.getItem("basket"); var globalSort = 0; var descriptions = document.getElementsByClassName("desc"); array.push(Margarita, Carbonara, Pollo, Americano, Calzone, Diablo, Vegetable, Berlusconi, Gourmeo, Hunting, Bavarian, Cheeses); var additional = ["сырный бортик", "пармезан", "аджика", "курица"]; var ccal = [50, 30, 15, 100]; var prices = [35, 15, 25, 50]; function byPrice(a,b) { if (parseInt(a.price.split(' ')) < parseInt(b.price.split(' '))){ return -1; } if (parseInt(a.price.split(' ')) > parseInt(b.price.split(' '))){ return 1; } return 0; } function byCalories(a,b) { if (parseInt(a.calories.split(' ')) < parseInt(b.calories.split(' '))){ return -1; } if (parseInt(a.calories.split(' ')) > parseInt(b.calories.split(''))){ return 1; } return 0; } sort = document.getElementById('sort'); ingredients = document.getElementById('ingredients'); bl = document.getElementsByClassName('s1'); sort.addEventListener('change', function() { let elem = document.getElementById("menu"); if (this.value === 'byPriceB') { array.sort(byPrice); if(globalSort === 1){ grid(); } else if(globalSort === 2){ list(); } else if(globalSort === 0){ alert("Выберите способ представления товаров!"); } } else if (this.value === 'byPriceL') { array.sort(byPrice); array.reverse(); if(globalSort === 1){ grid(); } else if(globalSort === 2){ list(); } else if(globalSort === 0){ alert("Выберите способ представления товаров!"); } } else if (this.value === 'byCaloriesB') { array.sort(byCalories); if(globalSort === 1){ grid(); } else if(globalSort === 2){ list(); } else if(globalSort === 0){ alert("Выберите способ представления товаров!"); } } else if (this.value === 'byCaloriesL') { array.sort(byCalories); array.reverse(); if(globalSort === 1){ grid(); } else if(globalSort === 2){ list(); } else if(globalSort === 0){ alert("Выберите способ представления товаров!"); } } }); ingredients.addEventListener('change', function() { for (let i = 0; i < bl.length; i++){ bl[i].style.opacity = 1; } if(globalSort === 1){ if (this.value === '<NAME>') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === 'помидоры') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === '<NAME>') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === 'пепперони') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === '<NAME>') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === 'сыр дор-блю') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === 'пармезан') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === 'соус из тунца') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } else if (this.value === 'сыр чеддер') { for (let i = 0; i < descriptions.length; i++){ if (!descriptions[i].innerText.includes(this.value)){ descriptions[i].parentElement.style.opacity = 0.5; } } } } else alert("Функция доступна только в режиме сетки!"); }); function grid(){ let elem = document.getElementById("menu"); while (elem.firstChild) { elem.removeChild(elem.firstChild); } globalSort = 1; for(let i=0; i<array.length; i++){ let block = document.createElement("div"); let img = document.createElement("img"); let name = document.createElement("h2"); let consist = document.createElement("p"); let calories = document.createElement("span"); let price = document.createElement("span"); consist.classList.add("desc"); block.classList.add("s1"); calories.classList.add("weight"); price.classList.add("price"); let addList = document.createElement("select"); addList.id = array[i].name; addList.classList.add("additionalList"); let addListItem = document.createElement("option"); addListItem.innerText = "--Добавить ингредиент--"; addListItem.value = array[i].name; addList.appendChild(addListItem); let buyBut = document.createElement("button"); buyBut.classList.add("buyBut"); buyBut.innerText = "Купить"; buyBut.setAttribute('data', "icon: '', name: ''"); buyBut.dataset.icon = array[i].img; buyBut.dataset.name = array[i].name; for(let i = 0; i<additional.length; i++){ let addListItem = document.createElement("option"); addListItem.value = i+1; addListItem.innerText = additional[i]; addList.appendChild(addListItem); } img.src = array[i].img; name.innerText = array[i].name; consist.innerText = array[i].consist; calories.innerText = array[i].calories; price.innerText = array[i].price; elem.appendChild(block); block.appendChild(img); block.appendChild(name); block.appendChild(calories); block.appendChild(consist); block.appendChild(price); block.appendChild(addList); block.appendChild(buyBut); imp = array[i].name; buyBut.addEventListener('click', function() { let count = document.getElementById("count"); if(count.innerText === "0"){ localStorage.setItem("basket", 0); } var basket = parseInt(localStorage.getItem("basket")); basket += 1; localStorage.setItem("basket", basket); count.innerHTML = ""; count.innerText = basket; localStorage.setItem(buyBut.dataset.name, buyBut.dataset.icon); for (var i = 0; i<localStorage.length; i++) { if(localStorage.key(i)==="basket") continue; let bought = document.getElementById("bought"); let block = document.createElement("div"); let img = document.createElement("img"); let name = document.createElement("h2"); let delBut = document.createElement("button"); delBut.innerText = "Удалить"; delBut.style.fontSize = "12px"; name.innerText = localStorage.key(i); img.src = localStorage.getItem(localStorage.key(i)); bought.appendChild(block); block.appendChild(img); block.appendChild(name); block.appendChild(delBut); delBut.addEventListener('click', function(){ localStorage.removeItem(name.innerText); basket-=1; localStorage.setItem("basket", basket); window.location.reload(); } ); } } ); addList.addEventListener('change', function(){ if(this.value === "1"){ let j1 = parseInt(array[i].calories.split(' ')); j1 += ccal[0]; let j2 = parseInt(array[i].price.split(' ')); j2 += prices[0]; calories.innerText = j1 + " ккал"; price.innerText = j2 + " грн"; } else if(this.value === "2"){ let j1 = parseInt(array[i].calories.split(' ')); j1 += ccal[1]; let j2 = parseInt(array[i].price.split(' ')); j2 += prices[1]; calories.innerText = j1 + " ккал"; price.innerText = j2 + " грн"; } else if(this.value === "3"){ let j1 = parseInt(array[i].calories.split(' ')); j1 += ccal[2]; let j2 = parseInt(array[i].price.split(' ')); j2 += prices[2]; calories.innerText = j1 + " ккал"; price.innerText = j2 + " грн"; } else if(this.value === "4"){ let j1 = parseInt(array[i].calories.split(' ')); j1 += ccal[3]; let j2 = parseInt(array[i].price.split(' ')); j2 += prices[3]; calories.innerText = j1 + " ккал"; price.innerText = j2 + " грн"; } } ); } } function list(){ let elem = document.getElementById("menu"); while (elem.firstChild) { elem.removeChild(elem.firstChild); } globalSort = 2; let list = document.createElement("ul"); elem.appendChild(list); list.classList.add("sort2"); for(let i=0; i<array.length; i++){ let item = document.createElement("li"); let img = document.createElement("img"); let name = document.createElement("span"); let calories = document.createElement("span"); let price = document.createElement("span"); name.classList.add("ulname"); calories.classList.add("ulweight"); price.classList.add("ulprice"); img.src = "img/pizza.png"; name.innerText = array[i].name; calories.innerText = array[i].calories; price.innerText = array[i].price; list.appendChild(item); item.appendChild(img); item.appendChild(name); item.appendChild(calories); item.appendChild(price); } } function newPizza() { let inp = document.getElementById("t1"); let c1 = document.getElementById("c1"); let c2 = document.getElementById("c2"); let c3 = document.getElementById("c3"); let c4 = document.getElementById("c4"); let c5 = document.getElementById("c5"); let img = "img/margarita.png"; let desc = ""; let ccal = 0; let price = 0; if(c1.checked){ ccal+=10; price+=10; desc+= "Курица, "; } if(c2.checked){ ccal+=20; price+=20; desc+= "Пармезан, "; } if(c3.checked){ ccal+=30; price+=30; desc+= "сыр чеддер, "; } if(c4.checked){ ccal+=40; price+=40; desc+= "соус песто, "; } if(c5.checked){ ccal+=50; price+=50; desc+= "помидоры, "; } var customPizza = new Pizza(img, inp.innerText, desc, ccal, price); grid(); } <file_sep>/README.md # task8 task8 for epam FE2019
70b33c82ebb4ce504351fd7871db267abcf8fcb4
[ "JavaScript", "Markdown" ]
2
JavaScript
Slashxdd/task8
d9aa61f7df1623415822a03f92a3ada59c975a3c
fee196562ebd19d79ac8d3aa76b40dd98e4a64d3
refs/heads/master
<file_sep>const AuthorizationError = require('../../Commons/exceptions/AuthorizationError'); const NotFoundError = require('../../Commons/exceptions/NotFoundError'); const CommentRepository = require('../../Domains/comments/CommentRepository'); const AddedComment = require('../../Domains/comments/entities/AddedComment'); const GetComment = require('../../Domains/comments/entities/GetComment'); class CommentRepositoryPostgres extends CommentRepository { constructor(pool, idGenerator) { super(); this._pool = pool; this._idGenerator = idGenerator; } async addComment(newComment, credentialId, threadId) { const { content } = newComment; const id = `comment-${this._idGenerator()}`; const date = new Date().toISOString(); const query = { text: 'INSERT INTO comments VALUES($1,$2,$3,$4,$5) RETURNING id, content, owner', values: [id, content, date, credentialId, threadId], }; const result = await this._pool.query(query); return new AddedComment({ ...result.rows[0] }); } async verifyCommenter(commentId, userId) { const query = { text: 'SELECT * FROM comments WHERE id = $1', values: [commentId], }; const result = await this._pool.query(query); if (!result.rowCount) { throw new NotFoundError('Comment not found'); } if (result.rows[0].owner !== userId) { throw new AuthorizationError('Anda tidak berhak mengakses resource ini'); } } async deleteComment(commentId) { const deleteComment = '1'; const query = { text: 'UPDATE comments SET is_delete = $1 WHERE id = $2 RETURNING id, is_delete', values: [deleteComment, commentId], }; const result = await this._pool.query(query); if (!result.rowCount) { throw new NotFoundError('comment not found'); } } async getComment(threadId) { const query = { text: `SELECT comments.id, users.username, comments.date, comments.content, comments.is_delete FROM comments LEFT JOIN users ON users.id = comments.owner WHERE comments.thread_id = $1 ORDER BY comments.date ASC`, values: [threadId], }; const result = await this._pool.query(query); const comments = []; // eslint-disable-next-line no-plusplus for (let i = 0; i < result.rowCount; i++) { const getComment = new GetComment({ ...result.rows[i], }); comments.push({ ...getComment }); } return comments; } } module.exports = CommentRepositoryPostgres; <file_sep>const AddCommentUseCase = require('../AddCommentUseCase'); const CommentRepository = require('../../../Domains/comments/CommentRepository'); const AddedComment = require('../../../Domains/comments/entities/AddedComment'); const NewComment = require('../../../Domains/comments/entities/NewComment'); const ThreadRepository = require('../../../Domains/threads/ThreadRepository'); describe('AddCommentUseCase', () => { it('should orcestrating add comment action correctly', async () => { const useCasePayload = { content: 'content', }; const expectedAddedComment = new AddedComment({ id: 'comment-123', content: 'content', owner: 'user-123', }); const newComment = new NewComment({ content: 'content', }); const credentialId = 'user-123'; const threadId = 'thread-123'; const mockCommentRepository = new CommentRepository(); const mockThreadRepository = new ThreadRepository(); // eslint-disable-next-line max-len mockThreadRepository.verifyAvailableThread = jest.fn().mockImplementation(() => Promise.resolve()); // eslint-disable-next-line max-len mockCommentRepository.addComment = jest.fn().mockImplementation(() => Promise.resolve(expectedAddedComment)); const addCommentUseCase = new AddCommentUseCase({ commentRepository: mockCommentRepository, threadRepository: mockThreadRepository, }); const addedComment = await addCommentUseCase.execute(useCasePayload, credentialId, threadId); expect(addedComment).toStrictEqual(expectedAddedComment); expect(mockThreadRepository.verifyAvailableThread).toBeCalledWith(threadId); expect(mockCommentRepository.addComment).toBeCalledWith(newComment, credentialId, threadId); }); }); <file_sep>const ThreadRepository = require('../../Domains/threads/ThreadRepository'); const AddedThread = require('../../Domains/threads/entities/AddedThread'); const InvariantError = require('../../Commons/exceptions/InvariantError'); const NotFoundError = require('../../Commons/exceptions/NotFoundError'); const GetThread = require('../../Domains/threads/entities/GetThread'); class ThreadRepositoryPostgres extends ThreadRepository { constructor(pool, idGenerator) { super(); this._pool = pool; this._idGenerator = idGenerator; } async verifyAvailableThread(threadId) { const query = { text: 'SELECT * FROM threads WHERE id = $1', values: [threadId], }; const result = await this._pool.query(query); if (!result.rowCount) { throw new NotFoundError('Thread tidak ditemukan'); } } async addThread(newThread, userId) { const { title, body } = newThread; const id = `thread-${this._idGenerator()}`; const date = new Date().toISOString(); const query = { text: 'INSERT INTO threads VALUES($1,$2,$3,$4,$5) RETURNING id, title, owner', values: [id, title, body, date, userId], }; const result = await this._pool.query(query); return new AddedThread({ ...result.rows[0] }); } async getThread(threadId) { const query = { text: `SELECT threads.id, threads.title, threads.body, threads.date, users.username FROM threads LEFT JOIN users ON users.id = threads.owner WHERE threads.id = $1`, values: [threadId], }; const result = await this._pool.query(query); if (!result.rowCount) { throw new NotFoundError('thread not found'); } return new GetThread({ ...result.rows[0] }); } } module.exports = ThreadRepositoryPostgres; <file_sep>const ThreadRepositoryPostgres = require('../ThreadRepositoryPostgres'); const ThreadsTableTestHelper = require('../../../../tests/ThreadsTableTestHelper'); const UsersTableTestHelper = require('../../../../tests/UsersTableTestHelper'); const pool = require('../../database/postgres/pool'); const NewThread = require('../../../Domains/threads/entities/NewThread'); const AddedThread = require('../../../Domains/threads/entities/AddedThread'); const InvariantError = require('../../../Commons/exceptions/InvariantError'); const NotFoundError = require('../../../Commons/exceptions/NotFoundError'); const GetThread = require('../../../Domains/threads/entities/GetThread'); describe('ThreadRepository postgres', () => { afterEach(async () => { await ThreadsTableTestHelper.cleanTable(); await UsersTableTestHelper.cleanTable(); }); afterAll(async () => { await pool.end(); }); describe('addThread function', () => { it('should persist thread', async () => { const newThread = new NewThread({ title: 'title', body: 'body', }); await UsersTableTestHelper.addUser({ id: 'user-123' }); const fakeIdGenerator = () => '123'; // stub const threadRepositoryPostgres = new ThreadRepositoryPostgres(pool, fakeIdGenerator); await threadRepositoryPostgres.addThread(newThread, 'user-123'); // assert const thread = await ThreadsTableTestHelper.findThreadById('thread-123'); expect(thread).toHaveLength(1); }); it('should return addedThread correctly', async () => { const newThread = new NewThread({ title: 'title', body: 'body', }); await UsersTableTestHelper.addUser({ id: 'user-123' }); const fakeIdGenerator = () => '123'; // stub const threadRepositoryPostgres = new ThreadRepositoryPostgres(pool, fakeIdGenerator); const addedThread = await threadRepositoryPostgres.addThread(newThread, 'user-123'); expect(addedThread).toBeInstanceOf(AddedThread); }); }); describe('verifyAvailableThread function', () => { it('should throw NotFoundError when thread not available', async () => { const threadRepositoryPostgres = new ThreadRepositoryPostgres(pool, {}); await expect(threadRepositoryPostgres.verifyAvailableThread('thread-123')).rejects.toThrowError(NotFoundError); }); it('should not throw NotFoundError when thread available', async () => { await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); const threadRepositoryPostgres = new ThreadRepositoryPostgres(pool, {}); await expect(threadRepositoryPostgres.verifyAvailableThread('thread-123')).resolves.not.toThrowError(NotFoundError); }); }); describe('getThread function', () => { it('should return getThread correctly', async () => { await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); const threadRepositoryPostgres = new ThreadRepositoryPostgres(pool, {}); const getThread = await threadRepositoryPostgres.getThread('thread-123'); expect(getThread).toBeInstanceOf(GetThread); }); it('should throw NotFoundError when thread not found', async () => { await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-124' }); const threadRepositoryPostgres = new ThreadRepositoryPostgres(pool, {}); await expect(threadRepositoryPostgres.getThread('thread-123')).rejects.toThrowError(NotFoundError); }); }); }); <file_sep>const CommentRepositoryPostgres = require('../CommentRepositoryPostgres'); const CommentsTableTestHelper = require('../../../../tests/CommentsTableTestHelper'); const pool = require('../../database/postgres/pool'); const NewComment = require('../../../Domains/comments/entities/NewComment'); const UsersTableTestHelper = require('../../../../tests/UsersTableTestHelper'); const ThreadsTableTestHelper = require('../../../../tests/ThreadsTableTestHelper'); const AddedComment = require('../../../Domains/comments/entities/AddedComment'); const NotFoundError = require('../../../Commons/exceptions/NotFoundError'); const AuthorizationError = require('../../../Commons/exceptions/AuthorizationError'); const GetComment = require('../../../Domains/comments/entities/GetComment'); describe('CommentRepository postgres', () => { afterEach(async () => { await CommentsTableTestHelper.cleanTable(); await UsersTableTestHelper.cleanTable(); await ThreadsTableTestHelper.cleanTable(); }); afterAll(async () => { await pool.end(); }); describe('addComment function', () => { it('should persist comment', async () => { const newComment = new NewComment({ content: 'content', }); const credentialId = 'user-123'; const threadId = 'thread-123'; await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); const fakeIdGenerator = () => '123'; const commentRepositoryPostgres = new CommentRepositoryPostgres(pool, fakeIdGenerator); await commentRepositoryPostgres.addComment(newComment, credentialId, threadId); const comment = await CommentsTableTestHelper.findCommentById('comment-123'); expect(comment).toHaveLength(1); }); it('should return addedComment correctly', async () => { const newComment = new NewComment({ content: 'content', }); const credentialId = 'user-123'; const threadId = 'thread-123'; await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); const fakeIdGenerator = () => '123'; const commentRepositoryPostgres = new CommentRepositoryPostgres(pool, fakeIdGenerator); // eslint-disable-next-line max-len const addedComment = await commentRepositoryPostgres.addComment(newComment, credentialId, threadId); expect(addedComment).toBeInstanceOf(AddedComment); }); }); describe('verifyCommenter function', () => { it('should not throw authorization error when commenter is true', async () => { const credentialId = 'user-123'; const commentId = 'comment-123'; await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); await CommentsTableTestHelper.addComment({ id: 'comment-123' }); const commentRepositoryPostgres = new CommentRepositoryPostgres(pool, {}); // eslint-disable-next-line max-len await expect(commentRepositoryPostgres.verifyCommenter(commentId, credentialId)).resolves.not.toThrowError(AuthorizationError); }); it('should throw authorization error when commenter is false', async () => { const credentialId = 'user-123'; const commentId = 'comment-124'; await UsersTableTestHelper.addUser({ id: 'user-124' }); await ThreadsTableTestHelper.addThread({ id: 'thread-124', owner: 'user-124' }); await CommentsTableTestHelper.addComment({ id: 'comment-124', owner: 'user-124', threadId: 'thread-124' }); const commentRepositoryPostgres = new CommentRepositoryPostgres(pool, {}); // eslint-disable-next-line max-len await expect(commentRepositoryPostgres.verifyCommenter(commentId, credentialId)).rejects.toThrowError(AuthorizationError); }); }); describe('deleteComment function', () => { it('should not throw NotFoundError when delete action correctly', async () => { const commentId = 'comment-123'; await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); await CommentsTableTestHelper.addComment({ id: 'comment-123' }); const commentRepositoryPostgres = new CommentRepositoryPostgres(pool, {}); // eslint-disable-next-line max-len await expect(commentRepositoryPostgres.deleteComment(commentId)).resolves.not.toThrowError(NotFoundError); }); it('should throw NotFoundError when delete action not correctly', async () => { const commentId = 'comment-123'; await UsersTableTestHelper.addUser({ id: 'user-124' }); await ThreadsTableTestHelper.addThread({ id: 'thread-124', owner: 'user-124' }); await CommentsTableTestHelper.addComment({ id: 'comment-124', owner: 'user-124', threadId: 'thread-124' }); const commentRepositoryPostgres = new CommentRepositoryPostgres(pool, {}); // eslint-disable-next-line max-len await expect(commentRepositoryPostgres.deleteComment(commentId)).rejects.toThrowError(NotFoundError); }); }); describe('getComment function', () => { it('should return array of getComment correctly', async () => { const expectedComment = { id: 'comment-123', username: 'dicoding', date: 'date', content: 'content', }; await UsersTableTestHelper.addUser({ id: 'user-123' }); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); await CommentsTableTestHelper.addComment({ id: 'comment-123', isDelete: '0' }); await CommentsTableTestHelper.addComment({ id: 'comment-124', isDelete: '0' }); const commentRepositoryPostgres = new CommentRepositoryPostgres(pool, {}); const comments = await commentRepositoryPostgres.getComment('thread-123'); expect(comments[0]).toEqual(expectedComment); }); }); }); <file_sep>class GetThreadUseCase { constructor({ threadRepository, commentRepository }) { this._threadRepository = threadRepository; this._commentRepository = commentRepository; } async execute(threadId) { const getThread = await this._threadRepository.getThread(threadId); const comments = await this._commentRepository.getComment(threadId); const detailThread = { ...getThread, comments, }; return detailThread; } } module.exports = GetThreadUseCase; <file_sep>const GetComment = require('../GetComment'); describe('A getComment entities', () => { it('should throw error when payload not contain needed property', () => { //arrange const payload = { id: 'id', username: 'username', }; //action expect(() => new GetComment(payload)).toThrowError('GET_COMMENT.NOT_CONTAIN_NEEDED_PROPERTY'); }); it('should throw error when payload not meet data type specification', () => { //arrange const payload = { id: 'id', username: 'username', date: 'date', content: 1234, is_delete: '0', }; //action and assert expect(() => new GetComment(payload)).toThrowError('GET_COMMENT.NOT_MEET_DATA_TYPE_SPECIFICATION'); }); it('should create getComment object correctly', () => { //arrange const payload = { id: 'id', username: 'username', date: 'date', content: 'content', is_delete: '0', }; //action const { id, username, date, content, } = new GetComment(payload); //assert expect(id).toEqual(payload.id); expect(content).toEqual(payload.content); expect(date).toEqual(payload.date); expect(username).toEqual(payload.username); }); it('should show status deleted comment when comment was deleted', () => { //arrange const payload = { id: 'id', username: 'username', date: 'date', content: 'content', is_delete: '1', }; //action const { id, username, date, content, } = new GetComment(payload); //assert expect(id).toEqual(payload.id); expect(content).toEqual('**komentar telah dihapus**'); expect(date).toEqual(payload.date); expect(username).toEqual(payload.username); }); }); <file_sep>class GetComment { constructor(payload) { this._verifyPayload(payload); const { id, username, date, content, is_delete } = payload; this.id = id; this.username = username; this.date = date; this.content = content; if (is_delete === '1') { this.content = '**komentar telah dihapus**'; } } _verifyPayload({ id, username, date, content, is_delete, }) { if (!id || !username || !date || !content || !is_delete) { throw new Error('GET_COMMENT.NOT_CONTAIN_NEEDED_PROPERTY'); } if (typeof id !== 'string' || typeof username !== 'string' || typeof date !== 'string' || typeof content !== 'string' || typeof is_delete !== 'string') { throw new Error('GET_COMMENT.NOT_MEET_DATA_TYPE_SPECIFICATION'); } } } module.exports = GetComment; <file_sep>/* eslint-disable camelcase */ exports.shorthands = undefined; exports.up = pgm => { pgm.addColumn('comments', { is_delete: { type: 'VARCHAR(2)', }, }); pgm.sql("UPDATE comments SET is_delete = '0' WHERE is_delete = NULL"); }; exports.down = pgm => { pgm.dropColumn('comments', 'is_delete'); }; <file_sep>const pool = require('../../database/postgres/pool'); const ThreadsTableTestHelper = require('../../../../tests/ThreadsTableTestHelper'); const createServer = require('../createServer'); const container = require('../../container'); const ServerTestHelper = require('../../../../tests/ServerTestHelper'); const UsersTableTestHelper = require('../../../../tests/UsersTableTestHelper'); const CommentsTableTestHelper = require('../../../../tests/CommentsTableTestHelper'); describe('/threads endpoint', () => { afterAll(async () => { await pool.end(); }); afterEach(async () => { await ThreadsTableTestHelper.cleanTable(); await UsersTableTestHelper.cleanTable(); await CommentsTableTestHelper.cleanTable(); }); describe('when POST /threads', () => { it('should response 201 and persisted thread', async () => { // arrange const requestPayload = { title: 'title', body: 'body', }; const accessToken = await ServerTestHelper.getAccessToken(); const server = await createServer(container); const response = await server.inject({ method: 'POST', url: '/threads', headers: { Authorization: `Bearer ${accessToken}`, }, payload: requestPayload, }); const responseJson = JSON.parse(response.payload); expect(response.statusCode).toEqual(201); expect(responseJson.status).toEqual('success'); expect(responseJson.data.addedThread).toBeDefined(); }); it('should response 400 when request payload not contain needed property', async () => { // arrange const requestPayload = { title: 'title', }; const accessToken = await ServerTestHelper.getAccessToken(); const server = await createServer(container); const response = await server.inject({ method: 'POST', url: '/threads', headers: { Authorization: `Bearer ${accessToken}`, }, payload: requestPayload, }); const responseJson = JSON.parse(response.payload); expect(response.statusCode).toEqual(400); expect(responseJson.status).toEqual('fail'); expect(responseJson.message).toEqual('tidak dapat membuat thread baru karena properti yang dibutuhkan tidak ada'); }); it('should response 400 when request payload not meet data type specification', async () => { // arrange const requestPayload = { title: 'title', body: 1234, }; const accessToken = await ServerTestHelper.getAccessToken(); const server = await createServer(container); const response = await server.inject({ method: 'POST', url: '/threads', headers: { Authorization: `Bearer ${accessToken}`, }, payload: requestPayload, }); const responseJson = JSON.parse(response.payload); expect(response.statusCode).toEqual(400); expect(responseJson.status).toEqual('fail'); expect(responseJson.message).toEqual('tidak dapat membuat thread baru karena tipe data tidak sesuai'); }); }); describe('when POST /threads/{threadId}', () => { it('should return detail thread correctly', async () => { const accessToken = await ServerTestHelper.getAccessToken(); await ThreadsTableTestHelper.addThread({ id: 'thread-123' }); await CommentsTableTestHelper.addComment({ id: 'comment-123' }); await CommentsTableTestHelper.addComment({ id: 'comment-124' }); const server = await createServer(container); const response = await server.inject({ method: 'GET', url: '/threads/thread-123', }); const responseJson = JSON.parse(response.payload); expect(response.statusCode).toEqual(200); expect(responseJson.status).toEqual('success'); expect(responseJson.data.thread).toBeDefined(); }); }); }); <file_sep>class GetThread { constructor(payload) { this._verifyPayload(payload); const { id, title, body, date, username } = payload; this.id = id; this.title = title; this.body = body; this.date = date; this.username = username; } _verifyPayload({ id, title, body, date, username, }) { if (!id || !title || !body || !date || !username) { throw new Error('GET_THREAD.NOT_CONTAIN_NEEDED_PROPERTY'); } if (typeof id !== 'string' || typeof title !== 'string' || typeof body !== 'string' || typeof date !== 'string' || typeof username !== 'string') { throw new Error('GET_THREAD.NOT_MEET_DATA_TYPE_SPECIFICATION'); } } } module.exports = GetThread; <file_sep>const CommentRepository = require('../../../Domains/comments/CommentRepository'); const ThreadRepository = require('../../../Domains/threads/ThreadRepository'); const DeleteCommentUseCase = require('../DeleteCommentUseCase'); describe('DeleteCommentUseCase', () => { it('should orcestrating delete comment action correctly', async () => { // arrange const mockCommentRepository = new CommentRepository(); const mockThreadRepository = new ThreadRepository(); mockCommentRepository.verifyCommenter = jest.fn().mockImplementation(() => Promise.resolve()); // eslint-disable-next-line max-len mockThreadRepository.verifyAvailableThread = jest.fn().mockImplementation(() => Promise.resolve()); mockCommentRepository.deleteComment = jest.fn().mockImplementation(() => Promise.resolve()); const deleteCommentUseCase = new DeleteCommentUseCase({ commentRepository: mockCommentRepository, threadRepository: mockThreadRepository, }); await deleteCommentUseCase.execute('user-123', 'thread-123', 'comment-123'); expect(mockCommentRepository.verifyCommenter).toBeCalledWith('comment-123', 'user-123'); expect(mockThreadRepository.verifyAvailableThread).toBeCalledWith('thread-123'); expect(mockCommentRepository.deleteComment).toBeCalledWith('comment-123'); }); }); <file_sep>class CommentRepository { async addComment(newComment, credentialId, threadId) { throw new Error('COMMENT_REPOSITORY.METHOD_NOT_IMPLEMENTED'); } async verifyCommenter(commentId, userId) { throw new Error('COMMENT_REPOSITORY.METHOD_NOT_IMPLEMENTED'); } async deleteComment(commentId) { throw new Error('COMMENT_REPOSITORY.METHOD_NOT_IMPLEMENTED'); } async getComment(threadId) { throw new Error('COMMENT_REPOSITORY.METHOD_NOT_IMPLEMENTED'); } } module.exports = CommentRepository;
36dce27b155f08c777841c81e5a0afd14cfc7b29
[ "JavaScript" ]
13
JavaScript
Asiftofficial/forum-api
313261a2dc3f0e9657d09b84f08c462caa573345
84c971c979d2855642218ecd47f99713c9b7a25b
refs/heads/master
<file_sep>using Bit.Model.Contracts; using Prism.Navigation; using System.Reflection; namespace System.Collections.Generic { public static class IDictionaryExtensions { public static IDto ToDto(this IDictionary<string, object> unTypedDto, TypeInfo dtoType) { if (unTypedDto == null) throw new ArgumentNullException(nameof(unTypedDto)); if (dtoType == null) throw new ArgumentNullException(nameof(dtoType)); IDto dto = (IDto)Activator.CreateInstance(dtoType); Dictionary<string, object> extraProps = null; if (dto is IOpenType openTypeDto) extraProps = openTypeDto.Properties = (openTypeDto.Properties ?? new Dictionary<string, object>()); foreach (KeyValuePair<string, object> KeyVal in unTypedDto) { PropertyInfo prop = dtoType.GetProperty(KeyVal.Key); object val = KeyVal.Value; if (prop != null) { if (prop.PropertyType.IsEnum && val != null) val = Enum.Parse(prop.PropertyType, KeyVal.Value.ToString()); if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && prop.PropertyType != typeof(string)) { // This converts List<object> which contains some Guid values to List<Guid> which contains some Guid values. IList propertyValue = (IList)Activator.CreateInstance(prop.PropertyType); foreach (object item in (IEnumerable)val) { propertyValue.Add(item); } val = propertyValue; } prop.SetValue(dto, val); } else { extraProps?.Add(KeyVal.Key, val); } } return dto; } public static TDto ToDto<TDto>(this IDictionary<string, object> unTypedDto) where TDto : class, IDto { return (TDto)unTypedDto.ToDto(typeof(TDto).GetTypeInfo()); } } } <file_sep>using Bit.ViewModel; using System.Threading; using System.Threading.Tasks; namespace System { public static class ObservableExtensions { public static IDisposable SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext) { return source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }); } public static IDisposable SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext, Func<Exception, Task> onError) { return source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, onError: async (originalExp) => { try { await onError(originalExp).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(new AggregateException(exp, originalExp)); } }); } public static IDisposable SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext, Func<Task> onCompleted) { return source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, onCompleted: async () => { try { await onCompleted().ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }); } public static IDisposable SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext, Func<Exception, Task> onError, Func<Task> onCompleted) { return source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, onError: async (originalExp) => { try { await onError(originalExp).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(new AggregateException(exp, originalExp)); } }, onCompleted: async () => { try { await onCompleted().ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }); } public static void SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext, CancellationToken token) { source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, token: token); } public static void SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext, Func<Exception, Task> onError, CancellationToken token) { source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, onError: async (originalExp) => { try { await onError(originalExp).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(new AggregateException(exp, originalExp)); } }, token: token); } public static void SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext, Func<Task> onCompleted, CancellationToken token) { source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, onCompleted: async () => { try { await onCompleted().ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, token: token); } public static void SubscribeAsync<T>(this IObservable<T> source, Func<T, Task> onNext, Func<Exception, Task> onError, Func<Task> onCompleted, CancellationToken token) { source.Subscribe(onNext: async (arg) => { try { await onNext(arg).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, onError: async (originalExp) => { try { await onError(originalExp).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(new AggregateException(exp, originalExp)); } }, onCompleted: async () => { try { await onCompleted().ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } }, token: token); } } } <file_sep>using Bit.Core.Contracts; using Bit.Core.Models; using Microsoft.ApplicationInsights; using Microsoft.Owin; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bit.Owin.Implementations { public class ApplicationInsightsLogStore : ILogStore { private class KeyVal { public string Key { get; set; } public string Value { get; set; } public override string ToString() { return $"Key: {Key}, Value: {Value}"; } } [Serializable] private class FatalException : Exception { public FatalException(string message) : base(message) { } } [Serializable] private class ErrorException : Exception { public ErrorException(string message) : base(message) { } } [Serializable] private class WarningException : Exception { public WarningException(string message) : base(message) { } } [Serializable] private class InformationException : Exception { public InformationException(string message) : base(message) { } } public virtual Lazy<IOwinContext> OwinContext { get; set; } public virtual IContentFormatter Formatter { get; set; } public virtual void SaveLog(LogEntry logEntry) { PerformLog(logEntry); } public virtual Task SaveLogAsync(LogEntry logEntry) { PerformLog(logEntry); return Task.CompletedTask; } private void PerformLog(LogEntry logEntry) { TelemetryClient telemetryClient = null; IUserInformationProvider userInformationProvider = null; bool isPerRequestTelemetryClient = false; if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.RequestUri))) { IOwinContext owinContext = OwinContext.Value; IDependencyResolver resolver = owinContext.GetDependencyResolver(); telemetryClient = resolver.Resolve<TelemetryClient>(); userInformationProvider = resolver.Resolve<IUserInformationProvider>(); isPerRequestTelemetryClient = true; } List<KeyVal> keyValues = logEntry.LogData.Select(ld => { string k = ld.Key; if (k == nameof(IRequestInformationProvider.HttpMethod) || k == nameof(IRequestInformationProvider.RequestUri) || k == nameof(IRequestInformationProvider.UserAgent) || k == "UserId" || k == "ResponseStatusCode" || k == nameof(IRequestInformationProvider.ClientIp) || ld.Value == null) return null; string v = null; if (ld.Value is string valueAsStr) v = valueAsStr; if (k == "ClientLogs" || k == "OperationArgs") { v = Formatter.Serialize(ld.Value); } else { v = ld.Value.ToString(); } return new KeyVal { Key = k, Value = v }; }) .Where(d => d != null) .ToList(); try { keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppEnvironmentName), Value = logEntry.AppEnvironmentName }); if (logEntry.AppServerProcessId.HasValue) keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppServerProcessId), Value = logEntry.AppServerProcessId.ToString() }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppServerAppDomainName), Value = logEntry.AppServerAppDomainName }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppServerOSVersion), Value = logEntry.AppServerOSVersion }); if (logEntry.AppServerDateTime.HasValue) keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString() }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppServerName), Value = logEntry.AppServerName }); if (logEntry.AppWasInDebugMode.HasValue) keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppWasInDebugMode), Value = logEntry.AppWasInDebugMode.ToString() }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppServerUserAccountName), Value = logEntry.AppServerUserAccountName }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppVersion), Value = logEntry.AppVersion }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.ApplicationName), Value = logEntry.ApplicationName }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.Severity), Value = logEntry.Severity }); keyValues.Add(new KeyVal { Key = nameof(LogEntry.Message), Value = logEntry.Message }); if (logEntry.Id.HasValue) keyValues.Add(new KeyVal { Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString() }); if (logEntry.AppServerThreadId.HasValue) keyValues.Add(new KeyVal { Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString() }); if (isPerRequestTelemetryClient == true) { if (userInformationProvider.IsAuthenticated()) telemetryClient.Context.User.AccountId = telemetryClient.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId(); LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent)); if (userAgent != null) telemetryClient.Context.User.UserAgent = (string)userAgent.Value; foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key)) { if (!telemetryClient.Context.Properties.ContainsKey(keyVal.Key)) telemetryClient.Context.Properties.Add(keyVal.Key, keyVal.Value); } } else { telemetryClient = new TelemetryClient(); Dictionary<string, string> customData = new Dictionary<string, string>(); foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key)) { if (!customData.ContainsKey(keyVal.Key)) customData.Add(keyVal.Key, keyVal.Value); } Exception ex = null; try { customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName); if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName)) ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName), args: new object[] { logEntry.Message }); } catch { } if (ex == null) { switch (logEntry.Severity) { case "Information": ex = new InformationException(logEntry.Message); break; case "Warning": ex = new WarningException(logEntry.Message); break; case "Error": ex = new ErrorException(logEntry.Message); break; case "Fatal": ex = new FatalException(logEntry.Message); break; default: ex = new Exception(logEntry.Message); break; } } telemetryClient.TrackException(ex, customData); } } finally { telemetryClient.Flush(); } } } } <file_sep>using BitCodeGenerator.Implementations; using BitCodeGenerator.Implementations.TypeScriptClientProxyGenerator; using BitTools.Core.Contracts; using Microsoft.CodeAnalysis; using System; using System.Diagnostics; using System.IO; using System.Linq; using Uno.SourceGeneration; namespace BitCodeGeneratorTask { public class BitSourceGenerator : SourceGenerator { private ISourceGeneratorLogger _logger; public override void Execute(SourceGeneratorContext context) { #if DEBUG Debugger.Launch(); #endif _logger = context.GetLogger(); DirectoryInfo projDir = new DirectoryInfo(Path.GetDirectoryName(context.Project.FilePath)); string solutionFullName = null; while (projDir.Parent != null) { string filePath = Path.Combine(projDir.FullName, "BitConfigV1.json"); if (File.Exists(filePath)) { solutionFullName = Directory.EnumerateFiles(projDir.FullName, "*.sln").FirstOrDefault(); break; } projDir = projDir.Parent; } CallGenerateCodes(context.Project.Solution.Workspace, solutionFullName); } private async void CallGenerateCodes(Workspace workspace, string solutionFullName) { Stopwatch sw = null; try { sw = Stopwatch.StartNew(); IProjectDtoControllersProvider controllersProvider = new DefaultProjectDtoControllersProvider(); IProjectDtosProvider dtosProvider = new DefaultProjectDtosProvider(controllersProvider); DefaultTypeScriptClientProxyGenerator generator = new DefaultTypeScriptClientProxyGenerator(new DefaultBitCodeGeneratorOrderedProjectsProvider(), new BitSourceGeneratorBitConfigProvider(solutionFullName), dtosProvider , new DefaultTypeScriptClientProxyDtoGenerator(), new DefaultTypeScriptClientContextGenerator(), controllersProvider, new DefaultProjectEnumTypesProvider(controllersProvider, dtosProvider)); await generator.GenerateCodes(workspace); Log($"Code Generation Completed in {sw.ElapsedMilliseconds} ms using {workspace.GetType().Name}"); } catch (Exception ex) { LogException("Code Generation failed.", ex); throw; } finally { sw?.Stop(); } } private void Log(string text) { _logger.Warn($">>>>> {text} {DateTimeOffset.Now} {typeof(BitSourceGenerator).Assembly.FullName} <<<<< \n"); } private void LogException(string text, Exception ex) { _logger.Error($">>>>> {text} {DateTimeOffset.Now} {typeof(BitSourceGenerator).Assembly.FullName}<<<<< \n {ex} \n", ex); } } } <file_sep>using Autofac; using Bit.ViewModel.Contracts; using IdentityModel.Client; using Newtonsoft.Json; using Prism.Autofac; using Prism.Ioc; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xamarin.Auth; using Xamarin.Essentials; namespace Bit.ViewModel.Implementations { public class DefaultSecurityService : ISecurityService { private static ISecurityService _current; public static ISecurityService Current => _current; public DefaultSecurityService(AccountStore accountStore, IClientAppProfile clientAppProfile, IDateTimeProvider dateTimeProvider, IContainerProvider containerProvider) { _clientAppProfile = clientAppProfile; _accountStore = accountStore; _dateTimeProvider = dateTimeProvider; _containerProvider = containerProvider; _current = this; } private readonly IClientAppProfile _clientAppProfile; private readonly AccountStore _accountStore; private readonly IDateTimeProvider _dateTimeProvider; private readonly IContainerProvider _containerProvider; public virtual bool IsLoggedIn() { Account account = GetAccount(); if (account == null) return false; Token token = account; return (_dateTimeProvider.GetCurrentUtcDateTime() - token.login_date) < TimeSpan.FromSeconds(token.expires_in); } public virtual async Task<bool> IsLoggedInAsync(CancellationToken cancellationToken = default(CancellationToken)) { Account account = await GetAccountAsync().ConfigureAwait(false); if (account == null) return false; Token token = account; return (_dateTimeProvider.GetCurrentUtcDateTime() - token.login_date) < TimeSpan.FromSeconds(token.expires_in); } private Account GetAccount() { return (_accountStore.FindAccountsForService(_clientAppProfile.AppName)).SingleOrDefault(); } private async Task<Account> GetAccountAsync() { return (await _accountStore.FindAccountsForServiceAsync(_clientAppProfile.AppName).ConfigureAwait(false)).SingleOrDefault(); } public virtual async Task<Token> Login(object state = null, string client_id = null, CancellationToken cancellationToken = default(CancellationToken)) { await Logout(state, client_id, cancellationToken).ConfigureAwait(false); CurrentAction = "Login"; CurrentLoginTaskCompletionSource = new TaskCompletionSource<Token>(); await Browser.OpenAsync(GetLoginUrl(state, client_id), BrowserLaunchMode.SystemPreferred).ConfigureAwait(false); return await CurrentLoginTaskCompletionSource.Task.ConfigureAwait(false); } public virtual async Task<Token> LoginWithCredentials(string username, string password, string client_id, string client_secret, string[] scopes = null, CancellationToken cancellationToken = default(CancellationToken)) { await Logout(state: null, client_id: client_id, cancellationToken: cancellationToken).ConfigureAwait(false); if (scopes == null) scopes = "openid profile user_info".Split(' '); TokenClient tokenClient = _containerProvider.GetContainer().Resolve<TokenClient>(new NamedParameter("clientId", client_id), new NamedParameter("secret", client_secret)); TokenResponse tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(username, password, scope: string.Join(" ", scopes), cancellationToken: cancellationToken).ConfigureAwait(false); if (tokenResponse.IsError) throw tokenResponse.Exception ?? new Exception($"{tokenResponse.Error} {tokenResponse.Raw}"); Account account = Token.FromTokenToAccount(tokenResponse); await _accountStore.SaveAsync(account, _clientAppProfile.AppName).ConfigureAwait(false); return account; } public virtual async Task Logout(object state = null, string client_id = null, CancellationToken cancellationToken = default(CancellationToken)) { Account account = GetAccount(); if (account != null) { await _accountStore.DeleteAsync(account, _clientAppProfile.AppName).ConfigureAwait(false); Token token = account; if (!string.IsNullOrEmpty(token.id_token)) { CurrentAction = "Logout"; CurrentLogoutTaskCompletionSource = new TaskCompletionSource<object>(); await Browser.OpenAsync(GetLogoutUrl(token.id_token, state, client_id), BrowserLaunchMode.SystemPreferred).ConfigureAwait(false); await CurrentLogoutTaskCompletionSource.Task.ConfigureAwait(false); } } } public virtual Token GetCurrentToken() { Account account = GetAccount(); if (account == null) return null; return account; } public virtual async Task<Token> GetCurrentTokenAsync(CancellationToken cancellationToken = default(CancellationToken)) { Account account = await GetAccountAsync().ConfigureAwait(false); if (account == null) return null; return account; } public virtual Uri GetLoginUrl(object state = null, string client_id = null) { state = state ?? new { }; string relativeUri = $"InvokeLogin?state={JsonConvert.SerializeObject(state)}&redirect_uri={ _clientAppProfile.OAuthRedirectUri}"; if (!string.IsNullOrEmpty(client_id)) relativeUri += $"&client_id={client_id}"; return new Uri(_clientAppProfile.HostUri, relativeUri: relativeUri); } public virtual Uri GetLogoutUrl(string id_token, object state = null, string client_id = null) { if (string.IsNullOrEmpty(id_token)) throw new ArgumentException("Id token may not be empty or null", nameof(id_token)); state = state ?? new { }; string relativeUri = $"InvokeLogout?state={JsonConvert.SerializeObject(state)}&redirect_uri={_clientAppProfile.OAuthRedirectUri}&id_token={id_token}"; if (!string.IsNullOrEmpty(client_id)) relativeUri += $"&client_id={client_id}"; return new Uri(_clientAppProfile.HostUri, relativeUri: relativeUri); } protected TaskCompletionSource<Token> CurrentLoginTaskCompletionSource { get; set; } protected string CurrentAction { get; set; } protected TaskCompletionSource<object> CurrentLogoutTaskCompletionSource { get; set; } public virtual async void OnSsoLoginLogoutRedirectCompleted(Uri url) { Dictionary<string, string> query = (Dictionary<string, string>)WebEx.FormDecode(url.Fragment); if (CurrentAction == "Logout") CurrentLogoutTaskCompletionSource.SetResult(null); else { Token token = query; Account account = Token.FromTokenToAccount(token); await _accountStore.SaveAsync(account, _clientAppProfile.AppName).ConfigureAwait(false); CurrentLoginTaskCompletionSource.SetResult(query); } } } } <file_sep>using Prism.Mvvm; using Prism.Navigation; using System; using System.Diagnostics; using System.Threading.Tasks; namespace Bit.ViewModel { public class BitViewModelBase : BindableBase, INavigatedAware, INavigatingAware, INavigationAware, IDestructible { public async void Destroy() { try { await DestroyAsync().ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } } public virtual Task DestroyAsync() { return Task.CompletedTask; } public async void OnNavigatedFrom(NavigationParameters parameters) { try { await OnNavigatedFromAsync(parameters).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } } public virtual Task OnNavigatedFromAsync(NavigationParameters parameters) { return Task.CompletedTask; } public async void OnNavigatedTo(NavigationParameters parameters) { try { await OnNavigatedToAsync(parameters).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } } public virtual Task OnNavigatedToAsync(NavigationParameters parameters) { return Task.CompletedTask; } public async void OnNavigatingTo(NavigationParameters parameters) { try { await OnNavigatingToAsync(parameters).ConfigureAwait(false); } catch (Exception exp) { BitExceptionHandler.Current.OnExceptionReceived(exp); } } public virtual Task OnNavigatingToAsync(NavigationParameters parameters) { return Task.CompletedTask; } } } <file_sep>using Bit.WebApi.Implementations; using Microsoft.AspNet.OData.Query; using Swashbuckle.OData; using System.Web.Http; namespace Swashbuckle.Application { public static class OpenApiExtensions { /// <summary> /// Calls <see cref="OpenApiExtensions.ApplyDefaultODataConfig(SwaggerDocsConfig, HttpConfiguration)"/> /// | Ignores ODataQueryOptions parameter type /// | Uses <see cref="ODataSwaggerProvider"/> /// </summary> public static SwaggerDocsConfig ApplyDefaultODataConfig(this SwaggerDocsConfig doc, HttpConfiguration webApiConfig) { doc.ApplyDefaultApiConfig(webApiConfig); doc.OperationFilter<OpenApiIgnoreParameterTypeOperationFilter<ODataQueryOptions>>(); doc.CustomProvider(defaultProvider => new ODataSwaggerProvider(defaultProvider, doc, webApiConfig).Configure(odataConfig => { odataConfig.EnableSwaggerRequestCaching(); odataConfig.IncludeNavigationProperties(); odataConfig.SetAssembliesResolver((System.Web.Http.Dispatcher.IAssembliesResolver)webApiConfig.DependencyResolver.GetService(typeof(System.Web.Http.Dispatcher.IAssembliesResolver))); })); return doc; } } } <file_sep>using AutoMapper; using Bit.Model.Contracts; namespace Bit.Model.Implementations { public class DefaultDtoEntityMapperConfiguration : IDtoEntityMapperConfiguration { public virtual void Configure(IMapperConfigurationExpression mapperConfigExpression) { mapperConfigExpression.ValidateInlineMaps = false; mapperConfigExpression.CreateMissingTypeMaps = true; } } } <file_sep>using Autofac; using Bit.CSharpClientSample.Data; using Bit.CSharpClientSample.ViewModels; using Bit.CSharpClientSample.Views; using Bit.Model.Events; using Bit.Tests.Model.Dto; using Bit.ViewModel.Contracts; using Bit.ViewModel.Implementations; using Prism; using Prism.Autofac; using Prism.Events; using Prism.Ioc; using System; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace Bit.CSharpClientSample { public partial class App : BitApplication { public App(IPlatformInitializer initializer) : base(initializer) { } protected async override Task OnInitializedAsync() { InitializeComponent(); bool isLoggedIn = await Container.Resolve<ISecurityService>().IsLoggedInAsync(); if (isLoggedIn) { await NavigationService.NavigateAsync("Nav/Main"); } else { await NavigationService.NavigateAsync("Login"); } IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>(); eventAggregator.GetEvent<TokenExpiredEvent>() .SubscribeAsync(async tokenExpiredEvent => await NavigationService.NavigateAsync("Login"), ThreadOption.UIThread); await base.OnInitializedAsync(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<NavigationPage>("Nav"); containerRegistry.RegisterForNavigation<LoginView, LoginViewModel>("Login"); containerRegistry.RegisterForNavigation<MainView, MainViewModel>("Main"); containerRegistry.GetBuilder().Register<IClientAppProfile>(c => new DefaultClientAppProfile { HostUri = new Uri("http://192.168.1.60/"), //HostUri = new Uri("http://127.0.0.1/"), //HostUri = new Uri("http://10.0.2.2"), OAuthRedirectUri = new Uri("Test://oauth2redirect"), AppName = "Test", ODataRoute = "odata/Test/" }).SingleInstance(); containerRegistry.RegisterRequiredServices(); containerRegistry.RegisterHttpClient(); containerRegistry.RegisterODataClient(); containerRegistry.RegisterIdentityClient(); containerRegistry.Register<SampleDbContext>(); containerRegistry.GetBuilder().Register(c => { ISyncService syncService = new DefaultSyncService<SampleDbContext>(c.Resolve<IContainerProvider>()); syncService.AddDtoSetSyncConfig(new DtoSetSyncConfig { DtoSetName = nameof(SampleDbContext.TestCustomers), OnlineDtoSet = odataClient => odataClient.For(nameof(SampleDbContext.TestCustomers)), OfflineDtoSet = dbContext => dbContext.Set<TestCustomerDto>() }); return syncService; }).SingleInstance(); containerRegistry.RegisterPopupService(); containerRegistry.RegisterForPopup<TestView, TestViewModel>("Test"); base.RegisterTypes(containerRegistry); } } } <file_sep>using Autofac; using Bit.ViewModel; using Bit.ViewModel.Contracts; using Bit.ViewModel.Implementations; using IdentityModel.Client; using Prism.Autofac; using Prism.Events; using Rg.Plugins.Popup.Contracts; using Rg.Plugins.Popup.Pages; using Rg.Plugins.Popup.Services; using Simple.OData.Client; using System; using System.Net.Http; using Xamarin.Auth; namespace Prism.Ioc { public static class IContainerRegistryExtensions { public static IContainerRegistry RegisterRequiredServices(this IContainerRegistry containerRegistry) { if (containerRegistry == null) throw new ArgumentNullException(nameof(containerRegistry)); ContainerBuilder containerBuilder = containerRegistry.GetBuilder(); containerBuilder.RegisterType<DefaultDateTimeProvider>().As<IDateTimeProvider>().SingleInstance().PreserveExistingDefaults(); return containerRegistry; } public static IContainerRegistry RegisterIdentityClient(this IContainerRegistry containerRegistry) { if (containerRegistry == null) throw new ArgumentNullException(nameof(containerRegistry)); ContainerBuilder containerBuilder = containerRegistry.GetBuilder(); containerBuilder.RegisterType<DefaultSecurityService>().As<ISecurityService>().SingleInstance().PreserveExistingDefaults(); #if Android containerBuilder.Register(c => AccountStore.Create(c.Resolve<Android.Content.Context>(), c.Resolve<IClientAppProfile>().AppName)).SingleInstance().PreserveExistingDefaults(); #else containerBuilder.Register(c => AccountStore.Create()).SingleInstance().PreserveExistingDefaults(); #endif containerBuilder.Register((c, parameters) => { return new TokenClient(address: new Uri(c.Resolve<IClientAppProfile>().HostUri, "core/connect/token").ToString(), clientId: parameters.Named<string>("clientId"), clientSecret: parameters.Named<string>("secret"), innerHttpMessageHandler: c.ResolveNamed<HttpMessageHandler>(ContractKeys.DefaultHttpMessageHandler)); }).PreserveExistingDefaults(); return containerRegistry; } public static IContainerRegistry RegisterHttpClient<THttpMessageHandler>(this IContainerRegistry containerRegistry) where THttpMessageHandler : HttpMessageHandler, new() { if (containerRegistry == null) throw new ArgumentNullException(nameof(containerRegistry)); ContainerBuilder containerBuilder = containerRegistry.GetBuilder(); containerBuilder .RegisterType<THttpMessageHandler>() .Named<HttpMessageHandler>(ContractKeys.DefaultHttpMessageHandler) .SingleInstance() .PreserveExistingDefaults(); containerBuilder.Register<HttpMessageHandler>(c => { return new AuthenticatedHttpMessageHandler(c.Resolve<IEventAggregator>(), c.Resolve<ISecurityService>(), c.ResolveNamed<HttpMessageHandler>(ContractKeys.DefaultHttpMessageHandler)); }) .Named<HttpMessageHandler>(ContractKeys.AuthenticatedHttpMessageHandler) .SingleInstance() .PreserveExistingDefaults(); containerBuilder.Register(c => { HttpMessageHandler authenticatedHttpMessageHandler = c.ResolveNamed<HttpMessageHandler>(ContractKeys.AuthenticatedHttpMessageHandler); HttpClient httpClient = new HttpClient(authenticatedHttpMessageHandler) { BaseAddress = c.Resolve<IClientAppProfile>().HostUri }; return httpClient; }).SingleInstance() .PreserveExistingDefaults(); return containerRegistry; } public static IContainerRegistry RegisterHttpClient(this IContainerRegistry containerRegistry) { if (containerRegistry == null) throw new ArgumentNullException(nameof(containerRegistry)); return RegisterHttpClient<BitHttpClientHandler>(containerRegistry); } public static IContainerRegistry RegisterODataClient(this IContainerRegistry containerRegistry) { if (containerRegistry == null) throw new ArgumentNullException(nameof(containerRegistry)); Simple.OData.Client.V4Adapter.Reference(); ContainerBuilder containerBuilder = containerRegistry.GetBuilder(); containerBuilder.Register(c => { HttpMessageHandler authenticatedHttpMessageHandler = c.ResolveNamed<HttpMessageHandler>(ContractKeys.AuthenticatedHttpMessageHandler); IClientAppProfile clientAppProfile = c.Resolve<IClientAppProfile>(); IODataClient odataClient = new ODataClient(new ODataClientSettings(new Uri(clientAppProfile.HostUri, clientAppProfile.ODataRoute)) { RenewHttpConnection = false, OnCreateMessageHandler = () => authenticatedHttpMessageHandler }); return odataClient; }).PreserveExistingDefaults(); containerBuilder .Register(c => new ODataBatch(c.Resolve<IODataClient>(), reuseSession: true)) .PreserveExistingDefaults(); return containerRegistry; } public static IContainerRegistry RegisterPopupService(this IContainerRegistry containerRegistry) { if (containerRegistry == null) throw new ArgumentNullException(nameof(containerRegistry)); ContainerBuilder containerBuilder = containerRegistry.GetBuilder(); containerBuilder .Register<IPopupNavigation>(c => PopupNavigation.Instance) .PreserveExistingDefaults(); containerBuilder.RegisterType<DefaultPopupNavigationService>().As<IPopupNavigationService>().SingleInstance().PreserveExistingDefaults(); return containerRegistry; } public static IContainerRegistry RegisterForPopup<TView, TViewModel>(this IContainerRegistry containerRegistry, string name) where TView : PopupPage where TViewModel : BitViewModelBase { if (containerRegistry == null) throw new ArgumentNullException(nameof(containerRegistry)); containerRegistry.Register<TViewModel>(); containerRegistry.Register<PopupPage, TView>(name); return containerRegistry; } } } <file_sep>using Prism.Events; using System; using System.Reactive.Subjects; namespace SubscribeAsyncTestProj { public class Tests { public void Test() { new Subject<string>().Subscribe((arg) => { }); new EventAggregator().GetEvent<TestEvent>().Subscribe(arg => { }); } } public class TestEvent : PubSubEvent<TestEvent> { } } <file_sep>using Newtonsoft.Json; namespace Bit.Data { public class ODataResponse<T> { [JsonProperty("value")] public virtual T Value { get; set; } } } <file_sep>#if Android using Xamarin.Forms.Platform.Android; namespace Bit.Droid { public class BitFormsAppCompatActivity : FormsAppCompatActivity { } } #endif
4a4806bbc26f3bee03d8c3e2f33b26f7b0c67c31
[ "C#" ]
13
C#
hamedhajiloo/bit-framework
2de5ad7bd00544116931ebc847dc4eed3ef2cb6d
577e4366a7c0f305edbc66a9eb06eac3deb3b32b
refs/heads/main
<file_sep>import logo from './logo.svg'; import './App.css'; import {Avatar} from '@material-ui/core'; import { makeStyles } from "@material-ui/core/styles"; import zulf_lit from "./zulf_lit.jpg"; const useStyles = makeStyles(theme => ({ large: { width: theme.spacing(8), height: theme.spacing(8) } })); //<Avatar alt="<NAME>" src="https://photos.google.com/share/AF1QipMMAQV4FeAtzYOFFDyOF2ANqj9RpsSvhfSERtPt8fNwdvWrRRCzxHVygCrje05Hzg/photo/AF1QipP7K1egE2x_HY9vQkr0fccxc6WacaCGdcc5WWeH?key=<KEY>" /> function App() { const classes = useStyles(); return ( <div> <Avatar alt="Zulf" src={zulf_lit} className={classes.large} /> <img src={zulf_lit} /> </div> ); } export default App;
770a6978a7dd5ed1514ef800155c500d39bed406
[ "JavaScript" ]
1
JavaScript
zulf73/ui-tests
813723ec3b889678605bacac123c7404416f9655
185231e3911bb320214989a3fa16c44e942fef25
refs/heads/master
<repo_name>Line-Yin/Visual-Question-Answering<file_sep>/S19 VQA/attention.py import torch import torch.nn as nn import torchvision.models as models from torch.nn.utils.rnn import pack_padded_sequence import torch.nn.functional as F class EncDec(nn.Module): def __init__(self, embed_size, hidden_size, attention_size, vocab_size, ans_vocab_size, num_layers, debug): super(EncDec, self).__init__() self.encoder = Enc(debug) self.decoder = Dec(embed_size, hidden_size, attention_size, vocab_size, ans_vocab_size, num_layers, debug) def forward(self, images, questions, lengths): img_features = self.encoder(images) logits = self.decoder(img_features, questions, lengths) logits = F.log_softmax(logits, dim=1) return logits def get_parameters(self): params = list(self.decoder.parameters()) + \ list(self.encoder.linear.parameters()) + \ list(self.encoder.bn.parameters()) return params class Enc(nn.Module): def __init__(self, debug): super(Enc, self).__init__() resnet = models.resnet152(pretrained=True) modules = list(resnet.children())[:-1] self.resnet = nn.Sequential(*modules) self.debug = debug def forward(self, images): with torch.no_grad(): features_maps = self.resnet(images) if self.debug: print('\ndone image encoder:') print('features_maps:', features_maps.size()) return features_maps class Dec(nn.Module): def __init__(self, embedding_features, lstm_features, attention_features, ques_vocab_size, ans_vocab_size, lstm_layers, debug): super(Dec, self).__init__() self.image_features = 2048 self.glimpses = 2 self.debug = debug self.question_encoder = QuestionEncoder(ques_vocab_size, embedding_features, lstm_features, lstm_layers, debug, drop=0.5) self.attention_model = Attention(self.image_features, lstm_features, attention_features, self.glimpses, debug=debug, drop=0.5,) self.classifier = Classifier(self.glimpses * self.image_features + lstm_features, lstm_features, ans_vocab_size, drop=0.5) def forward(self, features_maps, questions, lengths): question_features = self.question_encoder(questions, lengths) attention_features = self.attention_model(features_maps, question_features) attn_features_maps = apply_attention(features_maps, attention_features, self.debug) combined = torch.cat([attn_features_maps, question_features], dim=1) answer = self.classifier(combined) if self.debug: print('\ndone cat and fc:') print('combined features:', combined.size()) print('answer:', answer.size()) return answer class QuestionEncoder(nn.Module): def __init__(self, vocab_size, embed_size, hidden_size, num_layers, debug, drop): super(QuestionEncoder, self).__init__() self.embed = nn.Embedding(vocab_size, embed_size) self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True) self.drop = nn.Dropout(drop) self.tanh = nn.Tanh() self.debug = debug def forward(self, questions, lengths): embedded = self.embed(questions) tanhed = self.tanh(self.drop(embedded)) packed = pack_padded_sequence(tanhed, lengths, batch_first=True) hiddens, (hn, cn) = self.lstm(packed) if self.debug: print('\ndone questions encoder:') print('question features:', cn.squeeze(0).size()) return cn.squeeze(0) class Attention(nn.Module): def __init__(self, features_maps, question_features, attention_features, glimpses, debug, drop): super(Attention, self).__init__() self.v_conv = nn.Conv2d(features_maps, attention_features, 1, bias=False) self.q_linear = nn.Linear(question_features, attention_features) self.glimpses_conv = nn.Conv2d(attention_features, glimpses, 1) self.drop = nn.Dropout(drop) self.relu = nn.ReLU(inplace=True) self.debug = debug def forward(self, v, q): # image features to attention features v = self.v_conv(self.drop(v)) # print(v.size()) # question features to attention features q = self.q_linear(self.drop(q)) # print(q.size()) # tile question features to feature maps tiled_q = tile_2d(v, q) # print(tiled_q.size()) # combine v and q vq = self.relu(v + tiled_q) glimpses = self.glimpses_conv(self.drop(vq)) if self.debug: print('\ndone attention:') print('image_features:', v.size()) print('question_features:', q.size()) print('tiled_features:', tiled_q.size()) print('combined vq:', vq.size()) print('glimpses:', glimpses.size()) return glimpses def apply_attention(features_maps, attention, debug): # print('\ndone apply attention:') # print(features_maps.size()) # print(attention.size()) n, c = features_maps.size()[:2] glimpses = attention.size(1) # print('n, c, glimpses:', n, c, glimpses) features_maps = features_maps.view(n, 1, c, -1) # print('features maps:', features_maps.size()) attention = attention.view(n, glimpses, -1) # print('attention:', attention.size()) attention = F.softmax(attention, dim=-1) # print('attention:', attention.size()) attention = attention.unsqueeze(2) # print('attention:', attention.size()) weighted = attention * features_maps # print('weighted:', weighted.size()) weighted_mean = weighted.sum(dim=-1) # print('weighted mean:', weighted_mean.size()) # print('weighted mean return:', weighted_mean.view(n, -1).size()) if debug: print('\ndone apply attention:') print('n, c, glimpses:', n, c, glimpses) print('features maps:', features_maps.size()) print('attention:', attention.size()) print('weighted:', weighted.size()) print('weighted mean:', weighted_mean.size()) print('weighted mean return:', weighted_mean.view(n, -1).size()) return weighted_mean.view(n, -1) def tile_2d(feature_maps, feature_vec): n, c = feature_vec.size() spatial_size = feature_maps.dim() - 2 tiled = feature_vec.view(n, c, *([1] * spatial_size)).expand_as(feature_maps) return tiled class Classifier(nn.Sequential): def __init__(self, in_features, mid_features, out_features, drop): super(Classifier, self).__init__() self.add_module('drop1', nn.Dropout(drop)) self.add_module('lin1', nn.Linear(in_features, mid_features)) self.add_module('relu', nn.ReLU()) self.add_module('drop2', nn.Dropout(drop)) self.add_module('lin2', nn.Linear(mid_features, out_features)) <file_sep>/S19 VQA/utils.py import numpy as np from PIL import Image import os import h5py import pickle import json import torch import sys import matplotlib.pyplot as plt from torchvision import transforms default_transform = transforms.Compose([ transforms.RandomCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) def img_data_2_mini_batch(pos_mini_batch, img_data, batch_size): pos_mini_batch = pos_mini_batch.numpy() img_mini_batch = np.zeros((batch_size, 3, 256, 256)) for i, pos in enumerate(pos_mini_batch): img_mini_batch[i, :, :, :] = img_data[pos] return img_mini_batch # def imgs2batch(img_names, img_positions): # img_data = {} # for pos in img_positions: # img = imread('data/' + img_names[pos]) # img = np.transpose(img, (2, 0, 1)) # if pos not in img_data.keys(): # img_data[pos] = img # return img_data def imgs2batch(img_names, img_positions, transform=default_transform): img_data = [] for pos in img_positions: img = imread('data/' + img_names[pos], transform=transform) # if (transform is None): # img = np.transpose(img, (2, 0, 1)) img_data.append(img) return img_data def imread(path, transform=default_transform): if not os.path.exists(path): raise Exception("IMG_LOAD_ERR - Image File idx={}: [{}] not found".format(idx, img_path)) img = Image.open(path).convert("RGB") img = img.resize((256, 256)) if (transform is not None): img = transform(img) img = np.array(img)#, dtype=float) return img def gray2rgb(img): h, w = img.shape rgb_img = np.zeros((h, w, 3)) rgb_img[:, :, 0] = img rgb_img[:, :, 1] = img rgb_img[:, :, 2] = img return rgb_img def main(): val_data_json = json.load(open('cocoqa_data_prepro_93.json', 'r')) unique_img_val = val_data_json['unique_img_val'] val_data_h5 = h5py.File('cocoqa_data_prepro_93.h5', 'r') img_pos_val = val_data_h5['img_pos_val'][:] img_data = imgs2batch(unique_img_val, img_pos_val) print(len(unique_img_val)) print(len(img_data)) file = open('img_data_' + str(len(unique_img_val)) + '.pkl', 'wb') pickle.dump(img_data, file) file.close() if __name__ == '__main__': main() <file_sep>/S19 VQA/plotting.py import os, sys import matplotlib.pyplot as plt from bokeh.plotting import figure, output_file, show, save LOSS_OVER_N_EPOCHS_DICT_KEYS = ["train_loss", "test_loss"] SCORE_KEY_MAP = {'precision': 0, 'recall': 1, 'f1': 2} def validate_loss_over_n_dict_keys(loss_over_n_epochs: dict): assert all([key in LOSS_OVER_N_EPOCHS_DICT_KEYS for key in loss_over_n_epochs.keys()]) def plot_loss_over_n_epochs(loss_over_n_epochs: dict, title=None, file_path=None, hard_key = None, fig_size: tuple = (10, 6)): # validate_loss_over_n_dict_keys(loss_over_n_epochs) fig = plt.figure(figsize=fig_size) ax = fig.add_subplot(111) ax.set_xlabel('Epochs') ax.set_ylabel('Loss') if title: ax.set_title(title) if hard_key is None: hard_key = next(iter(loss_over_n_epochs.keys())) n_epochs = len(loss_over_n_epochs[hard_key]) for key in loss_over_n_epochs: # If nothing to plot just skip that split. if len(loss_over_n_epochs[key]) == 0: continue ax.plot(range(1, n_epochs + 1), loss_over_n_epochs[key], label=key) plt.legend() if file_path: file_path = os.path.join(PLOTTING_ROOT, file_path) print("File Path: ", file_path) fig.savefig(file_path) plt.show() def plot_score_over_n_epochs(scores_over_n_epochs: dict, score_type='f1', title=None, file_path=None, fig_size: tuple = (10, 6)): assert score_type in SCORE_KEY_MAP.keys(), "Invalid Score type." fig = plt.figure(figsize=fig_size) ax = fig.add_subplot(111) ax.set_xlabel('Epochs') ax.set_ylabel('{} Score'.format(score_type)) if title: ax.set_title(title) f1_score_key = SCORE_KEY_MAP[score_type] first_key = next(iter(scores_over_n_epochs.keys())) n_epochs = len(scores_over_n_epochs[first_key]) for key in scores_over_n_epochs: f1_score = [] if len(scores_over_n_epochs[key]) == 0: continue for epoch in range(n_epochs): f1_score.append(scores_over_n_epochs[key][epoch][f1_score_key]) ax.plot(range(1, n_epochs + 1), f1_score, label=key) plt.legend() plt.show() def get_empty_stat_over_n_epoch_dictionaries(): loss_over_epochs = { "train_loss": [], "val_loss": [], "test_loss": [] } scores_over_epochs = { "train_scores": [], "val_scores": [], "test_scores": [], "overall_scores": [] } return loss_over_epochs, scores_over_epochs def plot_line_chart_using_bokeh(x_axis_data: list, y_axis_data: list, colors: list, title: str, output_file_name: str, plot_height=350, plot_width=800, line_alpha=0.5, line_width=1, x_label='Time', y_label='Value', show_fig=True): assert len(x_axis_data) == len(y_axis_data) and len(x_axis_data) == len( y_axis_data), "Length miss-match for x-axis or y-axis data." p = figure(x_axis_type="datetime", title=title, plot_height=plot_height, plot_width=plot_width) p.xgrid.grid_line_color = None p.ygrid.grid_line_alpha = 0.5 p.xaxis.axis_label = x_label p.yaxis.axis_label = y_label p.multi_line(x_axis_data, y_axis_data, line_color=colors, line_width=line_width, line_alpha=line_alpha) output_file(output_file_name) if show_fig: show(p)<file_sep>/F18 VQA/prepro/prepro_val.py import json import numpy as np from collections import defaultdict from nltk.tokenize import word_tokenize import h5py data_type = 'uint8' def prepro_question(imgs): for i, data in enumerate(imgs): s = data['question'] txt = word_tokenize(str(s).lower()) data['processed_tokens'] = txt return imgs def build_vocab_question(imgs_val, include_map=False): # build vocabulary for question and answers. count_thr = 0 # count up the number of words counts = {} for img in imgs_val: for w in img['processed_tokens']: counts[w] = counts.get(w, 0) + 1 # cw = sorted([(count, w) for w, count in counts.items()], reverse=True) # print('top words and their counts:') # print('\n'.join(map(str, cw[:20]))) # print some stats # total_words = sum(counts.values()) # print('total words:', total_words) bad_words = [w for w, n in counts.items() if n <= count_thr] vocab = [w for w, n in counts.items() if n > count_thr] bad_count = sum(counts[w] for w in bad_words) # print('number of bad words: %d/%d = %.2f%%' % (len(bad_words), len(counts), len(bad_words) * 100.0 / len(counts))) # print('number of words in vocab would be %d' % (len(vocab),)) # print('number of <unk>: %d/%d = %.2f%%' % (bad_count, total_words, bad_count * 100.0 / total_words)) vocab.append('<unk>') vocab.append('<start>') vocab.append('<end>') vocab.append('<pad>') for img in imgs_val: txt = img['processed_tokens'] question = [w if counts.get(w, 0) > count_thr else '<unk>' for w in txt] question = ['<start>'] + question + ['<end>'] # print(question) img['final_question'] = question if include_map: itow = {i:w for i,w in enumerate(vocab)} # a 1-indexed vocab translation table wtoi = {w:i for i,w in enumerate(vocab)} # inverse table return imgs_val, vocab, itow, wtoi return imgs_val, vocab def get_top_answers(imgs_val): counts = {} for img in imgs_val: ans = img['ans'] counts[ans] = counts.get(ans, 0) + 1 cw = sorted([(count, w) for w, count in counts.items()], reverse=True) # print('top answer and their counts:') # print('\n'.join(map(str, cw[:20]))) vocab = [] for i in range(len(cw)): vocab.append(cw[i][1]) return vocab[:len(cw)] def encode_question(imgs_val, wtoi): max_length = 26 N = len(imgs_val) label_arrays_val = np.zeros((N, max_length), dtype=data_type) label_length_val = np.zeros(N, dtype=data_type) question_id_val = np.zeros(N, dtype=data_type) question_counter_val = 0 for i, img in enumerate(imgs_val): question_id_val[question_counter_val] = img['ques_id'] label_length_val[question_counter_val] = min(max_length, len(img['final_question'])) # record the length of this sequence question_counter_val += 1 for k, w in enumerate(img['final_question']): if k < max_length: label_arrays_val[i, k] = wtoi[w] return label_arrays_val, label_length_val, question_id_val def encode_answer(imgs_val, atoi): N = len(imgs_val) ans_arrays = np.zeros(N, dtype='uint32') for i, img in enumerate(imgs_val): ans_arrays[i] = atoi.get(img['ans'], -1) # -1 means wrong answer. return ans_arrays def get_unqiue_img(imgs_val): count_img = {} N = len(imgs_val) img_pos = np.zeros(N, dtype=data_type) for img in imgs_val: count_img[img['img_path']] = count_img.get(img['img_path'], 0) + 1 unique_img = [w for w, n in count_img.items()] imgtoi = {w: i for i, w in enumerate(unique_img)} # add one for torch, since torch start from 1. for i, img in enumerate(imgs_val): idx = imgtoi.get(img['img_path']) img_pos[i] = idx return unique_img, img_pos # ========================================================================= N_DATA_GENEREATE = 5000 val_data = json.load(open('vqa_raw_val_5000.json', 'r')) print('val_data:', len(val_data)) val_data = val_data[:N_DATA_GENEREATE] print(val_data) print(' ') # 'ques_id': 262148000, # 'img_path': 'val2014/COCO_val2014_000000262148.jpg', # 'question': 'Where is he looking?', # 'question_type': 'none of the above', # 'ans': 'down'} top_ans = get_top_answers(val_data) atoi = {w: i+1 for i, w in enumerate(top_ans)} itoa = {i+1: w for i, w in enumerate(top_ans)} print(top_ans) print('atoi\n', atoi) print('itoa\n', itoa) val_data = prepro_question(val_data) val_data, vocab = build_vocab_question(val_data) itow = {i+1:w for i,w in enumerate(vocab)} wtoi = {w:i+1 for i,w in enumerate(vocab)} print('itow\n', itow) print('wtoi\n', wtoi) print(val_data) ques_val, ques_length_val, question_id_val = encode_question(val_data, wtoi) print(ques_val) unique_img_val, img_pos_val = get_unqiue_img(val_data) print(unique_img_val) print(img_pos_val) # get the answer encoding. ans_val = encode_answer(val_data, atoi) print(' ') # print(ans_val) # print(question_id_val) # print(img_pos_val) # print(ques_length_val) # print(unique_img_val) # ========================================================================= h5py_name = 'cocoqa_data_prepro_' + str(len(ques_val)) + '.h5' json_name = 'cocoqa_data_prepro_' + str(len(ques_val)) + '.json' f = h5py.File(h5py_name, "w") f.create_dataset("ques_val", dtype=data_type, data=ques_val) f.create_dataset("ans_val", dtype=data_type, data=ans_val) f.create_dataset("question_id_val", dtype=data_type, data=question_id_val) f.create_dataset("img_pos_val", dtype=data_type, data=img_pos_val) f.create_dataset("ques_length_val", dtype=data_type, data=ques_length_val) f.close() print('wrote: ' + str(len(ques_val)), h5py_name) out = {} out['ix_to_word'] = itow out['ix_to_ans'] = itoa out['unique_img_val'] = unique_img_val json.dump(out, open(json_name, 'w')) print('wrote ' + str(len(ques_val)), json_name) <file_sep>/README.md # Visual-Question-Answering We implemented this VQA project using baseline methods (ResNet + LSTM) and the advanced methods (Stacked Attention Model). We trained our model on a relative small dataset for flexibility. For details, please check the final report. We implemented the work in Fall 2018 and refined the pipeline and code in Spring 2019. Here is the final accuracy table for comparison. ![alt text](https://github.com/Line-Yin/Visual-Question-Answering/blob/master/acc_table.png) <file_sep>/S19 VQA/rnn_att.py import torch import torch.nn as nn import torchvision.models as models from torch.nn.utils.rnn import pack_padded_sequence import torch.nn.functional as F class Enc(nn.Module): def __init__(self, embed_size): super(Enc, self).__init__() resnet = models.resnet152(pretrained=True) modules = list(resnet.children())[:-1] # delete the last fc layer. self.resnet = nn.Sequential(*modules) self.linear = nn.Linear(resnet.fc.in_features, embed_size) self.bn = nn.BatchNorm1d(embed_size, momentum=0.01) def forward(self, images): features = None with torch.no_grad(): features = self.resnet(images) features = features.reshape(features.size(0), -1) features = self.bn(self.linear(features)) return features class Dec(nn.Module): def __init__(self, embed_size, hidden_size, vocab_size, ans_vocab_size, num_layers, max_seq_length=26, rnn_type='lstm', use_prefix_n=2): super(Dec, self).__init__() self.embed = nn.Embedding(vocab_size, embed_size) if rnn_type == 'lstm': self.rnn = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True) elif rnn_type == 'gru': self.rnn = nn.GRU(embed_size, hidden_size, batch_first=True) else: self.rnn = nn.RNN(embed_size, hidden_size, batch_first=True) self.prefix_n = max(1, use_prefix_n) n_prefix_hidden_n = 1 + self.prefix_n self.linear = nn.Linear(n_prefix_hidden_n*hidden_size, ans_vocab_size) self.max_seg_length = max_seq_length def forward(self, features, captions, lengths): batch_size = captions.size(0) embeddings = self.embed(captions) unsq = features.unsqueeze(1) embeddings = torch.cat((features.unsqueeze(1), embeddings), 1) packed = pack_padded_sequence(embeddings, lengths, batch_first=True) # print 'packed',packed hiddens, (hn, cn) = self.rnn(packed) tmp = torch.nn.utils.rnn.pad_packed_sequence(hiddens) hiddens, hidden_lengths = tmp print(hiddens.shape) hn_l = [hiddens[i] for i in range(self.prefix_n+1)] + [hn[-1]] outputs = torch.cat(hn_l, dim=1) print('output shape', outputs.shape) outputs = self.linear(outputs) outputs = F.log_softmax(outputs, dim=1) return outputs class EncDec(nn.Module): def __init__(self, embed_size, hidden_size, vocab_size, ans_vocab_size, num_layers, max_seq_length=26, rnn_type='lstm', prefix_n=1): super(EncDec, self).__init__() self.embed_size = embed_size self.hidden_size = hidden_size self.vocab_size = vocab_size self.ans_vocab_size = ans_vocab_size self.num_layers = num_layers self.max_seq_length = max_seq_length self.encoder = Enc(embed_size) self.decoder = Dec(embed_size, hidden_size, vocab_size, ans_vocab_size, num_layers, max_seq_length, rnn_type, use_prefix_n=prefix_n) def forward(self, images, questions, lengths): img_features = self.encoder(images) logits = self.decoder(img_features, questions, lengths) return logits def get_parameters(self): params = list(self.decoder.parameters()) +\ list(self.encoder.linear.parameters()) +\ list(self.encoder.bn.parameters()) return params <file_sep>/S19 VQA/data_loader.py import torch import torch.utils.data as data import torchvision.transforms as transforms import torch.utils.data as Data import json import os, sys, re from PIL import Image import json, time import numpy as np import pandas as pd from tqdm import tqdm # from tqdm import tqdm_notebook as tqdm from random import shuffle import random from collections import defaultdict from nltk.tokenize import word_tokenize from utils import imread import h5py RANDOM_SEED = 9001 ann_path = 'data/v2_mscoco_val2014_annotations.json' q_path = 'data/v2_OpenEnded_mscoco_val2014_questions.json' i_path = 'data/val2014' i_prefix = 'COCO_val2014_' DEBUG = False PP = lambda parsed: print(json.dumps(parsed, indent=4, sort_keys=True)) def clean(words): # token = re.sub(r'\W+', '', word) tokens = words.lower() tokens = word_tokenize(tokens) return tokens def clean_answer(answer): token = re.sub(r'\W+', '', answer) token = clean(token) if (len(token)>1): return None return token[0] def collate_sort_by_q_wrap(dataset): def collate_sort_by_q(minibatch): max_seq_len = 0 minibatch.sort(key=lambda minibatch_tuple: minibatch_tuple[-1], reverse=True) for row in minibatch: idx, v,q,a,l = row max_seq_len = max(max_seq_len, l) for row in minibatch: idx, v,q,a,l = row q += [dataset.qtoi['<pad>'] for _i in range(max_seq_len-len(q))] return Data.dataloader.default_collate(minibatch) return collate_sort_by_q class VQADataSet(): def __init__(self, ann_path=ann_path, ques_path=q_path, img_path=i_path, TEST_SPLIT=0.2, Q=5, one_answer=True): t0 = time.time() self.one_answer = one_answer self.answer_maps = [] self.question_maps = {} self.splits = {'train':[], 'test':[]} self.Q = Q self.ann_path = ann_path self.quest_path = ques_path self.img_path = img_path self.special_tokens = ['<pad>','<start>', '<end>', '<unk>'] self.itoa, self.atoi = [], {} self.itoq, self.qtoi = [], {} self.vocab = {'answer': [] ,'question': []} self.max_length = -1 self.TEST_SPLIT = TEST_SPLIT self.qdf = None # Panda Frame of questions self.anns = None # List of annotations (with answers, quesiton_id, image_id) ### Load Dataset ### q_json = None with open(q_path, 'r') as q_f: q_json = json.load(q_f); self.qdf = pd.DataFrame(q_json['questions']) with open(ann_path, 'r') as ann_f: self.anns = json.load(ann_f)['annotations'] ### Initialize Data ### if (self.Q == -1): self.Q = len(self.anns) self._init_qa_maps() self._build_vocab() self._encode_qa_and_set_img_path() self._randomize_equally_distributed_splits() del self.anns # if DEBUG: print('VQADataSet init time: {}'.format(time.time() - t0)) @staticmethod def batchify_questions(q): return torch.stack(q).t() def build_data_loader(self, train=False, test=False, args=None): if (args is None): args = {'batch_size': 32} if test: args['shuffle'] = False elif train: args['shuffle'] = True batch_size = args['batch_size'] shuffle = args['shuffle'] print('batch_size: {} shuffle: {}'.format(batch_size, shuffle)) data_loader_split = VQADataLoader(self, train=train, test=test) data_generator = Data.DataLoader(dataset=data_loader_split, batch_size=batch_size, shuffle=shuffle, collate_fn=collate_sort_by_q_wrap(self)) return data_generator # set qdf, question_maps def _init_qa_maps(self): cnt = 0 for ann_idx in tqdm(range(self.Q)): ann = self.anns[ann_idx]; answer_set = set() answers = [] question_id = ann['question_id'] for ans in ann['answers']: ans_text = ans['answer'] ans_tokens = clean(ans_text) if (len(ans_tokens) != 1): continue ans_text = ans_tokens[0] if ans_text not in answer_set: ans['question_id'] = question_id answers.append(ans) answer_set.add(ans_text) if (self.one_answer): break if (len(answers) == 0): continue question = self.qdf.query('question_id == {}'.format(question_id)) self.answer_maps += answers self.question_maps[question_id] = question.to_dict(orient='records')[0] if (cnt >= self.Q): break cnt+=1 def _build_vocab(self): q_vocab = set() a_vocab = set() if DEBUG: print('build answer vocab') for ann in tqdm(self.answer_maps): answer = ann['answer'] # answer_tokens = clean(answer) # ann['tokens'] = answer_tokens ann['tokens'] = [answer] a_vocab.add(answer) if DEBUG: print('build question vocab)') for question_id, question_json in tqdm(self.question_maps.items()): question = question_json['question'] question_tokens = clean(question) question_json['tokens'] = ["<start>"] + question_tokens + ["<end>"] self.max_length = max(len(question_json['tokens']), self.max_length) q_vocab = q_vocab.union(set(question_tokens)) q_vocab_list = self.special_tokens + list(q_vocab) a_vocab_list = list(a_vocab) self.vocab['answer'] = a_vocab_list self.vocab['question'] = q_vocab_list self.itoq = self.vocab['question'] self.itoa = self.vocab['answer'] self.qtoi = {q: i for i,q in enumerate(q_vocab_list)} self.atoi = {a: i for i,a in enumerate(a_vocab_list)} def _encode_qa_and_set_img_path(self): if DEBUG: print('encode answers') for ann in tqdm(self.answer_maps): a_tokens = ann['tokens'] ann['encoding'] = [self.atoi[w]for w in a_tokens] if DEBUG: print('encode questions') for question_id, question_json in tqdm(self.question_maps.items()): image_id = question_json['image_id'] q_tokens = question_json['tokens'] question_json['encoding'] = [self.qtoi[w] for w in q_tokens] question_json['image_path'] = self._img_id_to_path(str(image_id)) def _img_id_to_path(self, img_id): eg = '000000000192' total = len(eg) full_img_id = '0'*(total-len(img_id)) + img_id img_f = i_path + "/" + i_prefix + full_img_id + ".jpg" img_f = img_f.strip() return img_f def _randomize_equally_distributed_splits(self): cntr = defaultdict(int) dist = defaultdict(list) for i, ann in enumerate(self.answer_maps): ans = ann['answer'] cntr[ans]+=1 dist[ans].append(i) splits = {'train': [], 'test': []} z_cnt = 0 for ans, idxes in tqdm(dist.items()): random.Random(RANDOM_SEED).shuffle(idxes) c = int(len(idxes)*self.TEST_SPLIT) splits['train'] += idxes[c:] splits['test'] += idxes[:c] sorted(splits['train']) sorted(splits['test']) self.splits = splits def __len__(self): return len(self.answer_maps) def get(self, idx, split_type): v,q,a = None, None, None try: split_keys = self.splits[split_type] ans_key = split_keys[idx] answer_json = self.answer_maps[ans_key] question_key = answer_json['question_id'] question_json = self.question_maps[question_key] except: print("ERR") return question_json, answer_json def size(self): return (len(self.question_maps), len(self.answer_maps)) def get_max_sequence_len(self): return self.max_length def decode_question(self, encoding): for x in encoding: if x < 0 or x >= len(self.itoq): raise Exception("DECODE_ERR: cannot find word-idx: {}".format(x)) sen_vec = [self.itoq[x] for x in encoding] sen = " ".join(sen_vec) return sen def decode_answer(self, encoding): if encoding < 0 or encoding >= len(self.itoa): raise Exception("DECODE_ERR: cannot find word-idx: {}".format(encoding)) return self.itoa[encoding] class VQADataLoader(data.Dataset): def __init__(self, dataset, train=False, test=False): assert(train+test==1) split_type = None if train: split_type = 'train' elif test: split_type = 'test' self.split_keys = dataset.splits[split_type] self.dataset = dataset self.split_type=split_type def __len__(self): return len(self.split_keys) ''' Returns: v: torch.Size([BATCH_SIZE, 3, 224, 224]) q: [tensor(a_0, a_1,...), tensor(a_0..)] a: tensor([ans_1, ans_2,...]) q_len: tensor([len_1, len_2,...]) , ''' def __getitem__(self, idx): v,q,a = -1, -1, -1 try: question_json, answer_json = self.dataset.get(idx, self.split_type) img_path = question_json['image_path'] v = imread(img_path) q = question_json['encoding'] a = answer_json['encoding'][0] q_len = len(q) except Exception as e: print("DATALOAD-ERR: " + str(e)) return idx, v, q, a, q_len if __name__ == '__main__': print("hello") <file_sep>/F18 VQA/helper/plot.py import numpy as np import matplotlib.pyplot as plt import pickle # name = 'attention_2_0.001_512_512' # # with open('result/' + name + '.pkl', 'rb') as f: # data = pickle.load(f) # # train_loss = data[0] # train_acc = data[1] # test_loss = data[2] # test_acc = data[3] # # plt.subplot(2, 2, 1) # plt.plot(range(len(train_loss)), train_loss, 'ro') # plt.title('train_loss') # # # plt.subplot(2, 2, 2) # plt.plot(range(len(train_acc)), train_acc, 'ro') # plt.title('train_acc') # # # plt.subplot(2, 2, 3) # plt.plot(range(len(test_loss)), test_loss, 'ro') # plt.title('test_loss') # # # plt.subplot(2, 2, 4) # plt.plot(range(len(test_acc)), test_acc, 'ro') # plt.title('test_acc ' + str(np.mean(sorted(test_acc, reverse=True)[:3]))) # # plt.subplots_adjust(hspace=0.5, wspace=0.5) # plt.show() # lstm l1 = [ 39.00, 40.67, 41.00, 40.00, 36.00, 37.67, 39.33, 39.67, 37.00, 39.33, 39.33, 38.67, 37.33, 39.67, 38.00, 39.00 ] # gru l2 = [ 37.00, 40.67, 39.00, 37.67, 41.67, 40.33, 36.67, 37.33 ] # rnn l3 = [ 35.67, 33.33, 36.67, 14.00, 39.67, 39.00, 35.33, 31.67 ] print(np.mean(l1)) print(np.mean(l2)) print(np.mean(l3)) <file_sep>/F18 VQA/output.py import os import pickle import numpy as np import matplotlib.pyplot as plt # model_name = 'attention_2' # # file_path = 'result/' + model_name # # attention_name1 = file_path + '_0.001_256_256.pkl' # attention_loss1 = pickle.load(open(attention_name1, 'rb'))[0] # attention_acc1 = np.mean(sorted(pickle.load(open(attention_name1, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc1 = format(attention_acc1, '.2f') # # attention_name2 = file_path + '_0.001_512_512.pkl' # attention_loss2 = pickle.load(open(attention_name2, 'rb'))[0] # attention_acc2 = np.mean(sorted(pickle.load(open(attention_name2, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc2 = format(attention_acc2, '.2f') # # attention_name3 = file_path + '_0.01_256_256.pkl' # attention_loss3 = pickle.load(open(attention_name3, 'rb'))[0] # attention_acc3 = np.mean(sorted(pickle.load(open(attention_name3, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc3 = format(attention_acc3, '.2f') # # attention_name4 = file_path + '_0.01_512_512.pkl' # attention_loss4 = pickle.load(open(attention_name4, 'rb'))[0] # attention_acc4 = np.mean(sorted(pickle.load(open(attention_name4, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc4 = format(attention_acc4, '.2f') # # X = range(1995) # # model_name = 'Attention_CN' # # plt.figure() # # plt.plot(X, sorted(attention_loss1, reverse=True)[5:], label='lr=0.001, emb=256, hid=256, acc=' + str(attention_acc1) + '%') # plt.plot(X, sorted(attention_loss2, reverse=True)[5:], label='lr=0.001, emb=512, hid=512, acc=' + str(attention_acc2) + '%') # plt.plot(X, sorted(attention_loss3, reverse=True)[5:], label='lr=0.01, emb=256, hid=256, acc=' + str(attention_acc3) + '%') # plt.plot(X, sorted(attention_loss4, reverse=True)[5:], label='lr=0.01, emb=512, hid=512, acc=' + str(attention_acc4) + '%') # plt.legend() # plt.title(model_name + ' Loss & Test Accuracy') # # plt.show() model_name = 'attetion' file_path = 'result/finished/' + model_name attention_name1 = file_path + '_0.01_256_256.pkl' attention_loss1 = pickle.load(open(attention_name1, 'rb'))[0] attention_acc1 = np.mean(sorted(pickle.load(open(attention_name1, 'rb'))[3], reverse=True)[:3]) * 100 attention_acc1 = format(attention_acc1, '.2f') model_name = 'fusion_gru' file_path = 'result/finished/' + model_name attention_name2 = file_path + '_0.001_512_512.pkl' attention_loss2 = pickle.load(open(attention_name2, 'rb'))[0] attention_acc2 = np.mean(sorted(pickle.load(open(attention_name2, 'rb'))[3], reverse=True)[:3]) * 100 attention_acc2 = format(attention_acc2, '.2f') model_name = 'naive_gru' file_path = 'result/finished/' + model_name attention_name3 = file_path + '_0.001_128_256.pkl' attention_loss3 = pickle.load(open(attention_name3, 'rb'))[0] attention_acc3 = np.mean(sorted(pickle.load(open(attention_name3, 'rb'))[3], reverse=True)[:3]) * 100 attention_acc3 = format(attention_acc3, '.2f') # attention_name4 = file_path + '_0.01_512_512.pkl' # attention_loss4 = pickle.load(open(attention_name4, 'rb'))[0] # attention_acc4 = np.mean(sorted(pickle.load(open(attention_name4, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc4 = format(attention_acc4, '.2f') X1 = range(995) X2 = range(1995) plt.figure() plt.plot(X2, sorted(attention_loss1, reverse=True)[5:], label='Attention - LSTM, lr=0.01, e=h=256, acc=' + str(39.17) + '%') plt.plot(X1, sorted(attention_loss3, reverse=True)[5:], label='Naive - GRU, lr=0.001, e=128, h=256, acc=' + str(37.97) + '%') plt.plot(X1, sorted(attention_loss2, reverse=True)[5:], label='Fusion - GRU, lr=0.001, e=h=512, acc=' + str(35.70) + '%') # plt.plot(X, sorted(attention_loss4, reverse=True)[5:], label='lr=0.01, emb=512, hid=512, acc=' + str(attention_acc4) + '%') plt.legend() plt.title('Training Loss & Averaged Test Accuracy') plt.xlabel('Training Iteration') plt.ylabel('Training Loss') plt.show() # model_name = 'attetion' # file_path = 'result/finished/' + model_name # # attention_name1 = file_path + '_0.01_256_256.pkl' # attention_loss1 = pickle.load(open(attention_name1, 'rb'))[0] # attention_acc1 = np.mean(sorted(pickle.load(open(attention_name1, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc1 = format(attention_acc1, '.2f') # # # model_name = 'naive_gru' # file_path = 'result/finished/' + model_name # # attention_name2 = file_path + '_0.001_128_256.pkl' # attention_loss2 = pickle.load(open(attention_name2, 'rb'))[0] # attention_acc2 = np.mean(sorted(pickle.load(open(attention_name2, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc2 = format(attention_acc2, '.2f') # # model_name = 'naive_rnn' # file_path = 'result/finished/' + model_name # # attention_name3 = file_path + '_0.001_128_256.pkl' # attention_loss3 = pickle.load(open(attention_name3, 'rb'))[0] # attention_acc3 = np.mean(sorted(pickle.load(open(attention_name3, 'rb'))[3], reverse=True)[:3]) * 100 # attention_acc3 = format(attention_acc3, '.2f') # # # attention_name4 = file_path + '_0.01_512_512.pkl' # # attention_loss4 = pickle.load(open(attention_name4, 'rb'))[0] # # attention_acc4 = np.mean(sorted(pickle.load(open(attention_name4, 'rb'))[3], reverse=True)[:3]) * 100 # # attention_acc4 = format(attention_acc4, '.2f') # # X1 = range(995) # X2 = range(1995) # # plt.figure() # # plt.plot(X2, sorted(attention_loss1, reverse=True)[5:], label='LSTM - Attention, lr=0.01, e=h=256, acc=' + str(38.85) + '%') # plt.plot(X1, sorted(attention_loss3, reverse=True)[5:], label='GRU - Naive, lr=0.001, e=128, h=256, acc=' + str(38.79) + '%') # plt.plot(X1, sorted(attention_loss2, reverse=True)[5:], label='RNN - Naive, lr=0.001, e=128, h=256, acc=' + str(33.17) + '%') # # plt.plot(X, sorted(attention_loss4, reverse=True)[5:], label='lr=0.01, emb=512, hid=512, acc=' + str(attention_acc4) + '%') # plt.legend() # plt.title('Training Loss & Averaged Test Accuracy') # # plt.xlabel('Training Iteration') # plt.ylabel('Training Loss') # # plt.show() <file_sep>/F18 VQA/prepro/data_json_val.py import json from nltk.tokenize import word_tokenize def generate_json_data(): ''' Put the VQA data into single json file, where [[Question_id, Image_id, Question, multipleChoice_answer, Answer] ... ] ''' num_data = 10000 num_val = 0 val = [] imdir = '%s/COCO_%s_%012d.jpg' val_anno = json.load(open('data/v2_mscoco_val2014_annotations.json', 'r')) val_ques = json.load(open('data/v2_OpenEnded_mscoco_val2014_questions.json', 'r')) print(len(val_anno['annotations'])) subtype = 'val2014' # for i in range(len(val_anno['annotations'])): for i in range(num_data): ans = val_anno['annotations'][i]['multiple_choice_answer'] if len(word_tokenize(str(ans).lower())) == 1: question_id = val_anno['annotations'][i]['question_id'] question_type = val_anno['annotations'][i]['question_type'] image_path = imdir % (subtype, subtype, val_anno['annotations'][i]['image_id']) question = val_ques['questions'][i]['question'] val.append( {'ques_id': question_id, 'img_path': image_path, 'question': question, 'question_type': question_type, 'ans': ans}) num_val += 1 if num_val == 5000: break print('Validation sample %d...' % (len(val))) json.dump(val, open('vqa_raw_val_' + str(num_val) + '.json', 'w')) if __name__ == "__main__": generate_json_data() <file_sep>/F18 VQA/train.py import torch import torch.nn as nn import torchvision.models as models from naive import Enc import json import h5py import numpy as np import matplotlib.pyplot as plt import torch.utils.data as Data import pickle from utils import img_data_2_mini_batch from torchvision import transforms # ========================================================================== val_data_json = json.load(open('cocoqa_data_prepro_93.json', 'r')) itow = val_data_json['ix_to_word'] itoa = val_data_json['ix_to_ans'] unique_img_val = val_data_json['unique_img_val'] # ========================================================================== val_data_h5 = h5py.File('cocoqa_data_prepro_93.h5', 'r') ques_val = val_data_h5['ques_val'][:] ans_val = val_data_h5['ans_val'][:] question_id_val = val_data_h5['question_id_val'][:] img_pos_val = val_data_h5['img_pos_val'][:] ques_length_val = val_data_h5['ques_length_val'][:] # ========================================================================== img_data = pickle.load(open('img_data_19.pkl', 'rb')) # ========================================================================== img_pos_val = torch.from_numpy(img_pos_val) ques_val = torch.from_numpy(ques_val) ans_val = torch.from_numpy(ans_val) print(img_pos_val.shape) print(ques_val.shape) print(ans_val.shape) train_loader = Data.DataLoader( dataset=Data.TensorDataset(img_pos_val, ques_val, ans_val), batch_size=100, shuffle=True, num_workers=2 ) encoder = Enc(embed_size=128) encoder.double() transform = transforms.Compose([ transforms.RandomCrop(256), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) # start your train for epoch in range(10): for i, (img_pos, ques, ans) in enumerate(train_loader): img_mini_batch = img_data_2_mini_batch(img_pos, img_data, 100) img_mini_batch = transform(img_mini_batch) print(img_mini_batch.shape) # Do LSTM for the questions -> embedded_words # embedded_words = embedded_words + features # Do LSTM # calculate loss with labels # keep training <file_sep>/S19 VQA/cluster_scripts/search_best_params.sh #!/usr/bin/env bash # #SBATCH --mem=15000 #SBATCH --job-name=student-life-grid-search #SBATCH --partition=1080ti-long #SBATCH --gres=gpu:1 #SBATCH --output=grid_search-%A.out #SBATCH --error=grid_search-%A.err #SBATCH --mail-type=ALL #SBATCH --ntasks-per-node=6 #SBATCH --nodes=1 #SBATCH --time=14-00:00:00 #SBATCH --mail-user=<EMAIL> # Log the jobid. echo $SLURM_JOBID - `hostname` >> ~/gypsum-jobs.txt cd ~/projects/MultiRes/student_life PYTHONPATH=../ python -m src.grid_search.grid_search <file_sep>/F18 VQA/model/fusion_lstm.py import torch import torch.nn as nn import torchvision.models as models from torch.nn.utils.rnn import pack_padded_sequence import torch.nn.functional as F class Enc(nn.Module): def __init__(self, embed_size): """Load the pretrained ResNet-152 and replace top fc layer.""" super(Enc, self).__init__() resnet = models.resnet152(pretrained=True) modules = list(resnet.children())[:-1] # delete the last fc layer. self.resnet = nn.Sequential(*modules) self.linear = nn.Linear(resnet.fc.in_features, embed_size) self.bn = nn.BatchNorm1d(embed_size, momentum=0.01) def forward(self, images): """Extract feature vectors from input images.""" with torch.no_grad(): features = self.resnet(images) features = features.reshape(features.size(0), -1) features = self.bn(self.linear(features)) return features class Dec(nn.Module): def __init__(self, embed_size, hidden_size, ques_vocab_size, ans_vocab_size, num_layers, max_seq_length=26): """Set the hyper-parameters and build the layers.""" super(Dec, self).__init__() self.embed = nn.Embedding(ques_vocab_size, embed_size) self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True) self.linear = nn.Linear(hidden_size * 2, ans_vocab_size) # self.classifier = Classifier(hidden_size * 2, 256, ans_vocab_size) self.max_seg_length = max_seq_length def forward(self, features, captions, lengths): """Decode image feature vectors and generates captions.""" embeddings = self.embed(captions) # print(embeddings.shape) # print(features.unsqueeze(1).shape) # embeddings = torch.cat((features.unsqueeze(1), embeddings), 1) packed = pack_padded_sequence(embeddings, lengths, batch_first=True) hiddens, (hn, cn) = self.lstm(packed) # tmp = torch.nn.utils.rnn.pad_packed_sequence(hn[-1], batch_first=True) # hiddens, hidden_lengths = tmp # print(features.shape) # print(hiddens[:, -1, :].shape) # print(hn.shape) # print(hn[-1].shape) # print(features.shape) print(features.shape) print(hn[-1].shape) hiddens = torch.cat((features, hn[-1]), 1) print(hiddens.shape) # print(hiddens.shape) outputs = self.linear(hiddens) # outputs = self.classifier(hiddens) outputs = F.log_softmax(outputs, dim=1) return outputs def sample(self, features, states=None): """Generate captions for given image features using greedy search.""" sampled_ids = [] inputs = features.unsqueeze(1) for i in range(self.max_seg_length): hiddens, states = self.lstm(inputs, states) # hiddens: (batch_size, 1, hidden_size) outputs = self.linear(hiddens.squeeze(1)) # outputs: (batch_size, vocab_size) _, predicted = outputs.max(1) # predicted: (batch_size) sampled_ids.append(predicted) inputs = self.embed(predicted) # inputs: (batch_size, embed_size) inputs = inputs.unsqueeze(1) # inputs: (batch_size, 1, embed_size) sampled_ids = torch.stack(sampled_ids, 1) # sampled_ids: (batch_size, max_seq_length) return sampled_ids class Classifier(nn.Sequential): def __init__(self, in_features, mid_features, out_features, drop=0.2): super(Classifier, self).__init__() self.add_module('drop1', nn.Dropout(drop)) self.add_module('lin1', nn.Linear(in_features, mid_features)) self.add_module('relu', nn.ReLU()) self.add_module('drop2', nn.Dropout(drop)) self.add_module('lin2', nn.Linear(mid_features, out_features)) <file_sep>/F18 VQA/model/att_model_2.py import torch import torch.nn as nn import torchvision.models as models from torch.nn.utils.rnn import pack_padded_sequence from torch.autograd import Variable import torch.nn.functional as F import sys def tile(feature_vector, feature_map): """ Repeat the same feature vector over all spatial positions of a given feature map. The feature vector should have the same batch size and number of features as the feature map. """ n, c = feature_vector.size() spatial_size = feature_map.dim() - 2 tiled = feature_vector.view(n, c, *([1] * spatial_size)).expand_as(feature_map) return tiled def apply_attention(input, attention): """ Apply any number of attention maps over the input. The attention map has to have the same size in all dimensions except dim=1. """ n, c = input.size()[:2] glimpses = attention.size(1) # flatten the spatial dims into the third dim, since we don't need to care about how they are arranged input = input.view(n, c, -1) attention = attention.view(n, glimpses, -1) s = input.size(2) # apply a softmax to each attention map separately # since softmax only takes 2d inputs, we have to collapse the first two dimensions together # so that each glimpse is normalized separately attention = attention.view(n * glimpses, -1) attention = F.softmax(attention) # apply the weighting by creating a new dim to tile both tensors over target_size = [n, glimpses, c, s] input = input.view(n, 1, c, s).expand(*target_size) attention = attention.view(n, glimpses, 1, s).expand(*target_size) weighted = input * attention # sum over only the spatial dimension weighted_mean = weighted.sum(dim=3) # the shape at this point is (n, glimpses, c, 1) return weighted_mean.view(n, -1) class Enc(nn.Module): def __init__(self, embed_size): """Load the pretrained ResNet-152 and replace top fc layer.""" super(Enc, self).__init__() resnet = models.resnet152(pretrained=True) modules = list(resnet.children())[:-1] # delete the last fc layer. self.resnet = nn.Sequential(*modules) self.linear = nn.Linear(resnet.fc.in_features, embed_size) self.bn = nn.BatchNorm1d(embed_size, momentum=0.01) def forward(self, images): """Extract feature vectors from input images.""" features = None with torch.no_grad(): features = self.resnet(images) flat_features = features.reshape(features.size(0), -1) flat_features = self.bn(self.linear(flat_features)) return features, flat_features DEBUG = False class Dec(nn.Module): def __init__(self, embed_size, hidden_size, vocab_size, ans_vocab_size, num_layers, max_seq_length=26): super(Dec, self).__init__() self.feature_map_n = 2048 # resnet feature self.embed_size=embed_size self.hidden_size=hidden_size self.vocab_size = vocab_size self.ans_vocab_size = ans_vocab_size self.glimpse_n = 2 self.language_model = LanguageModel(embed_size, hidden_size, vocab_size, ans_vocab_size, num_layers, max_seq_length=26) self.attention_model = AttentionModel(self.feature_map_n, hidden_size, 64, self.glimpse_n) self.classifier_in_n = self.glimpse_n * self.feature_map_n + hidden_size self.classifier = Classifier(self.classifier_in_n, 512, ans_vocab_size, drop=0.5) def forward(self, raw_features, features, captions, lengths): lang_feat = self.language_model(features,captions, lengths) # if (DEBUG): # print 'lang_feat', lang_feat.size() # print self.attention_model # print att_lang_feat = self.attention_model(raw_features, lang_feat) att_map = apply_attention(raw_features, att_lang_feat) # if DEBUG: # print '\nBefore combine' # print 'att_map', att_map.size() # print 'lang_feat', lang_feat.size() combined = torch.cat([att_map, lang_feat], dim=1) # if DEBUG: # print 'combined', combined.size() # print 'classifier_in_n', self.classifier_in_n answer = self.classifier(combined) # if DEBUG: print 'answer', answer.size() outputs = F.log_softmax(answer, dim=1) return outputs # return answer class Classifier(nn.Sequential): def __init__(self, in_features, mid_features, out_features, drop=0.0): super(Classifier, self).__init__() self.add_module('drop1', nn.Dropout(drop)) self.add_module('lin1', nn.Linear(in_features, mid_features)) self.add_module('relu', nn.ReLU()) self.add_module('drop2', nn.Dropout(drop)) self.add_module('lin2', nn.Linear(mid_features, out_features)) class LanguageModel(nn.Module): def __init__(self, embed_size, hidden_size, vocab_size, ans_vocab_size, num_layers, max_seq_length=26): super(LanguageModel, self).__init__() self.embed_size=embed_size self.hidden_size=hidden_size self.vocab_size = vocab_size self.ans_vocab_size = ans_vocab_size self.embed = nn.Embedding(vocab_size, embed_size) self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True) self.linear = nn.Linear(hidden_size, ans_vocab_size) self.max_seq_length = max_seq_length def forward(self, features, captions, lengths): batch_size = captions.size(0) embeddings = self.embed(captions) unsq = features.unsqueeze(1) embeddings = torch.cat((features.unsqueeze(1), embeddings), 1) packed = pack_padded_sequence(embeddings, lengths, batch_first=True) hiddens, (hn, cn) = self.lstm(packed) # language_output = self.linear(hn[-1]) # outputs = F.log_softmax(outputs, dim=1) # return outputs return cn.squeeze(0) # (batch, ) # return hn.squeeze(0) class AttentionModel(nn.Module): def __init__(self, img_feat_n, lang_feat_n, filter_1, filter_2): drop_rate = 0.0 super(AttentionModel, self).__init__() self.conv1 = nn.Conv2d(img_feat_n, filter_1, 1, bias=False) self.fc1 = nn.Linear(lang_feat_n, filter_1) self.conv2 = nn.Conv2d(filter_1, filter_2, 1) self.drop1 = nn.Dropout(drop_rate) self.relu = nn.ReLU(inplace=True) def forward(self, img_feat, lang_feat): # if DEBUG: print 'att_img_feat',img_feat.size(),'att_lang_feat',lang_feat.size() img_feat = self.conv1(self.drop1(img_feat)) # if DEBUG: print 'img_feat_1', img_feat.size() lang_feat = self.fc1(self.drop1(lang_feat)) # if DEBUG: print 'lang_feat_1', img_feat.size() # here shape of img_feat == lang_feat (e.g ([20, 64, 1, 1])) att_feat = tile(lang_feat, img_feat) # if DEBUG: print 'att_feat_1', att_feat.size() att_feat = self.relu(att_feat + img_feat) # if DEBUG: print 'att_feat_2', att_feat.size() att_out = self.conv2(self.drop1(att_feat)) # if DEBUG: print 'att_out',att_out.size() return att_out
a49d347137537ad54a76032839a992a34adf4f96
[ "Markdown", "Python", "Shell" ]
14
Python
Line-Yin/Visual-Question-Answering
f62717c28b51738c247efac37356eb8ca3a65231
53727eba2f4fa380409c54314ac451a4eb62cd7a
refs/heads/master
<file_sep># Android FontMetrics An Android app for measuring and testing FontMetrics ![App preview](/Xi2UG.png?raw=true) This app was originally created and used for these Stack Overflow questions: - http://stackoverflow.com/questions/27631736/meaning-of-top-ascent-baseline-descent-bottom-and-leading-in-androids-font - http://stackoverflow.com/a/42091739/ I decided to put the project on GitHub to make it easier to experiment with, and also so that other people will improve it. ## TODO If you want to help, here are some improvements that are needed: - Color code the checkbox items and the lines in the custom view - Keyboard popping up when first entering app isn't necessary - Add a few custom (free) fonts and add an option to select different fonts. <file_sep>package net.studymongolian.fontmetrics; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; public class FontMetricsView extends View { public final static int DEFAULT_FONT_SIZE_PX = 200; //private static final int PURPLE = Color.parseColor("#9315db"); //private static final int ORANGE = Color.parseColor("#ff8a00"); private static final float STROKE_WIDTH = 5.0f; private String mText; private int mTextSize; private Paint mAscentPaint; private Paint mTopPaint; private Paint mBaselinePaint; private Paint mDescentPaint; private Paint mBottomPaint; private Paint mMeasuredWidthPaint; private Paint mTextBoundsPaint; private TextPaint mTextPaint; private Paint mLinePaint; private Paint mRectPaint; private Rect mBounds; private boolean mIsTopVisible; private boolean mIsAscentVisible; private boolean mIsBaselineVisible; private boolean mIsDescentVisible; private boolean mIsBottomVisible; private boolean mIsBoundsVisible; private boolean mIsWidthVisible; public FontMetricsView(Context context) { super(context); init(); } public FontMetricsView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { mText = "My text line"; mTextSize = DEFAULT_FONT_SIZE_PX; mTextPaint = new TextPaint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(mTextSize); mTextPaint.setColor(Color.BLACK); Typeface tf = Typeface.createFromAsset(getResources().getAssets(), "Rich.ttf"); mTextPaint.setTypeface(tf); mLinePaint = new Paint(); mLinePaint.setColor(Color.RED); mLinePaint.setStrokeWidth(STROKE_WIDTH); mAscentPaint = new Paint(); mAscentPaint.setColor(getResources().getColor(R.color.ascent)); mAscentPaint.setStrokeWidth(STROKE_WIDTH); mTopPaint = new Paint(); mTopPaint.setColor(getResources().getColor(R.color.top)); mTopPaint.setStrokeWidth(STROKE_WIDTH); mBaselinePaint = new Paint(); mBaselinePaint.setColor(getResources().getColor(R.color.baseline)); mBaselinePaint.setStrokeWidth(STROKE_WIDTH); mBottomPaint = new Paint(); mBottomPaint.setColor(getResources().getColor(R.color.bottom)); mBottomPaint.setStrokeWidth(STROKE_WIDTH); mDescentPaint = new Paint(); mDescentPaint.setColor(getResources().getColor(R.color.descent)); mDescentPaint.setStrokeWidth(STROKE_WIDTH); mMeasuredWidthPaint = new Paint(); mMeasuredWidthPaint.setColor(getResources().getColor(R.color.measured_width)); mMeasuredWidthPaint.setStrokeWidth(STROKE_WIDTH); mTextBoundsPaint = new Paint(); mTextBoundsPaint.setColor(getResources().getColor(R.color.text_bounds)); mTextBoundsPaint.setStrokeWidth(STROKE_WIDTH); mTextBoundsPaint.setStyle(Paint.Style.STROKE); mRectPaint = new Paint(); mRectPaint.setColor(Color.BLACK); mRectPaint.setStrokeWidth(STROKE_WIDTH); mRectPaint.setStyle(Paint.Style.STROKE); mBounds = new Rect(); mIsTopVisible = true; mIsAscentVisible = true; mIsBaselineVisible = true; mIsDescentVisible = true; mIsBottomVisible = true; mIsBoundsVisible = true; mIsWidthVisible = true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // center the text baseline vertically int verticalAdjustment = this.getHeight() / 2; canvas.translate(0, verticalAdjustment); float startX = getPaddingLeft(); float startY = 0; float stopX = this.getMeasuredWidth(); float stopY = 0; // draw text canvas.drawText(mText, startX, startY, mTextPaint); // x=0, y=0 // draw lines startX = 0; if (mIsTopVisible) { startY = mTextPaint.getFontMetrics().top; stopY = startY; canvas.drawLine(startX, startY, stopX, stopY, mTopPaint); } if (mIsAscentVisible) { startY = mTextPaint.getFontMetrics().ascent; stopY = startY; //mLinePaint.setColor(Color.GREEN); canvas.drawLine(startX, startY, stopX, stopY, mAscentPaint); } if (mIsBaselineVisible) { startY = 0; stopY = startY; canvas.drawLine(startX, startY, stopX, stopY, mBaselinePaint); } if (mIsDescentVisible) { startY = mTextPaint.getFontMetrics().descent; stopY = startY; //mLinePaint.setColor(Color.BLUE); canvas.drawLine(startX, startY, stopX, stopY, mDescentPaint); } if (mIsBottomVisible) { startY = mTextPaint.getFontMetrics().bottom; stopY = startY; // mLinePaint.setColor(ORANGE); mLinePaint.setColor(Color.RED); canvas.drawLine(startX, startY, stopX, stopY, mBaselinePaint); } if (mIsBoundsVisible) { mTextPaint.getTextBounds(mText, 0, mText.length(), mBounds); float dx = getPaddingLeft(); canvas.drawRect(mBounds.left + dx, mBounds.top, mBounds.right + dx, mBounds.bottom, mTextBoundsPaint); } if (mIsWidthVisible) { // get measured width float width = mTextPaint.measureText(mText); // get bounding width so that we can compare them mTextPaint.getTextBounds(mText, 0, mText.length(), mBounds); // draw vertical line just before the left bounds startX = getPaddingLeft() + mBounds.left - (width - mBounds.width()) / 2; stopX = startX; startY = -verticalAdjustment; stopY = startY + this.getHeight(); canvas.drawLine(startX, startY, stopX, stopY, mMeasuredWidthPaint); // draw vertical line just after the right bounds startX = startX + width; stopX = startX; canvas.drawLine(startX, startY, stopX, stopY, mMeasuredWidthPaint); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = 200; int height = 200; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthRequirement = MeasureSpec.getSize(widthMeasureSpec); if (widthMode == MeasureSpec.EXACTLY) { width = widthRequirement; } else if (widthMode == MeasureSpec.AT_MOST && width > widthRequirement) { width = widthRequirement; } int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightRequirement = MeasureSpec.getSize(heightMeasureSpec); if (heightMode == MeasureSpec.EXACTLY) { height = heightRequirement; } else if (heightMode == MeasureSpec.AT_MOST && width > heightRequirement) { height = heightRequirement; } setMeasuredDimension(width, height); } // getters public Paint.FontMetrics getFontMetrics() { return mTextPaint.getFontMetrics(); } public Rect getTextBounds() { mTextPaint.getTextBounds(mText, 0, mText.length(), mBounds); return mBounds; } public float getMeasuredTextWidth() { return mTextPaint.measureText(mText); } // setters public void setText(String text) { mText = text; invalidate(); requestLayout(); } public void setTextSizeInPixels(int pixels) { mTextSize = pixels; mTextPaint.setTextSize(mTextSize); invalidate(); requestLayout(); } public void setTopVisible(boolean isVisible) { mIsTopVisible = isVisible; invalidate(); } public void setAscentVisible(boolean isVisible) { mIsAscentVisible = isVisible; invalidate(); } public void setBaselineVisible(boolean isVisible) { mIsBaselineVisible = isVisible; invalidate(); } public void setDescentVisible(boolean isVisible) { mIsDescentVisible = isVisible; invalidate(); } public void setBottomVisible(boolean isVisible) { mIsBottomVisible = isVisible; invalidate(); } public void setBoundsVisible(boolean isVisible) { mIsBoundsVisible = isVisible; invalidate(); } public void setWidthVisible(boolean isVisible) { mIsWidthVisible = isVisible; invalidate(); } }
0c96467d74fd199e9ce95cfdf3857e9b79031be4
[ "Markdown", "Java" ]
2
Markdown
barryzzz/AndroidFontMetrics
838e8a95fc22e729f5c488f4ba52c570647f44f5
a3f12d46265c36b97564cb23e08d470bf64e8613
refs/heads/master
<repo_name>robertchanny/FullStack360_Exercises<file_sep>/public/javascripts/word.js testWord = function() { var wordinput = document.getElementById('wordinput'); var currentWord = wordinput.value.toLowerCase(); var wordArray = currentWord.split(""); var reverseArray = reverseWord(wordArray); var wordString = wordArray.toString(); var reverseString = reverseArray.toString(); if (wordString == reverseString) { console.log("PALINDROME") return; } else { console.log("NOT PALINDROME") } } reverseWord = function(word) { newWord = []; for (i=word.length-1; i>=0; i--) { newWord.push(word[i]); } return newWord; }<file_sep>/public/javascripts/prime.js var isPrime = function() { var num = Number(document.getElementById('prime').value); if (num <= 0 || num == 1 || num >= 1000){ document.getElementById('primeResult').innerHTML = 'Invalid Input!'; return; } for (i=2; i<num; i++) { if (num % i == 0) { document.getElementById('primeResult').innerHTML = 'Not Prime!'; return; } } document.getElementById('primeResult').innerHTML = 'Prime!'; return; }<file_sep>/public/javascripts/removecolor.js // function removeColor(){ // document.getElementById('colorSelect').remove(document.getElementById('colorSelect').selectedIndex); // } function removeColor(){ var selectedOption = document.getElementById('colorSelect'); selectedOption.remove(this.selectedIndex); }<file_sep>/public/javascripts/number.js testNumbers = function() { var numlist = document.getElementById('largestNumber').value; numarray = numlist.split(','); biggestNumber = Number(numarray[0]); for (i=1; i<numarray.length; i++) { number = Number(numarray[i]); if (number > biggestNumber) { biggestNumber = number; } } document.getElementById('result').innerHTML = biggestNumber; }<file_sep>/public/javascripts/highlight.js var bolds = document.getElementsByTagName('strong'); var i = 0; highlight = function(bolds) { bolds[i].style.color = 'green'; } unhighlight = function(bolds) { bolds[i].style.color = 'black'; i++; } //TODO: make it loop through each bold and have each one take turns becoming green
bec9dd828a6399eb9c4a097eee577f87d85bdb7b
[ "JavaScript" ]
5
JavaScript
robertchanny/FullStack360_Exercises
4a8796131769011bc8f921fef24433332f09c28b
4085742168e6c34f3263f7fec882d0af32b24055
refs/heads/master
<repo_name>dabing1022/HearthStoneFans<file_sep>/HearthStoneFans/LogUtil.swift // // LogUtil.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation func printLog<T>(message: T, file: String = #file, method: String = #function, line: Int = #line) { #if DEBUG print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)") #endif } <file_sep>/HearthStoneFans/ViewController.swift // // ViewController.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import UIKit import RealmSwift class ViewController: UIViewController { @IBOutlet weak var gifImageView: GIFImageView! override func viewDidLoad() { super.viewDidLoad() DatabaseGeneratorManager.sharedInstance.generate() gifImageView.image = UIImage(named: "Card_Back_BlackTemple") } } <file_sep>/PythonScripts/README.md 1.use python3 2.use pyvenv - `pyvenv hearthstone` - `source hearthstone/bin/activate` 3.use `pip` to install libraries - Request - tqdm <file_sep>/HearthStoneFans/Models/HearthStoneConsts.swift // // HearthStoneConsts.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import UIKit // MARK: 卡牌类型 enum CardType: Int { case minion = 4 case spell = 5 case weapon = 7 func description() -> String { switch self { case .minion: return "仆从" case .spell: return "法术" case .weapon: return "武器" } } } // MARK: 卡牌杂项 enum CardMiscellaneous: Int { case none case hero = 3 case hero_power = 10 func description() -> String { switch self { case .hero: return "英雄" case .hero_power: return "英雄技能" default: return "" } } } // MARK: 质量 enum Quality: Int { case free = 0 case common = 1 case rare = 3 case epic = 4 case legendary = 5 func description() -> String { switch self { case .free: return "免费" case .common: return "普通" case .rare: return "稀有" case .epic: return "史诗" case .legendary: return "传说" } } func color() -> UIColor { switch self { case .free: return UIColor(colorLiteralRed: 135.0 / 255.0, green: 135.0 / 255.0, blue: 135.0 / 255.0, alpha: 1.0) case .common: return UIColor(colorLiteralRed: 255.0 / 255.0, green: 255.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0) case .rare: return UIColor(colorLiteralRed: 12.0 / 255.0, green: 68.0 / 255.0, blue: 122.0 / 255.0, alpha: 1.0) case .epic: return UIColor(colorLiteralRed: 78.0 / 255.0, green: 35.0 / 255.0, blue: 107.0 / 255.0, alpha: 1.0) case .legendary: return UIColor(colorLiteralRed: 146.0 / 255.0, green: 79.0 / 255.0, blue: 11.0 / 255.0, alpha: 1.0) } } } // MARK: 职业 enum HearthStoneClassType: Int { // 中立 case neutral = 0 // 战士 case warrior = 1 // 圣骑士 case paladin = 2 // 猎人 case hunter = 3 // 潜行者 case rogue = 4 // 牧师 case priest = 5 // 萨满 case shaman = 7 // 法师 case mage = 8 // 术士 case warlock = 9 // 德鲁伊 case druid = 11 func description() -> String { switch self { case .neutral: return "中立" case .warrior: return "战士" case .paladin: return "圣骑士" case .hunter: return "猎人" case .rogue: return "潜行者" case .priest: return "牧师" case .shaman: return "萨满" case .mage: return "法师" case .warlock: return "术士" case .druid: return "德鲁伊" } } } // MARK: 种族 enum RaceType: Int { // 无 case none = 0 // 野兽 case beast = 20 // 恶魔 case demon = 15 // 龙 case dragon = 24 // 机械 case mech = 17 // 鱼人 case murloc = 14 // 海盗 case pirate = 23 // 图腾 case totem = 21 func description() -> String { switch self { case .none: return "(无)" case .beast: return "野兽" case .demon: return "恶魔" case .dragon: return "龙" case .mech: return "机械" case .murloc: return "鱼人" case .pirate: return "海盗" case .totem: return "图腾" } } } <file_sep>/HearthStoneFans/Database/Generator/CardBackDatabaseGenerator.swift // // CardBackDatabaseGenerator.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import UIKit import RealmSwift class CardBackDatabaseGenerator : DatabaseGenerator { func generate() { if let path = Bundle.main.path(forResource: self.fileName, ofType: self.fileType) { if let data = FileManager.default.contents(atPath: path) { let jsonDic = JSON(data: data) printLog(message: jsonDic) let cardsbackArr = jsonDic["cardbacks"].arrayValue let realm = try! Realm() for cardbackDic in cardsbackArr { let cardback = CardBack() cardback.ID = cardbackDic["id"].intValue cardback.source = cardbackDic["source"].stringValue cardback.sourceid = cardbackDic["sourceid"].intValue cardback.note = cardbackDic["note"].stringValue cardback.comment = cardbackDic["comment"].stringValue cardback.enabled = cardbackDic["enabled"].intValue cardback.name = cardbackDic["name"].stringValue cardback.startdate = cardbackDic["startdate"].doubleValue cardback.enddate = cardbackDic["enddate"].doubleValue try! realm.write { realm.add(cardback) } } } } } } <file_sep>/HearthStoneFans/Models/Hero.swift // // Heroes.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift class Hero : Object { dynamic var ID = 0 // 英雄名称 dynamic var name = "" // 职业 dynamic var class_name = "" // 英雄技能 dynamic var hero_power = "" // 英雄技能卡牌ID dynamic var hero_power_card_id = 0 // 卡背ID dynamic var card_back_id = 0 override static func primaryKey() -> String { return "ID" } } <file_sep>/HearthStoneFans/Models/Card.swift // // Card.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift // MARK: 卡牌 class Card : Object { // 卡牌唯一ID dynamic var ID = 0 // 卡牌名称 dynamic var name = "" // 卡牌类型 private dynamic var rawType = 4 public var type: CardType { get { return CardType(rawValue: rawType)! } set { rawType = newValue.rawValue } } // 卡牌职业 private dynamic var rawClassType = 0 public var class_type: HearthStoneClassType { get { return HearthStoneClassType(rawValue: rawClassType)! } set { rawClassType = newValue.rawValue } } // 卡牌杂项 private dynamic var rawMiscellaneous = 0 public var miscellaneous: CardMiscellaneous { get { return CardMiscellaneous(rawValue: rawMiscellaneous)! } set { rawMiscellaneous = newValue.rawValue } } // 卡牌资源名称 dynamic var asset = "" // 金色卡牌资源名称 dynamic var golden_asset = "" override static func primaryKey() -> String { return "ID" } } <file_sep>/HearthStoneFans/Database/Generator/DatabaseGenerator.swift // // DatabaseGenerator.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation struct DatabaseGeneratorSourceFiles { static let cardback = "HearthStoneCardsBacks" static let seasons = "HearthStoneSeasons" } class DatabaseGenerator : NSObject { var fileName: String! var fileType: String! init(fileName: String, fileType: String) { super.init() self.fileName = fileName self.fileType = fileType } } <file_sep>/PythonScripts/Cards.py import json import shutil import requests from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool cardsImageHost = 'http://wow.zamimg.com/images/hearthstone/cards/zhcn/' originalCardImageBaseUrl = cardsImageHost + 'original/' mediumCardImageBaseUrl = cardsImageHost + 'medium/' smallCardImageBaseUrl = cardsImageHost + 'small/' animatedCardImageBaseUrl = cardsImageHost + 'animated/' pngSuffix = '.png?12585' gifSuffix = '_premium.gif?12585' <file_sep>/HearthStoneFans/Models/Adventure.swift // // Adventure.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift enum AdventureCategory: Int { // 练习模式 case practice = 0 // 纳克萨玛斯 case naxxramas // 黑石山 case blackrock_mountain // 探险者协会 case league_of_explorers // 卡拉赞 case karazhan func adventureName() -> String { switch self { case .practice: return "练习模式" case .naxxramas: return "纳克萨玛斯" case .blackrock_mountain: return "黑石山" case .league_of_explorers: return "探险者协会" case .karazhan: return "卡拉赞" } } } // MARK: 冒险 class Adventure: Object { // 冒险唯一ID dynamic var ID = 0 // 冒险名称 dynamic var name = "" // 冒险描述 dynamic var desc = "" // 冒险分类 private dynamic var rawCategory = 0 public var category: AdventureCategory { get { return AdventureCategory(rawValue: rawCategory)! } set { rawCategory = newValue.rawValue } } } <file_sep>/HearthStoneFans/Models/Achievement.swift // // Achievement.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift class Achievement : Object { // 成就唯一ID dynamic var ID = 0 // 成就名称 dynamic var name = "" // 来源 dynamic var source = "" // 可获得 dynamic var available = "" override static func primaryKey() -> String { return "ID" } } <file_sep>/HearthStoneFans/Models/Reward.swift // // Reward.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift enum RewardType: Int { // 无 case none = 0 // 经典卡包 case classic_card_pack // 金币 case gold // 竞技场奖励 case arena_credit // 卡背 case card_back } // 奖励 class Reward : Object { // 奖励个数 dynamic var nums = 0 // 奖励类型 private dynamic var rawType = 0 public var type: RewardType { get { return RewardType(rawValue: rawType)! } set { rawType = newValue.rawValue } } dynamic var card_back: CardBack? = nil // 奖励等级 dynamic var tier = "" // 每日几率 dynamic var daily_chance = "" } <file_sep>/HearthStoneFans/Database/Generator/DatabaseGeneratorManager.swift // // DatabaseGeneratorManager.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift class DatabaseGeneratorManager : NSObject { static let sharedInstance = DatabaseGeneratorManager() override init() { super.init() printLog(message: NSHomeDirectory()) } func generate() { do { try FileManager.default.removeItem(at: Realm.Configuration.defaultConfiguration.fileURL!) } catch {} CardBackDatabaseGenerator(fileName: DatabaseGeneratorSourceFiles.cardback, fileType: "json").generate() } } <file_sep>/HearthStoneFans/Models/Season.swift // // Season.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift // MARK: 赛季 class Season: Object { // 赛季唯一ID dynamic var ID = 0 // 赛季注释 dynamic var note = "" dynamic var comment = "" // 赛季开始日期 dynamic var startdate = 0 // 赛季结束日期 dynamic var enddate = 0 // 赛季名称 dynamic var name = "" override static func primaryKey() -> String { return "ID" } } <file_sep>/HearthStoneFans/Models/Boss.swift // // Boss.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift class Boss : Object { dynamic var ID = 0 // Boss名称 dynamic var name = "" // Boss描述 dynamic var desc = "" override static func primaryKey() -> String { return "ID" } } <file_sep>/PythonScripts/Achievements.py import requests from bs4 import BeautifulSoup host = 'http://cn.hearthhead.com/' urls = ['http://cn.hearthhead.com/cardbacks#gallery:0+1', 'http://cn.hearthhead.com/cardbacks#gallery:40+1'] def fetchAchievements(): for i, url in enumerate(urls): r = requests.get(url) if (r.status_code == 200): html_doc = r.text if __name__ == '__main__': fetchAchievements() <file_sep>/HearthStoneFans/Models/Quest.swift // // Quest.swift // HearthStoneFans // // Created by ChildhoodAndy on 16/10/6. // Copyright © 2016年 Sketchingame. All rights reserved. // import Foundation import RealmSwift // MARK: 任务 class Quest: Object { // 任务唯一ID dynamic var ID = 0 // 任务名称 dynamic var name = "" // 任务描述 dynamic var desc = "" // 任务奖励 dynamic var reward: Reward? = nil override static func primaryKey() -> String { return "ID" } } <file_sep>/PythonScripts/CardsBack.py import json import shutil import requests from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool cardbackImageHost = 'http://wow.zamimg.com/images/hearthstone/backs/' smallCardbackImageBaseUrl = cardbackImageHost + 'small/' mediumCardbackImageBaseUrl = cardbackImageHost + 'medium/' animatedCardbackImageBaseUrl = cardbackImageHost + 'animated/' pngSuffix = '.png?12585' gifSuffix = '.gif?12585' assetsArr = [] downloadCount = 0 def downloadCardBackImage_medium(asset): global downloadCount imageName = asset.split('/')[-1] pngImageName = imageName + ".png" pngUrl = mediumCardbackImageBaseUrl + imageName + pngSuffix print(pngImageName + " [" + pngUrl + "]") response = requests.get(pngUrl, stream=True) with open(pngImageName, 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) downloadCount += 1 print('下载完成 {0} --------- {1}/{2}'.format(pngImageName, downloadCount, len(assetsArr))) del response def downloadCardbackImage_gif(asset): global downloadCount imageName = asset.split('/')[-1] gifImageName = imageName + ".gif" gifUrl = animatedCardbackImageBaseUrl + imageName + gifSuffix print(gifImageName + " [" + gifUrl + "]") response = requests.get(gifUrl, stream=True) with open(gifImageName, 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) downloadCount += 1 print('下载完成 {0} --------- {1}/{2}'.format(gifImageName, downloadCount, len(assetsArr))) del response def assetsArrFromCardbacks(fileContent): cardbacksArr = fileContent['cardbacks'] for cardbackDic in cardbacksArr: asset = cardbackDic['asset'] assetsArr.append(asset) if __name__ == '__main__': file = 'HearthStoneCardsBacks.json' fp = open(file, 'r') dict = json.loads(fp.read()) fp.close() assetsArrFromCardbacks(dict) pool = ThreadPool(4) # download gif images # pool.map(downloadCardbackImage, assetsArr) # download medium png images pool.map(downloadCardBackImage_medium, assetsArr) pool.close() pool.join()
575097be56f73c4d8dcfdcdf4ce7490ef10dee09
[ "Swift", "Python", "Markdown" ]
18
Swift
dabing1022/HearthStoneFans
23e9d46011d8048b72b1efdb9a60e44d33338670
0dd76a42246ea4a6bd6844cd5c1b492eb5656506
refs/heads/master
<repo_name>soapnote/soapnote-app<file_sep>/sample/stuart-smalley-quiz/index.php <?php include('../../lib/main-header.php'); ?> <div id="container" class="container"> <?php include('soapnote.html'); ?> </div><file_sep>/lib/main-header.php <?php ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>soapnote.org = calculators + decision tools + SOAP samples</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1"> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-15622745-1', 'auto'); ga('send', 'pageview'); </script> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">SOAPnote.org</a> </div> <div> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> <li><a href="/special-search/">Search</a></li> <li><a href="/generator/">Form Generator</a></li> <li><a href="/lingo/">Lingo</a></li> <li><a href="/goodies/">Goodies</a></li> <li><a href="/help/">Help</a></li> </ul> </div> </div> </nav> <div class="container"> <h1>SOAPnote.org</h1> --> <p>An open source project to improve clinical documentation</p> </div><file_sep>/lib/generator-header.php <?php ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <script src="../lib/bootstrap-file-dialog/bootstrap.fd.js"></script> <link rel="stylesheet" href="../lib/bootstrap-file-dialog/bootstrap.fd.scss"> <link rel="stylesheet" href="../lib/bootstrap-file-dialog/bootstrap.fd.css">
e3d5f93ee03177908a687e81a6115efb36ce6354
[ "PHP" ]
3
PHP
soapnote/soapnote-app
8938048d7341206756fc58c8350a7efc32024300
2fe9b0772da1477b111a10163e20df5da9ab1f62
refs/heads/master
<file_sep>from django.db import models from datetime import datetime, date, time # Create your models here. class City(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name def get_breed(self): return self.name + ' belongs to ' def __repr__(self): return self.name + ' is added.' class Street(models.Model): name = models.CharField(max_length=30) city = models.ForeignKey(City, on_delete = models.CASCADE) def __str__(self): return self.name def get_breed(self): return self.name + ' belongs to ' def __repr__(self): return self.name + ' is added.' class Shops(models.Model): name = models.CharField(max_length=30) city = models.ForeignKey(City, on_delete = models.CASCADE) street = models.ForeignKey(Street, on_delete = models.CASCADE) home = models.IntegerField(default=1) time_open = models.CharField(max_length=15) time_close = models.CharField(max_length=15) @property def open(self): now = datetime.now() d = date.today() open = datetime.strptime(str(d) + ' ' + self.time_open, "%Y-%m-%d %H:%M") close = datetime.strptime(str(d) + ' ' + self.time_close, "%Y-%m-%d %H:%M") return now > open and now < close class Meta: unique_together = ('name', 'city', 'street') <file_sep>Репозитарий # https://github.com/alecs-shved/shops Тестовое задание. Реализовать сервис, который принимает и отвечает на HTTP запросы.. Подготовка выполняем: ``` $ pip install pipenv $ mkdir django-firecode $ cd django-firecode $ git init $ git clone https://github.com/alecs-shved/shops $ pipenv --python 3.6 $ pipenv shell $ pipenv install django==2.1.7 $ cd shops $ pipenv install djangorestframework==3.9.2 $ pipenv install psycopg2==2.7.7 $ python manage.py startapp shops ``` ### Database Install **Postregs 12** and make a new database `shops`. ``` $ sudo -i -u postgres $ psql $ createuser --interactive alecsander $ createdb -O alecsander shops ``` Make sure you have Python 3.7 or 3.6: ``` $ python3 --version Python 3.7.3 ``` ``` $ python3 manage.py runserver ``` $ pip install psycopg2-binary $ python3 manage.py runserver $ python manage.py test $ python3 manage.py runserver ``` Проверяем работу по тестовому заданию a. GET /city/ — получение всех городов из базы; $ curl -v -X POST --data '{"name": "Kupustin-Yar"}' -H "Content-Type: application/json" http://127.0.0.1:8000/city/ $ curl -v -X GET -H "Content-Type: application/json" http://127.0.0.1:8000/city/ b. GET /city/street/ — получение всех улиц города;(city_id — идентификатор города) $ curl -v -X POST --data '{"name":"Malina-street","city":1}' -H "Content-Type: application/json" http://127.0.0.1:8000/city/street/ $ curl -v -X GET -H "Content-Type: application/json" http://127.0.0.1:8000/city/street/ c. POST /shop/ — создание магазина; Данный метод получает json c объектом магазина, в ответ возвращает id созданной записи. $ curl -v -X POST --data '{"name":"shop-six","city":1, "street":1, "home":14, "time_open":"08:00", "time_close":"20:00"}' -H "Content-Type: application/json" http://127.0.0.1:8000/shop/ d. GET /shop/?street=&city=&open=0/1 — получение списка магазинов; i. Метод принимает параметры для фильтрации. Параметры не обязательны. В случае отсутствия параметров выводятся все магазины, если хоть один параметр есть , то по нему выполняется фильтрация. ii. Важно!: в объекте каждого магазина выводится название города и улицы, а не id записей. iii. Параметр open: 0 - закрыт, 1 - открыт. Данный статус определяется исходя из параметров «Время открытия», «Время закрытия» и текущего времени сервера. $ curl -v -X GET -H "Content-Type: application/json" "http://127.0.0.1:8000/shop/?street=Malina-street&city=Kupustin-Yar&open=1" end test ok!!<file_sep>from django.urls import path from . import views urlpatterns = [ path( 'city/', views.get_post_citys, name='get_post_citys' ), path( 'city/street/', views.get_post_street, name='get_post_street' ), path( 'shop/', views.get_post_shop, name='get_post_shop' ), ]<file_sep>import json from rest_framework.response import Response from rest_framework import status from django.test import TestCase, Client from django.urls import reverse from ..models import City, Street, Shops from ..serializers import CitySerializer, StreetSerializer, ShopsallSerializer # initialize the APIClient app client = Client() class GetAllCityTest(TestCase): """ Test module for GET all city API """ def setUp(self): City.objects.create( name='Kupustin-Yar',) City.objects.create( name='Astrahan',) def test_get_post_citys(self): # get API response response = client.get(reverse('get_post_citys')) # get data from db citys = City.objects.filter() serializer = CitySerializer(citys, many=True) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK) class CreateNewCityTest(TestCase): """ Test module for inserting a new city """ def setUp(self): self.valid_payload = { 'name': 'Kupustin-Yar', } self.invalid_payload = { 'name': '', } def test_create_valid_city(self): response = client.post( reverse('get_post_citys'), data=json.dumps(self.valid_payload), content_type='application/json' ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_create_invalid_city(self): response = client.post( reverse('get_post_citys'), data=json.dumps(self.invalid_payload), content_type='application/json' ) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) class GetAllstreetTest(TestCase): """ Test module for GET all street API """ def setUp(self): city = City.objects.create( name='Kupustin-Yar',) idu = City.objects.get(name='Kupustin-Yar').id Street.objects.create(name='Malina-street', city_id=idu) def test_get_post_streets(self): # get API response response = client.get(reverse('get_post_street')) # get data from db street = Street.objects.filter() serializer = StreetSerializer(street, many=True) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK) class GetAllshopsTest(TestCase): """ Test module for GET all shops API """ def setUp(self): city = City.objects.create( name='Kupustin-Yar',) street = Street.objects.create(name='Malina-street', city_id=city.id) Shops.objects.create( name='Shop-one', city_id=city.id, street_id=street.id, home=14, time_open='08:00', time_close='20:00') def test_get_post_shops(self): # get API response # get data from db url_list = [ '/shop/?street=Malina-street&city=Kupustin-Yar&open=1' ] response = client.get(url_list[0]) shops = filter(lambda x: x.open == True, Shops.objects.filter(city__name="Kupustin-Yar", street__name="Malina-street")) serializer = ShopsallSerializer(shops, many=True) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)<file_sep>from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.db.models import Q from .models import City, Street, Shops from .serializers import CitySerializer, StreetSerializer, ShopsallSerializer from datetime import datetime, date, time import json # Create your views here. @api_view(['GET', 'POST']) def get_post_citys(request): # get all city. Pos a if request.method == 'GET': citys = City.objects.filter() serializer = CitySerializer(citys, many=True) return Response(serializer.data) # insert a new record for a city elif request.method == 'POST': data = { 'name': request.data.get('name') } serializer = CitySerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'POST']) def get_post_street(request): # get all street to city. Pos b if request.method == 'GET': streets = Street.objects.filter() serializer = StreetSerializer(streets, many=True) return Response(serializer.data) # insert a new record for a street elif request.method == 'POST': data = { 'name': request.data.get('name'), 'city': request.data.get('city'), } serializer = StreetSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'POST']) def get_post_shop(request): search_terms = {} search_terms['street__name'] = request.GET.get('street') search_terms['city__name'] = request.GET.get('city') op = request.GET.get("open") if op == 1: ope = True else: ope = False if request.method == 'GET': if op is None: shops = Shops.objects.filter(**search_terms) else: shops = filter(lambda x: x.open != ope, Shops.objects.filter(**search_terms)) serializer = ShopsallSerializer(shops, many=True) return Response(serializer.data) elif request.method == 'POST': data = { 'name': request.data.get('name'), 'city': request.data.get('city'), 'street': request.data.get('street'), 'home': request.data.get('home'), 'time_open': request.data.get('time_open'), 'time_close': request.data.get('time_close'), } serializer = ShopsSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data['id'], status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <file_sep>from rest_framework import serializers from django.db import models from .models import City, Street, Shops class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('name',) class StreetSerializer(serializers.ModelSerializer): class Meta: model = Street fields = ('name','city',) class ShopsallSerializer(serializers.ModelSerializer): city_name = serializers.ReadOnlyField(source='city.name') street_name = serializers.ReadOnlyField(source='street.name') class Meta: model = Shops fields = ('id', 'name', 'city_name', 'street_name','home','time_open','time_close','open') <file_sep>from django.test import TestCase from ..models import City class CityTest(TestCase): """ Test module for City model """ def setUp(self): City.objects.create( name='Kap',) City.objects.create( name='Aral',) def test_city(self): city_casper = City.objects.get(name='Kap') city_muffin = City.objects.get(name='Aral') self.assertEqual( city_casper.get_breed(), "Kap belongs to ") self.assertEqual( city_muffin.get_breed(), "Aral belongs to ")
747b89848374e46585e6c697fc1e26c830544a22
[ "Markdown", "Python" ]
7
Python
alecs-shved/restone
d12d08a7ade4eea3e1e5c3e719d388b400c2af96
72ec02995a3b18d496f3b98573d8bf8fe51b04e8
refs/heads/master
<file_sep>/* * Copyright 2015 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.swagger.sample.controllers; import io.swagger.inflector.models.RequestContext; import io.swagger.inflector.models.ResponseContext; import io.swagger.test.models.Address; import io.swagger.test.models.User; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response.Status; import java.util.List; public class TestController { public ResponseContext formTest(RequestContext request, String user) { System.out.println("found it! " + user); return new ResponseContext() .status(Status.OK) .contentType(MediaType.APPLICATION_JSON_TYPE) .entity(user); } public ResponseContext postFormData(RequestContext request, Long id, String name) { // show a sample response return new ResponseContext() .status(Status.OK) .contentType(MediaType.APPLICATION_JSON_TYPE) .entity(new User() .id(id) .user(name)); } public ResponseContext overloadedResponse(RequestContext request, String arg1) { return new ResponseContext() .status(Status.OK) .entity(new User()); } public ResponseContext withModel(RequestContext request, String id, Address animal) { return new ResponseContext() .status(Status.OK) .entity("ok"); } public ResponseContext withModelArray(RequestContext request, String id, List<Address> modelArray) { return new ResponseContext() .status(Status.OK); } public ResponseContext arrayInputTest(RequestContext request, List<String> users) { return new ResponseContext() .status(Status.OK) .entity(users); } }<file_sep>/* * Copyright 2015 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.swagger.test.utils; import io.swagger.inflector.config.Configuration; import io.swagger.inflector.utils.ReflectionUtils; import io.swagger.models.Operation; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class ReflectionUtilsTest { ReflectionUtils utils = new ReflectionUtils(); @BeforeClass public void setup() throws Exception { utils.setConfiguration(Configuration.defaultConfiguration()); } @Test public void testCleanOperationId() throws Exception { String operationId = "hello"; assertEquals(utils.sanitizeToJava(operationId), "hello"); } @Test public void testOperationIdWithSpace() throws Exception { String operationId = "hello friends"; assertEquals(utils.sanitizeToJava(operationId), "hello_friends"); } @Test public void testOperationIdWithPunctuation() throws Exception { String operationId = "hello-my-friends and family"; assertEquals(utils.sanitizeToJava(operationId), "hello_my_friends_and_family"); } @Test public void testGetOperationName() throws Exception { Operation operation = new Operation() .tag("myTag"); String controllerName = utils.getControllerName(operation); assertEquals(controllerName, "io.swagger.sample.controllers.MyTag"); } @Test public void testGetOperationNameWithSpace() throws Exception { Operation operation = new Operation() .tag("my tag"); String controllerName = utils.getControllerName(operation); assertEquals(controllerName, "io.swagger.sample.controllers.My_tag"); } @Test public void testGetOperationNameWithPunctuation() throws Exception { Operation operation = new Operation() .tag("my-tags"); String controllerName = utils.getControllerName(operation); assertEquals(controllerName, "io.swagger.sample.controllers.My_tags"); } @Test public void testGetOperationNameWithWhitespace() throws Exception { Operation operation = new Operation() .tag(" myTags "); String controllerName = utils.getControllerName(operation); assertEquals(controllerName, "io.swagger.sample.controllers.MyTags"); } }<file_sep>## Dropwizard Inflector Sample Simple example showing how to use the inflector with dropwizard. Build with ``` mvn clean install ``` Run with ``` java -jar ./target/inflector-dropwizard-sample-1.0-SNAPSHOT.jar server server.yml ``` Have fun!
e309c051656a60a8921e48af6b4c8d1ceb487a1e
[ "Markdown", "Java" ]
3
Java
tomtit/swagger-inflector
e349080ed1b6cf7a77aa7a204d13f6bf08b40650
b1b3a75ac4461dc841107172e407ebf9a9599a35
refs/heads/main
<repo_name>hanssenamanda/Chatbot<file_sep>/greetings.py print ('Hello,whats your name?') if language == 'python' print('How are you python?)<file_sep>/n.py user_name = input("Hello, Human. What's your name? ") print(user_name) while True: original_user_response = input("My name is cas. What kind of movie would you like to hear about? ") user_response = original_user_response.lower() print(user_response) if "romcom" in user_response: print("the newest movie in 2021 is Coming 2 America that is rated pg-13") break if user_response == "romcom": print("the newest movie in 2021 is Coming 2 America that is rated pg-13") break if "horror" in user_response: print("the newest movie in 2021 is wrong turn that is rated R") break if user_response == "horror": print("the newest movie in 2021 is wrong turn") break if "comedy" in user_response: print("the newest movie in 2021 is Tom and jerry that is rated pg") break if user_response == "comedy": print("the newest movie in 2021 is Tom and jerry that is rated pg") break if "quit" in user_response: print("is exactly 'quit'") break if user_response == "quit": print("is exactly 'quit'") break print("interesting.... \ngood bye") #outside while loop #print("good bye")
37e10f238a553dad2294d19f24337ee36cc8bc4f
[ "Python" ]
2
Python
hanssenamanda/Chatbot
47e6fd466716a621c257c192ae278fee9e7391d3
9b2d9fdac2e118c86190ab7c46842517dd4d2e29
refs/heads/master
<repo_name>m-sarim-khan-bangash/React-JS-Mini-Project<file_sep>/src/Sdata.jsx const Sdata = [ { sname: "DARK", imgsrc: "https://wallpapercave.com/wp/wp4056410.jpg", title: "A Netflix Original Series", link: "https://www.netflix.com", }, { sname: "Extra Curricular", imgsrc: "https://m.media-amazon.com/images/M/MV5BNGQxMDcyOTEtZWZkNi00NzgwLWEzNjQtZmFhMGY5ZGRlMTdiXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_.jpg", title: "A Netflix Original Series", link: "https://www.netflix.com", }, { sname: "Stranger Things", imgsrc: "https://images-na.ssl-images-amazon.com/images/I/71OB1IywjLL._AC_SY679_.jpg", title: "A Netflix Original Series", link: "https://www.netflix.com", }, { sname: "The Vampire Diaries", imgsrc: "https://i.pinimg.com/originals/7e/59/3f/7e593fe7f57f3eb8245b91c440d3a226.jpg", title: "A Netflix Original Series", link: "https://www.netflix.com", }, { sname: "My First-2 Love", imgsrc: "https://i.mydramalist.com/2OEvwc.jpg?v=1", title: "A Netflix Original Series", link: "https://www.netflix.com", }, ]; export default Sdata; <file_sep>/src/App.js import "./App.css"; import Card from "./components/Card"; import Sdata from "./Sdata"; function App() { // console.log(Sdata[0]); return ( <> <h1 className="heading_style">List of top 5 Netflix Series in 2021</h1> {Sdata.map((value, index) => { return ( <Card key={index} imgsrc={value.imgsrc} title={value.title} sname={value.sname} link={value.link} /> ); })} ; </> ); } export default App;
95cdc7a4f8bbba5505b555ea5357c81fc1b377d5
[ "JavaScript" ]
2
JavaScript
m-sarim-khan-bangash/React-JS-Mini-Project
9439f7163f0335c9e6161d44e1d3f61dfd863ce5
b9854bf74256e1c847fb190ef51f354017f94f24
refs/heads/main
<repo_name>sanbad36/Node-Farm<file_sep>/index.js const fs = require('fs'); const http = require('http'); const url = require('url'); const slugify = require('slugify'); const replaceTemplate = require('./modules/replaceTemplate'); const tempOverview = fs.readFileSync( `${__dirname}/templates/template-overview.html`,'utf-8' ); const tempCard = fs.readFileSync( `${__dirname}/templates/template-card.html`, 'utf-8'); const tempProduct = fs.readFileSync(`${__dirname}/templates/template-product.html`, 'utf-8'); // Read the Main data json const data = fs.readFileSync(`${__dirname}/dev-data/data.json`, 'utf-8'); const dataObj = JSON.parse(data); const slugs = dataObj.map(el => slugify(el.productName, { lower: true })); console.log(slugs); // creating server with routes const server = http.createServer((req, res) => { // parsing the url and extracting the pathname and query string const { query, pathname } = url.parse(req.url, true); // Overview page if (pathname === '/' || pathname === '/overview') { res.writeHead(200, { 'Content-type': 'text/html' }); // replacing the HTML tempate present in the card , with the exact data. const cardsHtml = dataObj.map(el => replaceTemplate(tempCard, el)).join(''); // now we are replacing the original overview or home page with the html string which we received from the card html after filling the templates with the data const output = tempOverview.replace('{%PRODUCT_CARDS%}', cardsHtml); res.end(output); } // Product page, will be called with the query string, and accodingly we render the page with the id of that data in the json else if (pathname === '/product') { res.writeHead(200, { 'Content-type': 'text/html' }); // Here we are extracting only that data which matches the query string. const product = dataObj[query.id]; // replacing the product template only with that extracted data. const output = replaceTemplate(tempProduct, product); res.end(output); } } // Not Found else { res.writeHead(404, { 'Content-type': 'text/html', }); res.end('<h1>Page not found!</h1>'); } }); // Here the server is listing the client request. server.listen(8000, '127.0.0.1', () => { console.log('Listening to requests on port 8000'); }); <file_sep>/Readme.md # Node farm ### Project live link: [NODE FARM (node-farm.herokuapp.com)](https://node-farm.herokuapp.com/) ### sample screenshots: ![Untitled](Images/Untitled.png) ![Untitled](Images/Untitled1.png) ### Sample JSON: ![Untitled](Images/Untitled2.png) --- `npm init` ## Libraries used: `npm install slugify` `npm install nodemon --save-dev` `npm i nodmon --global` → to install the nodemon globally. `npm i express` ![Untitled](Images/Untitled3.png) `npm start` - To check thus any package is outdated `npm outdated` - Install a package with the required version number `npm install slugify@1.0.0` - Update the package `npm update slugify` - Uninstall package `npm uninstall express` - `npm install` --- `^version` **“Compatible with version”**, will update you to all future minor/patch versions, without incrementing the major version. `^2.3.4` will use releases from 2.3.4 to <3.0.0. `~version` **“Approximately equivalent to version”**, will update you to all future patch versions, without incrementing the minor version. `~1.2.3` will use releases from 1.2.3 to <1.3.0. --- - `version` Must match `version` exactly - `>version` Must be greater than `version` - `>=version` etc - `<version` - `<=version` - `~version` "Approximately equivalent to version" See [semver](https://github.com/npm/node-semver#versions) - `^version` "Compatible with version" See [semver](https://github.com/npm/node-semver#versions) - `1.2.x` 1.2.0, 1.2.1, etc., but not 1.3.0 - `http://...` See 'URLs as Dependencies' below - `` Matches any version - `""` (just an empty string) Same as `` - `version1 - version2` Same as `>=version1 <=version2`. - `range1 || range2` Passes if either range1 or range2 are satisfied. - `git...` See 'Git URLs as Dependencies' below - `user/repo` See 'GitHub URLs' below - `tag` A specific version tagged and published as `tag` See `[npm dist-tag](https://docs.npmjs.com/cli/v7/commands/npm-dist-tag)` - `path/path/path` See [Local Paths](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#local-paths) below For example, these are all valid: ``` { "dependencies": { "foo": "1.0.0 - 2.9999.9999", "bar": ">=1.0.2 <2.1.2", "baz": ">1.0.2 <=2.3.4", "boo": "2.0.1", "qux": "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0", "asd": "http://asdf.com/asdf.tar.gz", "til": "~1.2", "elf": "~1.2.3", "two": "2.x", "thr": "3.3.x", "lat": "latest", "dyl": "file:../dyl" } } ``` npm allows installing newer version of a package than the one specified. Using tilde (`~`) gives you bug fix releases and caret (`^`) gives you backwards-compatible new functionality as well. The problem is old versions usually don't receive bug fixes that much, so npm uses caret (`^`) as the default for `--save`. --- ### Extension used in vs code - prettier (Install→ settings→format on save ) - TODO highlight - TabNine - pug beautify - live server To configure the prettier →make a file with name → `.prettierrc` [Options · Prettier](https://prettier.io/docs/en/options.html) `To run the above app-` `you have to download the NPM in your machine. After that follow the below steps-` - `Clone the Repository in your local machine` - `Now go inside the Node Farm directory using the command line or linux terminal` - `Type command - npm install node index.js` - `Above command will create the local server.` ## Thank you!
0e8e86a464a23a86b464da6ae6140cb284b31ccf
[ "JavaScript", "Markdown" ]
2
JavaScript
sanbad36/Node-Farm
a95f1c2b11fba3c05ad7d2ba3507f64c1a4b073d
174891756b7953f7d550ba0454392345af82ba05
refs/heads/main
<file_sep>import Vue from 'vue' import { Header } from 'mint-ui'; import { Tabbar, TabItem } from 'mint-ui'; Vue.component(Tabbar.name, Tabbar); Vue.component(TabItem.name, TabItem); Vue.component(Header.name, Header);<file_sep>package com.example.GEEN.Util; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * @author hello * @title: Cache * @projectName fitness-course-service * @description: TODO * @date 2021/5/1816:45 */ public class Cache { private final static ConcurrentHashMap<String, List<String>> MAP = new ConcurrentHashMap<>(); /** * 添加缓存 */ public synchronized static void put(String key, List<String> data) { //清除原键值对 Cache.remove(key); //不设置过期时间 MAP.put(key, data); } /** * 读取缓存 */ public static List<String> get(String key) { return MAP.get(key); } /** * 清除缓存 */ public synchronized static void remove(String key) { MAP.remove(key); } } <file_sep>package com.example.fitnesscourseservice.Repository; import com.example.fitnesscourseservice.Entity.Course; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * @author nyx * @title: CourseRepository * @projectName fitness-course-service * @description: TODO * @date 2021/5/517:07 */ @Repository public interface CourseRepository extends JpaRepository<Course,Long> { public List<Course> findCourseByCategory(String category); public List<Course> findCourseByName(String name); } <file_sep>package com.example.dietplanservice; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DietPlanServiceApplicationTests { @Test void contextLoads() { } } <file_sep>package com.example.accountservice.Repository; import com.example.accountservice.Entity.UserInfo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserInfoRepository extends JpaRepository<UserInfo,Long> { List<UserInfo> findUserInfoByAccountName(String accountName); } <file_sep>import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Login from '../views/Login.vue' Vue.use(VueRouter) const routes = [{ path: '/', name: 'Home', component: Home, meta: { isLogin: true } }, { path: '/', name: 'Login1', component: Login, meta: { isLogin: false } }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/Login', name: 'Login2', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Login.vue') }, { path: '/training/home', name: 'TrainingHome', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/TrainingHome') }, { path: '/training/fix', name: 'FixTrainingPlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Training/FixTrainingPlan') }, { path: '/training/searchCourse', name: 'SearchCourse', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Training/SearchCourse') }, { path: '/training/createPlan', name: 'CreatePlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Training/CreatePlan') }, { path: '/training/changePlan', name: 'ChangePlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Training/ChangePlan') }, { path: '/training/deletePlan', name: 'DeletePlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Training/DeletePlan') }, { path: '/training/myPlan', name: 'MyPlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Training/MyPlan') }, { path: '/training/history', name: 'History', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Training/History') }, { path: '/user', name: 'UserLogin', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/UserLogin') }, { path: '/diet/home', name: 'DietHome', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/DietHome') }, { path: '/diet/myplan', name: 'MyDietPlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Diet/MyPlan') }, { path: '/diet/changeplan', name: 'ChangeDietPlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Diet/ChangePlan') }, { path: '/diet/createplan', name: 'CreateDietPlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Diet/CreatePlan') }, { path: '/diet/deleteplan', name: 'DeleteDietPlan', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Diet/DeletePlan') }, { path: '/diet/foodquery', name: 'FoodQuery', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/Diet/FoodQuery') }, { path: '/changeuserdata', name: 'ChangeUserData', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/ChangeUserData') } ] const router = new VueRouter({ routes }) export default router<file_sep>package com.example.GEEN.Controller; import com.example.GEEN.Entity.UserInfo; import com.example.GEEN.Service.UserInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin @RestController @RequestMapping("/api/v1/") public class UserInfoController { @Autowired private UserInfoService userInfoService; @RequestMapping("/getInfo/{accountName}") public UserInfo getInfo(@PathVariable("accountName") String accountName) { List<UserInfo> user = userInfoService.findUserInfoByName(accountName); if (user.size()>0) { return user.get(0); } else { return null; } } @RequestMapping("/changeInfo") public String changeInfo(@RequestParam(value = "accountName",required = true) String accountName, @RequestParam(value = "userName",required = true) String userName, @RequestParam(value = "sex",required = true) String sex, @RequestParam(value = "age",required = true) int age, @RequestParam(value = "weight",required = true) double weight, @RequestParam(value = "height",required = true) double height, @RequestParam(value = "chestCircum",required = true) double chestCircum, @RequestParam(value = "armCircum",required = true) double armCircum, @RequestParam(value = "hipCircum",required = true) double hipCircum, @RequestParam(value = "waistline",required = true) double waistline) { List<UserInfo> user = userInfoService.findUserInfoByName(accountName); if (user.size()>0) { user.get(0).setAccountName(accountName); user.get(0).setUserName(userName); user.get(0).setSex(sex); user.get(0).setAge(age); user.get(0).setWeight(weight); user.get(0).setHeight(height); user.get(0).setChestCircum(chestCircum); user.get(0).setArmCircum(armCircum); user.get(0).setHipCircum(hipCircum); user.get(0).setWaistline(waistline); userInfoService.saveInfo(user.get(0)); return "success"; } else { return "invalid account"; } } } <file_sep>package com.example.dietplanservice.Service; import com.example.dietplanservice.Entity.DietPlan; import jdk.jfr.Timestamp; import java.util.Date; import java.util.List; import java.util.Optional; /** * @author nyx * @title: DietPlanService * @projectName diet-plan-service * @description: TODO * @date 2021/4/2315:21 */ public interface DietPlanService { public Optional<DietPlan> findPlanById(Long id); public List<DietPlan> findPlanByNameAndTime(String accountName, Date date); public List<DietPlan> findPlanByName(String accountName); public void deletePlanById(Long id); public void changePlan(DietPlan plan); public List<DietPlan> findByTime(Date date); } <file_sep>package com.example.GEEN.Repository; import com.example.GEEN.Entity.TrainingPlan; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * @author nyx * @title: TrainingPlanRepository * @projectName training-plan-service * @description: TODO * @date 2021/5/113:31 */ @Repository public interface TrainingPlanRepository extends JpaRepository<TrainingPlan,Long> { public List<TrainingPlan> findTrainingPlanByAccountNameAndDate(String accountName, Date date); public List<TrainingPlan> findTrainingPlanByAccountName(String accountName); } <file_sep>package com.example.trainingplanservice.Service; import com.example.trainingplanservice.Entity.TrainingPlan; import java.util.Date; import java.util.List; import java.util.Optional; /** * @author nyx * @title: TrainingPlanService * @projectName training-plan-service * @description: TODO * @date 2021/5/113:35 */ public interface TrainingPlanService { public List<TrainingPlan> findPlanByNameAndDate(String accountName, Date date); public List<TrainingPlan> findPlanByName(String accountName); public void deletePlan(Long id); public void changePlan(TrainingPlan trainingPlan); public Optional<TrainingPlan> findPlanById(Long id); } <file_sep>package com.example.dietplanservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DietPlanServiceApplication { public static void main(String[] args) { SpringApplication.run(DietPlanServiceApplication.class, args); } } <file_sep>package com.example.GEEN.Service; import com.example.GEEN.Entity.Course; import java.util.List; import java.util.Optional; /** * @author nyx * @title: CourseService * @projectName fitness-course-service * @description: TODO * @date 2021/5/517:08 */ public interface CourseService { public List<Course> findByName(String name); public List<Course> findByCategory(String category); public Optional<Course> findByCourseId(Long id); public List<Course> findAllCourse(); public List<Course> search(String name,String category); } <file_sep>package com.example.dietplanservice.Service.ServiceImpl; import com.example.dietplanservice.Entity.DietPlan; import com.example.dietplanservice.Repository.DietPlanRepository; import com.example.dietplanservice.Service.DietPlanService; import jdk.jfr.Timestamp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Optional; /** * @author nyx * @title: DietPlanServiceImpl * @projectName diet-plan-service * @description: TODO * @date 2021/4/2315:28 */ @Service public class DietPlanServiceImpl implements DietPlanService { @Autowired private DietPlanRepository dietPlanRepository; @Override public Optional<DietPlan> findPlanById(Long id) { return dietPlanRepository.findById(id); } @Override public List<DietPlan> findPlanByNameAndTime(String accountName, Date date) { return dietPlanRepository.findDietPlanByAccountNameAndDate(accountName, date); } @Override public List<DietPlan> findPlanByName(String accountName) { return dietPlanRepository.findDietPlanByAccountName(accountName); } @Override public void deletePlanById(Long id) { dietPlanRepository.deleteById(id); } @Override public void changePlan(DietPlan plan) { dietPlanRepository.save(plan); } @Override public List<DietPlan> findByTime(Date date) { return dietPlanRepository.findDietPlanByDate(date); } } <file_sep>package com.example.GEEN.Repository; import com.example.GEEN.Entity.TrainingRecord; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; @Repository public interface TrainingRecordRepository extends JpaRepository<TrainingRecord,Long> { public List<TrainingRecord> findByAccountNameAndCategoryOrderByDateDesc(String accountName,String category); public List<TrainingRecord> findByAccountNameAndDate(String accountName,Date date); } <file_sep>package com.example.GEEN.Entity; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.util.Date; /** * @author nyx * @title: TrainingPlan * @projectName training-plan-service * @description: TODO * @date 2021/5/113:24 */ @Entity @Table(name = "training_plan") public class TrainingPlan { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long id; @Column(name = "account_name") public String accountName; @Column(name = "workout_name") public String workoutName; @Column(name = "group_num") public double groupNum; @Column(name = "times") public double times; @Column(name = "weight") public double weight; @CreationTimestamp @Column(name = "date") public Date date; public TrainingPlan(){ } public TrainingPlan(String accountName, String workoutName, double groupNum, double times, double weight) { this.accountName=accountName; this.workoutName=workoutName; this.groupNum=groupNum; this.times=times; this.weight=weight; } public String getAccountName() { return accountName; } public double getWeight() { return weight; } public Date getDate() { return date; } public double getGroupNum() { return groupNum; } public Long getId() { return id; } public double getTimes() { return times; } public String getWorkoutName() { return workoutName; } public void setId(Long id) { this.id = id; } public void setWeight(double weight) { this.weight = weight; } public void setDate(Date date) { this.date = date; } public void setGroupNum(double groupNum) { this.groupNum = groupNum; } public void setTimes(double times) { this.times = times; } public void setWorkoutName(String workoutName) { this.workoutName = workoutName; } public void setAccountName(String accountName) { this.accountName = accountName; } } <file_sep>package com.example.GEEN.Service.ServiceImpl; import com.example.GEEN.Entity.TrainingPlan; import com.example.GEEN.Repository.TrainingPlanRepository; import com.example.GEEN.Service.TrainingPlanService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Optional; /** * @author nyx * @title: TrainingPlanServiceImpl * @projectName training-plan-service * @description: TODO * @date 2021/5/113:46 */ @Service public class TrainingPlanServiceImpl implements TrainingPlanService { @Autowired private TrainingPlanRepository trainingPlanRepository; @Override public List<TrainingPlan> findPlanByNameAndDate(String accountName, Date date) { return trainingPlanRepository.findTrainingPlanByAccountNameAndDate(accountName,date); } @Override public List<TrainingPlan> findPlanByName(String accountName) { return trainingPlanRepository.findTrainingPlanByAccountName(accountName); } @Override public void deletePlan(Long id) { trainingPlanRepository.deleteById(id); } @Override public void changePlan(TrainingPlan trainingPlan) { trainingPlanRepository.save(trainingPlan); } @Override public Optional<TrainingPlan> findPlanById(Long id) { return trainingPlanRepository.findById(id); } } <file_sep>package com.example.GEEN.Service.ServiceImpl; import com.example.GEEN.Entity.Course; import com.example.GEEN.Repository.CourseRepository; import com.example.GEEN.Service.CourseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; /** * @author nyx * @title: CourseServiceImpl * @projectName fitness-course-service * @description: TODO * @date 2021/5/517:10 */ @Service public class CourseServiceImpl implements CourseService { @Autowired private CourseRepository courseRepository; @Override public List<Course> findByName(String name) { return courseRepository.findCourseByName(name); } @Override public List<Course> findByCategory(String category) { return courseRepository.findCourseByCategory(category); } @Override public Optional<Course> findByCourseId(Long id) { return courseRepository.findById(id); } @Override public List<Course> findAllCourse() { return courseRepository.findAll(); } @Override public List<Course> search(String name,String category) { return courseRepository.findCourseByNameLikeOrCategoryLike(name,category); } } <file_sep># SoftwareProjectManagement SPM course project <file_sep>package com.example.dietplanservice.Entity; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author nyx * @title: Food * @projectName diet-plan-service * @description: TODO * @date 2021/4/2315:05 */ @Entity @Table(name = "food") public class Food { @Id public Long id; public String name; public String measurement; public Double carbohydrate; public Double fat; public Double protein; public String vitamin; public Food(){ } public Long getId() { return id; } public String getName() { return name; } public String getMeasurement() { return measurement; } public Double getCarbohydrate() { return carbohydrate; } public Double getProtein() { return protein; } public Double getFat() { return fat; } public String getVitamin() { return vitamin; } } <file_sep>package com.example.GEEN.Service; import com.example.GEEN.Entity.UserInfo; import java.util.List; public interface UserInfoService { public List<UserInfo> findUserInfoByName(String accountName); public void saveInfo(UserInfo userInfo); } <file_sep>package com.example.fitnesscourseservice.Controller; import com.example.fitnesscourseservice.Entity.Course; import com.example.fitnesscourseservice.Service.CourseService; import com.example.fitnesscourseservice.Service.NonStaticResourceHttpRequestHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; /** * @author nyx * @title: CourseController * @projectName fitness-course-service * @description: * @date 2021/5/517:12 */ @RestController @RequestMapping("/api/v1/") public class CourseController { @Autowired private CourseService courseService; private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler; public CourseController(NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler) { this.nonStaticResourceHttpRequestHandler = nonStaticResourceHttpRequestHandler; } @GetMapping("/course/video") public void getVideo(HttpServletRequest request, HttpServletResponse response) throws Exception { String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);//获取resources文件夹的绝对地址 String id = request.getParameter("id"); String realPath = sourcePath +"static/video/"+id+".mp4"; System.out.println(realPath); Path filePath = Paths.get(realPath); if(Files.exists(filePath)) { String mimeType = Files.probeContentType(filePath); if(!StringUtils.isEmpty(mimeType)) { response.setContentType(mimeType); } request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE,filePath); nonStaticResourceHttpRequestHandler.handleRequest(request,response); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); } } @RequestMapping("/course/{id}") public Optional<Course> getById(@PathVariable("id") Long id) { return courseService.findByCourseId(id); } @RequestMapping("/course") public List<Course> getCourse(@RequestParam(value = "name",required = false) String name, @RequestParam(value = "category",required = false)String category) { if(name==null&&category==null) { return courseService.findAllCourse(); } else if(name==null) { return courseService.findByCategory(category); } else if(category==null) { return courseService.findByName(name); } else { return null; } } } <file_sep>package com.example.GEEN.Service.ServiceImpl; import com.example.GEEN.Entity.TrainingRecord; import com.example.GEEN.Repository.TrainingPlanRepository; import com.example.GEEN.Repository.TrainingRecordRepository; import com.example.GEEN.Service.TrainingRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Optional; @Service public class TraingingRecordServiceImpl implements TrainingRecordService { @Autowired private TrainingRecordRepository trainingRecordRepository; @Override public List<TrainingRecord> findTrainingRecordByAccountName(String accountName,String category) { return trainingRecordRepository.findByAccountNameAndCategoryOrderByDateDesc(accountName,category); } @Override public void addTrainingRecord(TrainingRecord trainingRecord) { trainingRecordRepository.save(trainingRecord); } @Override public Optional<TrainingRecord> findTrainingRecordById(Long id) { return trainingRecordRepository.findById(id); } @Override public List<TrainingRecord> findTrainingRecordByAccountNameAndTime(String accountName, Date date) { return trainingRecordRepository.findByAccountNameAndDate(accountName,date); } @Override public void deleteTrainingPlan(Long id) { trainingRecordRepository.deleteById(id); } } <file_sep>package com.example.accountservice.Controller; import com.example.accountservice.Entity.Account; import com.example.accountservice.Entity.RandomUtil; import com.example.accountservice.Entity.UserInfo; import com.example.accountservice.Service.AccountService; import com.example.accountservice.Service.MsmService; import com.example.accountservice.Service.UserInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.data.redis.core.RedisTemplate; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; @RestController @RequestMapping("/api/v1/") public class AccountController { @Autowired private AccountService accountService; @Autowired private MsmService msmService; @Autowired private UserInfoService userInfoService; @RequestMapping("/register") public Boolean register(@RequestParam("accountName") String accountName, @RequestParam("password") String password) { List<Account> account = accountService.findAccountByName(accountName); if(account.isEmpty()) { Account newAccount = new Account(accountName,password); accountService.saveAccount(newAccount); //级联插入 String userName = "用户"+accountName; UserInfo userInfo = new UserInfo(accountName,userName,"男",18,0.00,0.00,0.00,0.00,0.00,0.00); userInfoService.saveInfo(userInfo); return true; } else { return false; } } @RequestMapping("/login") public Boolean login(@RequestParam("accountName") String accountName, @RequestParam("password") String password) { List<Account> account = accountService.findAccountByNameAndPassword(accountName,password); if(account.size()>0) { return true; } else { return false; } } @RequestMapping("/changePassword") public Boolean changePassword(@RequestParam("accountName") String accountName, @RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) { List<Account> account = accountService.findAccountByNameAndPassword(accountName,oldPassword); if(account.size()>0) { account.get(0).setPassword(<PASSWORD>); accountService.saveAccount(account.get(0)); return true; } else { return false; } } @GetMapping("/verify") public String verifyEmail(@RequestParam("email") String email) { String code = RandomUtil.getFourBitRandom(); String title = "注册验证码"; Boolean success = msmService.send(email,title,code); if(success) { return code; } else { return "发送失败"; } } } <file_sep>package com.example.GEEN.Repository; import com.example.GEEN.Entity.UserInfo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserInfoRepository extends JpaRepository<UserInfo,Long> { List<UserInfo> findUserInfoByAccountName(String accountName); } <file_sep>package com.example.GEEN.Controller; import com.example.GEEN.GeenApplication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.transaction.Transactional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Transactional //测试后数据会回滚 @RunWith(SpringRunner.class) @SpringBootTest(classes = GeenApplication.class) public class accountTest { @Autowired private AccountController accountController; @Autowired private UserInfoController userInfoController; private MockMvc mockMvc; private MockMvc mockMvc2; @Before public void setup() { // 初始化构建 mockMvc = MockMvcBuilders.standaloneSetup(accountController).build(); mockMvc2 = MockMvcBuilders.standaloneSetup(userInfoController).build(); } @Test public void loginSuccessfully() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/login") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","73694<EMAIL>") .param("password","<PASSWORD>")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("登录测试用例1--------返回的数据 = " + responseString); } @Test public void loginWithWrongPassword() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/login") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","<EMAIL>") .param("password","1")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("登录测试用例2--------返回的数据 = " + responseString); } @Test public void loginWithWrongAccount() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/login") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","736941882") .param("password","<PASSWORD>")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("登录测试用例3--------返回的数据 = " + responseString); } @Test public void registerSuccessfully() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/register") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","<EMAIL>") .param("password","<PASSWORD>")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("注册测试用例1--------返回的数据 = " + responseString); } @Test public void registerWithAccountExisted() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/register") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","<EMAIL>") .param("password","<PASSWORD>")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("注册测试用例2--------返回的数据 = " + responseString); } @Test public void registerWithWrongAccount() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/register") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","736941882") .param("password","<PASSWORD>")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("注册测试用例3--------返回的数据 = " + responseString); } @Test public void validateSuccessfully() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/verify") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("email","<EMAIL>") ) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("邮箱验证测试用例1--------返回的数据 = " + responseString); } @Test public void changePasswordSuccessfully() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/changePassword") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","<EMAIL>") .param("oldPassword","<PASSWORD>") .param("newPassword","123")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("更改密码测试用例1--------返回的数据 = " + responseString); } @Test public void changePasswordWithWrongPassword() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/changePassword") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","<EMAIL>") .param("oldPassword","<PASSWORD>") .param("newPassword","123")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("更改密码测试用例2--------返回的数据 = " + responseString); } @Test public void changePasswordWithAccountNotExisted() throws Exception { String responseString = mockMvc.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/changePassword") //模拟请求的url,及请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED).param("accountName","73<EMAIL>") .param("oldPassword","<PASSWORD>") .param("newPassword","123")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("更改密码测试用例3--------返回的数据 = " + responseString); } @Test public void getInfoSuccessfully() throws Exception { String email = "<EMAIL>"; String responseString = mockMvc2.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/getInfo/"+email) //模拟请求的url,及请求的方法是get ) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("获取用户信息测试用例1--------返回的数据 = " + responseString); } @Test public void getInfoWithAccountNotExisted() throws Exception { String responseString = mockMvc2.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get("/api/v1/getInfo/1") //模拟请求的url,及请求的方法是get ) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("获取用户信息测试用例2--------返回的数据 = " + responseString); } @Test public void changeInfoSuccessfully() throws Exception { String responseString = mockMvc2.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; post("/api/v1/changeInfo") //模拟请求的url,及请求的方法是post .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("accountName","<EMAIL>") .param("userName","12345") .param("sex","男") .param("age","18") .param("weight","65") .param("height","1.70") .param("chestCircum","1") .param("armCircum","30") .param("hipCircum","0") .param("waistline","0")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("修改用户信息测试用例1--------返回的数据 = " + responseString); } @Test public void changeInfoWithInvalidAccount() throws Exception { String responseString = mockMvc2.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; post("/api/v1/changeInfo") //模拟请求的url,及请求的方法是post .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("accountName","1") .param("userName","12345") .param("sex","男") .param("age","18") .param("weight","65") .param("height","1.70") .param("chestCircum","1") .param("armCircum","30") .param("hipCircum","0") .param("waistline","0")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("修改用户信息测试用例2--------返回的数据 = " + responseString); } @Test public void changeInfoWithWrongData() throws Exception { String responseString = mockMvc2.perform( //执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; post("/api/v1/changeInfo") //模拟请求的url,及请求的方法是post .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("accountName","7<PASSWORD> <EMAIL>") .param("userName","12345") .param("sex","12") .param("age","-1") .param("weight","65") .param("height","1.70") .param("chestCircum","1") .param("armCircum","30") .param("hipCircum","0") .param("waistline","0")) .andExpect( status().isOk() //预期返回的状态码是200 ) .andReturn().getResponse().getContentAsString(); //将相应的数据转换为字符串 System.out.println("修改用户信息测试用例3--------返回的数据 = " + responseString); } } <file_sep>server.port = 8002 spring.datasource.url = jdbc:mysql://192.168.3.11:3306/Genn?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username = root spring.datasource.password = <PASSWORD> spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver <file_sep>package com.example.dietplanservice.Repository; import com.example.dietplanservice.Entity.DietPlan; import jdk.jfr.Timestamp; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * @author nyx * @title: DietPlanRepository * @projectName diet-plan-service * @description: TODO * @date 2021/4/2315:11 */ @Repository public interface DietPlanRepository extends JpaRepository<DietPlan,Long> { public List<DietPlan> findDietPlanByAccountNameAndDate(String accountName, Date date); public List<DietPlan> findDietPlanByAccountName(String accountName); public List<DietPlan> findDietPlanByDate(Date date); }
4da6e90c81020fdf084fd028eb194fbd61cf71a6
[ "JavaScript", "Java", "Markdown", "INI" ]
27
JavaScript
O3dipus/SoftwareProjectManagement
2eec9906f3ff4574c1197b766e61adf1958c563b
fe7a0d8fee3730489ca76fde99077614175fd205
refs/heads/master
<file_sep>// Learn TypeScript: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html // Learn Attribute: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { @property(cc.Label) label: cc.Label = null; // LIFE-CYCLE CALLBACKS: // onLoad () {} recorderManager: Object = null; start () { if(window.wx == undefined || !window.wx){ window['wx']={ getRecorderManager:function(){ return { onStart:()=>{}, onPause:()=>{}, onStop:()=>{}, stop:()=>{}, start:()=>{}, onFrameRecorded:()=>{}}; } } } this.recorderManager = wx.getRecorderManager(); // console.log(wx) this.node.on(cc.Node.EventType.TOUCH_START,function(){ this.started(); },this) this.node.on(cc.Node.EventType.TOUCH_END,function(){ this.recorderManager.stop(); },this) this.node.on(cc.Node.EventType.TOUCH_CANCEL,function(){ this.recorderManager.stop(); },this) this.recorderManager.onStart(() => { this.label.string = "开始中" console.log('recorder start') }) this.recorderManager.onPause(() => { this.label.string = "已暂停" console.log('recorder pause') }) this.recorderManager.onStop((res) => { this.label.string = "已结束" console.log('recorder stop', res) const { tempFilePath,duration,fileSize } = res; }) this.recorderManager.onFrameRecorded((res) => { this.label.string = "已达到最大大小" const { frameBuffer } = res console.log('frameBuffer.byteLength', frameBuffer.byteLength) }) } started(){ const options = { duration: 10000, sampleRate: 44100, numberOfChannels: 1, encodeBitRate: 192000, format: 'aac', // frameSize: 50 } this.recorderManager.start(options); } // update (dt) {} } <file_sep>// Learn TypeScript: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html // Learn Attribute: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { // LIFE-CYCLE CALLBACKS: gq1: object = { w:0, h:0, x:0, y:0 }; tiledGroups: cc.TiledObjectGroup[] = null; nullAnim: cc.Animation = null; nullNode: cc.Node = null; onLoad () { let titledMap =this.getComponent(cc.TiledMap); this.tiledGroups = titledMap.getObjectGroup("mapObj"); let point =this.tiledGroups.getObjects()[0]; this.gq1.w = point.height; this.gq1.h = point.height; this.gq1.x = point.x; this.gq1.y = point.y; } start () { this.nullNode = cc.find("Canvas/map/null"); this.nullNode.active = false; this.nullAnim = cc.find("Canvas/map/null").getComponent(cc.Animation); this.nullAnim.on("stop",function(type,state){ if(state.name == 'TanB'){ this.active = false; }else if(state.name == "Tan"){ this.active = true; } },this.nullNode) this.node.on(cc.Node.EventType.TOUCH_END,(e)=>{ // console.log(this.tiledGroups.getObjects()[0]) let point = {x:0,y:0,w:0,h:0}; point.x = e.touch._point.x/this.node.scaleX; point.y = e.touch._point.y/this.node.scaleY; // console.log(point.x/this.node.scaleX,point.y/this.node.scaleY,"===",this.gq1.x,this.gq1.y) if(this.ifCrash(this.gq1,point) && this.nullNode.active == false){ this.nullNode.active = true; console.log(1231) this.nullAnim.play("Tan"); } }) } ifCrash(tag,point){ if(point.x >=Number(tag.x) && point.x<=Number(tag.x)+Number(tag.w) && point.y <=Number(tag.y) && point.y>=Number(tag.y)-Number(tag.h)){ return true; }else{ return false; } } // update (dt) {} } <file_sep>// Learn TypeScript: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html // Learn Attribute: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { // LIFE-CYCLE CALLBACKS: // onLoad () {} start () { // let label = this.node.getComponent(cc.Label); // label.string = "1111111111111112" // // this.parentLabel.string = "qweqwe"; // // this.childLabel.string = "qweqwe"; // console.log(33,this.node) // console.log(444,this.parentLabel) // console.log(111,this.node.getChildByName("newlab")) } // update (dt) {} } <file_sep>// Learn TypeScript: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html // Learn Attribute: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { @property(cc.Prefab) labelText:cc.Prefab = null; labelNode: cc.Node = null; nullNode: cc.Node = null; newLabelNode : cc.Node = null; labelOK: boolean = false; // LIFE-CYCLE CALLBACKS: labelWidth: Number = 0; // onLoad () {} start () { this.labelNode = cc.instantiate(this.labelText); // this.node.addComponent("Text"); this.labelNode.x = 0; this.labelNode.y = 0; this.nullNode = this.labelNode.getChildByName("null"); this.newLabelNode = this.nullNode.getChildByName("newlab"); let nullX = (this.nullNode.width/2); this.newLabelNode.x = nullX; this.nullNode.x = -nullX; this.setLabel('66666666'); this.labelNode.setParent(this.node); var timeCallback = function (dt) { this.nullNode.width = 0; } this.scheduleOnce(timeCallback, 0.001); setTimeout(()=>{ this.setOk(); },2000) } setOk(){ this.labelOK = true; this.labelWidth = this.labelNode.width; cc.tween(this.nullNode) .to(1, {width: this.labelWidth},{easing:'quadInOut'}) .call(() => { console.log('This is a callback'); }) .start(); } setLabel(str:string){ this.labelNode.getComponent(cc.Label).string = str; this.newLabelNode.getComponent(cc.Label).string = str; } update (dt) { // if(this.labelOK&& (this.nullNode.width <= this.labelWidth)){ // console.log(dt) // this.nullNode.width += 5; // } // rr.width = 0; } }
4fa80651e110a5568d753ed1a8f548a2af011987
[ "TypeScript" ]
4
TypeScript
lipengrui/schoolGrame
ceeb6e1268e89d7650817580a50333c97873cf8f
f1881b887e9184124fa11e025602088bdbb1a288
refs/heads/master
<repo_name>mazal-gevyan/Movies<file_sep>/src/app/shared/interfaces/movie.interface.ts import { IBaseResponse } from "./response.interface"; export interface IMoviesResponse extends IBaseResponse { data: IMovie[]; } export interface IMovie { id: string; title: string; category: string; poster: string; imdbLink: string; } <file_sep>/src/app/shared/shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { MaterialModule } from './modules/material.module'; import { ApiInterceptor } from './interceptors/api.interceptor'; import { LoaderInterceptor } from './interceptors/loader.interceptor'; import { Page404Component } from './components/page404/page404.component'; import { CardComponent } from './components/card/card.component'; import { MovieFormDialogComponent } from './components/movie-form-dialog/movie-form-dialog.component'; const modules: any[] = [ CommonModule, HttpClientModule, ReactiveFormsModule, FormsModule, RouterModule, MaterialModule, ] const components: any[] = [ Page404Component, CardComponent, MovieFormDialogComponent, ]; @NgModule({ declarations: [...components], imports: [ ...modules ], exports: [ ...modules, ...components, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true, }, { provide: HTTP_INTERCEPTORS, useClass: LoaderInterceptor, multi: true, }, ] }) export class SharedModule {} <file_sep>/src/app/shared/services/auth.service.ts import { HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable, of } from 'rxjs'; const JWT_TOKEN = 'JwtToken'; @Injectable({ providedIn: 'root' }) export class AuthService { private isAuthenticatedSubject: BehaviorSubject<boolean>; public isAuthenticated: Observable<boolean>; fakeUsername: string = "username"; fakePassword: string = "<PASSWORD>"; constructor() { this.isAuthenticatedSubject = new BehaviorSubject<boolean>( this.jwtToken !== null ); this.isAuthenticated = this.isAuthenticatedSubject.asObservable(); } isUserAuthenticated() { return this.isAuthenticatedSubject.value; } setJwtToken(token: string) { sessionStorage.setItem(JWT_TOKEN, token); this.isAuthenticatedSubject.next(true); } get jwtToken(): string { return sessionStorage.getItem(JWT_TOKEN) || null; } logout(): void { localStorage.removeItem(JWT_TOKEN); } isUserLoggedIn(): boolean { if (this.jwtToken != null) { return true; } return false; } } <file_sep>/src/app/shared/services/api.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { ApiRoutes } from './api.routes'; import { IMovie, IMoviesResponse } from '@app/shared/interfaces/interfaces'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) { } login(username: string, password: string): Observable<any> { return this.http.post<any>(ApiRoutes.LOGIN, { username, password}); } getMovies(): Observable<IMoviesResponse> { return this.http.post<IMoviesResponse>(ApiRoutes.MOVIES, null); } addMovie(movie: IMovie): Observable<any> { return this.http.post<any>(ApiRoutes.ADD_MOVIE, { movie}); } deleteMovie(id: string): Observable<any> { return this.http.post<any>(ApiRoutes.DELETE_MOVIE, { id}); } }<file_sep>/src/app/movies/components/movies-list/movies-list.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { IMovie } from '@app/shared/interfaces/interfaces'; import { DataStoreService } from '@app/shared/services/services'; import { SubSink } from 'subsink'; @Component({ selector: 'app-movies-list', templateUrl: './movies-list.component.html', styleUrls: ['./movies-list.component.scss'] }) export class MoviesListComponent implements OnInit, OnDestroy { private subs = new SubSink(); movies: IMovie[]; constructor( private dataStoreService: DataStoreService) { } ngOnInit(): void { this.subs.add( this.dataStoreService.moviesSubject.subscribe( (movies: IMovie[]) => { this.movies = movies; } ) ); } ngOnDestroy(): void { this.subs.unsubscribe(); } } <file_sep>/src/app/shared/services/data-store.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { IMovie } from '../interfaces/interfaces'; @Injectable({ providedIn: 'root' }) export class DataStoreService { private _movies: BehaviorSubject<IMovie[]> = new BehaviorSubject(null); public readonly movies: Observable<IMovie[]> = this._movies.asObservable(); private _categories: BehaviorSubject<string[]> = new BehaviorSubject(null); public readonly categories: Observable<string[]> = this._categories.asObservable(); constructor() { } setMovies(movies: IMovie[]) { this._movies.next(movies); } get moviesSubject() { return this.movies; } setCategories(categories: string[]) { this._categories.next(categories); } get categoriesSubject() { return this.categories; } }<file_sep>/src/app/shared/services/api.routes.ts export const ApiRoutes = { LOGIN: '/login', MOVIES: '/movies', ADD_MOVIE: '/movies/movie', DELETE_MOVIE: '/movies/delete', }<file_sep>/src/app/shared/interfaces/response.interface.ts import { ResponseErrorType } from './../enums/enums.enum'; export interface IBaseResponse { isError: boolean; errorCode?: ResponseErrorType; errorMessage?: string; token: string; }<file_sep>/src/app/auth/components/login/login.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators, } from '@angular/forms'; import { Router } from '@angular/router'; import { ApiService, AuthService } from '@app/shared/services/services'; import { SubSink } from 'subsink'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit, OnDestroy { private subs = new SubSink(); logInForm: FormGroup; submitted: boolean = false; loading = false; constructor( private apiService: ApiService, private fb: FormBuilder, private authService: AuthService, private router: Router ) {} ngOnInit(): void { this.logInForm = this.createForm(); } createForm(): FormGroup { return this.fb.group({ username: ['', [Validators.required]], password: ['', [Validators.required, Validators.minLength(5)]], // username: [isDevEnvironment ? 'EREC9H' : '', [Validators.required]], // password: [isDevEnvironment ? '<PASSWORD>' : '', [Validators.required, Validators.minLength(5)]], }); } get f() { return this.logInForm.controls; } onSubmit(): void { this.submitted = true; if (this.logInForm.invalid) { return; } const { username, password } = this.logInForm?.value; this.subs.add( this.apiService .login(username, password) .subscribe(() => this.router.navigateByUrl('/')) ); } ngOnDestroy(): void { this.subs.unsubscribe(); } } <file_sep>/src/app/shared/enums/enums.enum.ts export enum ResponseErrorType { TechnicalError = 1, UserErrorMessage = 5 }<file_sep>/src/app/movies/components/side-bar/side-bar.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MovieFormDialogComponent } from '@app/shared/components/movie-form-dialog/movie-form-dialog.component'; import { DataStoreService } from '@app/shared/services/services'; import { SubSink } from 'subsink'; @Component({ selector: 'app-side-bar', templateUrl: './side-bar.component.html', styleUrls: ['./side-bar.component.scss'] }) export class SideBarComponent implements OnInit, OnDestroy { private subs = new SubSink(); categories: string[]; constructor(public dialog: MatDialog, private dataStoreService: DataStoreService) { } ngOnInit(): void { this.subs.add( this.dataStoreService.categoriesSubject.subscribe( (categories: string[]) => { this.categories = categories; } ) ); } openAddMovieForm() { this.dialog.open(MovieFormDialogComponent, { disableClose: true }); } ngOnDestroy(): void { this.subs.unsubscribe(); } } <file_sep>/src/app/movies/container/movies.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { IMovie, IMoviesResponse } from '@app/shared/interfaces/interfaces'; import { ApiService, DataStoreService } from '@app/shared/services/services'; import { SubSink } from 'subsink'; @Component({ selector: 'app-movies', templateUrl: './movies.component.html', styleUrls: ['./movies.component.scss'] }) export class MoviesComponent implements OnInit, OnDestroy { private subs = new SubSink(); constructor(private apiService: ApiService, private dataStoreService: DataStoreService) { } ngOnInit(): void { this.getMovies(); } getMovies() { this.subs.add( this.apiService.getMovies().subscribe( (res: IMoviesResponse) => { if (!res.isError && res?.data) { this.dataStoreService.setMovies(res?.data); this.filterCategories(res?.data); } }, (err) => { console.error(`response error ${err}`); } ) ); } filterCategories(data: IMovie[]){ const categories: string[] = data.map(item => item.category); console.log({ categories}); this.dataStoreService.setCategories(categories); } ngOnDestroy(): void { this.subs.unsubscribe(); } } <file_sep>/src/app/shared/enums/endpoints.enum.ts export enum Endpoint { Login = 'login', Movies = 'movies', AddMovie = 'movie', DeleteMovie = 'delete', } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { Page404Component } from './shared/components/page404/page404.component'; import { AuthGuard } from './shared/services/auth.guard'; const routes: Routes = [ { path: '', redirectTo: 'secure', pathMatch: 'full' }, // { path: '', redirectTo: 'auth', pathMatch: 'full' }, { path: 'auth', loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule) }, { path: 'secure', // 'movies', // canActivate: [AuthGuard], loadChildren: () => import('./movies/movies.module').then(m => m.MoviesModule) }, { path: 'page404', component: Page404Component }, { path: '**', redirectTo: 'page404', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }<file_sep>/src/app/shared/interceptors/api.interceptor.ts import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { catchError, tap } from 'rxjs/operators'; import { Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; import { environment } from '@environments/environment'; @Injectable() export class ApiInterceptor implements HttpInterceptor { constructor( private authService: AuthService, private router: Router ) { } intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>>{ request = request.clone({ url: `${environment.BASE_URL}${request.url}` }); return next.handle(request).pipe( tap((event: HttpEvent<any>) => { if (event instanceof HttpResponse) { if (event.headers.get('JwtToken')) this.authService.setJwtToken(event.headers.get('JwtToken')); } }), catchError(this.handleError.bind(this)) ); } private handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { console.error('An error occurred:', error.error.message); } else { if (error.status === 401) { console.log(`${error.status} Unauthorized server error`); this.authService.logout(); this.router.navigateByUrl("/auth/login"); } else { console.error( `Backend returned code ${error.status}, body was: ${JSON.stringify( error.error )}` ); this.router.navigateByUrl("/page404"); } } } }
cf3658231ce08ad2dfabed0ba9961d5f55c925a7
[ "TypeScript" ]
15
TypeScript
mazal-gevyan/Movies
0a8dfe2132ab9ecdd6f062aab4f78f5de5b6a0e2
c7607cdc5d5de33fb453b71e6016e9350c4129bb
refs/heads/master
<file_sep>from flask import Flask from flask import render_template import urllib import requests import re app = Flask(__name__) airports = [ "EPWR", "KMLJ", "K1NM", "GQNO", "LFLU", "CZSM", "KFDK", "KEKQ", "EGAA", "CZOL", "FXMM", "KCEU", "LFBM", "FJDG", "FWKI", "YPLM", "LFBU", "KTVI", "KAAO", "K06C", "YPXM", "MHPL", "K1LM", "KPXE", "SBAQ", "KLUK", "KSGR", "KSSC", "OPIS", "KSPG" ] #Регулярные выражения для выбора нужных параметров match_wind = re.compile(r'Wind: .* at (\d*) MPH') match_humidity = re.compile(r'Relative Humidity: ([\d]*)%') match_pressure = re.compile(r'Pressure \(altimeter\):.*\(([\d]*) hPa\)') #Сюда будут записываться предупреждения о погодных условиях warn = [] #Формирование сообщения с предупреждением по триггерам def air_warning(a, wind, hum, pres): if (wind >= 15): warn.append('\n' + a + ': wind speed ' + str(wind) + 'MPH') if (hum >= 70): warn.append('\n' + a + ': humidity ' + str(hum) + '%') if (pres >= 1016): warn.append('\n' + a + ': relative pressure' + str(pres) + ' hPa') #Получение данных def get_data(): for a in airports: link = 'http://tgftp.nws.noaa.gov/data/observations/metar/decoded/' + a + '.TXT' res = requests.get(link).text data_wind = match_wind.search(res) data_humidity = match_humidity.search(res) data_pressure = match_pressure.search(res) wind = 0 if (data_wind != None): wind = data_wind.group(1) hum = 0 if (data_humidity != None): hum = data_humidity.group(1) pres = 0 if (data_pressure != None): pres = data_pressure.group(1) air_warning(a, int(wind), int(hum), int(pres)) #Полученный список предупреждений передается в html-шаблон @app.route('/') def homepage(): get_data() return render_template('index.html', warn = warn) app.run('localhost', port=8000) <file_sep>Проект реализован с помощью flask, сервер на donkey1. Должен обновляться ежедневно (прописан @daily в crontab). На последней паре не была из-за простуды и не смогла разобраться с тем, какие конфиги должны быть в nginx. В итоге сделала самое основное - получение данных о погоде и вывод отчета с предупреждениями по тригерам. Мой вариант задания - 2, html-отчёт находится здесь: http://192.168.3.11:5004/
a796031d3693a4c4ca061dc70774d9dfff312529
[ "Python", "Text" ]
2
Python
olgavlas/airports
44a0c6533cf49d2f51360be1f1b242e8b01197db
bd307790417052b837994d0d13adfc0a50405be8
refs/heads/master
<file_sep>package servlet; import java.io.BufferedReader; import java.io.IOException; import java.net.URISyntaxException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.GsonBuilder; import unitofWork.InsertSensorData; import unitofWork.ViewSensorData; import unitofWork.impl.InsertSensorDataImpl; import unitofWork.impl.ViewSensorDataImpl; import java.util.ArrayList; import java.util.List; import entity.SensorData; public class ViewDataServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse response) { // Read from request String type=req.getParameter("type"); String StartDate=req.getParameter("startDate"); String EndDate=req.getParameter("endDate"); System.out.println("Val :"+StartDate+","+EndDate+ " , Type:"+type); ViewSensorData ins= new ViewSensorDataImpl(); try { List<SensorData> SenData= new ArrayList<SensorData>(); SenData= ins.readSensorDataFromDashDb(type, StartDate, EndDate); String json = null ; json=new GsonBuilder().disableHtmlEscaping().create().toJson(SenData); System.out.println("POST JSON "+json); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package entity; public class SensorData { private String TimeStamp; private String EntryID; private String Value; private String Parameter; public String getTimeStamp() { return TimeStamp; } public void setTimeStamp(String timeStamp) { TimeStamp = timeStamp; } public String getEntryID() { return EntryID; } public void setEntryID(String entryID) { EntryID = entryID; } public String getValue() { return Value; } public void setValue(String value) { Value = value; } public String getParameter() { return Parameter; } public void setParameter(String parameter) { Parameter = parameter; } } <file_sep>package servlet; import java.io.BufferedReader; import java.io.IOException; import java.net.URISyntaxException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import unitofWork.InsertSensorData; import unitofWork.Uservalidation; import unitofWork.ViewSensorData; import unitofWork.impl.InsertSensorDataImpl; import unitofWork.impl.UservalidationImpl; import unitofWork.impl.ViewSensorDataImpl; public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forwardingPage = "/admin.jsp"; String Id=request.getParameter("id"); System.out.println("user :"+Id); String Pwd=request.getParameter("password"); System.out.println("password:"+Pwd); String Message="Message"; Uservalidation ins= new UservalidationImpl(); if(Id== null || Id.isEmpty()){ Message="Username is mandatory"; System.out.println("MY Message :"+Message); request.setAttribute("msg", Message); request.setAttribute("wronguser", Id); forwardingPage = "/loginfailed.jsp"; } else{ if(Pwd==null|| Pwd.isEmpty()){ Message="Password is mandatory"; System.out.println("MY Message :"+Message); request.setAttribute("msg", Message); request.setAttribute("wronguser", Id); forwardingPage = "/loginfailed.jsp"; } else{ Message=ins.validateuser(Id,Pwd); System.out.println("Message"+Message); if(Message.equalsIgnoreCase("PASS")) { forwardingPage = "/admin.jsp"; System.out.println("The user"+Id); request.setAttribute("user",Id); } else{ Message="Sorry, You are not part of IOT AGRICULTURE TEAM ADMIN"; forwardingPage = "/loginfailed.jsp"; request.setAttribute("wronguser", Id); request.setAttribute("msg", Message); } } } forward(request, response, forwardingPage); } private void forward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher(url); dispatcher.forward(request, response); } } <file_sep># IOTAGRI IOT based agricultural monitoring using NODE MCU , Moisture sensor, DHT 11 . The Java web app was hosted in IBM bluemix and dashdb was used Thinkspeak service was use for data capturing and visualization <file_sep>package unitofWork.impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import entity.SensorData; import unitofWork.Uservalidation; public class UservalidationImpl implements Uservalidation { public String validateuser(String id, String pass) { String message="FAIL"; Connection con = null; try { Class.forName("com.ibm.db2.jcc.DB2Driver"); String jdbcurl ="jdbc:db2://dashdb-entry-yp-dal09-08.services.dal.bluemix.net:50000/BLUDB"; String user = "dash11787"; String password ="<PASSWORD>"; con = DriverManager.getConnection(jdbcurl, user, password); con.setAutoCommit(false); Statement stmt = null; String sqlStatement = ""; try { stmt = con.createStatement(); sqlStatement = "SELECT id from DASH11787.admin where id ='"+id+"' and password='"+pass+"'"; System.out.println(sqlStatement); ResultSet rs = stmt.executeQuery(sqlStatement); int i = 0; while (rs.next()) { message="PASS"; } System.out.println("Message:"+message); //con.close(); } catch (SQLException e) { System.out.println(e); } } catch (ClassNotFoundException ex) { System.out.println(ex); } catch (Exception e) { System.out.println(e); } /*finally{ try { //con.close(); } catch (SQLException e) { e.printStackTrace(); } }*/ return message; } } <file_sep>package unitofWork; public interface Uservalidation { public String validateuser(String id, String password); } <file_sep>package unitofWork.impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import unitofWork.InsertSensorData; public class InsertSensorDataImpl implements InsertSensorData { public String insertSensorDataInDashDb(String type, String value) throws Exception { String msg=""; Connection con = null; try { Class.forName("com.ibm.db2.jcc.DB2Driver"); String jdbcurl ="jdbc:db2://dashdb-entry-yp-dal09-08.services.dal.bluemix.net:50000/BLUDB"; String user = "dash11787"; String password ="<PASSWORD>"; con = DriverManager.getConnection(jdbcurl, user, password); con.setAutoCommit(false); Statement stmt = null; String sqlStatement = ""; try { stmt = con.createStatement(); System.out.println(type); if(type.equalsIgnoreCase("Temperature")) { sqlStatement = "INSERT into DASH11787.IOT_TEMPERATURE ( TEMPERATURE,TIME_STAMM) values("+value+",current timestamp)"; System.out.println(sqlStatement); stmt.executeUpdate(sqlStatement); con.commit(); con.close(); } else if (type.equalsIgnoreCase("humidity")) { sqlStatement = "INSERT into DASH11787.IOT_HUMIDITY ( HUMIDITY,TIME_STAMP) values("+value+",current timestamp)"; System.out.println(sqlStatement); stmt.executeUpdate(sqlStatement); con.commit(); con.close(); } else if (type.equalsIgnoreCase("moisture")) { sqlStatement = "INSERT into DASH11787.IOT_MOISTURE ( MOISTURE,TIME_STAMP) values("+value+",current timestamp)"; System.out.println(sqlStatement); stmt.executeUpdate(sqlStatement); con.commit(); con.close(); } else if (type.equalsIgnoreCase("salinity")) { sqlStatement = "INSERT into DASH11787.IOT_SALINITY ( SALINITY,TIME_STAMP) values("+value+",current timestamp)"; System.out.println(sqlStatement); stmt.executeUpdate(sqlStatement); con.commit(); con.close(); } } catch (SQLException e) { System.out.println(e); } } catch (ClassNotFoundException ex) { System.out.println(ex); } finally{ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return msg; } } <file_sep>package unitofWork.impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import entity.SensorData; import unitofWork.ViewSensorData; public class ViewSensorDataImpl implements ViewSensorData { public List<SensorData> readSensorDataFromDashDb(String type, String startDate,String endDate) throws Exception { String msg=""; Connection con = null; List<SensorData> SenData = new ArrayList<SensorData>(); try { Class.forName("com.ibm.db2.jcc.DB2Driver"); String jdbcurl ="jdbc:db2://dashdb-entry-yp-dal09-08.services.dal.bluemix.net:50000/BLUDB"; String user = "dash11787"; String password ="<PASSWORD>"; con = DriverManager.getConnection(jdbcurl, user, password); con.setAutoCommit(false); Statement stmt = null; String sqlStatement = ""; try { stmt = con.createStatement(); System.out.println(type); if(type.equalsIgnoreCase("Temperature")) { if(endDate==null|| endDate.trim().isEmpty()) { sqlStatement = "select * from DASH11787.iot_TEMPERATURE where date(TIME_STAMM) = '"+startDate+"'"; } else { sqlStatement = "select * from DASH11787.iot_TEMPERATURE where date(TIME_STAMM) BETWEEN '"+startDate+"' AND '"+endDate+"'"; } } else if (type.equalsIgnoreCase("humidity")) { if(endDate==null || endDate.trim().isEmpty()) { sqlStatement = "select * from DASH11787.iot_HUMIDITY where date(TIME_STAMP) = '"+startDate+"'"; } else { sqlStatement = "select * from DASH11787.iot_HUMIDITY where date(TIME_STAMP) BETWEEN '"+startDate+"' AND '"+endDate+"'"; } } else if (type.equalsIgnoreCase("moisture")) { if(endDate==null || endDate.trim().isEmpty()) { sqlStatement = "select * from DASH11787.iot_MOISTURE where date(TIME_STAMP) = '"+startDate+"'"; } else { sqlStatement = "select * from DASH11787.iot_MOISTURE where date(TIME_STAMP) BETWEEN '"+startDate+"' AND '"+endDate+"'"; } } else if (type.equalsIgnoreCase("salinity")) { if(endDate==null || endDate.trim().isEmpty()) { sqlStatement = "select * from DASH11787.iot_SALINITY where date(TIME_STAMP) = '"+startDate+"'"; } else { sqlStatement = "select * from DASH11787.iot_SALINITY where date(TIME_STAMP) BETWEEN '"+startDate+"' AND '"+endDate+"'"; } } System.out.println(sqlStatement); ResultSet rs = stmt.executeQuery(sqlStatement); int i = 0; while (rs.next()) { SensorData sData= new SensorData(); if(type.equalsIgnoreCase("Temperature")) { sData.setValue(rs.getString("TEMPERATURE")); sData.setParameter("TEMPERATURE"); sData.setEntryID(rs.getString("RECORD_NO")); sData.setTimeStamp(rs.getString("TIME_STAMM"));; } else if(type.equalsIgnoreCase("humidity")) { sData.setValue(rs.getString("HUMIDITY")); sData.setParameter("HUMIDITY"); sData.setEntryID(rs.getString("RECORD NO")); sData.setTimeStamp(rs.getString("TIME_STAMP"));; } else if(type.equalsIgnoreCase("moisture")) { sData.setValue(rs.getString("MOISTURE")); sData.setParameter("MOISTURE"); sData.setEntryID(rs.getString("RECORD NO")); sData.setTimeStamp(rs.getString("TIME_STAMP"));; } else if(type.equalsIgnoreCase("salinity")) { sData.setValue(rs.getString("SALINITY")); sData.setParameter("SALINITY"); sData.setEntryID(rs.getString("RECORD NO")); sData.setTimeStamp(rs.getString("TIME_STAMP"));; } SenData.add(sData); } //con.close(); } catch (SQLException e) { System.out.println(e); } } catch (ClassNotFoundException ex) { System.out.println(ex); } catch (Exception e) { System.out.println(e); } /*finally{ try { //con.close(); } catch (SQLException e) { e.printStackTrace(); } }*/ return SenData; } }
445ef508c475a7a66ca7453274905e11333bfc65
[ "Markdown", "Java" ]
8
Java
somnathkhamaru/IOTAGRI
e7d6fdb0eef1e6ffb06dbad4e675ce0760930202
94f5f2ac920d211fdaeac62059baa96bfe5e2876
refs/heads/main
<file_sep># Simple_js A collection of small projects/ reference code worked on in JS through primarily Codecademy. --- 10/13/2021 --- Files moved over to new PC.<file_sep>let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.'; let overusedWords = ['really', 'very', 'basically']; let unnecessaryWords = ['extremely', 'literally', 'actually' ]; // Determining a word count using .split() const storyWords = story.split(" "); // console.log(storyWords); console.log(`The word count is ${storyWords.length}.`); // "Filtering" the unnecessary words from the string using the .filter() and the .includes() const betterWords = storyWords.filter(function(word) { return !unnecessaryWords.includes(word) }) // console.log(betterWords); // Counting the amount of times the "overly used words" are used in the string using a 'for' loop let reallyCount = 0; let veryCount = 0; let basicallyCount = 0; for (word of storyWords) { if (word === 'really') { reallyCount += 1 } else if (word === 'very') { veryCount += 1 } else if (word === 'basically') { basicallyCount += 1 } } // Establishing a sentence count: again using 'for' loop and comparing the final index of each word to the punctuation that indicates the end of a sentence. let sentenceCount = 0; for (word of storyWords) { if (word[word.length - 1] === '.' || word[word.length - 1] === '!') { sentenceCount += 1 } } // Printing all data as per direction console.log(`The total sentence count is ${sentenceCount}.`); console.log(`Overly Used Word Count: (Really = ${reallyCount} Very = ${veryCount} Basically = ${basicallyCount})`); console.log(betterWords.join(' ')); <file_sep>const team = { _games: [{ opponent: '<NAME>', teamPoints: 20, opponentPoints: 42 }, { opponent: 'Hawks', teamPoints: 36, opponentPoints: 17 }, { opponent: 'Tigers', teamPoints: 28, opponentPoints: 14 } ], _players: [{ firstName: 'John', lastName: 'Doe', age: 20 }, { firstName: 'Adam', lastName: 'Smith', age: 23 }, { firstName: 'Anthony', lastName: 'Robinson', age: 21 } ], // Getter method for _games get games() { return this._games; }, // Getter method for _players get players() { return this._players; }, // Method for adding new players addPlayer(firstName, lastName, age) { let player = { firstName: firstName, lastName: lastName, age: age }; this.players.push(player); }, // Method for adding new game scores addGame(opponent, teamPoints, opponentPoints) { let game = { opponent: opponent, teamPoints: teamPoints, opponentPoints: opponentPoints }; this.games.push(game); } }; // Invoking add methods team.addPlayer('Steph', 'Curry', 28); team.addPlayer('Lisa', 'Leslie', 44); team.addPlayer('Bugs', 'Bunny', 76); //console.log(team.players); team.addGame('Colts', 48, 36); team.addGame('Saints', 14, 36); team.addGame('Bills', 32, 10); console.log(team.games);<file_sep>// Write your code below let bobsFollowers = ['Leslie', 'Tom', 'April', 'Andy']; let tinasFollowers = ['Leslie', 'Tom', 'Ron']; let mutualFollowers = []; for (let i = 0; i < bobsFollowers.length; i++) { for (let j = 0; j < tinasFollowers.length; j++) { if (bobsFollowers[i] === tinasFollowers[j]) { mutualFollowers.push(bobsFollowers[i]); } } } console.log(mutualFollowers.toString());
1a57e7068b8d0a26c0f81bd55e59993ce8441a21
[ "Markdown", "JavaScript" ]
4
Markdown
PartinMD/Simple_js
6ff5bc7915964120d3063df703f726e2bce5a6a0
80b4900b614325111ce8068dff328a38fcfa656b
refs/heads/master
<file_sep>-- phpMyAdmin SQL Dump -- version 4.9.1 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Feb 14, 2020 at 03:10 PM -- Server version: 8.0.17 -- PHP Version: 7.3.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `libery` -- -- -------------------------------------------------------- -- -- Table structure for table `book_infos` -- CREATE TABLE `book_infos` ( `BookNo` int(11) NOT NULL, `BookName` varchar(100) NOT NULL, `Author` varchar(100) NOT NULL, `Description` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -- Dumping data for table `book_infos` -- INSERT INTO `book_infos` (`BookNo`, `BookName`, `Author`, `Description`) VALUES (1001, 'พัฒนา Web Apps ด้วย React Bootstrap + Redux', 'ศุภชัย สมพานิช', 'เรียนรู้การสร้างส่วนแสดงผลด้วย React อธิบายเป็นขั้นตอน Step By Step มีตัวอย่างประกอบให้เห็นผลชัดเจน หลักการทำงาน Redux และ Context API วิธีใช้งานระบบฐานข้อมูล SQL Server 2019'), (1002, 'คู่มือเขียนโปรแกรมภาษา Python ฉบับปรับปรุง', 'ณัฐวัตร คำภักดี', 'Python เบื้องต้นโดยใช้ Jupyter Notebook, เขียนโปรแกรม Graphical User Interface (GUI), Object-Oriented Programming (OOP), เชื่อมต่อฐานข้อมูล MariaDB, Django Web Framework'), (1003, 'คู่มือพัฒนาเว็บแอพพลิเคชั่นด้วย Angular', 'ศุภชัย สมพานิช', 'ใช้ร่วมกับ Ionic Framework สร้างเว็บแอพแบบ Responsive ด้วย Bootstrap ครอบคลุม Angular เวอร์ชั่น 8 และ 9 เป็นต้นไป เหมาะสำหรับนักเรียน นักศึกษา นักพัฒนาโปรแกรม และผู้สนใจทั่วไป'), (1004, 'Artificial Intelligence with Machine Learning', 'รศ.ดร. ปริญญา สงวนสัตย์', 'เรียนอัลกอริทึมของ Machine Learning เพื่อสร้างสมองอันทรงพลังให้กับงานด้าน AI, Data Mining, Pattern Recognition, Computer Vision และงานสาขาอื่นที่เกี่ยวข้อง'), (1005, 'พัฒนาเว็บแอพพลิเคชันด้วย Node.js Express+MongoDB', 'จีราวุธ วารินทร์', 'เรียนรู้การสร้างเว็บแอพพลิเคชันด้วย Node.js+Express และวิธีจัดการฐานข้อมูล MongoDB อธิบายพื้นฐานการใช้งาน Node.js ครบทุกเรื่องที่จำเป็น เรียนรู้เกี่ยวกับโมดูล พร้อมตัวอย่างการใช้งานโมดูลยอดนิยม ฯลฯ'), (1006, 'พัฒนา IOT บนแพลตฟอร์ม Arduino ด้วย NodeMCU', 'ภาสกร พาเจริญ', 'IOT เบื้องต้น, เตรียมอุปกรณ์ และโปรแกรมให้พร้อม, การทดสอบ และอัพโหลดโปรแกรม, ขาอินพุต/เอาต์พุต GPIO, การเชื่อมต่อ ADC, Pulse Width Modulation (PWM), การรับส่งข้อมูลระหว่างอุปกรณ์ ฯลฯ'), (1007, 'คู่มือเขียนโปรแกรมด้วยภาษา C ฉบับสมบูรณ์', 'อรพิน ประวัติบริสุทธิ์', 'คู่มือเขียนโปรแกรมด้วยภาษา C ฉบับสมบูรณ์\r\nเรียนรู้การเขียนโปรแกรมภาษา C เพื่อต่อยอดสู่ Objective-C, C#, C++, PHP, Java'), (1008, 'คณิตศาสตร์วิศวกรรมไฟฟ้า', 'ศ.กิตติคุณ มงคล เดชนครินทร์', 'หนังสือโครงการตำราภาควิชาวิศวกรรมไฟฟ้าเพื่อเป็นเสาหลักเเห่งปัญญา คณะวิศวกรรมศาสตร์ จุฬาลงกรณ์มหาวิทยาลัย'), (1009, 'สัญญาณ ระบบ และการควบคุม', 'วัชรพงษ์ โขวิฑูรกิจ', 'หนังสือเล่มนี้เหมาะสำหรับนิสิตนักศึกษา วิศวกร และผู้ที่สนใจศึกษาเกี่ยวกับสัญญาณ ระบบ และการควบคุม ซึ่งเป็นพื้นฐานสำคัญในด้านวิศวกรรมไฟฟ้าและศาสตร์อื่น ๆ ที่เกี่ยวข้อง\r\n'), (1010, 'การวิเคราะห์โครงสร้าง', 'ผศ.ดร. ณัฐพงศ์ ดำรงวิริยะนุภาพ', 'หนังสื่อเล่มนี้มีวัตถุประสงค์เพื่อเสริมสร้างความเข้าใจในพื้นฐานของการวิเคาระห์โครงสร้างและพฤติกรรมของโครงสร้างภายใต้น้ำหนักบรรทุก ซึ่งจะเป็นการวิเคราะห์โครงสร้างดีเทอร์มิเนททางสถิตโดยวิธีต่างๆ'); -- -------------------------------------------------------- -- -- Table structure for table `borrow` -- CREATE TABLE `borrow` ( `BorrowID` int(11) NOT NULL, `BorrowDate` date NOT NULL, `BookID` int(11) NOT NULL, `StudentCode` int(11) NOT NULL, `ReturnDate` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -- Dumping data for table `borrow` -- INSERT INTO `borrow` (`BorrowID`, `BorrowDate`, `BookID`, `StudentCode`, `ReturnDate`) VALUES (1, '2020-02-29', 1006, 5888, '2020-03-01'), (2, '2020-02-15', 1002, 7215, NULL), (3, '2020-02-27', 1001, 3057, '2020-02-28'), (4, '2020-02-19', 1010, 4832, '2020-02-20'), (5, '2020-02-21', 1008, 2703, NULL); -- -------------------------------------------------------- -- -- Table structure for table `student` -- CREATE TABLE `student` ( `StudentCode` char(10) NOT NULL, `StudentName` varchar(100) NOT NULL, `Department` varchar(100) NOT NULL, `BirthDate` date NOT NULL, `Age` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- -- Dumping data for table `student` -- INSERT INTO `student` (`StudentCode`, `StudentName`, `Department`, `BirthDate`, `Age`) VALUES ('7215', 'กันตภณ', 'CPE', '1999-11-14', 20), ('7058', 'อานนท์', 'CPE', '1999-08-12', 20), ('4832', 'รัตนศักดิ์', 'CE', '1999-05-21', 20), ('2703', 'ธิดารัตน์', 'EE', '1999-10-14', 31), ('5888', 'สนายุทธ', 'CPE', '1999-09-09', 20), ('5466', 'วุฒินันท์', 'IT', '1998-06-05', 80), ('4428', 'ภานุมาศ', 'IT', '1999-02-23', 20), ('3057', 'นลินภัสร์', 'CS', '1999-10-15', 20), ('3917', 'พรทิพย์', 'EE', '1999-11-04', 20), ('5383', 'วิภาดา', 'CPE', '1999-01-05', 20); -- -- Indexes for dumped tables -- -- -- Indexes for table `book_infos` -- ALTER TABLE `book_infos` ADD PRIMARY KEY (`BookNo`); -- -- Indexes for table `borrow` -- ALTER TABLE `borrow` ADD PRIMARY KEY (`BorrowID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `book_infos` -- ALTER TABLE `book_infos` MODIFY `BookNo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1011; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
2ffb0b6279a523c3b906fe39049d5914fe919f00
[ "SQL" ]
1
SQL
atoiyu123/DatabaseLibrary
390777065e67c79e538c3e309dfd1a98aa36c31a
ae8d52f53b05a5aae98abce2eb263782546560a9
refs/heads/master
<file_sep>const offerRoutes = require('./products'); const myofferRoutes = require('./myoffers'); const appRouter = (app, fs) => { //include home route app.get('/', (req, res) => { res.send('This is Home route'); }); offerRoutes(app, fs); myofferRoutes(app, fs); }; module.exports = appRouter;
22d6b89122ccb670b88512ed254ee88e018de339
[ "JavaScript" ]
1
JavaScript
VamshiPaka/AmazonJson
29c3eaf0d4846111ea043d95d6e9ba928fd15698
46123516fcbe24a07c8a94b1563cefaf8c3af33e
refs/heads/master
<repo_name>Mouhsineham/VotreBanque<file_sep>/ReadMe.md ## votre baque project created by angualar v4.1.1 and spring v4.3 # pris requise install java export the path ru the command ``` $ mvn clean install ``` <file_sep>/src/main/java/org/sid/metier/IBanqueMetier.java package org.sid.metier; import org.sid.entities.Compte; import org.sid.entities.Operation; import org.springframework.data.domain.Page; public interface IBanqueMetier { public Compte consulterCompte(String codeCpte); public void verser(String codeCpte,double montant); public void retirer(String codeCpte,double montant); public void virement(String codeCpte1, String codeCpte2, double montant); public Page<Operation> listOperation(String codeCpte, int page,int size); }
bdf5dfc2bbfec156d0204ddae5fa2f849a9980ea
[ "Markdown", "Java" ]
2
Markdown
Mouhsineham/VotreBanque
f37cbc1c5846284923235f7e1f8b69538d79520b
f3cf00c4f64396b952f51cb6eb58b3a8ba4e1921
refs/heads/master
<file_sep>import { EntityManager, MikroORM } from '@mikro-orm/core'; import { Seeder } from '@mikro-orm/seeder'; import { SqliteDriver } from '@mikro-orm/sqlite'; import { House } from './entities/house.entity'; import { Project } from './entities/project.entity'; import { User } from './entities/user.entity'; class ProjectSeeder extends Seeder { async run(em: EntityManager): Promise<void> { const project = em.create(Project, { name: 'Construction', owner: 'Donald Duck', worth: 313, }); await em.persistAndFlush(project); em.clear(); } } class UserSeeder extends Seeder { async run(em: EntityManager): Promise<void> { const user = em.create(User, { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', }); await em.persistAndFlush(user); em.clear(); } } class DatabaseSeeder extends Seeder { run(em: EntityManager): Promise<void> { return this.call(em, [ ProjectSeeder, UserSeeder, ]); } } describe('Run seeders', () => { let orm: MikroORM<SqliteDriver>; beforeAll(async () => { orm = await MikroORM.init({ entities: [Project, User, House], type: 'sqlite', dbName: ':memory:', }); await orm.getSchemaGenerator().createSchema(); }); afterAll(() => orm.close(true)); test('that by calling DatabaseSeeder both ProjectSeeder and UserSeeder have been called', async () => { const seeder = new DatabaseSeeder(); await seeder.run(orm.em); const projects = await orm.em.findAndCount(Project, {}); expect(projects[1]).toBe(1); const users = await orm.em.findAndCount(User, {}); expect(users[1]).toBe(1); }); });
c1bb3d654f5ebca428620b291e8916e552f20cac
[ "TypeScript" ]
1
TypeScript
JoelVenable/mikro-orm
8e1e4897a4be6b55ef2805ca38107535c39368c6
5740198d684dd1f3069a0972d88e5e60c81d6cf4
refs/heads/master
<file_sep>package com.no1.data.entity; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; public class FirstDayPerformance { // performance_id int private int performanceId; // open_price double private Double openPrice; // close_price double private Double closePrice; // open_premium double private Double openPremium; // closing_gains double private Double closingGains; // turnover_rate double private Double turnoverRate; // maximum_increase double private Double maximumIncrease; // first_day_open_date date @DateTimeFormat(pattern = "yyyy-MM-dd") private Date firstDayOpenDate; // total_gains double private Double totalGains; // continuous_word_boards_number int private Integer continuousWordBoardsNumber; // open_day_average_price double private Double openDayAveragePrice; // every_one_makes_profit int private Integer everyOneMakesProfit; public int getPerformanceId() { return performanceId; } public void setPerformanceId(int performanceId) { this.performanceId = performanceId; } public Double getOpenPrice() { return openPrice; } public void setOpenPrice(Double openPrice) { this.openPrice = openPrice; } public Double getClosePrice() { return closePrice; } public void setClosePrice(Double closePrice) { this.closePrice = closePrice; } public Double getOpenPremium() { return openPremium; } public void setOpenPremium(Double openPremium) { this.openPremium = openPremium; } public Double getClosingGains() { return closingGains; } public void setClosingGains(Double closingGains) { this.closingGains = closingGains; } public Double getTurnoverRate() { return turnoverRate; } public void setTurnoverRate(Double turnoverRate) { this.turnoverRate = turnoverRate; } public Double getMaximumIncrease() { return maximumIncrease; } public void setMaximumIncrease(Double maximumIncrease) { this.maximumIncrease = maximumIncrease; } public Date getFirstDayOpenDate() { return firstDayOpenDate; } public void setFirstDayOpenDate(Date firstDayOpenDate) { this.firstDayOpenDate = firstDayOpenDate; } public Double getTotalGains() { return totalGains; } public void setTotalGains(Double totalGains) { this.totalGains = totalGains; } public Integer getContinuousWordBoardsNumber() { return continuousWordBoardsNumber; } public void setContinuousWordBoardsNumber(Integer continuousWordBoardsNumber) { this.continuousWordBoardsNumber = continuousWordBoardsNumber; } public Double getOpenDayAveragePrice() { return openDayAveragePrice; } public void setOpenDayAveragePrice(Double openDayAveragePrice) { this.openDayAveragePrice = openDayAveragePrice; } public Integer getEveryOneMakesProfit() { return everyOneMakesProfit; } public void setEveryOneMakesProfit(Integer everyOneMakesProfit) { this.everyOneMakesProfit = everyOneMakesProfit; } } <file_sep>package com.no1.data.service.impl; import com.no1.data.BaseTest; import com.no1.data.entity.Stock; import com.no1.data.mapper.StockMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; public class StockServiceImplTest extends BaseTest { @Resource private StockMapper stockMapper; @Test public void findByPage() { Map map = new HashMap(); map.put("stockValue",null); map.put("stockOrder",null); List<Stock> stockList = stockMapper.findByPage(map); for (Stock s:stockList) { System.out.println(s.getStockName()+":"+s.getListingDate()); } } }<file_sep>package com.no1.data.entity; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; public class IssueStatus { // status_id int private int statusId; // stock_code varchar private String stockCode; // stock_name varchar private String stockName; // purchase_code varchar private String purchaseCode; // listing_place varchar private String listingPlace; // issue_price double private Double issuePrice; // ipo_pe_ratio double private Double ipoPeRatio; // pe_ratio_reference_industry varchar private String peTatioReferenceIndustry; // reference_industry_pe_ratio double private Double referenceIndustryPeRatio; // issue_face_value double 发行面值(元) private Double issueFaceValue; // total_actual_fund_raised double 实际募集资金总额(亿元) private Double totalActualFundRaised; // online_release_date date 网上发行日期 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date onlineReleaseDate; // offline_distribution_date date 网下配售日期 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date offlineDistributionDate; // number_online_issuance int 网上发行数量(股) private Integer numberOnlineIssuance; // offline_distribution_quantity int 网下配售数量(股) private Integer offlineDistributionQuantity; // number_old_stock_transfers int 老股转让数量(股) private Integer numberOldStockTransfers; // total_issue_quantity int 总发行数量(股) private Integer totalIssueQuantity; // purchase_limit int 申购数量上限(股) private Integer purchaseLimit; // payment_date date 中签缴款日期 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date paymentDate; // online_market_capitalization double 网上顶格申购需配市值(万元) private Double onlineMarketCapitalization; // online_purchase_market_value_confirm_date date 网上申购市值确认日 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date onlinePurchaseMarketValueConfirmDate; // offline_purchase_market_value double 网下申购需配市值(万元) private Double offlinePurchaseMarketValue; // offline_purchase_market_value_confirm_date date 网下申购市值确认日 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date offlinePurchaseMarketValueConfirmDate; public Double getIssueFaceValue() { return issueFaceValue; } public void setIssueFaceValue(Double issueFaceValue) { this.issueFaceValue = issueFaceValue; } public Double getTotalActualFundRaised() { return totalActualFundRaised; } public void setTotalActualFundRaised(Double totalActualFundRaised) { this.totalActualFundRaised = totalActualFundRaised; } public Date getOnlineReleaseDate() { return onlineReleaseDate; } public void setOnlineReleaseDate(Date onlineReleaseDate) { this.onlineReleaseDate = onlineReleaseDate; } public Date getOfflineDistributionDate() { return offlineDistributionDate; } public void setOfflineDistributionDate(Date offlineDistributionDate) { this.offlineDistributionDate = offlineDistributionDate; } public Integer getNumberOnlineIssuance() { return numberOnlineIssuance; } public void setNumberOnlineIssuance(Integer numberOnlineIssuance) { this.numberOnlineIssuance = numberOnlineIssuance; } public Integer getOfflineDistributionQuantity() { return offlineDistributionQuantity; } public void setOfflineDistributionQuantity(Integer offlineDistributionQuantity) { this.offlineDistributionQuantity = offlineDistributionQuantity; } public Integer getNumberOldStockTransfers() { return numberOldStockTransfers; } public void setNumberOldStockTransfers(Integer numberOldStockTransfers) { this.numberOldStockTransfers = numberOldStockTransfers; } public Integer getTotalIssueQuantity() { return totalIssueQuantity; } public void setTotalIssueQuantity(Integer totalIssueQuantity) { this.totalIssueQuantity = totalIssueQuantity; } public Integer getPurchaseLimit() { return purchaseLimit; } public void setPurchaseLimit(Integer purchaseLimit) { this.purchaseLimit = purchaseLimit; } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date paymentDate) { this.paymentDate = paymentDate; } public Double getOnlineMarketCapitalization() { return onlineMarketCapitalization; } public void setOnlineMarketCapitalization(Double onlineMarketCapitalization) { this.onlineMarketCapitalization = onlineMarketCapitalization; } public Date getOnlinePurchaseMarketValueConfirmDate() { return onlinePurchaseMarketValueConfirmDate; } public void setOnlinePurchaseMarketValueConfirmDate(Date onlinePurchaseMarketValueConfirmDate) { this.onlinePurchaseMarketValueConfirmDate = onlinePurchaseMarketValueConfirmDate; } public Double getOfflinePurchaseMarketValue() { return offlinePurchaseMarketValue; } public void setOfflinePurchaseMarketValue(Double offlinePurchaseMarketValue) { this.offlinePurchaseMarketValue = offlinePurchaseMarketValue; } public Date getOfflinePurchaseMarketValueConfirmDate() { return offlinePurchaseMarketValueConfirmDate; } public void setOfflinePurchaseMarketValueConfirmDate(Date offlinePurchaseMarketValueConfirmDate) { this.offlinePurchaseMarketValueConfirmDate = offlinePurchaseMarketValueConfirmDate; } public Double getIssuePrice() { return issuePrice; } public void setIssuePrice(Double issuePrice) { this.issuePrice = issuePrice; } public Double getIpoPeRatio() { return ipoPeRatio; } public void setIpoPeRatio(Double ipoPeRatio) { this.ipoPeRatio = ipoPeRatio; } public String getPeTatioReferenceIndustry() { return peTatioReferenceIndustry; } public void setPeTatioReferenceIndustry(String peTatioReferenceIndustry) { this.peTatioReferenceIndustry = peTatioReferenceIndustry; } public Double getReferenceIndustryPeRatio() { return referenceIndustryPeRatio; } public void setReferenceIndustryPeRatio(Double referenceIndustryPeRatio) { this.referenceIndustryPeRatio = referenceIndustryPeRatio; } public int getStatusId() { return statusId; } public void setStatusId(int statusId) { this.statusId = statusId; } public String getStockCode() { return stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } public String getStockName() { return stockName; } public void setStockName(String stockName) { this.stockName = stockName; } public String getPurchaseCode() { return purchaseCode; } public void setPurchaseCode(String purchaseCode) { this.purchaseCode = purchaseCode; } public String getListingPlace() { return listingPlace; } public void setListingPlace(String listingPlace) { this.listingPlace = listingPlace; } } <file_sep>package com.no1.data.mapper; import com.no1.data.entity.NewStockMarket; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; @Repository public interface NewStockMarketMapper { //查询新股上会数据并排序 public List<NewStockMarket> findAll(Map map); } <file_sep>/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50553 Source Host : localhost:3306 Source Database : datacenter Target Server Type : MYSQL Target Server Version : 50553 File Encoding : 65001 Date: 2019-03-04 18:09:46 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for ballot_number -- ---------------------------- DROP TABLE IF EXISTS `ballot_number`; CREATE TABLE `ballot_number` ( `ballot_number_id` int(11) NOT NULL AUTO_INCREMENT, `last_four_digits` varchar(255) DEFAULT NULL, `last_five_digits` varchar(255) DEFAULT NULL, `last_six_digits` varchar(255) DEFAULT NULL, `last_seven_digits` varchar(255) DEFAULT NULL, `last_eight_digits` varchar(255) DEFAULT NULL, `last_nine_digits` varchar(255) DEFAULT NULL, PRIMARY KEY (`ballot_number_id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of ballot_number -- ---------------------------- INSERT INTO `ballot_number` VALUES ('1', '1049,3549,6049,8549', '51537', '632073,132073,504323', '3944272,5194272,6444272,7694272,8944272,0194272,1444272,2694272', '20034027,70034027', '008650301'); INSERT INTO `ballot_number` VALUES ('2', '1599,4099,6599,9099', '26342,38842,51342,63842,76342,88842,01342,13842', '376279,501279,626279,751279,876279,001279,126279,251279', '8224052,3224052,6895339', '41141244,61141244,81141244,01141244,21141244,40806665,65806665,90806665,15806665', '138857896'); INSERT INTO `ballot_number` VALUES ('3', '184,684', '17452,29952,42452,54952,67452,79952,92452,04952', '707846,207846,679581', '5299103,6549103,7799103,9049103,4049103,2799103,1549103,0299103,8775005', '65979854,78479854,90979854,53479854,40979854,28479854,15979854,03479854', null); INSERT INTO `ballot_number` VALUES ('4', '6591,1591,3609', null, '012368,212368,412368,612368,812368,204469,454469,704469,954469', '4645759,6645759,8645759,0645759,2645759,0041493', '49795164', null); INSERT INTO `ballot_number` VALUES ('5', '9742,4742,6561', '98562,18562,38562,58562,78562,12003,62003', '468775,718775,968775,218775', '9437085,1437085,3437085,5437085,7437085', '32940567', '194798504'); INSERT INTO `ballot_number` VALUES ('6', '6864,9364,4364,1864', '35557,48057,60557,73057,85557,98057,23057,10557,36891', '546323,046323', '6315293,7565293,8815293,5065293,3815293,2565293,1315293,0065293', '75205517,69924471,26911295,52383175,00759927,23748948', null); INSERT INTO `ballot_number` VALUES ('7', '725', '25385', '835996,960996,710996,585996,460996,335996,210996,085996,103533', '6767641,8767641,4767641,2767641,0767641', '01227325,21227325,41227325,61227325,81227325,66748125,16748125', null); INSERT INTO `ballot_number` VALUES ('8', '0808,5808,3878', '32460,82460', '471793', '7019193,9019193,1019193,3019193,5019193,8158077', '18295056,43295056,68295056,93295056', '102741010'); -- ---------------------------- -- Table structure for first_day_performance -- ---------------------------- DROP TABLE IF EXISTS `first_day_performance`; CREATE TABLE `first_day_performance` ( `performance_id` int(11) NOT NULL AUTO_INCREMENT, `open_price` double DEFAULT NULL, `close_price` double DEFAULT NULL, `open_premium` double DEFAULT NULL, `closing_gains` double DEFAULT NULL, `turnover_rate` double DEFAULT NULL, `maximum_increase` double DEFAULT NULL, `first_day_open_date` date DEFAULT NULL, `total_gains` double DEFAULT NULL, `continuous_word_boards_number` int(11) DEFAULT NULL, `open_day_average_price` double DEFAULT NULL, `every_one_makes_profit` int(11) DEFAULT NULL, PRIMARY KEY (`performance_id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of first_day_performance -- ---------------------------- INSERT INTO `first_day_performance` VALUES ('1', '9.19', '11.03', '19.97', '43.99', '0.07', '43.99', '2019-02-21', '383.29', '13', '37.02', '14680'); INSERT INTO `first_day_performance` VALUES ('2', '35.22', '42.26', '20', '43.99', '0.11', '43.99', '2019-02-26', '146.1', '6', '72.23', '21440'); INSERT INTO `first_day_performance` VALUES ('3', '5.62', '6.74', '20.09', '44.02', '0.1', '44.02', null, null, null, null, null); INSERT INTO `first_day_performance` VALUES ('4', '26.51', '31.81', '20.01', '44', '0.12', '44', null, null, null, null, null); INSERT INTO `first_day_performance` VALUES ('5', '12.61', '15.13', '19.98', '43.96', '0.07', '43.96', null, null, null, null, null); INSERT INTO `first_day_performance` VALUES ('6', '6.84', '8.21', '20', '44.04', '0.07', '44.04', null, null, null, null, null); INSERT INTO `first_day_performance` VALUES ('7', '2.88', '2.88', '44', '44', '0.07', '44', null, null, null, null, null); INSERT INTO `first_day_performance` VALUES ('8', '22.46', '26.96', '19.98', '44.02', '0.17', '44.02', '2019-02-18', '148.24', '6', '46.47', '13875'); -- ---------------------------- -- Table structure for industry_section -- ---------------------------- DROP TABLE IF EXISTS `industry_section`; CREATE TABLE `industry_section` ( `section_id` int(11) NOT NULL AUTO_INCREMENT, `section_name` varchar(255) DEFAULT NULL COMMENT '板块名称', `latest_price` double DEFAULT NULL COMMENT '最新价', `up_down_limit` double DEFAULT NULL COMMENT '涨跌额', `up_down_range` varchar(255) DEFAULT NULL COMMENT '涨跌幅', `total_market_value` double DEFAULT NULL, `total_market_unit` varchar(255) DEFAULT NULL COMMENT '总市值', `turnover_rate` varchar(255) DEFAULT NULL COMMENT '换手率', `rising_number` int(11) DEFAULT NULL COMMENT '上涨家数', `drop_number` int(11) DEFAULT NULL COMMENT '下跌家数', `leading_stock` varchar(255) DEFAULT NULL COMMENT '领涨股票', `up_downs` varchar(255) DEFAULT NULL COMMENT '涨跌幅', PRIMARY KEY (`section_id`) ) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of industry_section -- ---------------------------- INSERT INTO `industry_section` VALUES ('1', '安防设备', '765.99', '-4.07', '-0.53%', '4696', '亿', '0.62%', '7', '13', '迪威迅', '1.41%'); INSERT INTO `industry_section` VALUES ('2', '包装材料', '523.71', '4.02', '0.77%', '1298', '亿', '0.91%', '11', '12', '顺灏股份', '10.06%'); INSERT INTO `industry_section` VALUES ('3', '保险', '1362.63', '2.75', '0.20%', '2.66', '万亿', '0.31%', '4', '3', '中国太保', '1.99%'); INSERT INTO `industry_section` VALUES ('4', '玻璃陶瓷', '16555.63', '41.19', '0.25%', '2376', '亿', '0.33%', '10', '12', '福莱特', '10.03%'); INSERT INTO `industry_section` VALUES ('5', '材料行业', '15391.47', '143.78', '0.94%', '5153', '亿', '2.10%', '43', '23', '乐凯胶片', '9.97%'); INSERT INTO `industry_section` VALUES ('6', '船舶制造', '377.32', '-1.21', '-0.32%', '1685', '亿', '0.25%', '2', '9', '*ST宝鼎', '4.94%'); INSERT INTO `industry_section` VALUES ('7', '电力行业', '8803.72', '0.89', '0.01%', '1.34', '万亿', '0.27%', '26', '31', '穗恒运A', '9.98%'); INSERT INTO `industry_section` VALUES ('8', '电信运营', '899.2', '-1.82', '-0.20%', '2279', '亿', '0.33%', '3', '2', '中国联通', '0.35%'); INSERT INTO `industry_section` VALUES ('9', '电子信息', '10887.27', '-66.79', '-0.61%', '7674', '亿', '1.09%', '24', '78', '中信国安', '6.15%'); INSERT INTO `industry_section` VALUES ('10', '电子元件', '9550.27', '-20.75', '-0.22%', '2.19', '万亿', '2.12%', '71', '141', '超频三', '10.03%'); INSERT INTO `industry_section` VALUES ('11', '多元金融', '509.33', '-2.97', '-0.58%', '3514', '亿', '1.25%', '5', '18', '易见股份', '9.99%'); INSERT INTO `industry_section` VALUES ('12', '房地产', '12569.74', '43.32', '0.35%', '2.11', '万亿', '0.51%', '76', '45', '粤泰股份', '8.81%'); INSERT INTO `industry_section` VALUES ('13', '纺织服装', '8756.69', '-34.37', '-0.39%', '4161', '亿', '0.34%', '28', '50', '多喜爱', '4.07%'); INSERT INTO `industry_section` VALUES ('14', '钢铁行业', '4607.55', '53.95', '1.18%', '7315', '亿', '0.42%', '35', '2', '沙钢股份', '5.57%'); INSERT INTO `industry_section` VALUES ('15', '港口水运', '6472.41', '-44.17', '-0.68%', '6356', '亿', '0.32%', '6', '21', '盐田港', '1.86%'); INSERT INTO `industry_section` VALUES ('16', '高速公路', '4557.17', '-8.48', '-0.19%', '2686', '亿', '0.18%', '6', '9', '城发环境', '2.44%'); INSERT INTO `industry_section` VALUES ('17', '工程建设', '14106.89', '-7.37', '-0.05%', '1.41', '万亿', '0.22%', '35', '35', '百利科技', '6.58%'); INSERT INTO `industry_section` VALUES ('18', '工艺商品', '23703.99', '12.21', '0.05%', '76.34', '亿', '0.58%', '2', '1', '德艺文创', '0.30%'); INSERT INTO `industry_section` VALUES ('19', '公用事业', '5584.57', '20.5', '0.37%', '2942', '亿', '0.36%', '21', '15', 'ST升达', '3.60%'); INSERT INTO `industry_section` VALUES ('20', '贵金属', '646.97', '12.48', '1.97%', '2450', '亿', '1.43%', '12', '0', '金贵银业', '5.54%'); INSERT INTO `industry_section` VALUES ('21', '国际贸易', '8485.47', '-69.27', '-0.81%', '1074', '亿', '0.40%', '6', '17', '物贸B股', '1.15%'); INSERT INTO `industry_section` VALUES ('22', '航天航空', '22429.56', '-344.16', '-1.51%', '4014', '亿', '0.33%', '0', '25', '炼石航空', '0.00%'); INSERT INTO `industry_section` VALUES ('23', '化肥行业', '633.17', '-0.1', '-0.02%', '1815', '亿', '0.23%', '8', '11', '*ST柳化', '1.64%'); INSERT INTO `industry_section` VALUES ('24', '化工行业', '11748.54', '-11.99', '-0.10%', '1.33', '万亿', '0.40%', '71', '105', '同益股份', '10.01%'); INSERT INTO `industry_section` VALUES ('25', '化纤行业', '9650.13', '-66.01', '-0.68%', '2881', '亿', '0.43%', '5', '17', '*ST尤夫', '4.79%'); INSERT INTO `industry_section` VALUES ('26', '环保工程', '510.47', '-3.23', '-0.63%', '2821', '亿', '0.73%', '14', '29', '博天环境', '3.23%'); INSERT INTO `industry_section` VALUES ('27', '机械行业', '14918.67', '-11.97', '-0.08%', '1.6', '万亿', '0.44%', '87', '136', '山东矿机', '10.16%'); INSERT INTO `industry_section` VALUES ('28', '家电行业', '9235.55', '27.5', '0.30%', '1.18', '万亿', '0.28%', '31', '16', '*ST德奥', '3.91%'); INSERT INTO `industry_section` VALUES ('29', '交运设备', '6392.46', '3.32', '0.05%', '3654', '亿', '0.20%', '10', '13', '华铁股份', '3.12%'); INSERT INTO `industry_section` VALUES ('30', '交运物流', '4825.06', '-10.23', '-0.21%', '7671', '亿', '0.26%', '16', '33', '德新交运', '7.64%'); INSERT INTO `industry_section` VALUES ('31', '金属制品', '626.27', '-1.21', '-0.19%', '3356', '亿', '0.51%', '26', '30', '经纬辉开', '4.57%'); INSERT INTO `industry_section` VALUES ('32', '旅游酒店', '11419.44', '-20.83', '-0.18%', '3112', '亿', '0.25%', '13', '22', '宋城演艺', '3.32%'); INSERT INTO `industry_section` VALUES ('33', '煤炭采选', '5141.34', '3.21', '0.06%', '9227', '亿', '0.20%', '13', '15', '*ST安泰', '2.97%'); INSERT INTO `industry_section` VALUES ('34', '民航机场', '4400.62', '-30.36', '-0.69%', '5996', '亿', '0.15%', '2', '11', '白云机场', '1.14%'); INSERT INTO `industry_section` VALUES ('35', '木业家具', '12297.42', '-11.07', '-0.09%', '2352', '亿', '0.42%', '14', '21', '顾家家居', '2.53%'); INSERT INTO `industry_section` VALUES ('36', '酿酒行业', '25371.52', '411.3', '1.65%', '1.95', '万亿', '0.37%', '37', '1', '今世缘', '5.25%'); INSERT INTO `industry_section` VALUES ('37', '农牧饲渔', '9459.19', '40.91', '0.43%', '8707', '亿', '0.46%', '34', '32', '朗源股份', '10.06%'); INSERT INTO `industry_section` VALUES ('38', '农药兽药', '743.18', '-1.62', '-0.22%', '2002', '亿', '0.48%', '8', '17', '扬农化工', '1.83%'); INSERT INTO `industry_section` VALUES ('39', '汽车行业', '15568.13', '-43.75', '-0.28%', '1.91', '万亿', '0.35%', '49', '94', '浙江仙通', '7.48%'); INSERT INTO `industry_section` VALUES ('40', '券商信托', '112982.34', '1335.85', '1.20%', '2.6', '万亿', '0.77%', '39', '1', '国盛金控', '10.03%'); INSERT INTO `industry_section` VALUES ('41', '软件服务', '605.67', '-4.72', '-0.77%', '1.61', '万亿', '0.84%', '42', '119', '顶点软件', '3.79%'); INSERT INTO `industry_section` VALUES ('42', '商业百货', '12429.84', '-61.58', '-0.49%', '7067', '亿', '0.53%', '16', '54', '商业城', '2.13%'); INSERT INTO `industry_section` VALUES ('43', '石油行业', '4138.25', '-39.56', '-0.95%', '2.52', '万亿', '0.08%', '5', '32', 'ST准油', '4.66%'); INSERT INTO `industry_section` VALUES ('44', '食品饮料', '13900.51', '-30.08', '-0.22%', '9827', '亿', '0.33%', '24', '42', '千禾味业', '5.52%'); INSERT INTO `industry_section` VALUES ('45', '输配电气', '11593.53', '-72.53', '-0.62%', '8858', '亿', '0.44%', '21', '83', '通达股份', '6.86%'); INSERT INTO `industry_section` VALUES ('46', '水泥建材', '19779.6', '458.48', '2.37%', '5965', '亿', '1.17%', '38', '7', '四川金顶', '10.05%'); INSERT INTO `industry_section` VALUES ('47', '塑胶制品', '7099.68', '-12.04', '-0.17%', '2846', '亿', '0.64%', '17', '34', '海达股份', '9.93%'); INSERT INTO `industry_section` VALUES ('48', '通讯行业', '8971.78', '-118.97', '-1.31%', '1.26', '万亿', '1.03%', '15', '80', '万隆光电', '10.01%'); INSERT INTO `industry_section` VALUES ('49', '文化传媒', '7579.91', '-65.56', '-0.86%', '9603', '亿', '0.55%', '17', '73', '紫天科技', '9.98%'); INSERT INTO `industry_section` VALUES ('50', '文教休闲', '540.1', '-3.04', '-0.56%', '2851', '亿', '0.68%', '8', '24', '姚记扑克', '4.22%'); INSERT INTO `industry_section` VALUES ('51', '医疗行业', '771.5', '-7.8', '-1.00%', '7429', '亿', '0.93%', '11', '48', '千山药机', '4.12%'); INSERT INTO `industry_section` VALUES ('52', '医药制造', '19134.73', '-108.78', '-0.57%', '2.88', '万亿', '0.64%', '59', '157', '龙津药业', '10.05%'); INSERT INTO `industry_section` VALUES ('53', '仪器仪表', '6739.42', '-33.88', '-0.50%', '2031', '亿', '0.51%', '14', '28', '凯发电气', '2.51%'); INSERT INTO `industry_section` VALUES ('54', '银行', '3106.77', '-4.15', '-0.13%', '10.29', '万亿', '0.06%', '2', '29', 'N西行', '44.02%'); INSERT INTO `industry_section` VALUES ('55', '有色金属', '8381.56', '-58.91', '-0.70%', '9989', '亿', '0.41%', '14', '58', 'XR贵研铂', '9.97%'); INSERT INTO `industry_section` VALUES ('56', '园林工程', '614.61', '-2.75', '-0.45%', '1129', '亿', '0.68%', '6', '17', '*ST毅达', '4.26%'); INSERT INTO `industry_section` VALUES ('57', '造纸印刷', '5829.04', '-81.77', '-1.38%', '2068', '亿', '0.95%', '5', '27', '美利云', '1.97%'); INSERT INTO `industry_section` VALUES ('58', '珠宝首饰', '488.99', '-4.04', '-0.82%', '792.5', '亿', '1.00%', '3', '11', '萃华珠宝', '2.37%'); INSERT INTO `industry_section` VALUES ('59', '专用设备', '1051.23', '-3.84', '-0.36%', '4639', '亿', '0.77%', '24', '62', '华菱星马', '10.07%'); INSERT INTO `industry_section` VALUES ('60', '装修装饰', '587.02', '-2.19', '-0.37%', '1394', '亿', '0.49%', '9', '18', '柯利达', '4.00%'); INSERT INTO `industry_section` VALUES ('61', '综合行业', '5351.1', '-57.78', '-1.07%', '1611', '亿', '0.54%', '4', '20', '*ST工新', '4.82%'); -- ---------------------------- -- Table structure for issue_mode -- ---------------------------- DROP TABLE IF EXISTS `issue_mode`; CREATE TABLE `issue_mode` ( `mode_id` int(11) NOT NULL AUTO_INCREMENT, `mode_type` varchar(255) DEFAULT NULL, `mode_descrip` varchar(255) DEFAULT NULL, PRIMARY KEY (`mode_id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of issue_mode -- ---------------------------- INSERT INTO `issue_mode` VALUES ('1', '市值申购,网下询价配售,网上定价发行', '采用网下向配售对象询价配售与网上市值申购定价发行相结合的方式;或采用中国证监会要求或认可的其他方式'); INSERT INTO `issue_mode` VALUES ('2', '市值申购,网下询价配售,网上定价发行', '采用网下向投资者询价配售和网上向社会公众投资者定价发行相结合的方式或中国证监会等监管审核部门认可的其他发行方式'); INSERT INTO `issue_mode` VALUES ('3', '市值申购,网下询价配售,网上定价发行', '采用网下向询价对象配售和网上向符合资格的社会公众投资者定价发行相结合的方式或中国证监会认可的其他发行方式'); INSERT INTO `issue_mode` VALUES ('4', '市值申购,网下询价配售,网上定价发行', '网下向配售对象询价配售和网上按市值申购方式向社会公众投资者定价发行相结合的方式进行;或采用中国证监会核准的其他发行方式'); INSERT INTO `issue_mode` VALUES ('5', '市值申购,网下询价配售,网上定价发行', '采用网下向询价对象配售和网上向社会公众投资者定价发行相结合的方式或中国证监会认可的其他发行方式'); INSERT INTO `issue_mode` VALUES ('6', '市值申购,网下询价配售,网上定价发行', '本次发行采用网下向投资者询价配售和网上向持有深圳市场非限售A股和非限售存托凭证市值的社会公众投资者定价发行相结合的方式进行'); INSERT INTO `issue_mode` VALUES ('7', '市值申购,网下询价配售,网上定价发行', '采用网下向询价对象配售和网上向社会公众投资者定价发行相结合的方式'); INSERT INTO `issue_mode` VALUES ('8', '市值申购,网下询价配售,网上定价发行', '采用网下向投资者询价配售与网上按市值申购定价发行相结合的方式或证券监管部门认可的其他发行方式'); INSERT INTO `issue_mode` VALUES ('9', '市值申购,网下询价配售,网上定价发行', ' 采用网下向投资者询价配售和网上按市值申购向持有上海市场非限售A股份市值的社会公众投资者定价发行相结合的方式,或采用中国证监会核准的其他发行方式'); INSERT INTO `issue_mode` VALUES ('10', '市值申购,网下询价配售,网上定价发行', '采用网下向询价对象配售和网上向社会公众投资者定价发行相结合的方式或中国证监会认可的其他方式'); -- ---------------------------- -- Table structure for issue_status -- ---------------------------- DROP TABLE IF EXISTS `issue_status`; CREATE TABLE `issue_status` ( `status_id` int(11) NOT NULL AUTO_INCREMENT, `stock_code` varchar(255) DEFAULT NULL, `stock_name` varchar(255) DEFAULT NULL, `purchase_code` varchar(255) DEFAULT NULL, `listing_place` varchar(255) DEFAULT NULL, `issue_price` double DEFAULT NULL, `ipo_pe_ratio` double DEFAULT NULL, `pe_ratio_reference_industry` varchar(255) DEFAULT NULL, `reference_industry_pe_ratio` double DEFAULT NULL, `issue_face_value` double DEFAULT NULL COMMENT '发行面值(元)', `total_actual_fund_raised` double DEFAULT NULL COMMENT '实际募集资金总额(亿元)', `online_release_date` date DEFAULT NULL COMMENT '网上发行日期', `offline_distribution_date` date DEFAULT NULL COMMENT '网下配售日期', `number_online_issuance` int(11) DEFAULT NULL COMMENT '网上发行数量(股)', `offline_distribution_quantity` int(11) DEFAULT NULL COMMENT '网下配售数量(股)', `number_old_stock_transfers` int(11) DEFAULT NULL COMMENT '老股转让数量(股)', `total_issue_quantity` int(11) DEFAULT NULL COMMENT '总发行数量(股)', `purchase_limit` int(11) DEFAULT NULL COMMENT '申购数量上限(股)', `payment_date` date DEFAULT NULL COMMENT '中签缴款日期', `online_market_capitalization` double DEFAULT NULL COMMENT '网上顶格申购需配市值(万元)', `online_purchase_market_value_confirm_date` date DEFAULT NULL COMMENT '网上申购市值确认日', `offline_purchase_market_value` double DEFAULT NULL COMMENT '网下申购需配市值(万元)', `offline_purchase_market_value_confirm_date` date DEFAULT NULL COMMENT '网下申购市值确认日', PRIMARY KEY (`status_id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of issue_status -- ---------------------------- INSERT INTO `issue_status` VALUES ('1', '603681', '永冠新材', '732681', '上海证券交易所', '10', '22.98', '化学原料和化学制品制造业', '17.6', '1', '4.16', '2019-03-14', '2019-03-14', '16659000', '24988901', null, '41647901', '16000', '2019-03-18', '16', null, '6000', '2019-02-12'); INSERT INTO `issue_status` VALUES ('2', '002958', '青农商行', '002958', '深证证券交易所', '3.96', '10.74', '货币金融服务', '6.79', '1', '22', '2019-03-13', '2019-03-13', '166666500', '388889056', null, '555555556', '166500', '2019-03-15', '166.5', null, '1000', '2019-02-12'); INSERT INTO `issue_status` VALUES ('3', '002950 ', '奥美医疗', '002950', '深圳证券交易所 ', '11.03', '22.03', '专用设备制造业', '35.53', '1', '5.29', '2019-02-27', '2019-02-27', '43200000', '4800000', null, '48000000', '14000', '2019-03-01', '14', null, '1000', '2019-02-19'); INSERT INTO `issue_status` VALUES ('4', '300761', '立华股份', '300761', '深圳证券交易所', '29.35', '16.05', '畜牧业', '26.63', '1', '12.12', '2019-01-30', '2019-01-30', '37152000', '4128000', null, '41280000', '12000', '2019-02-01', '12', null, '1000', '2019-01-22'); INSERT INTO `issue_status` VALUES ('5', '600928', ' 西安银行', '730928', '上海证券交易所', '4.68', '10.28', '货币金融服务', '6.49', '1', '20.8', '2019-02-19', '2019-02-19', '400001000', '44443445', null, '44444445', '133000', '2019-02-21', '133', null, '1000', '2019-01-15'); INSERT INTO `issue_status` VALUES ('6', '300758', '七彩化学', '300758', '深圳证券交易所', '22.09', '22.99', '化学原料和化学制品制造业', '17.11', '1', '5.89', '2019-02-13', '2019-02-13', '24012000', '2668000', null, '26680000', '10500', '2019-02-15', '10.5', null, '1000', '2019-01-09'); INSERT INTO `issue_status` VALUES ('7', '002949', '华阳国际', '002949', '深圳证券交易所', '10.51', '22.99', '专业技术服务业', '30.11', '1', '5.15', '2019-02-13', '2019-02-13', '44127000', '4903000', null, '49030000', '19500', '2019-02-15', '19.5', null, '1000', '2019-01-29'); INSERT INTO `issue_status` VALUES ('8', '603956', '威派格', '732956', '上海证券交易所', '5.7', '22.97', '专用设备制造业', '33.9', '1', '2.43', '2019-02-12', '2019-02-12', '38337000', '4259100', null, '42596100', '12000', '2019-02-14', '12', null, '6000', '2019-01-28'); INSERT INTO `issue_status` VALUES ('9', '601865', '福莱特', '780865', '上海证券交易所', '2', '9.56', '非金属矿物制品业', '15.45', '0.25', '3', '2019-01-29', '2019-01-29', '135000000', '15000000', null, '150000000', '45000', '2019-01-31', '45', null, '5000', '2019-01-21'); INSERT INTO `issue_status` VALUES ('10', '002947', '恒铭达', '002947', '深圳证券交易所', '18.72', '22.99', '计算机、通信和其他电子设备制造业', '25.47', '1', '5.69', '2019-01-23', '2019-01-23', '27340500', '3037503', null, '30378003', '12000', '2019-01-25', '12', null, '1000', '2019-01-14'); -- ---------------------------- -- Table structure for new_stock_market -- ---------------------------- DROP TABLE IF EXISTS `new_stock_market`; CREATE TABLE `new_stock_market` ( `new_stock_id` int(11) NOT NULL AUTO_INCREMENT, `corporate_name` varchar(255) DEFAULT NULL, `declaration_date` date DEFAULT NULL, `meet_date` date DEFAULT NULL, `current_state` varchar(255) DEFAULT NULL, `purchase_date` date DEFAULT NULL, `quantity_issued` double DEFAULT NULL, `place_listed` varchar(255) DEFAULT NULL, `underwriter` varchar(255) DEFAULT NULL, `declaration_form` varchar(255) DEFAULT NULL, PRIMARY KEY (`new_stock_id`) ) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of new_stock_market -- ---------------------------- INSERT INTO `new_stock_market` VALUES ('1', '南通超达装备股份有限公司', '2018-11-02', '2019-01-29', '上会未通过', null, '1820', '上交所', '中泰证券', null); INSERT INTO `new_stock_market` VALUES ('2', '广东南方新媒体股份有限公司', '2018-07-06', '2019-01-29', '上会通过', null, '3210', '创业板', '华西证券', null); INSERT INTO `new_stock_market` VALUES ('3', '信利光电股份有限公司', '2017-12-19', '2019-01-29', '上会未通过', null, '8000', '中小板', '中国银河证券', null); INSERT INTO `new_stock_market` VALUES ('4', '江苏国茂减速机股份有限公司', '2018-04-23', '2019-01-15', '暂缓表决', null, '15000', '上交所', '国泰君安证券', null); INSERT INTO `new_stock_market` VALUES ('5', '南京泉峰汽车精密技术股份有限公司', '2018-07-31', '2019-01-08', '上会通过', null, '5000', '上交所', '中国国际金融证券', null); INSERT INTO `new_stock_market` VALUES ('6', '云南震安减震科技股份有限公司', '2018-06-15', '2019-01-08', '上会通过', null, '2000', '创业板', '民生证券', null); INSERT INTO `new_stock_market` VALUES ('7', '博通集成电路(上海)股份有限公司', '2018-05-18', '2019-01-03', '上会通过', null, '3467.84', '上交所', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('8', '亚世光电股份有限公司', '2018-04-09', '2019-01-03', '上会通过', null, '1927', '中小板', '招商证券', null); INSERT INTO `new_stock_market` VALUES ('9', '奥美医疗用品股份有限公司', '2018-06-05', '2018-12-25', '上会通过', '2019-02-27', '4800', '中小板', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('10', '厦门纵横集团股份有限公司', '2018-03-26', '2018-12-25', '取消审核', null, '5834', '上交所', '太平洋证券', null); INSERT INTO `new_stock_market` VALUES ('11', '宁波锦浪新能源科技股份有限公司', '2018-05-11', '2018-12-21', '上会通过', null, '2000', '创业板', '海通证券', null); INSERT INTO `new_stock_market` VALUES ('12', '苏州富士莱医药股份有限公司', '2018-10-18', '2018-12-18', '上会未通过', null, '2200', '上交所', '华林证券', null); INSERT INTO `new_stock_market` VALUES ('13', '上海永冠众诚新材料科技(集团)股份有限公司', '2018-04-09', '2018-12-18', '上会通过', '2019-03-14', '4164.79', '上交所', '东兴证券', null); INSERT INTO `new_stock_market` VALUES ('14', '中创物流股份有限公司', '2018-03-26', '2018-12-18', '上会通过', null, '6666.67', '上交所', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('15', '浙江三美化工股份有限公司', '2018-10-18', '2018-12-11', '上会通过', null, '5973.38', '上交所', '长江证券', null); INSERT INTO `new_stock_market` VALUES ('16', '石药集团新诺威制药股份有限公司', '2018-09-07', '2018-12-11', '上会通过', null, '5000', '创业板', '安信证券', null); INSERT INTO `new_stock_market` VALUES ('17', '浙江每日互动网络科技股份有限公司', '2018-05-02', '2018-12-11', '上会通过', null, '4010', '创业板', '东方花旗证券', null); INSERT INTO `new_stock_market` VALUES ('18', '四川金时科技股份有限公司', '2018-08-22', '2018-12-04', '上会通过', null, '4500', '中小板', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('19', '上海威派格智慧水务股份有限公司', '2018-07-24', '2018-12-04', '上会通过', '2019-02-12', '4259.61', '上交所', '中信建投证券', null); INSERT INTO `new_stock_market` VALUES ('20', '常州银河世纪微电子股份有限公司', '2018-04-12', '2018-12-04', '上会未通过', null, '3193.34', '创业板', '中信建投证券', null); INSERT INTO `new_stock_market` VALUES ('21', '深圳市华阳国际工程设计股份有限公司', '2018-07-13', '2018-11-27', '上会通过', '2019-02-13', '4903', '中小板', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('22', '国科恒泰(北京)医疗科技股份有限公司', '2018-05-15', '2018-11-27', '上会未通过', null, '5000', '上交所', '长城证券', null); INSERT INTO `new_stock_market` VALUES ('23', '上海瀚讯信息技术股份有限公司', '2018-03-29', '2018-11-27', '上会通过', null, '3336', '创业板', '长城证券', null); INSERT INTO `new_stock_market` VALUES ('24', '陕西西凤酒股份有限公司', '2018-05-02', '2018-11-20', '取消审核', null, '10000', '上交所', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('25', '青岛农村商业银行股份有限公司', '2018-01-10', '2018-11-20', '上会通过', '2019-03-13', '0', '中小板', '招商证券', null); INSERT INTO `new_stock_market` VALUES ('26', '江苏立华牧业股份有限公司', '2017-11-14', '2018-11-20', '上会通过', '2019-01-30', '5000', '创业板', '中泰证券', null); INSERT INTO `new_stock_market` VALUES ('27', '明阳智慧能源集团股份公司', '2018-07-20', '2018-11-13', '上会通过', '2019-01-11', '27590', '上交所', '申万宏源证券', null); INSERT INTO `new_stock_market` VALUES ('28', '苏州恒铭达电子科技股份有限公司', '2018-05-11', '2018-11-13', '上会通过', '2019-01-23', '3037.8', '中小板', '国金证券', null); INSERT INTO `new_stock_market` VALUES ('29', '华致酒行连锁管理股份有限公司', '2017-10-25', '2018-11-13', '上会通过', '2019-01-17', '5788.87', '创业板', '西部证券', null); INSERT INTO `new_stock_market` VALUES ('30', '广东日丰电缆股份有限公司', '2018-05-24', '2018-11-06', '取消审核', null, '4302', '中小板', '东莞证券', null); INSERT INTO `new_stock_market` VALUES ('31', '康龙化成(北京)新药技术股份有限公司', '2018-04-13', '2018-11-06', '上会通过', '2019-01-15', '6563', '创业板', '东方花旗证券', null); INSERT INTO `new_stock_market` VALUES ('32', '鞍山七彩化学股份有限公司', '2018-04-12', '2018-11-06', '上会通过', '2019-02-13', '2668', '创业板', '长江证券', null); INSERT INTO `new_stock_market` VALUES ('33', '罗博特科智能科技股份有限公司', '2018-04-09', '2018-10-30', '上会通过', '2018-12-26', '2000', '创业板', '民生证券', null); INSERT INTO `new_stock_market` VALUES ('34', '西安银行股份有限公司', '2018-03-29', '2018-10-30', '上会通过', '2018-02-19', '133333.33', '上交所', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('35', '常州通宝光电股份有限公司', '2018-03-28', '2018-10-30', '取消审核', null, '1880', '创业板', '招商证券', null); INSERT INTO `new_stock_market` VALUES ('36', '苏州龙杰特种纤维股份有限公司', '2018-08-29', '2018-10-23', '上会通过', '2019-01-04', '2973.5', '上交所', '国信证券', null); INSERT INTO `new_stock_market` VALUES ('37', '浙江力邦合信智能制动系统股份有限公司', '2018-05-28', '2018-10-23', '上会未通过', null, '4200', '上交所', '中信证券', null); INSERT INTO `new_stock_market` VALUES ('38', '青岛蔚蓝生物股份有限公司', '2018-04-17', '2018-10-23', '上会通过', '2019-01-03', '3866.7', '上交所', '广发证券', null); INSERT INTO `new_stock_market` VALUES ('39', '上海秦森园林股份有限公司', '2018-01-17', '2018-10-10', '上会未通过', null, '7093.86', '上交所', '光大证券', null); INSERT INTO `new_stock_market` VALUES ('40', '有友食品股份有限公司', '2017-12-27', '2018-10-10', '上会通过', null, '7950', '上交所', '东北证券', null); INSERT INTO `new_stock_market` VALUES ('41', '珠海安联锐视科技股份有限公司', '2018-05-08', '2018-09-27', '上会未通过', null, '1720', '创业板', '兴业证券', null); -- ---------------------------- -- Table structure for purchase_status -- ---------------------------- DROP TABLE IF EXISTS `purchase_status`; CREATE TABLE `purchase_status` ( `status_id` int(11) NOT NULL AUTO_INCREMENT, `open_date` date DEFAULT NULL, `listing_date` date DEFAULT NULL, `lottery_rate_online_distribution` decimal(10,5) DEFAULT NULL, `lottery_rate_offline_distribution` decimal(10,5) DEFAULT NULL COMMENT '网下配售中签率', `date_announcement_result_successful_signature` date DEFAULT NULL COMMENT '中签结果公告日期', `subscription_multiples_offline_distribution` decimal(10,2) DEFAULT NULL COMMENT '网下配售认购倍数', `accumulated_number_quoted_shares` decimal(10,2) DEFAULT NULL COMMENT '初步询价累计报价股数(万股)', `accumulative_quotation_multiple` decimal(10,2) DEFAULT NULL COMMENT '初步询价累计报价倍数', `number_valid_online_subscribers` int(11) DEFAULT NULL COMMENT '网上有效申购户数(户)', `number_valid_offline_subscribers` int(11) DEFAULT NULL COMMENT '网下有效申购户数(户)', `number_effective_shares_purchased_online` decimal(10,2) DEFAULT NULL COMMENT '网上有效申购股数(万股)', `number_effective_shares_purchased_offline` decimal(10,2) DEFAULT NULL COMMENT '网上有效申购股数(万股)', PRIMARY KEY (`status_id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of purchase_status -- ---------------------------- INSERT INTO `purchase_status` VALUES ('1', '2019-03-18', null, null, null, '2019-03-18', null, '1686100.00', '675.00', null, null, null, null); INSERT INTO `purchase_status` VALUES ('2', '2019-03-15', null, null, null, '2019-03-15', null, '7335940.00', '189.00', null, null, null, null); INSERT INTO `purchase_status` VALUES ('3', '2019-03-01', null, '0.04138', '0.01650', '2019-03-01', '6054.00', '2956210.00', '879.82', '14085664', '4887', '10439091.40', '2906110.00'); INSERT INTO `purchase_status` VALUES ('4', '2019-02-01', '2019-02-18', '0.04884', '0.02850', '2019-02-01', '3512.79', '1470100.00', '508.76', '10366519', '4933', '7606878.55', '1450080.00'); INSERT INTO `purchase_status` VALUES ('5', '2019-02-21', '2019-03-01', '0.20840', '0.03840', '2019-02-21', '2602.21', '12057210.00', '387.55', '12188695', '4079', '19194034.90', '11565100.00'); INSERT INTO `purchase_status` VALUES ('6', '2019-02-15', '2019-02-22', '0.03096', '0.02790', '2019-02-15', '3579.76', '1475680.00', '921.84', '11591176', '3240', '7755297.05', '955080.00'); INSERT INTO `purchase_status` VALUES ('7', '2019-02-15', '2019-02-26', '0.03745', '0.01810', '2019-02-15', '5520.64', '2770370.00', '941.73', '13265840', '4565', '11782637.75', '2706770.00'); INSERT INTO `purchase_status` VALUES ('8', '2019-02-14', '2019-02-22', '0.04929', '0.01100', '2019-02-14', '9122.70', '3944250.00', '1322.77', '11652780', '3903', '7778144.80', '3885450.00'); INSERT INTO `purchase_status` VALUES ('9', '2019-01-31', '2019-02-15', '0.10196', '0.01120', '2019-01-31', '8903.99', '13481980.00', '1284.00', '10877522', '4457', '13240844.10', '13355980.00'); INSERT INTO `purchase_status` VALUES ('10', '2019-01-25', '2019-02-01', '0.03216', '0.02100', '2019-01-25', '4769.31', '1496160.00', '820.85', '12188031', '4860', '8500135.75', '1448680.00'); -- ---------------------------- -- Table structure for research_report -- ---------------------------- DROP TABLE IF EXISTS `research_report`; CREATE TABLE `research_report` ( `report_id` int(11) NOT NULL AUTO_INCREMENT, `report_title` varchar(255) DEFAULT NULL COMMENT '研报', `organization_name` varchar(255) DEFAULT NULL COMMENT '机构名称', `rating_change` varchar(255) DEFAULT NULL COMMENT '评级变动', `rating_category` varchar(255) DEFAULT NULL COMMENT '评级类别', `report_date` date DEFAULT NULL COMMENT '报告日期', `report_industry` int(11) NOT NULL, PRIMARY KEY (`report_id`), KEY `report_industry` (`report_industry`), CONSTRAINT `research_report_ibfk_1` FOREIGN KEY (`report_industry`) REFERENCES `industry_section` (`section_id`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of research_report -- ---------------------------- INSERT INTO `research_report` VALUES ('1', '储能设备行业重大事项点评:广东调频辅助服务市场启动,储能市场再迎利好', '华创证券', '维持', '持有', '2018-08-22', '1'); INSERT INTO `research_report` VALUES ('2', '国防军工2018行业投资策略:站在军工高景气周期的起点', '天风证券', '无', '增持', '2017-12-12', '1'); INSERT INTO `research_report` VALUES ('3', '国防军工行业事件点评:美国重返月球 太空经济启航', '东兴证券', '维持', '持有', '2017-12-12', '1'); INSERT INTO `research_report` VALUES ('4', '多元金融行业简评:资金信托新规呼之欲出,关注信托基本面改善进程', '中信建投', '调高', '增持', '2019-03-01', '40'); INSERT INTO `research_report` VALUES ('5', '证券行业事件点评:资本市场改革与制度创新有序推进,券商拥抱发展良机', '中银国际', '无', null, '2019-02-28', '40'); INSERT INTO `research_report` VALUES ('6', '非银金融:粤港澳大湾区专题报告-险种迎发展机遇 金融政策持续向好', '平安证券', '维持', '持有', '2019-02-28', '40'); INSERT INTO `research_report` VALUES ('7', '证监会2月27日新闻发布会解析:奠定监管基调,引导行业改善发展', '华泰证券', '维持', '增持', '2019-02-28', '40'); INSERT INTO `research_report` VALUES ('8', '非银行金融专业:关于《证券基金经营机...', '长城证券', '维持', '持有', '2019-02-27', '40'); INSERT INTO `research_report` VALUES ('9', '非银行金融行业:交投活跃度提升,券商Beta业绩贡献显著', '东方证券', '维持', '持有', '2019-02-27', '40'); INSERT INTO `research_report` VALUES ('10', '轻工行业周报:底部推荐并继续看好裕同科技和盈趣科技', '中泰证券', '维持', '增持', '2019-02-28', '2'); INSERT INTO `research_report` VALUES ('11', '包装印刷行业研究报告:包装行业投资逻辑: 按海外巨头发展之图,', '东吴证券', '首次', '增持', '2018-09-12', '2'); INSERT INTO `research_report` VALUES ('12', '保险行业即时点评:投资端持续改善,价值增长前景可期', '华泰证券', '维持', '增持', '2019-02-28', '3'); INSERT INTO `research_report` VALUES ('13', '保险行业跟踪报告:牛市如何配保险?', '华创证券', '维持', '持有', '2019-02-26', '3'); INSERT INTO `research_report` VALUES ('14', '上市险企1月保费数据点评:寿险负债端好转,财险增速超预期', '中信建投', '维持', '买入', '2019-02-22', '3'); INSERT INTO `research_report` VALUES ('15', '2019年1月上市险企保费收入综评:寿险略显压力,产险继续向好', '群益证券', '无', null, '2019-02-22', '3'); INSERT INTO `research_report` VALUES ('16', '保险行业点评:保费端和利率端预期正在好转,大湾区建设对于保险业', '天风证券', '维持', '增持', '2019-02-19', '3'); INSERT INTO `research_report` VALUES ('17', '2019年1月上市险企保费数据点评:新单承压下NBV增速预期平稳关注', '申万宏源', '无', '持有', '2019-02-18', '3'); INSERT INTO `research_report` VALUES ('18', '保险业2018年报前瞻:龙头险企保费与价值稳定增长,投资收益波动', '申万宏源', '无', '持有', '2019-02-11', '3'); INSERT INTO `research_report` VALUES ('19', '保险行业2018年年报业绩前瞻:低估值已反映悲观预期边际改善凸显', '平安证券', '维持', '持有', '2019-02-11', '3'); INSERT INTO `research_report` VALUES ('20', '保险行业:2019年年度投资策略:保险结构持续改善,估值底部边际凸', '华融证券', '首次', '持有', '2019-02-01', '3'); INSERT INTO `research_report` VALUES ('21', '中国寿险市场:下一个五年的增长引擎:产品保障升级与创新', '麦肯锡咨询', '无', null, '2019-02-01', '3'); INSERT INTO `research_report` VALUES ('22', '保险行业重大事件快评:短期波动不掩长期价值', '国信证券', '无', '增持', '2019-01-31', '3'); INSERT INTO `research_report` VALUES ('23', '12月保费数据点评:保费增速缓行,新单保费平安实现正增长', '中银国际', '无', null, '2019-01-30', '3'); INSERT INTO `research_report` VALUES ('24', '关于保险投资端松绑事项的点评:新规投资端松绑有望缓解市场投资', '长城证券', '无', null, '2019-01-30', '3'); INSERT INTO `research_report` VALUES ('25', '保险行业1-12月数据点评:人身险翘尾收官,财险增速仍下滑', '万联证券', '维持', '增持', '2019-01-30', '3'); INSERT INTO `research_report` VALUES ('26', '保险行业跟踪报告:增速回暖,利率还寒‚最难将息', '华创证券', '维持', '持有', '2019-01-25', '3'); -- ---------------------------- -- Table structure for stock -- ---------------------------- DROP TABLE IF EXISTS `stock`; CREATE TABLE `stock` ( `stock_id` int(11) NOT NULL AUTO_INCREMENT, `stock_code` varchar(255) DEFAULT NULL COMMENT '股票代码', `stock_name` varchar(255) DEFAULT NULL COMMENT '股票简称', `purchase_code` varchar(255) DEFAULT NULL COMMENT '申购代码', `total_num` int(11) DEFAULT NULL, `online_distribution` int(11) DEFAULT NULL COMMENT '网上发行', `market_capitalization` double DEFAULT NULL, `purchase_ceiling` double DEFAULT NULL, `issue_price` double DEFAULT NULL, `latest_price` double DEFAULT NULL, `first_day_close` double DEFAULT NULL, `purchase_date` date DEFAULT NULL, `date_publication_winning_number` date DEFAULT NULL, `date_successful_payment` date DEFAULT NULL, `listing_date` date DEFAULT NULL, `announcement_date_online_signing_rate` date DEFAULT NULL, `ipo_pe_ratio` double DEFAULT NULL, `winning_rate` double DEFAULT NULL, `money_for_each` int(11) DEFAULT NULL, `frozen_funds_online` int(11) DEFAULT NULL, `frozen_funds_offline` int(11) DEFAULT NULL, `frozen_funds` int(11) DEFAULT NULL, `first_day_open` double DEFAULT NULL, `first_day_gain` varchar(255) DEFAULT NULL, `turnover_rate` varchar(255) DEFAULT NULL, `sum_money` int(11) DEFAULT NULL, `thaw_date` date DEFAULT NULL, PRIMARY KEY (`stock_id`), KEY `stock_code` (`stock_code`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of stock -- ---------------------------- INSERT INTO `stock` VALUES ('1', '603681', '永冠新材', '732681', '4165', '1666', '16', '1.6', '10', '10', null, '2019-03-14', '2019-03-18', '2019-03-18', null, null, '22.98', null, '415', '125', '155', '4865', '3.5', '45%', '20%', '486', null); INSERT INTO `stock` VALUES ('2', '002958', '青农商行', '002958', '55556', '16667', '166.5', '16.65', '3.96', '3.96', null, '2019-03-13', '2019-03-15', '2019-03-15', null, null, '10.74', null, '820', '851', '412', '487', '1.5', '25%', '25%', '456', null); INSERT INTO `stock` VALUES ('3', '002950', '奥美医疗', '002950', '4800', '1440', '14', '1.4', '11.03', null, null, '2019-02-27', '2019-03-01', '2019-03-01', null, null, '22.03', null, '96', '434', '451', '4697', null, '69%', '14%', '485', '2019-02-15'); INSERT INTO `stock` VALUES ('4', '600928', '西安银行', '730928', '44444', '40000', '133', '13.3', '4.68', '4.68', null, '2019-02-19', '2019-02-21', '2019-01-21', '2019-03-01', '2019-02-20', '10.28', '0.2084', '167', '361', '125', '416', null, '54%', '36%', '745', null); INSERT INTO `stock` VALUES ('5', '300758', '七彩化学', '300758', '2668', '2401', '10.5', '1.05', '22.09', '31.81', null, '2019-02-13', '2019-02-15', '2019-02-15', '2019-02-22', null, '22.99', '0.031', '161', '145', '412', '8964', '6.2', '48%', '14%', '756', null); INSERT INTO `stock` VALUES ('6', '002949', '华阳国际', '002949', '4903', '4413', '19.5', '1.95', '10.51', '10.51', null, '2019-02-13', '2019-02-15', '2019-02-15', '2019-02-26', '2019-03-02', '22.99', '0.0375', '119', '145', '451', '4946', '4.3', '36%', '15%', '478', '2019-02-22'); INSERT INTO `stock` VALUES ('7', '603956', '威派格', '732956', '4260', '3834', '12', '1.2', '5.7', '8.21', '0.001', '2019-02-12', '2019-02-14', '2019-02-14', '2019-02-22', null, '22.97', '0.0493', '176', '545', '124', '794', '0.4', '45%', '45%', '964', null); INSERT INTO `stock` VALUES ('8', '300761', '立华股份', '300761', '4128', '3715', '12', '1.2', '29.35', '61.88', '42.26', '2019-01-30', '2019-02-01', '2019-02-01', '2019-02-18', null, '16.05', '0.0488', '111', '264', '450', '4671', '0.9', '48%', '34%', '874', '2019-02-23'); INSERT INTO `stock` VALUES ('9', '601865', '福莱特', '780865', '15000', '13500', '45', '4.5', '2', '4.64', '2.88', '2019-01-29', '2019-01-31', '2019-01-31', '2019-02-15', '2019-02-28', '9.56', '0.102', '104', '256', '145', '1647', '1.25', '48%', '15%', '415', null); INSERT INTO `stock` VALUES ('10', '002947', '恒铭达', '002947', '3038', '2734', '12', '1.2', '18.72', '53.6', '26.96', '2019-01-23', '2019-01-25', '2019-01-25', '2019-02-01', null, '22.99', '0.0322', '107', '456', '156', '3512', '3.36', '47%', '15%', '784', null); INSERT INTO `stock` VALUES ('11', '300755', '华致酒行', '300755', '5789', '5210', '23', '2.3', '16.79', '28.66', '24.18', '2019-01-17', '2019-01-21', '2019-01-21', '2019-01-29', null, '22.98', '0.0467', '198', '452', '145', '451', '2.28', '36%', '41%', '876', '2019-02-24'); INSERT INTO `stock` VALUES ('12', '603351', '威尔药业', '732351', '1667', '1667', '16', '1.6', '35.5', '60.21', '51.12', '2019-01-16', '2019-01-18', '2019-01-18', '2019-01-30', '2019-02-20', '22.99', '0.0183', '163', '147', '136', '1547', '1.35', '49%', '14%', '786', null); INSERT INTO `stock` VALUES ('13', '002946', '新乳业', '002946', '8537', '7683', '25.5', '2.55', '5.45', '18.91', '7.85', '2019-01-16', '2019-01-18', '2019-01-18', '2019-01-25', null, '22.96', '0.0602', '255', '156', '149', '1546', '1.01', '48%', '35%', '784', null); INSERT INTO `stock` VALUES ('14', '300759', '康龙化成', '300759', '6563', '5907', '19.5', '1.95', '7.66', '37.29', '11.03', '2019-01-15', '2019-01-17', '2019-01-17', '2019-01-28', '2019-02-26', '22.99', '0.0567', '389', '457', '105', '4613', '2.05', '44%', '28%', '786', null); -- ---------------------------- -- Table structure for stock_items -- ---------------------------- DROP TABLE IF EXISTS `stock_items`; CREATE TABLE `stock_items` ( `itme_id` int(11) NOT NULL AUTO_INCREMENT, `issue_status` int(11) DEFAULT NULL, `stock_code` varchar(11) DEFAULT NULL, `issue_mode` int(11) DEFAULT NULL, `purchase_status` int(11) DEFAULT NULL, `items_underwriter` int(11) DEFAULT NULL, `items_ballot` int(11) DEFAULT NULL, `items_perform` int(11) DEFAULT NULL, `business_scope` varchar(255) DEFAULT NULL, `main_business` varchar(255) DEFAULT NULL, PRIMARY KEY (`itme_id`), KEY `issue_status` (`issue_status`), KEY `issue_mode` (`issue_mode`), KEY `purchase_status` (`purchase_status`), KEY `stock_items_ibfk_2` (`stock_code`), KEY `items_underwriter` (`items_underwriter`), KEY `items_ballot` (`items_ballot`), KEY `items_perform` (`items_perform`), CONSTRAINT `stock_items_ibfk_1` FOREIGN KEY (`issue_status`) REFERENCES `issue_status` (`status_id`), CONSTRAINT `stock_items_ibfk_2` FOREIGN KEY (`stock_code`) REFERENCES `stock` (`stock_code`), CONSTRAINT `stock_items_ibfk_3` FOREIGN KEY (`issue_mode`) REFERENCES `issue_mode` (`mode_id`), CONSTRAINT `stock_items_ibfk_4` FOREIGN KEY (`purchase_status`) REFERENCES `purchase_status` (`status_id`), CONSTRAINT `stock_items_ibfk_5` FOREIGN KEY (`items_underwriter`) REFERENCES `underwriter` (`underwriter_id`), CONSTRAINT `stock_items_ibfk_6` FOREIGN KEY (`items_ballot`) REFERENCES `ballot_number` (`ballot_number_id`), CONSTRAINT `stock_items_ibfk_7` FOREIGN KEY (`items_perform`) REFERENCES `first_day_performance` (`performance_id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of stock_items -- ---------------------------- INSERT INTO `stock_items` VALUES ('1', '1', '603681', '1', '1', '1', null, null, '生产胶带,包装装潢印刷(限分支经营),经营本企业自产产品的出口业务和本企业所需的机械设备、零配件、原辅材料的进口业务(不另附进出口上面目录),销售橡胶制品、粘胶制品、日用百货、纸制品、胶带原纸,离型纸,化工产品及原料(除危险化学品)、纺织品 、离型膜、包装材料,实业投资,投资管理。但国家限制公司经营或禁止进出口的商品及技术除外。', '各类胶带产品的研发、生产和销售。'); INSERT INTO `stock_items` VALUES ('2', '2', '002958', '2', '2', '6', null, null, '吸收本外币公众存款;发放本外币短期、中期和长期贷款;办理国内外结算;办理票据承兑与贴现;代理发行、代理兑付、承销政府债券;买卖政府债券、金融债券;从事本外币同业拆借;从事银行卡(借记卡)业务; 代理收付款项及代理保险业务;提供保管箱服务; 外汇汇款; 买卖、代理买卖外汇;提供信用证服务及担保; 外汇资信调查、咨询和见证业务;基金销售;经中国银行业监督管理委员会批准的其他业务。( 依法须经批准的项目,经相关部门批准后方可开展经营活动)。', '本行主营业务主要包括公司银行业务、零售银行业务、资金业务及国际业务。'); INSERT INTO `stock_items` VALUES ('3', '3', '002950', '3', '3', '7', '1', null, '生产、销售、研发医用卫生材料、无纺布制品及其它医疗用品、卫生用品、体育用品、婴儿用品、纺织、服装;货物进出口贸易(不包括进口商品分销业务;国家限制公司经营或限制进出口的商品或技术除外);机械设备租赁;房屋出租;商务信息咨询服务、会务会展服务(按许可证或批准文件核定内容经营,未取得相关有效许可或批准文件的,不得经营)', '医用敷料等一次性医用耗材的研发、生产和销售'); INSERT INTO `stock_items` VALUES ('4', '4', '300761', '4', '4', '2', '2', '2', '鸡:雪山鸡(配套系)(祖代)生产(限分支机构生产)、鸡:雪山鸡(配套系)(父母代)经营(限分支机构经营)【国家禁止类的除外】;苗鸡、商品鸡饲养(限分支机构饲养);(肉鸡)配合饲料生产;粮食收购(限于自用)。商品鸡、饲料原料、饲料添加剂的国内采购、批发(不涉及国营贸易管理商品,涉及配额、许可证管理商品的,按国家有关规定办理申请)。(依法须经批准的项目,经相关部门批准后方可开展经营活动)', '黄羽鸡、生猪、肉鹅的生产与销售'); INSERT INTO `stock_items` VALUES ('5', '5', '600928', '5', '5', '3', '3', '3', '吸收公众存款;发放短期、中期和长期贷款;办理国内结算;办理票据贴现;发行金融债券;代理发行、代理兑付、承销政府债券;买卖政府债券;从事同业拆借;提供担保;代理收付款项及代理保险业务;提供保管箱业务;办理地方财政信用周转使用资金的委托贷款业务;外汇存款、外汇贷款、外汇汇款、外汇兑换、国际结算、外汇票据的承兑和贴现;结汇、售汇、代客外汇买卖;资信调查、咨询、见证业务;经中国银行业监督管理委员会批准的其他业务。', '金融业务、零售金融业务和资金业务等'); INSERT INTO `stock_items` VALUES ('6', '6', '300758', '6', '6', '4', '4', '4', '许可经营项目:1,8-萘二甲酸酐生产。一般经营项目:染、颜料和染、颜料中间体、水处理剂、化工机械、化工防腐剂、润滑剂、医药中间体、农药中间体、精细化工产品、化工原料生产销售。经营货物及技术进出口。(依法须经批准的项目,经相关部门批准后方可开展经营活动。)', '高性能有机颜料、溶剂染料及相关中间体的研发、生产与销售'); INSERT INTO `stock_items` VALUES ('7', '7', '002949', '7', '7', '5', '5', '5', '工程设计及咨询,工程监理,项目管理;工程总承包及所需设备材料的采购和销售;兴办实业(具体项目另行申报);经营进出口业务。(以上内容法律、行政法规、国务院决定禁止的项目除外,限制的项目取得许可后方可经营)。', '建筑设计和研发及其延伸业务'); INSERT INTO `stock_items` VALUES ('8', '8', '603956', '8', '8', '8', '6', '6', '在水资源专业领域内从事技术开发、技术咨询、技术转让、技术服务,给排水成套设备、金属制品生产、销售,直饮水设备生产、销售,软件开发、销售,机电设备、电气设备、五金交电批兼零,普通机电设备维修,商务信息咨询,从事货物及技术的进出口业务,环保工程专业承包、机电安装建设工程施工,电子建设工程专业施工,建筑智能化建设工程专业施工,建筑装修装饰建设工程专业施工。(依法须经批准的项目,经相关部门批准后方可开展经营活动)', '从事二次供水设备的研发、生产、销售与服务,同时公司逐步开展二次供水智慧管理平台系统的研发、搭建和运维,为二次供水设备的集中化管理提供支持'); INSERT INTO `stock_items` VALUES ('9', '9', '601865', '9', '9', '9', '7', '7', '特种玻璃、镜子、玻璃制品的生产,建筑材料、贵金属的批发,码头货物装卸服务,玻璃、镜子、设备、玻璃原材料及相关辅料、玻璃窑炉材料的进出口业务。以上涉及许可证的凭证经营。', '光伏玻璃、浮法玻璃、工程玻璃和家居玻璃的研发、生产和销售,以及玻璃用石英矿的开采和销售和EPC光伏电站工程建设'); INSERT INTO `stock_items` VALUES ('10', '10', '002947', '10', '10', '10', '8', '8', '电子材料及器件、绝缘材料及器件、光学材料及器件、纳米材料及器件、精密结构件、纸制品的研发、设计、加工、生产、销售;货物及技术的进出口业务;包装装潢印刷品印刷(按《印刷许可证》核定范围核定类别经营)(前述经营项目中法律、行政法规规定前置许可经营、限制经营、禁止经营的除外)(依法须经批准的项目,经相关部门批准后方可开展经营活动)', '消费电子功能性器件、消费电子防护产品、消费电子外盒保护膜的设计、研发、生产与销售'); -- ---------------------------- -- Table structure for underwriter -- ---------------------------- DROP TABLE IF EXISTS `underwriter`; CREATE TABLE `underwriter` ( `underwriter_id` int(11) NOT NULL AUTO_INCREMENT, `lead_underwriter` varchar(255) DEFAULT NULL, `underwriter_manner` varchar(255) DEFAULT NULL, `preissue_net_assets_per_share` double DEFAULT NULL, `net_assets_per_share_after_issuance` double DEFAULT NULL, `dividend_policy` varchar(255) DEFAULT NULL, PRIMARY KEY (`underwriter_id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of underwriter -- ---------------------------- INSERT INTO `underwriter` VALUES ('1', '东兴证券股份有限公司', '余额包销', '6.97', '7.39', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('2', '中泰证券股份有限公司', '余额包销', '9.34', '11.23', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('3', '中信证券股份有限公司', '余额包销', '4.68', '4.66', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('4', '长江证券承销保荐有限公司', '余额包销', '5.78', '9.43', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('5', '中信证券股份有限公司', '余额包销', '3.38', '4.94', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('6', '招商证券股份有限公司', '余额包销', '3.95', '3.94', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('7', '中信证券股份有限公司 ', '余额包销', '3.28', '4.04', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('8', '中信建投证券股份有限公司', '余额包销', '1.97', '2.25', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('9', '广发证券股份有限公司', '余额包销', '1.92', '1.91', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('10', '国金证券股份有限公司', '余额包销', '5.12', '8.17', '股票发行前公司滚存未分配利润由发行后的新老股东按持股比例共享。'); INSERT INTO `underwriter` VALUES ('11', null, null, null, null, null); <file_sep>package com.no1.data.entity; public class StockItems { // itme_id int private int itemId; // issue_status int private IssueStatus issueStatus; // issue_mode int private IssueMode issueMode; // purchase_status private PurchaseStatus purchaseStatus; //items_underwriter int private Underwriter underwriter; //items_ballot private BallotNumber ballotNumber; //items_perform private FirstDayPerformance firstDayPerformance; // business_scope varchar 经营范围 private String businessScope; // main_business varchar 主营业务 private String mainBusiness; public String getBusinessScope() { return businessScope; } public void setBusinessScope(String businessScope) { this.businessScope = businessScope; } public String getMainBusiness() { return mainBusiness; } public void setMainBusiness(String mainBusiness) { this.mainBusiness = mainBusiness; } public FirstDayPerformance getFirstDayPerformance() { return firstDayPerformance; } public void setFirstDayPerformance(FirstDayPerformance firstDayPerformance) { this.firstDayPerformance = firstDayPerformance; } public BallotNumber getBallotNumber() { return ballotNumber; } public void setBallotNumber(BallotNumber ballotNumber) { this.ballotNumber = ballotNumber; } public Underwriter getUnderwriter() { return underwriter; } public void setUnderwriter(Underwriter underwriter) { this.underwriter = underwriter; } public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public IssueStatus getIssueStatus() { return issueStatus; } public void setIssueStatus(IssueStatus issueStatus) { this.issueStatus = issueStatus; } public IssueMode getIssueMode() { return issueMode; } public void setIssueMode(IssueMode issueMode) { this.issueMode = issueMode; } public PurchaseStatus getPurchaseStatus() { return purchaseStatus; } public void setPurchaseStatus(PurchaseStatus purchaseStatus) { this.purchaseStatus = purchaseStatus; } } <file_sep>package com.no1.data.service; import com.github.pagehelper.PageInfo; import com.no1.data.entity.NewStockMarket; public interface NewStockMarketService { /** * 获取新股上会数据,分页,排序 * @param currentPage 当前页 * @param pageSize 每页记录数 * @param sortValue 排序的字段 * @param sortOrder 排序方式 * @return */ public PageInfo<NewStockMarket> findItemByPage(int currentPage, int pageSize, String sortValue, String sortOrder); } <file_sep>package com.no1.data.entity; import java.util.List; public class IndustrySection { // section_id int private int sectionId; // section_name varchar private String sectionName; // latest_price double private Double latestPrice; // up_down_limit double private Double upDownLimit; // up_down_range varchar 涨跌幅 private String upDownRange; // total_market_value varchar 总市值 private Double totalMarketValue; // total_market_unit varchar 总市值单位 private String totalMarketUnit; // turnover_rate varchar 换手率 private String turnoverRate; // rising_number int 上涨家数 private Integer risingNumber; // drop_number int 下跌家数 private Integer dropNumber; // leading_stock varchar 领涨股票 private String leadingStock; // up_downs varchar 涨跌幅 private String upDowns; private List<ResearchReport> researchReportList; public int getSectionId() { return sectionId; } public void setSectionId(int sectionId) { this.sectionId = sectionId; } public String getSectionName() { return sectionName; } public void setSectionName(String sectionName) { this.sectionName = sectionName; } public Double getLatestPrice() { return latestPrice; } public void setLatestPrice(Double latestPrice) { this.latestPrice = latestPrice; } public Double getUpDownLimit() { return upDownLimit; } public void setUpDownLimit(Double upDownLimit) { this.upDownLimit = upDownLimit; } public String getUpDownRange() { return upDownRange; } public void setUpDownRange(String upDownRange) { this.upDownRange = upDownRange; } public Double getTotalMarketValue() { return totalMarketValue; } public void setTotalMarketValue(Double totalMarketValue) { this.totalMarketValue = totalMarketValue; } public String getTotalMarketUnit() { return totalMarketUnit; } public void setTotalMarketUnit(String totalMarketUnit) { this.totalMarketUnit = totalMarketUnit; } public String getTurnoverRate() { return turnoverRate; } public void setTurnoverRate(String turnoverRate) { this.turnoverRate = turnoverRate; } public Integer getRisingNumber() { return risingNumber; } public void setRisingNumber(Integer risingNumber) { this.risingNumber = risingNumber; } public Integer getDropNumber() { return dropNumber; } public void setDropNumber(Integer dropNumber) { this.dropNumber = dropNumber; } public String getLeadingStock() { return leadingStock; } public void setLeadingStock(String leadingStock) { this.leadingStock = leadingStock; } public String getUpDowns() { return upDowns; } public void setUpDowns(String upDowns) { this.upDowns = upDowns; } public List<ResearchReport> getResearchReportList() { return researchReportList; } public void setResearchReportList(List<ResearchReport> researchReportList) { this.researchReportList = researchReportList; } } <file_sep>package com.no1.data.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { /** * 跳转到新股数据解析页面 * @return */ @RequestMapping("/findAnalysisNewStockData") public String findAnalysisNewStockData(){ return "analysisNewStockData"; } /** * 跳转到新股日历页面 * @return */ @RequestMapping("/findNewStockCalendar") public String index(){ return "newStockCalendar"; } /** * 跳转到行业板块页面 * @return */ @RequestMapping("/industrySection") public String industrySection(){ return "industrySection"; } /** * 跳转到新股申购页面 * @return */ @RequestMapping("/stock") public String stock(){ return "stock"; } /** * 跳转到新股上会页面 * @return */ @RequestMapping("/newStockMarket") public String newStockMarket(){ return "newStockMarket"; } /** * 跳转到首页 * @return */ @RequestMapping("/hello") public String hello(){ return "industrySection"; } }
a80965b7ef6654eeb27fd2560c81b42318baf864
[ "Java", "SQL" ]
9
Java
niucyNo1/data
0c983e1b0cdd327aa0911a13f914dcba93ff45fb
be5d45f11ca5f0b6276ff0946093f4305e6ea3cb
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { TestLibService } from './test-lib.service'; @Component({ selector: 'lib-test-lib', template: ` <p> test-lib works!<br/> {{this.testLibService.label}} </p> `, styles: [] }) export class TestLibComponent implements OnInit { constructor(public testLibService: TestLibService) { } public ngOnInit() { this.testLibService.label = 'shared-service'; } }
55118da3460de90714037f5819488143a4b84361
[ "TypeScript" ]
1
TypeScript
sharkvik/test-lib
305d617b0769898ab2fc39e11af5c9e11ab83d1e
282804cad2d138652aff6d26e07f9f270b00c287
refs/heads/master
<repo_name>ShenJieSuzhou/AADSniffer<file_sep>/AADSniffer/Podfile target 'AADSniffer' do pod 'OpenCV', '~> 3.2.0' pod 'TesseractOCRiOS', '~> 4.0.0' end
7e2ce2b54d7e3b679268db858a94393358cbd367
[ "Ruby" ]
1
Ruby
ShenJieSuzhou/AADSniffer
ddb6d0568c06fdbb702ee32f31fadb4fc8862016
6e07e4282ce0f8292837ad3ad3f777a233d60f2b
refs/heads/master
<repo_name>IUMREDDY/Python-practical-2020-2021<file_sep>/practical_11.py import pickle try: with open("Books.dat", "rb") as f: BOOKS = pickle.load(f) except FileNotFoundError: BOOKS = [] def save(): with open("Books.dat", "wb") as f: pickle.dump(BOOKS, f) def insert_record(): book = {} book["number"] = int(input("Book Number: ")) book["name"] = input("Name: ") book["category"] = input("Category: ") book["page_count"] = int(input("Pages: ")) book["price"] = float(input("Price: ")) print() BOOKS.append(book) save() def read_records(lst=BOOKS): for book in lst: print("Book Number:", book["number"]) print("Name:", book["name"]) print("Category:", book["category"]) print("Pages:", book["page_count"]) print("Price:", book["price"], "\n") def get_sci_books(): sci_books = [] for book in BOOKS: if book["category"] == "sci": sci_books.append(book) read_records(sci_books) def get_books_price_great(): matching_books = [] for book in BOOKS: if book["price"] > 200: matching_books.append(book) read_records(matching_books) print("1: Insert Record") print("2: Display All Records") print("3: Display Books with Category 'sci'") print("4: Display Books with Price > 200") print("5: Exit\n") while True: choice = int(input("Choice: ")) print() if choice == 1: insert_record() elif choice == 2: read_records() elif choice == 3: get_sci_books() elif choice == 4: get_books_price_great() elif choice == 5: break <file_sep>/practical 4/shape/rectangle.py def p(l,b): p=2*(l+b) return float(p) def a(l,b): a=l*b return float(a) <file_sep>/practical 2.py from time import sleep #Sum of digits def sumd(): n=int(input("Enter the number:")) t=n sum=0 while t>0: r=t%10 sum=sum+r t//=10 print("The sum of the digits of",n,"is",sum) #Palindrome or not def pal(): num=int(input("Enter anything: ")) temp=num rev=0 while(num>0): dig=num%10 rev=rev*10+dig num=num//10 if(temp==rev): print("The number is palindrome.") else: print("The number is not a palindrome.") #Armstrong or not def arm(): n=int(input("Enter the number:")) t=n sum=0 while t>0: r=t%10 sum=sum+r**3 t//=10 if sum==n: print(n,"is an Armstrong") else: print(n,"is NOT an Armstrong") while True: print("1 for Palindrome or not \n2 for Sum of digits \n3 for Armstrong or not") print() ch=int(input("Enter your choice: ")) if ch==1: pal() if ch==2: sumd() if ch==3: arm() print() sleep(1)<file_sep>/practical_6.py def lin_search(): l=input("Enter the list: ").split() x=input("Element to be searched: ") print(f"List:{l}") for i in range(0,len(l)): if l[i]==x: return print (f"Element found at index: {i} ") return print("Element not found.") def bin_search(): l=eval(input("\nEnter the numbers : ")) l.sort() print(f"List:{l}") x=eval(input("Element to be searched: ")) left,right=0,len(l)-1 while left<=right: mid=(left+right)//2 if x==l[mid]: return print(f"Element found at index: {mid}") if x<l[mid]: right=mid-1 else: left=mid+1 return print("Element not found.") print("1- Linear search \n2- Binary search") print("3- Exit") while True: ch=int(input("Choice: ")) if ch==1: lin_search() if ch==2: bin_search() if ch==3: exit() print()<file_sep>/practical_5_mysql.py import mysql.connector as mc cnx = mc.connect(host="localhost",user="root", password="<PASSWORD>") cursor = cnx.cursor() cursor.execute("use practicals") def add_student(): name = input("Name: ") marks = input("Marks: ") print() add = "INSERT INTO student(name, marks) " "VALUES (%s, %s)" data = (name, int(marks)) cursor.execute(add,data) def remove_student(): name = input("Name: ").strip().title() remove= "DELETE FROM student WHERE name LIKE %s" data = (name,) cursor.execute(remove,data) print(f"Query OK. {cursor.rowcount} rows affected.\n") def display_student(): print("Leave blank to show all.") name = input("Name: ").strip().title() print() if name == "": display= "select * from student" student_data = tuple() else: display= "select * from student where name like %s" student_data = (name,) cursor.execute(display, student_data) match_list = cursor.fetchall() if match_list: for id_no, name_, marks in match_list: print(f"[{id_no}]{name_}: {marks}") print() else: print("No students found.\n") def modify_student(): name = input("Name: ").strip().title() marks = input("New Marks: ") modify= "update student SET marks=%s where name=%s" data = (int(marks), name) cursor.execute(modify,data) print(f"Query OK. {cursor.rowcount} rows affected.\n") print("1- Add student") print("2- Remove student") print("3- Display student Marks") print("4- Modify student Marks") print("5- Exit\n") while True: choice = input("choice: ") print() if choice == "1": add_student() elif choice == "2": remove_student() elif choice == "3": display_student() elif choice == "4": modify_student() elif choice == "5": cursor.close() cnx.close() break<file_sep>/practical_9/practical_9.py '''Write a python program to read the content of text file and display the total number of consonants, vowels, upper case letters, lower case letters, digits and special characters.''' f = open("para.txt") lines = f.readlines() f.close() vowels = ("a", "e", "i", "o", "u") c, v, u, l, d, s = 0,0,0,0,0,0 for line in lines: line = line.split() for word in line: for char in word: if char.isalpha(): if char in vowels: v += 1 if not char in vowels: c += 1 if char.isupper(): u += 1 if char.islower(): l += 1 if char.isdigit(): d += 1 if not char.isalnum(): s += 1 print("No. of consonants =",c) print("No. of vowels =",v) print("No. of digits =",d) print("No. of upper case =",u) print("No. of lower case =",l) print("No. of special =",s)<file_sep>/practical 4/shape/__init__.py from shape import rectangle from shape import circle<file_sep>/practical_10/practical_10.py '''10. Write a menu driven program using binary file a) Insert Student Record (Rollno, Name, Marks) b) Display Record c) Search based on Roll no d) Update Marks e) Delete a record f) Exit''' import pickle try: with open("bin.dat", "rb") as f: student_record = pickle.load(f) except FileNotFoundError: student_record = {} def save(): with open("bin.dat", "wb") as f: pickle.dump(student_record, f) def insert_record(): roll_no = int(input("Roll Number: ")) name = input("Name: ") marks = input("Marks: ") print() student_record[roll_no] = [name, marks] print("Record added.") def display_records(): if len(student_record) == 0: print("No students found.") else: print("Roll No | Name | Marks\n") for student in student_record: print(student, *student_record[student], sep=" | ") def search_for_record(): roll_no = int(input("Roll Number to search for: ")) print() if roll_no in student_record: print(roll_no, *student_record[roll_no], sep=" | ") else: print("Student not found.") def update_marks(): roll_no = int(input("Roll Number: ")) print() if roll_no in student_record: print(roll_no, *student_record[roll_no], sep=" | ") marks = int(input("New Marks: ")) student_record[roll_no][1] = marks else: print("Student not found.") def delete_record(): roll_no = int(input("Roll Number: ")) print() if roll_no in student_record: print(roll_no, *student_record[roll_no], sep=" | ") confirm = input("Confirm delete? (y/n): ") if confirm.lower() == "y": del student_record[roll_no] else: print("Student not found.") print("1: Insert Record") print("2: Display Records") print("3: Search based on Roll Number") print("4: Update Marks") print("5: Delete Record") print("6: Exit\n") while True: choice = int(input("Choice: ")) print() if choice == 1: insert_record() if choice == 2: display_records() if choice == 3: search_for_record() if choice == 4: update_marks() if choice == 5: delete_record() if choice == 6: break save() print() <file_sep>/practical_12.py import csv try: with open("employee.csv", "r", newline="") as csvfile: empreader = csv.reader(csvfile) EMPLOYEES = list(empreader) print(EMPLOYEES) except FileNotFoundError: EMPLOYEES = [] def save(): with open("employee.csv", "w", newline="") as csvfile: empwriter = csv.writer(csvfile) empwriter.writerows(EMPLOYEES) def new_employee(): emp_no = input("Employee Number: ") name = input("Name: ") salary = input("Salary: ") print() EMPLOYEES.append([emp_no, name, salary]) print(EMPLOYEES) save() def search_for_employee(): emp_no = input("Employee Number to Search for: ") print() for employee in EMPLOYEES: if employee[0] == emp_no: print("Name:", employee[1]) print("Salary:", employee[2], "\n") break else: print("Employee Not Found\n") print("1: Add New Employee") print("2: Search for Employee") print("3: Exit\n") print() while True: choice = input("Choice: ") if choice == "1": new_employee() elif choice == "2": search_for_employee() elif choice == "3": break <file_sep>/practical 4/shape/circle.py def p(r): p=2*22/7*r return p def a(r): a=22/7*r*r return a <file_sep>/practical_3.py from time import sleep def prime(): num=int(input("Enter the number: ")) if num>1: for i in range(2, num): if (num % i)==0: print(num,"is not a prime number") break else: print(num,"is a prime number") else: print(num,"is not a prime number") def perf(): num=int(input(" Please Enter any Number: ")) sum=0 for i in range(1,num): if(num%i==0): sum=sum+i if (sum==num): print(num,"is a Perfect Number") else: print(num,"is not a Perfect Number") while True: print("1 for Prime or not \n2 for Perfect or not") ch=int(input('Enter your choice: ')) if ch==1: prime() if ch==2: perf() print() sleep(1)<file_sep>/practical_8.py '''Write a python program to create a stack called Employee, to perform the basic operations on stack using list. The list contains two values – employee number and employee name.''' Employee = [[102,"sample1"],[103,"sample2"]] while True: print("\n1 Add\n2 Remove\n3 Show") ch = int(input("Enter your choice: ")) if ch == 1: num = int(input("Employee number: ")) name = input("Employee name: ") l = [num, name] Employee.append(l) if ch == 2: if Employee: print("Removed:",Employee.pop()) else: print("\nStack is empty") if ch == 3: for t in Employee[::-1]: print(t)<file_sep>/practical 1 .py student={} n=int(input("Enter number of winners: ")) print() for i in range(n): print(i+1) name=input("Enter name of winner: ") wins=int(input("Enter number of wins: ")) student[name]=wins print() print("Name of the winners","\t","Number of wins") for j in student: print(j,"\t","\t","\t",student[j]) <file_sep>/practical_7.py def bub_sort(l): n=len(l)-1 for i in range(n): for j in range(n-i): if l[j]>l[j+1]: l[j],l[j+1]=l[j+1],l[j] print(f"Sorted list: {l}") def insert_sort(l): for i in range(1,len(l)): while l[i-1]>l[i] and i>0: l[i],l[i-1]=l[i-1],l[i] i-=1 print(f"Sorted list: {l}") print("1- Bubble sort \n2- Insertion sort") print("3- Exit") while True: ch=int(input("Choice: ")) if ch==3: exit() l=eval(input("Enter the list: ")) if ch==1: bub_sort(l) if ch==2: insert_sort(l) print() "[25,34,0,987,65,43,234,567,89,0,369,48,45,7654]"<file_sep>/practical 4/pratical 4.py from time import sleep from shape import * print("1- Perimeter of Circle \n2- Area of Circle") print("3- Perimeter of Rectangle \n4- Area of Rectangle") print("5- Exit") while True: ch=int(input("Your choice: ")) if ch==1: r=float(input("Radius of the circle: ")) print("The perimeter is: ",circle.p(r)) if ch==2: r=float(input("Radius of the circle: ")) print("The area is: ",circle.a(r)) if ch==3: l=float(input("length: ")) b=float(input("breadth: ")) print("The perimeter is: ",rectangle.p(l,b)) if ch==4: l=float(input("length: ")) b=float(input("breadth: ")) print("The area is: ",rectangle.a(l,b)) if ch==5: exit() print() sleep(1)
3ba557267b0046c6817d76f238b99ef1e17ed583
[ "Python" ]
15
Python
IUMREDDY/Python-practical-2020-2021
432e9f00d8ad454a61ecd6ab9a1681833f2b0934
958c8031b2fea5dba7c32c65f015ee837b004989
refs/heads/master
<file_sep>var MyRoutes = require('./MyRoutes.js'); class PizarrasRoutes extends MyRoutes{ constructor(express, router, sql, bodyParser, config){ super(express, router, sql, bodyParser, config); //Alta Pizarra router.post('/altaPizarra', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Pizarras_Insert ' + ' @titulo = "' + req.body.titulo + '", @idEquipo = "' + req.body.idEquipo + '", @fechaInicio = "' + req.body.fechaInicio + '", @fechaFin = "' + req.body.fechaFin + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Modificar Pizarra router.post('/ModificarPizarra', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Pizarras_Update ' + ' @idPizarra = "' + req.body.idPizarra + '", @titulo = "' + req.body.titulo + '", @fechaInicio = "' + req.body.fechaInicio + '", @fechaFin = "' + req.body.fechaFin + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Borrar Pizarra router.post('/BorrarPizarra', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Pizarras_Delete @idPizarra = ' + req.body.idPizarra, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Consultar Pizarra de un equipo router.post('/consultarPizarra', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC ConsultarPizarraEquipo @idEquipo = ' + req.body.idEquipo, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); router.post('/consultarNotasPizarra', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC ConsultarNotasPizarra @idPizarra = ' + req.body.idPizarra, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Consultar Pizarras coincidentes router.post('/consultarPizarraCoincidentes', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Buscar_PizarrasCoincidentes' +' @idPizarra = "' + req.body.idPizarra +'", @fechaInicio = "' + req.body.fechaInicio +'", @fechaFin = "' + req.body.fechaFin +'", @idEquipo = "'+ req.body.idEquipo + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Consultar Pizarra activa de un usuario router.post('/consultarPizarraActivaUsuario', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC ConsultarPizarraActivaUsuario @idUsuario = ' + req.body.idUsuario, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Consultar Pizarra activa de un equipo router.post('/consultarPizarraActivaEquipo', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC ConsultarPizarraActivaEquipo @idEquipo = ' + req.body.idEquipo, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Listar pizarras de un equipo router.post('/pizarrasEquipo', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Listar_PizarrasDeUnEquipo @idEquipo = ' + req.body.idEquipo, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); } } module.exports = PizarrasRoutes; <file_sep>class MyRoutes { constructor(express, router, sql, bodyParser, config) { this.express = express; this.router = router; this.sql = bodyParser; this.config = config; } } module.exports = MyRoutes; <file_sep>var MyRoutes = require('./MyRoutes.js'); class LogrosRoutes extends MyRoutes{ constructor(express, router, sql, bodyParser, config){ super(express, router, sql, bodyParser, config); //Alta Logro router.post('/altaLogro', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Logros_Insert ' + ' @nombre = "' + req.body.nombre + '", @descripcion = "' + req.body.descripcion + '", @idEmpresa = "' + req.body.idEmpresa + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); router.post('/ganarLogro', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC GanarPremio ' + ' @idLogro = "' + req.body.idLogro + '", @idUsuario = "' + req.body.idUsuario + '", @fecha = "' + req.body.fecha + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Modificar Logro router.post('/modificarLogro', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Logros_Update ' + ' @idLogro = "' + req.body.idLogro + '", @nombre = "' + req.body.nombre + '", @descripcion = "' + req.body.descripcion + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Borrar Logro --> sp borra en la columna de LogroCondicion, LogroUsuario y Logro router.post('/borrarLogro', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Logros_Delete @idLogro = ' + req.body.idLogro, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Consultar logros de un usuario router.post('/consultarLogrosUsuario', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC ConsultarLogrosDeUnUsuario @idLogro = ' + req.body.idLogro, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Listar condiciones de un logro router.post('/condiciones', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC Listar_Condiciones @idLogro = ' + req.body.idLogro, (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Borrar La condicion de un logro --> usará el boton delete condicion router.post('/borrarLogroCondicion', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC LogrosCondiciones_delete ' + ' @idLogro = "' + req.body.idLogro + '", @idCondicion = "' + req.body.idCondicion + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); //Agregar condicion a un Logro router.post('/agregarCondicion', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query(' EXEC LogrosCondiciones_Insert ' + ' @idLogro = "' + req.body.idLogro + '", @idCondicion = "' + req.body.idCondicion + '", @idValor = "' + req.body.idValor + '", @puntuacion = "' + req.body.puntuacion + '", @modificador = "' + req.body.modificador + '", @excluyente = "' + req.body.excluyente + '"', (err, result) => { console.dir(result.recordset) console.log(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); } } module.exports = LogrosRoutes; <file_sep>const jwt = require('jsonwebtoken'); const secret = 'Fernandez'; const expirationTime = 50; exports.generateToken = (user) =>{ let userString = JSON.stringify(user); let token=jwt.sign({userID: user, exp:expirationTime }, secret); return token; }; exports.validateToken = (token) => { return new Promise((resolve, reject) => { jwt.verify(token, secret, (err, payload) => { if (err) { reject(err); }else{ resolve(payload); } }); }); };<file_sep>const UsuariosRoutes = require( './myRoutes/UsuariosRoutes'); const EquiposRoutes = require('./myRoutes/EquiposRoutes'); const ValoresRoutes = require('./myRoutes/ValoresRoutes'); const LogrosRoutes = require('./myRoutes/LogrosRoutes'); const EmpresasRoutes = require('./myRoutes/EmpresasRoutes'); const NotasRoutes = require('./myRoutes/NotasRoutes'); const PizarrasRoutes = require('./myRoutes/PizarrasRoutes'); var express = require('express'); var router = express.Router(); var sql = require('mssql'); var bodyParser = require('body-parser'); const config = { user: 'Usuario', password : '<PASSWORD>', server : "localhost\\SQLEXPRESS", port : 1433, database : 'OnBoardDataBase', options: { encrypt: true } }; //const pool = new sql.ConnectionPool(config); router.use(bodyParser.json()); let usuariosRoutes = new UsuariosRoutes(express, router, sql, bodyParser, config); let equiposRoutes = new EquiposRoutes(express, router, sql, bodyParser, config); let valoresRoutes = new ValoresRoutes(express, router, sql, bodyParser,config); let logrosRoutes = new LogrosRoutes(express, router, sql, bodyParser, config); let empresasRoutes = new EmpresasRoutes(express, router, sql, bodyParser, config); let notasRoutes = new NotasRoutes(express, router, sql, bodyParser, config); let pizarrasRoutes = new PizarrasRoutes(express, router, sql, bodyParser, config); /* GET function. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); //Listar empresas router.get('/empresas', function(req, res, next) { try{ sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .execute('OnBoardDataBase.dbo.Listar_Empresas', (err, result) => { console.log(result.recordset); //datos let datos = result.recordset; res.send({status: "OK", data: datos}); }); }) } catch(e){ console.log(e); res.send({ status: "error", message: e }); } }); //Listar usuarios por equipo router.post('/usuariosPorEquipo', function(req, res, next){ try { sql.connect(config, err => { if(err) console.log("Control de error"); new sql.Request() .query('EXEC Listar_UsuariosPorEquipo @idEquipo = ' + req.body.idEquipo, (err, result) => { console.dir(result.recordset) let datos = result.recordset; res.send( { status: "OK", data : datos } ); sql.close(); }); }); } catch(e) { console.log(e); res.send({ status: "error", message: e }); } }); module.exports = router;
9d8bbd46a8e97d056cec9d381e98b8e74b2ceec6
[ "JavaScript" ]
5
JavaScript
GerooMohedano/recognition-board-backend
1f0055bce5be15b5b20f5b43c7b0b47aff03fac7
90e41f153fedefb9b93107718b47d8a11029763d
refs/heads/master
<repo_name>githubwwp/dcmsxcx<file_sep>/src/main/webapp/util/ajaxUtil.js /* 公用ajax函数 */ function ajaxFun(url, datas, cb) { $.ajax({ url : url, type : "post", data : datas, success : function(json) { cb.call(this, json); }, error : function(xhr) { if (xhr.status == "404") { alert("404 Not Found"); } else if (xhr.status == "500") { alert("500 Servlet Exception"); } else { alert(xhr.status); } } }); } <file_sep>/src/main/java/dcmsxcx/service/manage/SessionManaService.java package dcmsxcx.service.manage; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Service; @Service public class SessionManaService { /** * 添加登录状态 * <p /> * 2018-4-19 by wwp */ public void setSessionByAccountId(String account_id, HttpSession session) { // 获取用户信息 session.setAttribute("userId", account_id); } } <file_sep>/src/main/java/dcmsxcx/service/db/EmployeeService.java package dcmsxcx.service.db; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service public class EmployeeService { @Autowired private JdbcTemplate jdbcTemplate; /** * 获取员工测试 * 2018-4-19 by wwp */ String sql = "select * from (select Emp_id emp_id, Emp_name emp_name from dcms_employee_information limit 10 ) aa"; public List<Map<String, Object>> getSomeEmployee(){ List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); return list; } } <file_sep>/src/main/java/dcmsxcx/web/controller/LoginController.java package dcmsxcx.web.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; import net.sf.json.spring.web.servlet.view.JsonView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import dcmsxcx.service.db.WechatRelaService; import dcmsxcx.service.manage.SessionManaService; import dcmsxcx.util.HttpUtil; import dcmsxcx.util.StringUtil; @Controller @RequestMapping("login") @Scope("prototype") public class LoginController extends BaseController { @Autowired private SessionManaService sessionManaService; @Autowired private WechatRelaService wechatRelaService; /** * 登录操作 * 2018-4-17 by wwp */ @RequestMapping("doLogin") public ModelAndView doLogin(String username, String password, String userId, HttpServletRequest request) { log.info("doLogin, username: " + username); HttpSession session = request.getSession(); Map<String, Object> rstMap = new HashMap<String, Object>(); // 验证参数 if(StringUtil.isNotBlank(username) && StringUtil.isNotBlank(password)){ boolean isAccount = this.isAccountValid(username, password); // 登录验证 if(isAccount){ sessionManaService.setSessionByAccountId(username, session); // 同步企业微信和 易汇帐号关系 wechatRelaService.addOrEditRela(userId, username); rstMap.put(RST_CODE, RST_SUCC); rstMap.put(RST_MSG, "登录成功"); } else{ rstMap.put(RST_CODE, "01"); rstMap.put(RST_MSG, "帐号或密码错误!"); } } else{ rstMap.put(RST_CODE, "01"); rstMap.put(RST_MSG, "请输入帐号或密码"); } return new ModelAndView(new JsonView(), rstMap); } /** * 登出 * 2018-4-19 by wwp */ @RequestMapping("logout.do") public ModelAndView logout(HttpServletRequest request) { HttpSession session = request.getSession(); session.removeAttribute("userId"); // 移除用户属性 return new ModelAndView("redirect:/login.jsp"); } /** * 帐号,密码验证 * 2018-4-18 by wwp */ private boolean isAccountValid(String account, String password){ String dcmsUrl = "http://10.30.18.15:8080/dcms/iwap.ctrl"; Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("txcode", "xcx1001"); paramMap.put("account", account); paramMap.put("password", <PASSWORD>); try{//TODO post请求失败 String paramUrl = "http://10.30.18.15:8080/dcms/iwap.ctrl?txcode=xcx1001&account="+account+"&password="+<PASSWORD>; String str = HttpUtil.sendPost(paramUrl); log.info(str); JSONObject json = JSONObject.fromObject(str); JSONObject ret = json.getJSONObject("ret"); String rst_code = ret.getString("rst_code"); if("00".equals(rst_code)){ return true; } }catch(Exception e){ e.printStackTrace(); } return false; } } <file_sep>/src/main/java/dcmsxcx/constant/WebConstant.java package dcmsxcx.constant; /** * web常量 * * @author wwp * @date 2018-4-12 */ public class WebConstant { /** * 返回成功 */ public static final String RST_SUCC = "00"; /** * 返回状态码键 */ public static final String RST_CODE = "rst_code"; /** * 返回信息键 */ public static final String RST_MSG = "rst_msg"; /** * 返回数据 */ public static final String RST_DATA = "rstData"; } <file_sep>/src/main/java/dcmsxcx/web/filter/LoginFilter.java package dcmsxcx.web.filter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import dcmsxcx.util.StringUtil; public class LoginFilter implements Filter { private Logger log = Logger.getLogger(this.getClass()); @Override public void destroy() { } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper((HttpServletResponse) arg1); HttpSession session = request.getSession(); String requestUri = request.getRequestURI(); log.debug("requestUri: " + requestUri); // 登录用户没有限制 String userId = StringUtil.trimNull(session.getAttribute("userId")); if (StringUtil.isNotBlank(userId)) { chain.doFilter(arg0, arg1); return; } // 开放地址 if((request.getContextPath()+"/").equals(requestUri)){ chain.doFilter(arg0, arg1); return; } List<String> openAddList = new ArrayList<String>(); openAddList.add("/doLogin.do"); openAddList.add("/login.jsp"); openAddList.add("/wechatLogin.do"); for (String s : openAddList) { if (requestUri.indexOf(s) != -1) { chain.doFilter(arg0, arg1); return; } } // TODO自定义js不缓存 responseWrapper.sendRedirect(request.getContextPath() + "/login.jsp"); return; } @Override public void init(FilterConfig arg0) throws ServletException { } } <file_sep>/src/main/webapp/jsp/dialy/js/dialyAdd.js $(function(){ $("#date").calendar(); });<file_sep>/src/main/java/dcmsxcx/web/listener/CustomServletContextListener.java package dcmsxcx.web.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.log4j.Logger; public class CustomServletContextListener implements ServletContextListener { private Logger log = Logger.getLogger(this.getClass()); @Override public void contextInitialized(ServletContextEvent sce) { log.info("---项目启动---"); } @Override public void contextDestroyed(ServletContextEvent sce) { log.info("---项目销毁---"); } }
af8e6c433e88b258e6d53698aabf3c6306d40da7
[ "JavaScript", "Java" ]
8
JavaScript
githubwwp/dcmsxcx
43751ec02bcb7c826726aab147e6add95ee43c96
180b8150b43f3e2ffe06e038155bf6442a7b31c2
refs/heads/master
<repo_name>dengjiaxing/Spring_Method_Injection<file_sep>/src/com/djx/bean/StandardLookupDemo.java package com.djx.bean; public class StandardLookupDemo implements DemoBean { private MyHelper myHelper; public MyHelper getMyHelper() { return myHelper; } public void setMyHelper(MyHelper myHelper) { myHelper = myHelper; } @Override public MyHelper getHelper() { // TODO Auto-generated method stub return myHelper; } @Override public void someOperation() { // TODO Auto-generated method stub myHelper.doSomethingHelpful(); } }
0df8f82782dea57d603931217b99373231ae355c
[ "Java" ]
1
Java
dengjiaxing/Spring_Method_Injection
27534834c8c20c57f0dbadd25681059521793287
c1d9b8f9def0f4de2b0a8a441033ec2e4193a82a
refs/heads/master
<repo_name>luiszeni/FunWithDate<file_sep>/src/br/com/luiszeni/funwithdateoperation/DateFormatException.java package br.com.luiszeni.funwithdateoperation; /** This class represents an exception that is throw when an date is in wrong format. * @author <NAME> * @version 1.1 */ public class DateFormatException extends Exception{ private static final long serialVersionUID = 1L; public DateFormatException(String message) { super(message); } } <file_sep>/README.txt I will try to solve the given problem: You should create the following function: public String changeDate(String date, char op, long value); Where, date: An date as String in the format dd/MM/yyyy HH24:mi; op: Can be only + | -; value: the value that should be incremented/decremented. It will be expressed in minutes; Restrictions: You shall not work with non-native classes / libraries; You shall not make use of neither Date nor Calendar classes; If the op is not valid an exception must be thrown; If the value is smaller than zero, you should ignore its signal; If the result sum is bigger than max value to the field, you should increment its immediate bigger field; Ignore the fact that February have 28/29 days and always consider only 28 days; Ignore the daylight save time rules. Example: changeDate("01/03/2010 23:00", '+', 4000) = "04/03/2010 17:40"
24c756296328e6559bcdec2c48391b1498ea58e2
[ "Java", "Text" ]
2
Java
luiszeni/FunWithDate
a1fca53affc046bed2db24c8d3f89aea4392b4b3
411dc3a9db967401f1386d001334dddb62b703cf
refs/heads/master
<repo_name>JanhaviMakwana/ReackTasks<file_sep>/clock-task/src/components/ShowDate.js import React from 'react'; const showDate = (props) => { let newDate = null; if (props.show) { const date = props.date; newDate = date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getFullYear(); } return ( <div> <h1>{newDate} </h1> </div> ); } export default showDate;<file_sep>/timer-adv/src/Timer/Key/Key.js import React from 'react'; import './Key.css'; class Key extends React.Component { render() { return ( <button className="key" onClick={this.props.onClick}> {this.props.value} </button> ); } } export default Key;<file_sep>/clock-task/src/containers/Clock.js import React from 'react'; import Toggle from '../components/Toggle'; import ShowDate from '../components/ShowDate'; class Clock extends React.Component { constructor(props) { super(props); this.state = { date: new Date(), show: false }; } componentDidMount() { this.timerID = setInterval( () => this.setState({ date: new Date() }), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } toggleHandler = () => { this.setState({ show: !this.state.show }); } render() { return ( <div> <Toggle clicked={this.toggleHandler} show={this.state.show} /> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> <ShowDate show={this.state.show} date={this.state.date} /> </div> ); } } export default Clock;<file_sep>/blog-list/src/components/FullPost/FullPost.js import React from 'react'; import { withRouter } from 'react-router-dom'; import axios from '../../axios'; import './FullPost.css'; class FullPost extends React.Component { constructor(props) { super(props); this.state = { post: null } } componentDidMount() { const id = this.props.id console.log(this.props.id); if (id) { axios.get('/posts/' + this.props.id) .then(response => { this.setState({ post: response.data }) console.log(response.data); }) .catch(error => { console.log(error); this.setState({ error: error }) }); } } onClosePostHandler = () => { this.props.history.push('/'); } render() { let post = <p id="loading">Please select a post</p> if (this.props.id) { post = <p id="loading">Loading...</p> } if (this.state.post) { post = ( <div className="FullPost"> <h1>{this.state.post.title}</h1> <h2>{this.state.post.body}</h2> <div className="Edit"> <button onClick={this.onClosePostHandler}>Close</button> </div> </div> ); } return post; } }; export default withRouter(FullPost); <file_sep>/clock-task/src/components/Toggle.js import React from 'react'; const Toggle = (props) => ( <button onClick={props.clicked}> {!props.show ? 'Show Date' : 'Hide Date'} </button> ); export default Toggle;<file_sep>/timer-adv/src/Timer/Display/Display.js import React from 'react'; import Time from '../Time'; import './Display.css' const Display = (props) => { const time = new Time(); return ( <div className="display"> { props.timeInterval && ( <div className="time">{time.getTime(props.timeInterval)}</div> ) } {!props.timeInterval && <div> <div> <label className="label">H</label> <label className="label">M</label> <label className="label">S</label> </div> <div className="input-div"> <input className="Input" type="text" maxLength="2" placeholder="00" onFocus={() => props.onFocusChange('H')} onChange={props.onInputChange} value={props.hours} /><div className="span"><h1>:</h1></div> <input className="Input" type="text" maxLength="2" placeholder="00" onFocus={() => props.onFocusChange('M')} onChange={props.onInputChange} value={props.minutes} /><div className="span"><h1>:</h1></div> <input className="Input" type="text" maxLength="2" placeholder="00" onFocus={() => props.onFocusChange('S')} onChange={props.onInputChange} value={props.seconds} /> </div> </div> } </div> ); } Display.defaultProps = { onInputChange: () => { }, hours: '00', minutes: '00', seconds: '00' } export default Display;<file_sep>/blog-list/src/components/Blog/Blog.js import React from 'react'; import { Route, withRouter } from 'react-router-dom'; import { Switch } from 'react-router'; import Posts from '../Posts/Posts'; import FullPost from '../FullPost/FullPost'; import './Blog.css' class Blog extends React.Component { constructor(props) { super(props); this.state = { selectedPostId: null } } postClickedHandler = (id) => { this.setState({ selectedPostId: id }); this.props.history.push('/full-post'); } render() { return ( <div className="Blog"> <header className="Header"> <nav> <ul> <button><li><a href="/">Home</a></li></button> <button><li><a href="/full-post">Full Post</a></li></button> </ul> </nav> </header> <Switch> <Route path="/full-post" exact render={() => <FullPost id={this.state.selectedPostId} />} /> <Route path="/" render={() => <Posts clicked={this.postClickedHandler} />} /> </Switch> </div> ); } } export default withRouter(Blog);<file_sep>/timer-task/src/Timer/ShowTimer/ShowTimer.js import React from 'react'; import './ShowTimer.css' const showTimer = (props) => { return ( <div className={'showTimer' + ((props.status === 'START' || props.status === 'STOP') && props.count <= 10 ? ' danger' : '')}> <h1>{props.count}</h1> </div> ); } export default showTimer; <file_sep>/timer-task/src/Timer/Timer.js import React from 'react'; import ShowTimer from '../Timer/ShowTimer/ShowTimer'; import './Timer.css'; class Timer extends React.Component { constructor(props) { super(props); this.state = { timer: 0, start: false, touched: false, status: null } } shouldComponentUpdate() { if (this.state.timer === 0) { return false; } else { return true; } } onTimerChangeHandler = (event) => { this.setState({ timer: event.target.value }) } onTimerStartHandler = () => { this.setState({ start: true, touched: true, status: 'START' }) console.log("Started"); this.timeInterval = setInterval(() => { this.setState({ timer: this.state.timer > 1 ? this.state.timer - 1 : this.onTimerStopHandler() }) }, 1000); } onTimerStopHandler = () => { this.setState({ timer: this.state.timer, touched: false, start: false, status: 'STOP' }); clearInterval(this.timeInterval); } onTimerResetHandler = () => { this.setState({ timer: 0, touched: false, start: false, status: null }); clearInterval(this.timeInterval); } render() { return ( <div className="Timer"> <input className="Input" type="text" placeholder="Enter seconds" onChange={(ev) => this.onTimerChangeHandler(ev)} /><br /><br /> <div> { this.state.status !== 'START' && this.state.status !== 'STOP' && <button className="btn start" onClick={this.onTimerStartHandler}>START</button> } { this.state.status === 'START' && (<div> <button className="btn stop" onClick={() => this.onTimerStopHandler()}>STOP</button> <button className="btn reset" onClick={() => this.onTimerResetHandler()}>RESET</button> </div>) } {this.state.status === 'STOP' && (<div> <button className="btn resume" onClick={() => this.onTimerStartHandler()}>RESUME</button> <button className="btn reset" onClick={() => this.onTimerResetHandler()}>RESET</button> </div>) } </div> <br /> <ShowTimer count={this.state.timer} status={this.state.status} touched={this.state.touched} /> </div> ); } } export default Timer;<file_sep>/blog-list/src/components/Posts/Post.js import React from 'react'; import './Post.css'; const post = (props) => { return ( <div className="Post" onClick={props.clicked}> <h3>Post No:{props.post.id}</h3> <h2>{props.post.title}</h2> </div> ); }; export default post;<file_sep>/movie-list/src/components/Header/Header.js import React from 'react'; import './Header.css'; const Header = (props) => ( <div className="Header"> <i className="fa fa-film"></i> <div>{props.title}</div> </div> ); export default Header; <file_sep>/movie-list/src/components/movies/MovieList/MovieList.js import React from 'react'; import MoviePanel from '../MoviePanel/MoviePanel'; import './MovieList.css'; const getMovies = (movies) => { return ( <div> { movies.map(movie => <MoviePanel key={movie.id} movie={movie} />) } </div> ); } const MovieList = (props) => ( <div className="MovieList"> {getMovies(props.movies)} </div> ); export default MovieList;
9800e22c44eb3c9e916f2752d0994b040adcaa2a
[ "JavaScript" ]
12
JavaScript
JanhaviMakwana/ReackTasks
17590f41f18f3d8a1af5e0fa9a6aff3dd7538652
ffd02b4e93d2e21d41a1f30010b4965acdb9cefa
refs/heads/master
<repo_name>rafaelgibam/BASE_API_SPRING_OAUTH2<file_sep>/src/main/java/br/com/gestaotrading/domain/Operacao.java package br.com.gestaotrading.domain; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Data; @Data @Entity(name = "TBGTS002_OPERACAO") public class Operacao { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_OPERACAO") private Long id; @Column(name = "VALOR_OPERACAO") private BigDecimal valorOperacao; @Column(name = "LUCRO_OPERACAO") private BigDecimal lucroOperacao; @Temporal(TemporalType.DATE) private Date dataOperacao; @OneToOne private Corretora corretora; } <file_sep>/src/main/java/br/com/gestaotrading/repository/CorretoraRepository.java package br.com.gestaotrading.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import br.com.gestaotrading.domain.Corretora; @Repository public interface CorretoraRepository extends JpaRepository<Corretora, Long>{ } <file_sep>/src/main/resources/application.properties server.port=8080 server.servlet.context-path=/api/v1 spring.datasource.url=jdbc:h2:~/test;DB_CLOSE_DELAY=-1 spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.h2.console.enabled=true spring.h2.console.path=/h2-console spring.h2.console.settings.trace=false spring.h2.console.settings.web-allow-others=false spring.jpa.hibernate.ddl-auto=update <file_sep>/src/main/java/br/com/gestaotrading/repository/OperacaoRepository.java package br.com.gestaotrading.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import br.com.gestaotrading.domain.Operacao; @Repository public interface OperacaoRepository extends JpaRepository<Operacao, Long> { } <file_sep>/src/main/java/br/com/gestaotrading/domain/Banca.java package br.com.gestaotrading.domain; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Data; @Data @Entity(name = "TBGTS001_BANCA") public class Banca { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_BANCA") private Long id; @Column(name = "VALOR_BANCA") private BigDecimal valorBanca; @Temporal(TemporalType.DATE) private Date dataFechamentoDiaBanca; @OneToOne private Corretora corretora; } <file_sep>/src/main/java/br/com/gestaotrading/controller/OperacaoController.java package br.com.gestaotrading.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import br.com.gestaotrading.domain.Operacao; import br.com.gestaotrading.repository.OperacaoRepository; @RequestMapping("/operacoes") @RestController public class OperacaoController { @Autowired private OperacaoRepository operacaoRepository; @GetMapping public Page<Operacao> getPage(Pageable pageable) { return operacaoRepository.findAll(pageable); } @GetMapping("/all") public List<Operacao> getAll() { return operacaoRepository.findAll(); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public Operacao save(@RequestBody Operacao banca) { return operacaoRepository.save(banca); } @PutMapping("/{id}") public Operacao update(@RequestBody Operacao banca, @PathVariable Long id) { banca.setId(id); return operacaoRepository.save(banca); } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { operacaoRepository.deleteById(id); } }
c064500c8ed778e29aa2bac8953eabcd64e3053c
[ "Java", "INI" ]
6
Java
rafaelgibam/BASE_API_SPRING_OAUTH2
df72f263a6065af53bc7e9e0fd211d15875d7795
c71738e4d62bbc36432a850cd03d41466dabdc9a
refs/heads/master
<file_sep>package com.basedefense.game.entity.components; import com.badlogic.ashley.core.Component; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; public class WeaponPartComponent implements Component { public Entity owner; public Vector3 position_in_weapon = new Vector3(); public Vector2 scale = new Vector2(1.0f, 1.0f); public float rotation = 0.0f; public boolean isHidden = false; public void addPartToWeapon(Entity entityToAttach){ owner = entityToAttach; } public void setPartOffSet(Vector3 offsetCoordinates){ position_in_weapon = offsetCoordinates; } }<file_sep>package com.basedefense.game.viewports; import com.badlogic.gdx.Gdx; public class Viewport { private static final String TAG = Viewport.class.getSimpleName(); public static float viewportWidth; public static float viewportHeight; public static float virtualWidth; public static float virtualHeight; public static float physicalWidth; public static float physicalHeight; public static float aspectRatio; public void setupViewport(int width, int height){ //Make the viewport a percentage of the total display area virtualWidth = width; virtualHeight = height; //Current viewport dimensions viewportWidth = virtualWidth; viewportHeight = virtualHeight; //pixel dimensions of display physicalWidth = Gdx.graphics.getWidth(); physicalHeight = Gdx.graphics.getHeight(); //aspect ratio for current viewport aspectRatio = (virtualWidth / virtualHeight); //update viewport if there could be skewing if( physicalWidth / physicalHeight >= aspectRatio){ //Letterbox left and right viewportWidth = viewportHeight * (physicalWidth/ physicalHeight); viewportHeight = virtualHeight; }else{ //letterbox above and below viewportWidth = virtualWidth; viewportHeight = viewportWidth * (physicalHeight/ physicalWidth); } Gdx.app.debug(TAG, "WorldRenderer: virtual: (" + virtualWidth + "," + virtualHeight + ")" ); Gdx.app.debug(TAG, "WorldRenderer: viewport: (" + viewportWidth + "," + viewportHeight + ")" ); Gdx.app.debug(TAG, "WorldRenderer: physical: (" + physicalWidth + "," + physicalHeight + ")" ); Gdx.app.debug(TAG, "WorldRenderer: ratio: (" + viewportWidth / physicalWidth + "," + viewportHeight / physicalHeight + ")" ); } } <file_sep>package com.basedefense.game.entity.components; import com.badlogic.ashley.core.Component; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; /* Emplacement are attanched to a hardpoint and contains weapons or systems */ public class EmplacementComponent implements Component { public Entity owner; public Vector3 position_in_hardpoint = new Vector3(); public Vector2 scale = new Vector2(1.0f, 1.0f); public float rotation = 0.0f; public boolean isHidden = false; public void attachEntityTo(Entity entityToAttach){ owner = entityToAttach; } public void setEntityAttachmentPointOffSet(Vector3 offsetCoordinates){ position_in_hardpoint = offsetCoordinates; } }<file_sep>package com.basedefense.game.entity.components; import com.badlogic.ashley.core.Component; import com.badlogic.ashley.signals.Listener; import com.badlogic.ashley.signals.Signal; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; public class TransformComponent implements Component, Listener<Float> { public Vector3 position = new Vector3(); public Vector2 scale = new Vector2(1.0f, 1.0f); public float rotation = 0.0f; public boolean isHidden = false; @Override public void receive(Signal<Float> signal, Float rotationchange) { rotation += rotationchange; } }<file_sep>package com.basedefense.game.entity.components; import com.badlogic.ashley.core.Component; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; public class AttachmentPointComponent implements Component { public Entity parent; public Vector3 offset = new Vector3(); public Vector2 scale = new Vector2(1.0f, 1.0f); public float rotation = 0.0f; public boolean isHidden = false; public void attachEntityTo(Entity entityToAttach){ parent = entityToAttach; } public void setEntityAttachmentPointOffSet(Vector3 offsetCoordinates){ offset = offsetCoordinates; } } <file_sep>package com.basedefense.game; import com.badlogic.gdx.Game; import com.badlogic.gdx.assets.AssetManager; import com.basedefense.game.views.MainGameScreen; import com.basedefense.game.utility.Utility; public class BaseDefense extends Game { public MainGameScreen mainScreen; public final AssetManager manager = new AssetManager(); @Override public void create () { Utility.queueAddImages(manager); manager.finishLoading(); mainScreen = new MainGameScreen(this); setScreen(mainScreen); } @Override public void dispose () { mainScreen.dispose(); manager.dispose(); } } <file_sep>package com.basedefense.game.entity.components; import com.badlogic.ashley.core.Component; /** * This components hold the stats used by the system to calculate * the movements. * * @paramater baseRotationSpeed: the base rotation speed before any modification * @paramater baseVelX: the base velX speed before any modification * @paramater baseVelY: the base velY speed before any modification * @paramater rotationSpeed: the rotation speed used to calculate the player rotation * @paramater velX: the speed used to calculate the player position * @paramater velY: the speed used to calculate the player position */ public class MovementStatsComponent implements Component { public float baseRotationSpeed = 0.0f; public float baseVelX = 0.0f; public float baseVelY = 0.0f; public float rotationSpeed = 0.0f; public float velX = 0.0f; public float velY = 0.0f; } <file_sep>package com.basedefense.game.entity.factories; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.basedefense.game.entity.components.TextureComponent; import com.basedefense.game.entity.components.TransformComponent; import com.basedefense.game.entity.components.MovementStatsComponent; import com.basedefense.game.entity.components.WeaponComponent; import com.basedefense.game.entity.components.PlayerPartComponent; import com.basedefense.game.entity.components.HardPointComponent; import com.basedefense.game.entity.components.EmplacementComponent; import com.basedefense.game.entity.components.StateComponent; import com.basedefense.game.entity.components.AttachmentPointComponent; import com.basedefense.game.entity.components.ConnectorPoint; import com.basedefense.game.entity.components.WeaponPartComponent; import com.basedefense.game.templates.PlayerPartConfigurationTemplate; import static com.basedefense.game.loaders.Assets.*; public class EntityConfigurationFactory { private AssetManager manager; public EntityConfigurationFactory(AssetManager manager){ this.manager = manager; } public void setPlayer(Entity player){ //player.getComponent(TextureComponent.class).setTexture(manager.get(BASE_PARTS_ATLAS, TextureAtlas.class) // .findRegion("basepart_1x1_bottom")); // player.getComponent(TransformComponent.class).position.set(100 - player.getComponent(TextureComponent.class).center.x, // 100 - player.getComponent(TextureComponent.class).center.x,0); player.getComponent(TransformComponent.class).position.set(0, 0 ,0); player.getComponent(TransformComponent.class).rotation = 0; player.getComponent(TransformComponent.class).scale = new Vector2(1.0f, 1.0f); setPlayerMovementStats(player); // player.getComponent(TransformComponent.class).isHidden = true; } public void setPlayerPart(Entity playerPart, PlayerPartConfigurationTemplate ppconfig ){ playerPart.getComponent(TextureComponent.class).setTexture(manager.get(BASE_PARTS_ATLAS, TextureAtlas.class) .findRegion(ppconfig.getTexture())); // playerPart.getComponent(StateComponent.class).set(StateComponent.IDLE); setPlayerPartMovementStats(playerPart); // weapon.getComponent(TransformComponent.class).isHidden = true; } public void setHardPoint(Entity hardPoint, String size){ if (size == "medium") hardPoint.getComponent(TextureComponent.class).setTexture(manager.get(BASE_PARTS_ATLAS, TextureAtlas.class) .findRegion("weapon_hardpoint_turret_medium_open")); if (size == "small") hardPoint.getComponent(TextureComponent.class).setTexture(manager.get(BASE_PARTS_ATLAS, TextureAtlas.class) .findRegion("weapon_hardpoint_turret_small_open")); hardPoint.getComponent(StateComponent.class).set(StateComponent.IDLE); setHardPointMovementStats(hardPoint); // weapon.getComponent(TransformComponent.class).isHidden = true; } public void setEmplacement(Entity emplacement, String size){ if (size == "medium") emplacement.getComponent(TextureComponent.class).setTexture(manager.get(WEAPON_ATLAS, TextureAtlas.class) .findRegion("emplacement_turret_cannon_medium_mk1")); if (size == "small") emplacement.getComponent(TextureComponent.class).setTexture(manager.get(WEAPON_ATLAS, TextureAtlas.class) .findRegion("emplacement_turret_cannon_medium_mk1")); emplacement.getComponent(StateComponent.class).set(StateComponent.IDLE); setEmplacementMovementStats(emplacement); // weapon.getComponent(TransformComponent.class).isHidden = true; } public void setWeaponPart(Entity weaponPart){ weaponPart.getComponent(TextureComponent.class).setTexture(manager.get(WEAPON_ATLAS, TextureAtlas.class) .findRegion("cannon_ammo_chamber_01_mk1")); // weaponPart.getComponent(TextureComponent.class).region = manager.get(CANNON_MEDIUM, TextureAtlas.class) // .findRegion("cannon_01_mk1"); weaponPart.getComponent(StateComponent.class).set(StateComponent.IDLE); setWeaponPartMovementStats(weaponPart); // weapon.getComponent(TransformComponent.class).isHidden = true; } public void setPlayerMovementStats(Entity player){ MovementStatsComponent msc = player.getComponent(MovementStatsComponent.class); msc.rotationSpeed = 1.8f; msc.velX = 2.0f; msc.velY = 2.0f; } public void setWeapon(Entity weapon){ // Animation<TextureRegion> shooting; // shooting = new Animation<TextureRegion>(0.133f, manager.get(CANNON_MEDIUM_ANIMATED,TextureAtlas.class) // .getRegions(), Animation.PlayMode.LOOP); // weapon.getComponent(TextureComponent.class).region = manager.get(CANNON_MEDIUM, TextureAtlas.class) // .findRegion("cannon_01_mk1"); // weapon.getComponent(AnimationComponent.class).animations.put(StateComponent.SHOOTING,shooting); weapon.getComponent(StateComponent.class).set(StateComponent.IDLE); setWeaponMovementStats(weapon); // weapon.getComponent(TransformComponent.class).isHidden = true; } public void setTurret(Entity turret){ turret.getComponent(TextureComponent.class).region = manager.get(WEAPON_ATLAS, TextureAtlas.class) .findRegion("turret_01_mk1"); turret.getComponent(StateComponent.class).set(StateComponent.IDLE); setWeaponMovementStats(turret); // weapon.getComponent(TransformComponent.class).isHidden = true; } public void setMissileTurret(Entity turret){ Animation<TextureRegion> shooting; turret.getComponent(TextureComponent.class).region = manager.get(WEAPON_ATLAS, TextureAtlas.class) .findRegion("turret_03_mk1"); turret.getComponent(StateComponent.class).set(StateComponent.SHOOTING); setWeaponMovementStats(turret); // weapon.getComponent(TransformComponent.class).isHidden = true; } public void setWeaponMovementStats(Entity weapon){ MovementStatsComponent msc = weapon.getComponent(MovementStatsComponent.class); msc.rotationSpeed = 0.0f; } public void setPlayerPartMovementStats(Entity part){ MovementStatsComponent msc = part.getComponent(MovementStatsComponent.class); msc.rotationSpeed = 0.0f; } public void setHardPointMovementStats(Entity part){ MovementStatsComponent msc = part.getComponent(MovementStatsComponent.class); msc.rotationSpeed = 0.0f; } public void setEmplacementMovementStats(Entity weapon){ MovementStatsComponent msc = weapon.getComponent(MovementStatsComponent.class); msc.rotationSpeed = 1.8f; } public void setWeaponPartMovementStats(Entity weaponpart){ MovementStatsComponent msc = weaponpart.getComponent(MovementStatsComponent.class); msc.rotationSpeed = 0.0f; } /** Offsetz is for locate the weapon above or below the player. Z is calculated playerz + offsetz */ public void setPlayerAttachments(Entity player, Entity entityToAttach,int offsetx, int offsety, int offsetz) { AttachmentPointComponent apc = entityToAttach.getComponent(AttachmentPointComponent.class); TransformComponent eta = entityToAttach.getComponent(TransformComponent.class); TransformComponent pt = player.getComponent(TransformComponent.class); eta.position.x = pt.position.x - entityToAttach.getComponent(TextureComponent.class).center.x + offsetx; eta.position.y = pt.position.y - entityToAttach.getComponent(TextureComponent.class).center.y + offsety; eta.position.z = pt.position.z + offsetz; if (apc != null) { apc.setEntityAttachmentPointOffSet(new Vector3(offsetx, offsety, offsetz)); apc.attachEntityTo(player); } } /** Offsetz is for locate the weapon above or below the player. Z is calculated playerz + offsetz Note that we add the center to the offset. This is done because normally the offset is calculated to the center of the texture, and for parts me want to user the left corner. With normal offset the part will be located with its center in the offset. With the alteration now the left corner of the part is draw in the offset */ public void attachPlayerPart(Entity player, Entity part,int offsetx, int offsety, int offsetz) { PlayerPartComponent ppc = part.getComponent(PlayerPartComponent.class); TransformComponent eta = part.getComponent(TransformComponent.class); TransformComponent pt = player.getComponent(TransformComponent.class); Vector2 part_center = part.getComponent(TextureComponent.class).center; // System.out.println("Center:" + part_center.x); eta.position.x = pt.position.x + offsetx; eta.position.y = pt.position.y + offsety; eta.position.z = pt.position.z + offsetz; if (ppc != null) { ppc.setEntityAttachmentPointOffSet(new Vector3(offsetx + part_center.x, offsety + part_center.y, offsetz)); ppc.attachEntityTo(player); } } /** Offsetz is for locate the weapon above or below the player. Z is calculated playerz + offsetz */ public void attachHardPointToPart(Entity part, Entity hardpoint,int offsetx, int offsety, int offsetz) { HardPointComponent hpc = hardpoint.getComponent(HardPointComponent.class); TransformComponent eta = hardpoint.getComponent(TransformComponent.class); TransformComponent pt = part.getComponent(TransformComponent.class); Vector2 part_center = part.getComponent(TextureComponent.class).center; // System.out.println("Center:" + part_center.x); eta.position.x = pt.position.x + offsetx; eta.position.y = pt.position.y + offsety; eta.position.z = pt.position.z + offsetz; if (hpc != null) { hpc.setEntityAttachmentPointOffSet(new Vector3(offsetx, offsety, offsetz)); hpc.attachEntityTo(part); } } /** Offsetz is for locate the weapon above or below the player. Z is calculated playerz + offsetz */ public void attachEmplacementToHardPoint(Entity hardpoint, Entity emplacement,int offsetx, int offsety, int offsetz) { EmplacementComponent ec = emplacement.getComponent(EmplacementComponent.class); TransformComponent eta = emplacement.getComponent(TransformComponent.class); TransformComponent pt = hardpoint.getComponent(TransformComponent.class); Vector2 part_center = hardpoint.getComponent(TextureComponent.class).center; // System.out.println("Center:" + part_center.x); eta.position.x = pt.position.x + offsetx; eta.position.y = pt.position.y + offsety; eta.position.z = offsetz; if (ec != null) { ec.setEntityAttachmentPointOffSet(new Vector3(offsetx, offsety, offsetz)); ec.attachEntityTo(hardpoint); } } /** Offsetz is for locate the weapon above or below the player. Z is calculated playerz + offsetz */ public void addWeaponPartToEmplacement(Entity emplacement, Entity weaponpart,int offsetx, int offsety, int offsetz) { WeaponPartComponent wpc = weaponpart.getComponent(WeaponPartComponent.class); TransformComponent eta = weaponpart.getComponent(TransformComponent.class); TransformComponent pt = emplacement.getComponent(TransformComponent.class); Vector2 emplacement_center = emplacement.getComponent(TextureComponent.class).center; //System.out.println("Center:" + part_center.x); eta.position.x = pt.position.x + offsetx - emplacement_center.x; eta.position.y = pt.position.y + offsety - emplacement_center.y; eta.position.z = offsetz; if (wpc != null) { wpc.setPartOffSet(new Vector3(offsetx, offsety, offsetz)); wpc.addPartToWeapon(emplacement); } } /** Offsetz is for locate the weapon above or below the player. Z is calculated playerz + offsetz */ public void attachWeaponToEmplacement(Entity emplacement, Entity weapon,int offsetx, int offsety, int offsetz) { WeaponComponent wc = weapon.getComponent(WeaponComponent.class); TransformComponent eta = weapon.getComponent(TransformComponent.class); TransformComponent pt = emplacement.getComponent(TransformComponent.class); Vector2 part_center = emplacement.getComponent(TextureComponent.class).center; //System.out.println("Center:" + part_center.x); eta.position.x = pt.position.x + offsetx; eta.position.y = pt.position.y + offsety; eta.position.z = offsetz; if (wc != null) { wc.setWeaponPointOffSet(new Vector3(offsetx, offsety, offsetz)); wc.attachWeaponTo(emplacement); } } public void setConnectorPoint(Entity entity, int offsetx, int offsety, int offsetz){ ConnectorPoint cp = entity.getComponent(ConnectorPoint.class); if (cp != null){ cp.offset = new Vector3(offsetx,offsety,offsetz); } } } <file_sep>package com.basedefense.game.entity.systems; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.basedefense.game.entity.components.BulletComponent; import com.basedefense.game.entity.components.Mapper; import com.basedefense.game.entity.components.TransformComponent; import static com.basedefense.game.utility.Utility.calculateVectorialX; import static com.basedefense.game.utility.Utility.calculateVectorialY; public class BulletSystem extends IteratingSystem{ @SuppressWarnings("unchecked") public BulletSystem(){ super(Family.all(BulletComponent.class).get()); } @Override protected void processEntity(Entity entity, float deltaTime) { //get bullet components BulletComponent bullet = Mapper.bulletCom.get(entity); TransformComponent trans = Mapper.transCom.get(entity); trans.position.y = trans.position.y + calculateVectorialY(bullet.vel,trans.rotation); trans.position.x = trans.position.x + calculateVectorialX(bullet.vel,trans.rotation); bullet.activeTime += deltaTime; if(bullet.activeTime > 1){ bullet.isDead = true; } //check if bullet is dead if(bullet.isDead){ System.out.println("Bullet died"); } } }
62e68242b1d835fd1c1a1ab732a6d17b6e5094cc
[ "Java" ]
9
Java
ArielCosta13/BaseDefenses
01e871bfd6614c97cc26bacb5926b0d8b6d2abcd
dadb34e1511451b1deff781ab694fad50771928c
refs/heads/master
<file_sep>package controlador; import java.util.ArrayList; import modelo.*; public class sujetoMundo { // Atributos Tren misTrenes[]; Senal misSenales[]; /* Revisado por Christian ├?lvarez -Se han colocado las llaves, renombrar correctamente los atributos. */ // observadores misObservadores[]; ArrayList<Observador> misObservadores; // SOLO DEL MUNDO // M├ętodos void anadir(Observer miObservador){// A├▒adir un observador a cierto sujeto misObservadores.add(miObservador); } void quitar(Observer miObservador){ // Obvio, joder misObservadores.remove(miObservador); } void notificar(){ // Recibir un update // Supongo que notificar a los observadores for (Observador o : misObservadores) o.notificar(); } void actualizar(){ // Actualizar la informaci├│n de un sujeto (m├ętodo de un observador) for (Observador o : misObservadores) o.actualizar(); } void getEstado(){ // Toma un estado de una entidad // ┬┐qu├ę entidad? } void setEstado(){ // Modifica el estado de una entidad // ┬┐qu├ę entidad? } }
7b75ecf764126b6661429b18ed4aabdb67977be3
[ "Java" ]
1
Java
miguecab/I-love-Trains
edec12b0e7f522e886867729334d138d15c3b824
d9e563e184ddea66d28f58fb27f7f835c8192146
refs/heads/master
<file_sep>import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; import { TodosComponent } from './todos.component'; import { TodoService } from './todo.service'; import { of } from 'rxjs'; import { HttpClientModule } from '@angular/common/http'; describe('TodosComponent', () => { let component: TodosComponent; let fixture: ComponentFixture<TodosComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [TodosComponent], imports: [HttpClientModule], providers: [TodoService] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TodosComponent); component = fixture.componentInstance; }); it('should load todos from the server', fakeAsync(() => { //fixture.debugElement.injector.get(TodoService) let service = TestBed.get(TodoService); //spyOn(service, 'getTodos').and.returnValue(of([1, 2, 3])); spyOn(service, 'getTodosPromise').and.returnValue(Promise.resolve([1, 2, 3])); fixture.detectChanges(); // use whenStable() withh async because the expect function called before the promise has been completed // so that this test will fail because the todos array hasn't been assigned with the value from server yet // fixture.whenStable().then(() => {//returns a promise that is resolved when all async calls are completed // expect(component.todos.length).toBe(3); // }); // with fakeAsync we can use expect without promise tick();// simulate a passage of time expect(component.todos.length).toBe(3); })); }); <file_sep>import { greet } from "./greet"; describe('greet', function () { // one or more it (specs or tests) it('should include the name in the message', () => { expect(greet("Amir")).toContain("Amir"); }); }); <file_sep>import { TestBed, ComponentFixture } from '@angular/core/testing'; import { VoterComponent } from './voter.component'; import { By } from '@angular/platform-browser'; describe('VoterComponent', () => { let component: VoterComponent; let fixture: ComponentFixture<VoterComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [VoterComponent] }); fixture = TestBed.createComponent(VoterComponent); component = fixture.componentInstance; fixture.detectChanges(); //fixture.nativeElement // return html element which is the root dom element of the component template //fixture.debugElement // wrapper around the native element //fixture.changeDetectorRef// can change detection manually }); it('should render total votes', () => { component.othersVote = 20; component.myVote = 1; fixture.detectChanges(); let debugElement = fixture.debugElement.query(By.css('.vote-count'));//match first let el: HTMLElement = debugElement.nativeElement; //fixture.debugElement.queryAll(By.css('.vote-count'));//match all //By.directive // directive on element expect(el.innerText).toContain('21'); }); it('should highlight the upvote button if I have upvoted', () => { component.myVote = 1; fixture.detectChanges(); let debugElement = fixture.debugElement.query(By.css('.glyphicon-menu-up')); expect(debugElement.classes['highlighted']).toBeTruthy(); }); it('should increase total votes when I click the upvote button', () => { let button = fixture.debugElement.query(By.css('.glyphicon-menu-up')); button.triggerEventHandler('click', null);// name of event & the object to pass by this event expect(component.totalVotes).toBe(1); }); });
3f832eb9c349e6fbf77e15db3a62e4ce22442ff6
[ "TypeScript" ]
3
TypeScript
AmirHassanFouad/AngularUnitTesting
1a73d6d8be75cb22444ce12913168e3edf881af9
01182fe6bd1b04496fcfb8504366d78d901a63c0
refs/heads/master
<file_sep>$(function() { $('button').on('click', function(e) { $(this).css({ 'display': 'none' }); var conexion = $.ajax({ url: 'https://randomuser.me/api/?results=100', dataType: 'json', success: function(data) {} }); conexion.done(function(data) { var i = 0; for (persona of data["results"]) { $("#listado").append("<div class=\"fila\" id=\"" + i + "\">" + "<figure><img src=" + persona["picture"]["large"] + "></img></figure>" + "<p>" + persona["name"]["first"] + " " + persona["name"]["last"] + "<br>" + persona["email"] + "<br>" + persona["location"]["street"] + ", " + persona["location"]["postcode"] + ", " + persona["location"]["city"] + " (" + persona["location"]["state"] + ")" + "</p></div>") i++; }; }); }); $('body').on('click', '.fila', function(e) { // duda, por qué body y por qué ,fila var id = $(this).attr('id'); var conexion2 = $.ajax({ url: 'https://randomuser.me/api/?results=1', dataType: 'json', success: function(data) {} }); conexion2.done(function(data) { var pers = data["results"][0]; // RESULTS 0 porque sé como me llegan los datos y llega el primer elemento $('#' + id).html("<figure><img src=" + pers["picture"]["large"] + "></img></figure>" + "<p>" + pers["name"]["first"] + " " + pers["name"]["last"] + "<br>" + pers["email"] + "<br>" + pers["location"]["street"] + ", " + pers["location"]["postcode"] + ", " + pers["location"]["city"] + " (" + pers["location"]["state"] + ")" + "</p>"); }); }); });<file_sep>$(function(e){ $('.divas').on('click', function(event) { location="divas/"+$(this).attr('id')+".html" }); $('.divas').on('mouseover', function(e){ $('h1').text($(this).data('name')); }); });<file_sep>$(function() { var conexion = $.ajax({ url: 'http://jorgesanchez.net/practicas/iaw/practica05/elecciones.xml', dataType: 'xml' }); conexion.done(function(datos) { var elecciones = $(datos).find("eleccion"); for (var eleccion of elecciones) { $('#tipo').append("<br><option value=" + ($(eleccion).attr("tipo")) + ">" + ($(eleccion).attr("tipo")) + "</option)") // ($(eleccion).attr("tipo")); esto solo si funciona } }); $('#tipo').on('change', function(e) { var opcion = $(this).val(); $('#fecha>option').remove(); var conexion2 = $.ajax({ url: 'http://jorgesanchez.net/practicas/iaw/practica05/elecciones.xml', dataType: 'xml' }); conexion2.done(function(datos) { var elecciones = $(datos).find("eleccion"); for (var eleccion of elecciones) { if ($(eleccion).attr('tipo') == opcion) { var fechas = $(eleccion).find("texto"); for (var fecha of fechas) { $('#fecha').append("<br><option value=" + ($(fecha).text()) + ">" + ($(fecha).text()) + "</option>"); } } } }); }); });
860675c7a4417086665f119e2e7b99f5e500d1cf
[ "JavaScript" ]
3
JavaScript
powervic/Practicas-IAW
69edabbd639a0d092000d0fc6d688bf1b768d841
a6c9449a9fe39806896c913764ca252dba29cd2c
refs/heads/master
<file_sep>import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import DataGridHeader from './Header'; import DataGridItem from './Item'; function DataGrid (props) { const { items, formFields, browserHistory } = props; if (items.length === 0) { return ( <p>Create some records first.</p> ); } return ( <div data-tpl="DataGrid"> <table> <DataGridHeader /> <tbody> { items.map((item) => { return ( <DataGridItem key={item.id} item={item} formFields={formFields} browserHistory={browserHistory} /> ); }) } </tbody> </table> <p className="number-of-records">Number of records: {items.length}</p> </div> ); } export default connect((store) => { const { items, formFields } = store.data; return { items, formFields }; })(DataGrid); <file_sep>import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { add as addItem } from '../store/actions/data'; import { FormGroup, Button, ButtonGroup, Col } from 'react-bootstrap'; import Form from './../components/Form'; import FormHeader from './../components/Form/Header'; import FormFooter from './../components/Form/Footer'; import Toastr from 'toastr'; import { isItemValid } from './../helpers'; class CreateView extends Component { constructor() { super(); this.createItem = this.createItem.bind(this); this.updateTempItem = this.updateTempItem.bind(this); } updateTempItem(item) { this.setState({ item }); } createItem() { const { item } = this.state; const { formFields } = this.props; if (isItemValid(item, formFields)) { Toastr.success('New employee was added...', 'Great!'); this.props.addItem(item); this.props.history.push('/'); } else { Toastr.error('Please fill all fields...', 'Error'); } } render() { return ( <Form updateTempItem={this.updateTempItem}> <FormHeader> <Link to="/" className="btn"> Back to items list </Link> <h2>Create new item</h2> </FormHeader> <FormFooter> <FormGroup> <Col smOffset={2} sm={10}> <Button onClick={() => this.createItem()}> Create Item </Button> </Col> </FormGroup> </FormFooter> </Form> ); } } export default connect((store) => { const { formFields } = store.data; return { formFields }; }, { addItem })(CreateView); <file_sep>import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { remove as deleteItem } from '../store/actions/data'; import { Button, ButtonGroup } from 'react-bootstrap'; import { getSelectedItem, getItemId, renderMessage } from './../helpers'; import Toastr from 'toastr'; class DeleteView extends Component { static handleCancel() { window.history.back(); } constructor(props) { super(props); const { items, match } = props; const { id: selectedId } = match.params; this.state = { selectedId }; } handleConfirm() { const { selectedId: id } = this.state; this.props.deleteItem(id); Toastr.warning('Employee was removed.'); this.props.history.push('/'); } render() { return ( <div data-view="delete"> { renderMessage('warning', 'Are you sure you want to delete this item?') } <ButtonGroup> <Button onClick={() => this.handleConfirm()}>Confirm</Button> <Button onClick={() => DeleteView.handleCancel()}>Cancel</Button> </ButtonGroup> </div> ); } } export default connect((store) => { const { items } = store.data; return { items }; }, { deleteItem })(DeleteView); <file_sep>import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { update as updateItem } from './../store/actions/data'; import { FormGroup, Button, ButtonGroup, Col } from 'react-bootstrap'; import Form from './../components/Form'; import FormHeader from './../components/Form/Header'; import FormFooter from './../components/Form/Footer'; import { getSelectedItem, getItemId, isItemValid } from './../helpers'; import Toastr from 'toastr'; class UpdateView extends Component { constructor(props) { super(props); this.updateTempItem = this.updateTempItem.bind(this); const { items, match } = props; const { id: selectedId } = match.params; items.forEach((item) => { if (item.id.toString() === selectedId) { this.state = { item: Object.assign({}, item) }; } }); } updateTempItem(item) { this.setState({ item }); } handleSave() { const { item } = this.state; const { formFields } = this.props; if (isItemValid(item, formFields)) { Toastr.success('Employee\'s details were updated.'); this.props.updateItem(item); this.props.history.push('/'); } else { Toastr.error('Please fill all fields...', 'Error'); } } handleCancel() { this.props.history.push('/'); } render() { const { item } = this.state; return ( <Form item={item} updateTempItem={this.updateTempItem}> <FormHeader> <Link to="/" className="btn"> Back to items list </Link> <h2>Read</h2> </FormHeader> <FormFooter> <FormGroup> <Col smOffset={2} sm={10}> <Button onClick={() => this.handleSave()}>Save changes</Button> </Col> </FormGroup> </FormFooter> </Form> ); } } export default connect((store) => { const { items, formFields } = store.data; return { items, formFields }; }, { updateItem })(UpdateView); <file_sep>import * as actions from './../actions/data'; import { getIdFromLabel } from './../../helpers'; const defaultState = { sorting: { lastPropName: null, lastDirection: null }, formFields: [ { label: 'ID', dataType: 'number' }, { label: 'First name', dataType: 'text' }, { label: 'Last name', dataType: 'text', required: true }, { label: 'Age', dataType: 'number' }, { label: 'Bio', dataType: 'text' }, { label: 'Start date', dataType: 'date', required: false } ], items: [ { id: 1111, first_name: 'Jan', last_name: 'Chalupa', age: 11, bio: 'Bla bla bla...', bio_HTML: '<p>Bla bla bla...</p>', start_date: '2017-02-01' }, { id: 2222, first_name: 'David', last_name: 'Slavík', age: 22, bio: 'Bla bla bla...', bio_HTML: '<p>Bla bla bla...</p>', start_date: '2016-09-01' }, { id: 3333, first_name: 'Martin', last_name: 'Dušek', age: 33, bio: 'Bla bla bla...', bio_HTML: '<p>Bla bla bla...</p>', start_date: '2014-03-01' } ] }; export default function data(state = defaultState, action) { switch (action.type) { case actions.ADD_ITEM: { const { item: newItem } = action; newItem.id = generateId(state.items); return { ...state, items: [...state.items, newItem] }; } case actions.UPDATE_ITEM: { const { item: updatedItem } = action; const { id: updatedId } = updatedItem; const updatedItems = state.items.map((item) => { if (item.id.toString() === updatedId.toString()) { return updatedItem; } return item; }); return { ...state, items: updatedItems }; } case actions.DELETE_ITEM: { return { ...state, items: state.items.filter((item) => { return item.id.toString() !== action.id; }) }; } case actions.SORT_ITEMS: { const { label } = action; const { items, sorting, formFields } = state; const { items: itemsSorted, metadata } = sort(getIdFromLabel(label), items, sorting, formFields); return { ...state, items: itemsSorted, sorting: metadata }; } default: return state; } } function generateId(items) { const existingIds = []; const generatedId = Math.round(Math.random() * 10000).toString(); if (items) { items.forEach((item) => { existingIds.push(item.id); }); } if (existingIds.indexOf(generatedId) > -1 || generatedId < 1000 || generatedId > 9999) { generateId(); } return generatedId; } function getDataType(id, formFields) { let dataType; formFields.forEach((field) => { if (getIdFromLabel(field.label) === id.toString()) { dataType = field.dataType; } }); return dataType; } function sort(propertyName, items, metadata, fields) { const propertyType = getDataType(propertyName, fields); const itemsClone = [...items]; const metadataClone = { ...metadata }; if (metadataClone.lastPropName === propertyName && metadataClone.lastDirection === 'original') { if (propertyType !== 'number') { itemsClone.sort((a, b) => { if (a[propertyName] < b[propertyName]) { return 1; } else if (a[propertyName] > b[propertyName]) { return -1; } return 0; }); } else { itemsClone.sort((a, b) => { return b[propertyName] - a[propertyName]; }); } if (metadataClone.lastPropName === propertyName) { metadataClone.lastDirection = metadataClone.lastDirection !== 'original' ? 'original' : 'reversed'; } else { metadataClone.lastDirection = 'original'; } } else { if (propertyType !== 'number') { itemsClone.sort((a, b) => { if (a[propertyName] < b[propertyName]) { return -1; } else if (a[propertyName] > b[propertyName]) { return 1; } return 0; }); } else { itemsClone.sort((a, b) => { return a[propertyName] - b[propertyName]; }); } metadataClone.lastDirection = 'original'; } metadataClone.lastPropName = propertyName; return { items: itemsClone, metadata: metadataClone }; } <file_sep>import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { sort as sortItems } from './../../store/actions/data'; import { getIdFromLabel } from './../../helpers'; class Header extends Component { constructor(props) { super(props); const { items } = props; this.state = { numberOfRecords: items.length }; } componentDidMount() { this.props.sortItems(); } componentWillUnmount() { this.props.sortItems(); } getDataType(property) { const { dataTypes } = this.state; let dataType = 'text'; Object.keys(dataTypes).forEach((key) => { if (property === key) { dataType = dataTypes[key]; } }); return dataType; } handleClick(label) { this.props.sortItems(label); } render() { const { numberOfRecords } = this.state; const { formFields, sorting } = this.props; return ( <thead> <tr> { formFields.map((field) => { const { label, dataType } = field; const isSingleRecord = numberOfRecords === 1; const className = (!isSingleRecord && sorting.lastPropName === getIdFromLabel(label)) ? sorting.lastDirection : null; return ( <td key={label} data-type={dataType} className={className}> <button onClick={!isSingleRecord ? () => this.handleClick(label) : null}> {label} </button> </td> ); }) } </tr> </thead> ); } } export default connect((store) => { const { items, formFields, sorting } = store.data; return { items, formFields, sorting }; }, { sortItems })(Header); <file_sep>import React from 'react'; import { Alert } from 'react-bootstrap'; export function isItemValid(item, fields) { let isValid = true; Object.keys(item).forEach((key) => { const value = item[key]; fields.forEach((field) => { if (isValid) { if (key === getIdFromLabel(field.label) && field.required) { if (isNotNullOrEmpty(value)) { isValid = false; } } else if (key === 'id') { isValid = true; } } }); }); return isValid; } export function getIdFromLabel(label) { return label.replace(/\s/, '_').toLowerCase(); } export function isNotNullOrEmpty(value) { return value === null || value === undefined || value === 'null' || value === 'undefined' || value === '' || value === ' '; } export function renderMessage(style, message) { return ( <Alert bsStyle={style}> { message } </Alert> ); } <file_sep>import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { Button, ButtonGroup, Form, FormGroup, FormControl, ControlLabel, Col } from 'react-bootstrap'; import jQuery from 'jquery'; import CKEditor from 'react-ckeditor-component'; import { getIdFromLabel } from './../../helpers'; class GenericForm extends Component { constructor(props) { super(props); const { isReadOnly, item, formFields } = this.props; const itemDataPlaceholder = {}; if (item) { formFields.forEach((field) => { const id = getIdFromLabel(field.label); if (Object.keys(item).indexOf(id) === -1) { item[id] = null; } }); this.state = { isReadOnly, item }; } else if (formFields) { formFields.forEach((field) => { const id = getIdFromLabel(field.label); itemDataPlaceholder[id] = null; }); this.state = { isReadOnly, item: itemDataPlaceholder }; } } componentDidMount() { const { updateTempItem } = this.props; const { item } = this.state; if (updateTempItem) { updateTempItem(item); } } handleChange(e, property, dataType) { const { updateTempItem } = this.props; const { item } = this.state; if (dataType === 'richtext') { const value = e; item[`${property}_HTML`] = value; item[property] = value.replace(/<.+?>/g, ' '); } else { item[property] = e.target.value; } updateTempItem(item); } render() { const { formFields, readOnly: isReadOnly } = this.props; const { item } = this.state; const fieldsFiltered = formFields.filter((field) => { if (getIdFromLabel(field.label) === 'id') { return 0; } return 1; }); const fieldsBlock = fieldsFiltered.map((field) => { const id = getIdFromLabel(field.label); let inputBlock; if (field.dataType === 'richtext') { const value = item[`${id}_HTML`]; if (isReadOnly) { const ckEditorConfig = { readOnly: true, toolbarCanCollapse: true, toolbarStartupExpanded: false }; inputBlock = ( <CKEditor activeClass="p10" config={ckEditorConfig} content={value} /> ); } else { inputBlock = ( <CKEditor activeClass="p10" onChange={(value) => this.handleChange(value, id, 'richtext')} content={value} /> ); } } else { // Text, number, date, ... const value = item[id]; inputBlock = ( <FormControl type={field.dataType} disabled={isReadOnly} defaultValue={value} onChange={(e) => this.handleChange(e, id)} /> ); } return ( <FormGroup key={id} required={field.required}> <Col componentClass={ControlLabel} sm={2}> {field.label} </Col> <Col sm={10}> {inputBlock} </Col> </FormGroup> ); }); return ( <Form horizontal> {this.props.children ? this.props.children[0] : null} {fieldsBlock} {this.props.children ? this.props.children[1] : null} </Form> ); } } export default connect((store) => { const { formFields } = store.data; return { formFields }; })(GenericForm); <file_sep>import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { FormGroup, Button, ButtonGroup, Col } from 'react-bootstrap'; import Form from './../components/Form'; import FormHeader from './../components/Form/Header'; import FormFooter from './../components/Form/Footer'; import { getSelectedItem, getItemId } from './../helpers'; class ReadView extends Component { constructor(props) { super(props); const { items, match } = props; const { id: selectedId } = match.params; items.forEach((item) => { if (item.id.toString() === selectedId) { this.state = { item }; } }); } redirectToList() { this.props.history.push('/'); } redirectToUpdate() { const { item } = this.state; const { id } = item; this.props.history.push(`/update/${id}`); } redirectToDelete() { const { item } = this.state; const { id } = item; this.props.history.push(`/delete/${id}`); } render() { const { item } = this.state; return ( <Form item={item} readOnly> <FormHeader> <Link to="/" className="btn"> Back to items list </Link> <h2>Read</h2> </FormHeader> <FormFooter> <FormGroup> <Col smOffset={2} sm={10}> <ButtonGroup> <Button onClick={() => this.redirectToUpdate()}>Edit</Button> <Button onClick={() => this.redirectToDelete()}>Delete</Button> </ButtonGroup> </Col> </FormGroup> </FormFooter> </Form> ); } } export default connect((store) => { const { items, formFields } = store.data; return { items, formFields }; })(ReadView); <file_sep>import React, { PropTypes } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import MainView from '../views/MainView'; import CreateView from '../views/CreateView'; import ReadView from '../views/ReadView'; import UpdateView from '../views/UpdateView'; import DeleteView from '../views/DeleteView'; export default function Root() { const pages = [ { path: '/', component: MainView }, { path: '/create', component: CreateView }, { path: '/read/:id', component: ReadView }, { path: '/update/:id', component: UpdateView }, { path: '/delete/:id', component: DeleteView } ]; return ( <Router> <Switch> { pages.map((page, i) => { const { path, component } = page; const key = path.replace(/[/:]/g, ''); return ( <Route key={key} path={path} exact component={component} /> ); }) } </Switch> </Router> ); } <file_sep>import 'babel-polyfill'; import 'svgxuse'; import init from './init'; import factory from './factory'; import { render } from './render'; import Root from './components/Root'; import configureStore from './store/configureStore'; const app = (config) => { const store = configureStore(config); render(Root, document.querySelector('#root'), {}, store); }; app(window.config);
a3dbe3dea2110b0acb5a3984b52d911aa882e8dc
[ "JavaScript" ]
11
JavaScript
honzachalupa/crud-react-redux
e5c13b1e007638c64421b946bc8a6592db547d34
5c88a9ce1c3f9431524b478abcf342c35c03c93b
refs/heads/master
<repo_name>geminas/gemini<file_sep>/src/components/todolist/todolist.js import React,{Component,PropType} from 'react' let TodoApp =React.createClass({ render(){ return ( <div> <TodoView items={this.props.items} deleteTodo={this.props.del}/> <TodoControl addTodo={this.props.add}/> </div> ) } }) class TodoView extends Component{ handleDelete(id){ // console.log(e) //console.log(e.target) console.log(id) this.props.deleteTodo(id) } render(){ return ( <ul> { this.props.items.map(v=>{ return( <li key={v.id}> <label>{v.id}:</label> <span>{v.msg}</span> <span><button data-id={v.id} onClick={()=>{this.handleDelete(v.id)}}>DELETE</button></span> </li> ) }) } </ul> ) } } class TodoControl extends Component{ handleClick(e){ this.props.addTodo(this.refs.ctl_input.value) this.refs.ctl_input.value='' } render(){ return ( <div> <input ref="ctl_input" id="todo-ctl-input" placeholder="You Can Write What You Wanna Do Here" type="text"/> <button onClick={this.handleClick.bind(this)} ><span>Add Todo</span></button> </div> ) } } export default TodoApp<file_sep>/src/components/animatebox/animatebox.js import React,{Component} from 'react' import TransitionGroup from 'react-addons-transition-group'; import {findDOMNode} from 'react-dom' import ReactCSSTransitionGroup from 'react/lib/ReactCSSTransitionGroup'; class Box extends Component{ componentWillEnter(cb){ const el=findDOMNode(this) TweenMax.fromTo(el,0.3,{y:100,opacity:0},{y:0,opacity:1.0,onComplete:cb}); } componentWillLeave(cb){ const el=findDOMNode(this) TweenMax.fromTo(el,0.3,{y:0,opacity:1.0},{y:100,opacity:0,onComplete:cb}); } render(){ return( <div className="box"> <style >{` .box{ color:red; background:blue; width:50px; height:50px; margin-top:10px; } `}</style> </div> ) } } class Box2 extends Component{ render(){ return( <div className="box2"> <style >{` .box{ color:red; background:blue; width:50px; height:50px; margin-top:10px; } `}</style> </div> ) } } class Box3 extends Component{ componentWillEnter(cb){ const el=findDOMNode(this) TweenMax.fromTo(el,0.3,{x:100,opacity:0},{x:0,opacity:1.0,onComplete:cb}); } componentWillLeave(cb){ const el=findDOMNode(this) TweenMax.fromTo(el,0.3,{x:0,opacity:1.0},{x:100,opacity:0,onComplete:cb}); } render(){ return( <div className="box3"> <style >{` .box3{ color:red; background:brown; width:50px; height:50px; margin-top:10px; } `}</style> </div> ) } } class AnimateBox extends Component{ // getInitialState(){ // return { // shouldShowBox: true // } // } constructor(props){ super(props) this.state={ shouldShowBox:true } } toggleBox(){ this.setState({ shouldShowBox: !this.state.shouldShowBox }); } render(){ return ( <div className="animate-box"> <style>{` .example-enter { opacity: 0.01; } .example-enter.example-enter-active { opacity: 1; transition: opacity 500ms ease-in; } .example-leave { opacity: 1; } .box2{ color:red; background:green; width:50px; height:50px; margin-top:10px; } .example-leave.example-leave-active { opacity: 0.01; transition: opacity 300ms ease-in; } `}</style> <div> <button onClick={this.toggleBox.bind(this)}> Button </button> <TransitionGroup> {this.state.shouldShowBox&&<Box/>} </TransitionGroup> <ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}> {this.state.shouldShowBox&&<Box2/>} </ReactCSSTransitionGroup> <TransitionGroup> {this.state.shouldShowBox&&<Box3/>} </TransitionGroup> </div> </div> ) } } export default AnimateBox;
3d471621a854de579cfcd9de2c3c7bd777abb812
[ "JavaScript" ]
2
JavaScript
geminas/gemini
5cc33a2d393760e7c0ed9150cef9e61bc05cb7cb
78f901bf0aa917ed414f90e9d404231ab74b4390
refs/heads/master
<repo_name>chepe263/quick-dirty-node-mailer<file_sep>/index.js const mailgun = require("mailgun-js"); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = process.env.PORT || 3001; const ejs = require('ejs'); const fs = require('fs'); if(process.env.DO_LOAD_DOTENV == undefined){ const dotenv = require('dotenv').config(); } const mg = mailgun({apiKey: process.env.MAILGUN_APIKEY, domain: process.env.MAILGUN_DOMAIN}); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.get('/', (req, res) => res.redirect(process.env.REDIRECT_HOME || 'http://google.com')) var allowCrossDomain = function(req, res, next) { var allowed_from = process.env.CORS_ALLOW_ORIGINS.split(";"); var should_allow = allowed_from.indexOf(req.get('origin')) !== -1; if(should_allow){ console.log("Welcome to my mailer!"); res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); // intercept OPTIONS method if ('OPTIONS' == req.method) { res.sendStatus(200); } else { next(); } } else { console.log("Get out of here!", req.get('origin')); res.status(403).json({"result": "you are not allowed to talk to me"}) } }; app.use(allowCrossDomain); app.post('/mail-ami', (req, res) => { var missing_info = []; if(!req.body.nombre || req.body.nombre.toString().length < 3){ missing_info.push("nombre < 3"); } if(!req.body.email ||req.body.email.toString().length < 3){ missing_info.push("email < 3"); } if(!req.body.telefono || req.body.telefono.toString().length < 6){ missing_info.push("telefono < 3"); } if(!req.body.servicio || req.body.servicio.toString().length < 3){ missing_info.push("servicio < 3"); } if(!req.body.mensaje || req.body.mensaje.toString().length < 3){ missing_info.push("mensaje < 3"); } if (missing_info.length > 0){ res.status(403).json({status: "error", "data": missing_info}); return; } //load templates var contents_html = fs.readFileSync('templates/legales-ami.html', 'utf8'); var contents_text = fs.readFileSync('templates/legales-ami.txt', 'utf8'); //parse templates var compiled_html = ejs.render(contents_html, { nombre: req.body.nombre, email: req.body.email, telefono: req.body.telefono, servicio: req.body.servicio, mensaje: req.body.mensaje, }); var compiled_text = ejs.render(contents_text, { nombre: req.body.nombre, email: req.body.email, telefono: req.body.telefono, servicio: req.body.servicio, mensaje: req.body.mensaje, }); const data = { from: process.env.MAIL_FROM_LEGALES_AMI || 'Formulario Contacto <<EMAIL>>', to: process.env.MAIL_TO_LEGALES_AMI, subject: 'Formulario de Contacto', text: compiled_text, html: compiled_html, 'h:Reply-To': process.env.MAIL_REPLY_TO }; var message_status = mg.messages().send(data, function (error, body) { //console.log(body); if(body.message == 'Queued. Thank you.'){ res.json({"result": "ok"}) } else { res.json({"result": "nope"}) } return body; }); //res.send('Hello World!') }) app.listen(port, () => console.log(`Example app listening on port ${port}!`))<file_sep>/.env.example MAILGUN_APIKEY='' MAILGUN_BASE_URL='' MAILGUN_DOMAIN='' MAIL_REPLY_TO='' MAIL_TO='' CORS_ALLOW_ORIGINS='' //Do not let people snoop aroud my home. REDIRECT_HOME=''
116bad28ecc98a971d60754d78825bf62334e963
[ "JavaScript", "Shell" ]
2
JavaScript
chepe263/quick-dirty-node-mailer
e37bf1683d45115135e9c51789853af60053cb16
161f20c5e541e99250ec5b680b0a7899a1808ab1
refs/heads/master
<file_sep>normal[:mod_php5_apache2][:packages] = [ "php7.0-xsl", "php7.0-curl", "php7.0-gd", "php7.0-mcrypt" ] <file_sep># Cookbook Name:: apache2 # Recipe:: mod_php7 # case node[:platform_family] when 'debian' package 'libapache2-mod-php7.0' do action :install options '--force-yes' end when 'rhel' package 'php' do action :install notifies :run, "execute[generate-module-list]", :immediately not_if 'which php' end # remove stock config file File.join(node[:apache][:dir], 'conf.d', 'php.conf') do action :delete end # replace with debian config template File.join(node[:apache][:dir], 'mods-available', 'php7.0.conf') do source 'mods/php5.conf.erb' notifies :restart, "service[apache2]" end end apache_module 'php7.0' do if platform_family?('rhel') filename 'libphp5.so' end end<file_sep>package 'php-mysql' do options '--force-yes' package_name value_for_platform_family( 'rhel' => 'php-mysql', 'debian' => 'php7.0-mysql' ) end
603ea81708762463613da3bda4668562d3a68d33
[ "Ruby" ]
3
Ruby
salvianoo/opsworks-custom-cookbooks
ededd7769a607904163338207b540de10fa2a6e8
80c1f169bb1873822df5f6569b8c799231f3b559
refs/heads/master
<repo_name>luismikg/MyMap<file_sep>/app/src/main/java/com/example/luismiguel/mymap/MainActivity.kt package com.example.luismiguel.mymap import android.content.Intent import android.content.SharedPreferences import android.content.pm.ActivityInfo import android.content.res.Configuration import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.preference.PreferenceManager import android.view.Menu import android.view.MenuItem import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.widget.Toast class MainActivity : AppCompatActivity() { private var isSmarthone: Boolean = true private var preferencesChanged: Boolean = false companion object { public const val NUMBER_PLACES_TO_SHOW = "prefNumberButtons" public const val PREFERENCE_ZOOM = "prefZoom" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) this.initActivity() //https://www.skyscanner.es/noticias/10-lugares-espectaculares-del-mundo-que-deberias-visitar //PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener( preferencesChangeListener ) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { if( this.isSmarthone ){ //this.menuInflater.inflate(R.menu.configuration_places, menu) this.menuInflater.inflate(R.menu.configuration_buttons, menu) } return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val preferencesIntent:Intent = Intent(this, PreferencesPlacesConfigurations::class.java) startActivity( preferencesIntent ) return super.onOptionsItemSelected(item) } private fun initActivity(){ this.initScreen() this.initActions() } private fun initScreen(){ val screenSize:Int = resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK if( screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE || screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE ) { this.isSmarthone = false } if( this.isSmarthone ){ this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT }else{ this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } } private fun initActions(){ PreferenceManager.setDefaultValues(this, R.xml.preferences, false) //Registro del "listener" para SharedPreferences PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(preferencesChangeListener) } private val preferencesChangeListener = OnSharedPreferenceChangeListener { sharedPreferences, key -> // Called when the user changes the app's preferences. this.preferencesChanged = true // User changed app settings. val placesFragment = supportFragmentManager.findFragmentById(R.id.placesFragment) as MapAndPlacesFragment if (key == NUMBER_PLACES_TO_SHOW) { // Number of choices to display changed. placesFragment.updateGuessRows(sharedPreferences) }else if( key == PREFERENCE_ZOOM ){ placesFragment.updateZoom(sharedPreferences) } Toast.makeText(this@MainActivity, "Ok", Toast.LENGTH_SHORT).show() } } <file_sep>/app/src/main/java/com/example/luismiguel/mymap/MapsActivity.kt package com.example.luismiguel.mymap import android.content.pm.PackageManager import android.location.Location import android.os.Bundle import android.support.v4.app.ActivityCompat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions class MapsActivity : SupportMapFragment(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private lateinit var lastLocation:Location private lateinit var fusedLocationProviderClient: FusedLocationProviderClient private var zoom:Float = 10.0f companion object { private const val LOCATION_PERMISSION_REQUEST_CODE = 1 } override fun onCreateView(p0: LayoutInflater, p1: ViewGroup?, p2: Bundle?): View? { val v: View? = super.onCreateView(p0, p1, p2) this.getMapAsync(this) this.fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity!!) return v } private fun setUpMap(){ if( ActivityCompat.checkSelfPermission(activity!!, android.Manifest.permission.ACCESS_FINE_LOCATION )!=PackageManager.PERMISSION_GRANTED ){ requestPermissions(arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE ) } else { this.mMap.isMyLocationEnabled = true this.fusedLocationProviderClient.lastLocation.addOnSuccessListener(activity!!) { location -> if (location != null) { this.lastLocation = location val currentLatLng = LatLng(location.latitude, location.longitude) this.mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, this.zoom)) } } } } public fun setMarker( nombre:String, latitude:Double, longitude:Double){ val place = LatLng( latitude, longitude ) val markerOpcions = MarkerOptions().position( place ) markerOpcions.title( nombre ) this.mMap.addMarker( markerOpcions ) this.mMap.animateCamera( CameraUpdateFactory.newLatLngZoom(place, this.zoom) ) } public fun clearMarked(){ this.mMap.clear() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { this.setUpMap() } public fun setZoom( zoom:Float ){ this.zoom = zoom this.setUpMap() } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap mMap.uiSettings.isZoomGesturesEnabled = true this.setUpMap() } } /*https://stackoverflow.com/questions/41753706/show-current-location-inside-google-map-fragment https://androidteachers.com/kotlin-for-android/get-location-in-android-with-kotlin/ */ <file_sep>/app/src/main/java/com/example/luismiguel/mymap/MapAndPlacesFragment.kt package com.example.luismiguel.mymap import android.content.Context import android.content.SharedPreferences import android.content.res.Resources import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout // TODO: Rename parameter arguments, choose names that match data class Site(val nombre:String, val latitude:Double, val longitude:Double) /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [MapAndPlacesFragment.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [MapAndPlacesFragment.newInstance] factory method to * create an instance of this fragment. * */ class MapAndPlacesFragment : Fragment() { // TODO: Rename and change types of parameters private lateinit var layoutPlaces: ArrayList<LinearLayout> //Places lateinit var place1:Site lateinit var place2:Site lateinit var place3:Site lateinit var place4:Site lateinit var place5:Site lateinit var place6:Site lateinit var place7:Site lateinit var place8:Site lateinit var place9:Site lateinit var place10:Site override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view:View = inflater.inflate(R.layout.fragment_map_and_places, container, false) this.initActivity( view ) return view } private fun initActivity( view: View ){ this.initActions( view ) } private fun initActions( view: View ){ this.initLayoutPlaces( view ) this.initButtonPlaces( view ) } private fun initLayoutPlaces( view: View ){ this.layoutPlaces = ArrayList() this.layoutPlaces.add( view.findViewById(R.id.layoutPlaces1) ) this.layoutPlaces.add( view.findViewById(R.id.layoutPlaces2) ) this.layoutPlaces.add( view.findViewById(R.id.layoutPlaces3) ) this.layoutPlaces.add( view.findViewById(R.id.layoutPlaces4) ) this.layoutPlaces.add( view.findViewById(R.id.layoutPlaces5) ) //Places this.place1 = Site( getString(R.string.site1), -20.1337772, -67.4891345) this.place2 = Site( getString(R.string.site2), -14.087238, -75.763030) this.place3 = Site( getString(R.string.site3), -38.261346, 175.123145) this.place4 = Site( getString(R.string.site4), -25.695245, -54.436658) this.place5 = Site( getString(R.string.site5), -30.591075, 115.160251) this.place6 = Site( getString(R.string.site6), 2.264229, -73.794448) this.place7 = Site( getString(R.string.site7), 38.629180, 34.803982) this.place8 = Site( getString(R.string.site8), -21.650979, 35.469177) this.place9 = Site( getString(R.string.site9), 55.240813, -6.511553) this.place10 = Site( getString(R.string.site10), -50.494702, -73.137639) } private fun initButtonPlaces( view: View ){ val buttonSite1:Button = view.findViewById(R.id.site1) as Button val buttonSite2:Button = view.findViewById(R.id.site2) as Button val buttonSite3:Button = view.findViewById(R.id.site3) as Button val buttonSite4:Button = view.findViewById(R.id.site4) as Button val buttonSite5:Button = view.findViewById(R.id.site5) as Button val buttonSite6:Button = view.findViewById(R.id.site6) as Button val buttonSite7:Button = view.findViewById(R.id.site7) as Button val buttonSite8:Button = view.findViewById(R.id.site8) as Button val buttonSite9:Button = view.findViewById(R.id.site9) as Button val buttonSite10:Button = view.findViewById(R.id.site10) as Button buttonSite1.setOnClickListener { view -> this.showPlace("place1") } buttonSite2.setOnClickListener { view -> this.showPlace("place2") } buttonSite3.setOnClickListener { view -> this.showPlace("place3") } buttonSite4.setOnClickListener { view -> this.showPlace("place4") } buttonSite5.setOnClickListener { view -> this.showPlace("place5") } buttonSite6.setOnClickListener { view -> this.showPlace("place6") } buttonSite7.setOnClickListener { view -> this.showPlace("place7") } buttonSite8.setOnClickListener { view -> this.showPlace("place8") } buttonSite9.setOnClickListener { view -> this.showPlace("place9") } buttonSite10.setOnClickListener { view -> this.showPlace("place10") } } // TODO: Rename method, update argument and hook method into UI event private fun showPlace( place: String ){ val mapActivity = childFragmentManager.findFragmentById(R.id.mapFragment) as MapsActivity mapActivity.clearMarked() when(place){ "place1" -> { mapActivity.setMarker( this.place1.nombre, this.place1.latitude, place1.longitude ) } "place2" -> mapActivity.setMarker( this.place2.nombre, this.place2.latitude, place2.longitude ) "place3" -> mapActivity.setMarker( this.place3.nombre, this.place3.latitude, place3.longitude ) "place4" -> mapActivity.setMarker( this.place4.nombre, this.place4.latitude, place4.longitude ) "place5" -> mapActivity.setMarker( this.place5.nombre, this.place5.latitude, place5.longitude ) "place6" -> mapActivity.setMarker( this.place6.nombre, this.place6.latitude, place6.longitude ) "place7" -> mapActivity.setMarker( this.place7.nombre, this.place7.latitude, place7.longitude ) "place8" -> mapActivity.setMarker( this.place8.nombre, this.place8.latitude, place8.longitude ) "place9" -> mapActivity.setMarker( this.place9.nombre, this.place9.latitude, place9.longitude ) "place10" -> mapActivity.setMarker( this.place10.nombre, this.place10.latitude, place10.longitude ) } } public fun updateGuessRows( sharedPreferences: SharedPreferences ){ val numberPlacesToShow:String = sharedPreferences.getString( MainActivity.NUMBER_PLACES_TO_SHOW,"10" ) val numberLayoutButtonVisibled = Integer.parseInt(numberPlacesToShow) / 2; for (layout:LinearLayout in this.layoutPlaces){ layout.visibility = View.GONE } for (i in 0..numberLayoutButtonVisibled-1){ layoutPlaces[i].visibility = View.VISIBLE } } public fun updateZoom( sharedPreferences: SharedPreferences ){ val strZoom = sharedPreferences.getString( MainActivity.PREFERENCE_ZOOM, "10.0" ) val mapActivity = childFragmentManager.findFragmentById(R.id.mapFragment) as MapsActivity mapActivity.setZoom( strZoom.toFloat() ) } } <file_sep>/app/src/main/java/com/example/luismiguel/mymap/PreferencesPlacesConfigurations.kt package com.example.luismiguel.mymap import android.os.Bundle import android.support.v7.app.AppCompatActivity class PreferencesPlacesConfigurations : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_preferences_places_configurations) } }
62edb11f82dcbb67ee5e4178d7bfb2edc7d68de5
[ "Kotlin" ]
4
Kotlin
luismikg/MyMap
79b7cbe96f67b8a136eca4117247ed9fd1b6e9ad
515d4341f6ea788bd10d9b3b7b8acae3f7ec137a
refs/heads/master
<repo_name>heyMP/SidrJS<file_sep>/sidrjs.js (function ($) { Drupal.behaviors.sidrjs = { attach: function (context, settings) { //Set variables from the module var target = Drupal.settings.sidrjs.sidrjs_target; var menu_output = Drupal.settings.sidrjs.sidrjs_selected_menu_output; //Add the Responsive menu $('body').prepend('<div id="mobile-header"><a id="responsive-menu-button" href="#sidr-main">Menu</a></div>'); //Invoke Sidr $('#responsive-menu-button').sidr({ name: 'sidr-main', //the source is the sidr_target variable //from the admin menu source: menu_output }); } }; }(jQuery));<file_sep>/README.md SidrJS ====== This is a Drupal module that utilizes the sidr.js jQuery plugin developed by <NAME>. http://www.berriart.com/sidr <file_sep>/sidrjs_config_form.inc <?php /* * Sidrjs Configuration Settings Form */ function sidrjs_config_form($form, &$form_state) { $form['sidrjs_target'] = array( '#type' => 'textfield', '#title' => t('Target'), '#default_value' => variable_get('sidrjs_target'), '#description' => t('Include the ID of the div the contains the navigation you want to render in the Sidr.js mobile navigation.'), ); $form['sidrjs_menus'] = array( '#type' => 'checkboxes', '#title' => t('Menus'), '#default_value' => variable_get('sidrjs_menus'), '#options' => menu_list_system_menus(), '#description' => t('Select the menus you want to display in the Sidr mobile navigation.') ); $form['sidrjs_theme'] = array( '#type' => 'radios', '#title' => t('Theme'), '#default_value' => variable_get('sidrjs_theme', 'dark'), '#options' => array( 'dark' => t('Dark'), 'light' => t('Light') ), '#description' => t('Select which style theme to use.'), ); return (system_settings_form($form)); }
2c9a434e765fff9fa405606924ac69b3072d263d
[ "JavaScript", "PHP", "Markdown" ]
3
JavaScript
heyMP/SidrJS
ffc9db9f6057ffd6887d40f556afbadbd7e2e9f2
ce0ce6c640ef99ae75a005a3a754df26477b5823
refs/heads/master
<file_sep>Django==2.2.7 gunicorn==19.9.0 pytz==2019.3 sqlparse==0.3.0 virtualenv==16.7.7 whitenoise==4.1.4 <file_sep>from django.contrib import admin from .models import Student , Eventlst , Pointstable class StudentAdmin(admin.ModelAdmin): list_display = ('admno','sname','gender','category','house','sclass','ssec','event1','event2','event3') class EventAdmin(admin.ModelAdmin): list_display = ('eventname','status') ordering =('eventname',) class PointsAdmin(admin.ModelAdmin): list_display = ('admno','event','points') admin.site.register(Student, StudentAdmin) admin.site.register(Eventlst, EventAdmin) admin.site.register(Pointstable, PointsAdmin)<file_sep># Generated by Django 2.2.6 on 2019-10-30 09:20 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Student', fields=[ ('admno', models.AutoField(primary_key=True, serialize=False)), ('sname', models.CharField(max_length=100)), ('category', models.CharField(max_length=5)), ('house', models.CharField(max_length=10)), ('sclass', models.IntegerField()), ('event1', models.CharField(max_length=20)), ('event2', models.CharField(max_length=20)), ], ), ] <file_sep> from django.shortcuts import render import datetime from django.shortcuts import redirect from django.http import HttpResponse from django.db import connection from .models import Student , Eventlst , Pointstable context={} def adm(request): cursor = connection.cursor() cursor.execute("SELECT adm_student.sname ,adm_student.sclass,adm_student.ssec,adm_student.category,adm_student.house,max(adm_pointstable.points)as tpoints FROM adm_student INNER JOIN adm_pointstable ON adm_student.admno = adm_pointstable.admno GROUP BY adm_student.sname") context['top'] = cursor.fetchall() admlst = Student.objects.values('admno') adm_lst = [] for v in admlst: adm_lst.append(v['admno']) context['adm_lst'] = adm_lst if request.POST: up_gadm = request.POST['upadmno'] context['up_adm']=up_gadm return redirect('/up_details/') user = request.user if user.is_authenticated: if user.is_superuser: return render(request,"admin.html",context) else: fltr = user.username reg_stu = Student.objects.filter(house=fltr) context['reg_det']=reg_stu return render(request,"st_house.html",context) else: return redirect('/login/') def add_stu(request): selectclass=[2,3,4,5,6,7,8,9,10,11,12] context['selectclass']=selectclass eventlst = Eventlst.objects.values('eventname') w = [] for x in eventlst: w.append(x['eventname']) context['eventlst'] = w if request.POST: #return HttpResponse("<script>console.log('in backend')</script>") sadmno = request.POST.get('admno') sname = request.POST.get('sname') scate = request.POST.get('ageGroup') shouse = request.POST.get('shouse') event1 = request.POST.get('event1') event2 = request.POST.get('event2') sclass = request.POST.get('sclass') sgen = request.POST.get('gender') ssec = request.POST.get('ssec') if sclass in ["11","12"]: adddetails = Student(admno=sadmno,sname=sname,category=scate,gender=sgen,sclass=sclass,ssec=ssec,event1=event1,event2=event2).save() else: add_details = Student(admno=sadmno,sname=sname,category=scate,gender=sgen,house=shouse,sclass=sclass,ssec=ssec,event1=event1,event2=event2).save() user = request.user if user.is_authenticated: return render(request,"add_stu.html",context) else: return redirect('/login/') def up_details(request): up_status = 0 up_adm = context['up_adm'] up_studetails = Student.objects.filter(admno = up_adm) context['predet'] = up_studetails if len(up_studetails) > 0: if request.POST: usadmno = request.POST.get('admno') usname = request.POST.get('sname') ushouse = request.POST.get('shouse') uevent1 = request.POST.get('event1') uevent2 = request.POST.get('event2') usclass = request.POST.get('sclass') up_studetails.update(admno=usadmno,sname=usname,house=ushouse,sclass=usclass,event1=uevent1,event2=uevent2) up_status = 1 if up_status == 1: return redirect('/dashboard/') user = request.user if user.is_authenticated: return render(request,"up_details.html",context) else: return redirect('/login/') def up_points(request): peventlst = Eventlst.objects.values('eventname') wx = [] for x in peventlst: wx.append(x['eventname']) context['peventlst'] = wx if request.POST: padmno = request.POST['padmno'] pgame = request.POST['pgame'] evgpoint = 0 if pgame == "relay(4x100)": evgpoint = request.POST['relayp'] else: evgpoint = request.POST['nrmlp'] evpoint = Pointstable(admno=padmno,event=pgame,points=evgpoint).save() user = request.user if user.is_authenticated: if user.is_superuser: return render(request,"up_points.html",context) else: return redirect("dashboard") else: return redirect('/login/') def up_event(request): pre_stat = Eventlst.objects.values('eventname').filter(status=False) pre_lst = [] for er in pre_stat: pre_lst.append(er['eventname']) context['prestat'] = pre_lst if request.POST: up_stat = request.POST['upevent'] Pre_stat=Eventlst.objects.filter(eventname=up_stat).update(status=True) user = request.user if user.is_authenticated: if user.is_superuser: return render(request,"up_event.html",context) else: return redirect("dashboard") else: return redirect('/login/') <file_sep>{% extends "adm_layout.html" %} {% block body %} <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-2 col-md-3 col-lg-2"></div> <div class="col-sm-8 col-md-6 col-lg-8"> <div class="card"> <div class="card-header bg-primary text-center"> TOP PERFORMERS </div> <div class="card-body bg-dark"> <table class="table table-dark table-hover"> <thead> <th>Student's name</th> <th>Class</th> <th>Section</th> <th>Category</th> <th>House</th> <th>Total points</th> </thead> <tbody> {% for x in top%} <tr> <td>{{x.0}}</td> <td> {{x.1}} </td> <td> {{x.2}} </td> <td>{{x.3}}</td> <td> {{x.4}} </td> <td> {{x.5}} </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> <div class="col-sm-2 col-md-3 col-lg-2"></div> </div> <br><br> </div> {% endblock %}<file_sep># Generated by Django 2.2.6 on 2019-10-30 09:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adm', '0001_initial'), ] operations = [ migrations.CreateModel( name='Eventlst', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('eventname', models.CharField(max_length=20)), ('status', models.BooleanField(default=0)), ], ), migrations.CreateModel( name='Pointstable', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('admno', models.IntegerField()), ('event', models.CharField(max_length=20)), ('points', models.IntegerField()), ], ), ] <file_sep>from django.shortcuts import render , redirect from django.contrib.auth import login, authenticate, logout from adm.models import Student , Eventlst , Pointstable from django.db import connection incontext = {} def index(request): user = request.user if user.is_authenticated: return redirect("dashboard") cursor = connection.cursor() upc_event = Eventlst.objects.values('eventname').filter(status=False) upc_lst = [] for f in upc_event: upc_lst.append(f['eventname']) incontext['upcoming'] = upc_lst[0:5] comp_event = Eventlst.objects.values('eventname').filter(status=True) comp_lst = [] for e in comp_event: comp_lst.append(e['eventname']) incontext['completed'] = comp_lst[0:5] fgraph = cursor.execute("SELECT adm_student.house as house, SUM( CASE WHEN points IN (3,20) THEN 1 ELSE 0 END ) AS goldcount,SUM( CASE WHEN points IN (2,15) THEN 1 ELSE 0 END ) AS silvercount, SUM( CASE WHEN points IN (1,10) THEN 1 ELSE 0 END ) AS bronzecount,sum(adm_pointstable.points)as tpoints FROM adm_student INNER JOIN adm_pointstable ON adm_student.admno = adm_pointstable.admno GROUP BY adm_student.house") frow = cursor.fetchall() incontext['pt'] = frow return render(request,"index.html",incontext) def login_view(request): user = request.user if user.is_authenticated: return redirect("dashboard") if request.POST: usr = request.POST['usr'] psw = request.POST['pswd'] user = authenticate(username=usr,password=psw) if user: login(request, user) return redirect("dashboard") return render(request,"login.html") def logout_view(request): logout(request) return redirect("index") <file_sep>from django.db import models class Student(models.Model): admno = models.AutoField(primary_key=True) sname = models.CharField(max_length=100) category = models.CharField(max_length=5) gender = models.CharField(max_length=6,default="NULL") house = models.CharField(max_length=10,null=True) sclass = models.IntegerField() ssec = models.CharField(max_length=10,default="NULL") event1 = models.CharField(max_length=20,default="NULL") event2 = models.CharField(max_length=20,default="NULL") event3 = models.CharField(max_length=20,null=True) class Eventlst(models.Model): eventname = models.CharField(max_length=20) status = models.BooleanField(default=False) class Pointstable(models.Model): admno = models.IntegerField() event = models.CharField(max_length=20) points = models.IntegerField() <file_sep>"""atheletics URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from index import views as index_views from adm import views as adm_views urlpatterns = [ path('admin/', admin.site.urls), path('',index_views.index, name="index"), path('dashboard/',adm_views.adm, name="dashboard"), path('add_stud/',adm_views.add_stu, name="add_stu"), path('up_details/',adm_views.up_details, name="up_details"), path('up_points/',adm_views.up_points, name="up_points"), path('up_event/',adm_views.up_event, name="up_event"), path('login/',index_views.login_view, name="u_login"), path('logout/',index_views.logout_view, name="u_logout"), ] <file_sep># Generated by Django 2.2.6 on 2019-11-04 08:10 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('adm', '0003_pointstable_medals'), ] operations = [ migrations.RenameField( model_name='pointstable', old_name='medals', new_name='medal', ), ] <file_sep>{% extends "adm_layout.html" %} {% block body %} <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-2 col-md-3 col-lg-4"></div> <div class="col-sm-8 col-md-6 col-lg-4"> <div class="card" background="transparent"> <div class="card-header bg-primary"> Update Event details </div> <div class="card-body"> <form method="POST" action="/up_event/"> {% csrf_token %} <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">Select Game</span> </div> <Select name="upevent" class="custom-select form-control" required> {% for a in prestat%} <option value="{{a}}">{{a}}</option> {% endfor %} </Select> </div><br> <input type="submit"> </form> </div> </div> </div> <div class="col-sm-2 col-md-3 col-lg-4"></div> </div> <br><br><br> </div> {% endblock %}<file_sep># Generated by Django 2.2.4 on 2008-07-30 19:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('adm', '0004_auto_20191104_1340'), ] operations = [ migrations.RemoveField( model_name='pointstable', name='medal', ), ] <file_sep># Generated by Django 2.2.4 on 2008-07-30 20:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adm', '0005_remove_pointstable_medal'), ] operations = [ migrations.AddField( model_name='student', name='gender', field=models.CharField(default='NULL', max_length=6), ), migrations.AddField( model_name='student', name='ssec', field=models.CharField(default='NULL', max_length=10), ), migrations.AlterField( model_name='student', name='event1', field=models.CharField(default='NULL', max_length=20), ), migrations.AlterField( model_name='student', name='event2', field=models.CharField(default='NULL', max_length=20), ), ] <file_sep># Generated by Django 2.2.6 on 2019-11-04 08:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adm', '0002_eventlst_pointstable'), ] operations = [ migrations.AddField( model_name='pointstable', name='medals', field=models.CharField(default='0', max_length=20), ), ]
9fe8ec15be7c6d7a37dea997235bb438c29a9a0b
[ "Python", "Text", "HTML" ]
14
Text
gauravkr133/hissport
3779a107656d6a7b3b38f898d932c468d4ccdeb2
3ede9cc4baaf279036fff22038e8b9d4364dae1e
refs/heads/master
<repo_name>extrem7/Simbock<file_sep>/webpack.admin.js const mix = require('laravel-mix') const config = require('./webpack.config') require('laravel-mix-svg-vue') require('laravel-mix-merge-manifest') mix.webpackConfig({ output: {chunkFilename: 'admin/js/chunks/[name].js?id=[chunkhash]'}, ...config }) mix.options({processCssUrls: false}) mix.sass('modules/Admin/resources/scss/app.scss', 'public/admin/css').version().sourceMaps() mix.js('modules/Admin/resources/js/app.js', 'public/admin/js').vue().svgVue({svgPath: 'modules/Admin/resources/assets/svg'}).version().sourceMaps() mix.copy('node_modules/pace-js/themes/blue/pace-theme-minimal.css', 'public/admin/css/pace.css') mix.copy('node_modules/pace-js/pace.min.js', 'public/admin/js/pace.js') mix.copy('modules/Admin/resources/assets/img', 'public/admin/img') mix.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/admin/webfonts') mix.mergeManifest() <file_sep>/app/Models/Interfaces/SearchRecordable.php <?php namespace App\Models\Interfaces; use Illuminate\Database\Eloquent\Relations\HasMany; interface SearchRecordable { public function searchQueries(): HasMany; } <file_sep>/database/migrations/2020_09_23_143709_create_volunteer_certificates_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerCertificatesTable extends Migration { public function up() { Schema::create('volunteer_certificates', function (Blueprint $table) { $table->id(); $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->string('title'); $table->string('issuing_authority')->nullable(); $table->year('year')->nullable(); $table->string('description')->nullable(); }); } public function down() { Schema::dropIfExists('volunteer_certificates'); } } <file_sep>/modules/Frontend/Http/Controllers/CompanyController.php <?php namespace Modules\Frontend\Http\Controllers; use App\Models\Company; use App\Models\Vacancy; use Auth; class CompanyController extends Controller { public function show(Company $company) { $this->seo()->setTitle("$company->name | Companies"); $company->load('logoMedia', 'city', 'size', 'vacancies'); $company->append(['logo', 'employment', 'location']); $company->vacancies->transform(fn(Vacancy $v) => $v->append(['employment', 'date', 'location'])); share(compact('company')); return view('frontend::companies.show'); } public function self() { return $this->show(Auth::getUser()->company); } } <file_sep>/modules/Frontend/resources/js/plugins/index.js import Vue from 'vue' import dayjs from 'dayjs' Vue.mixin({ methods: { shared: (key) => shared()[key], notify(text, variant = 'success', delay = 3, position = 'top') { this.$bus.emit('alert', {variant, text, delay, position}) }, dayjs } }) import route, {Ziggy} from 'ziggy' Vue.mixin({ methods: { route: (name, params, absolute) => route('frontend.' + name, params, absolute, Ziggy), isRoute: (name) => route(null, {}, null, Ziggy).current('frontend.' + name), routeIncludes: (fragments) => route(null, {}, null, Ziggy) .current() .match(new RegExp(`(${fragments.join('|')})`)) } }) import './axios' import {VBModal, VBTooltip} from 'bootstrap-vue' Vue.directive('b-modal', VBModal) Vue.directive('b-tooltip', VBTooltip) import VueBus from 'vue-bus' import SvgVue from 'svg-vue' import './ls' import VueLazyload from 'vue-lazyload' import VueScrollTo from 'vue-scrollto' import VueObserveVisibility from 'vue-observe-visibility' Vue.use(VueBus) Vue.use(SvgVue) Vue.use(VueLazyload, { error: '/dist/img/no-image.jpg', }) Vue.use(VueScrollTo) Vue.use(VueObserveVisibility) <file_sep>/app/Models/Volunteers/Resume.php <?php namespace App\Models\Volunteers; use Illuminate\Database\Eloquent\Model; use Spatie\MediaLibrary\MediaCollections\Models\Media; class Resume extends Model { public const UPDATED_AT = null; protected $table = 'volunteer_resumes'; protected $fillable = ['title', 'file_id']; protected $appends = ['url']; public function file(): Media { return Media::find($this->file_id); } public function getUrlAttribute(): string { return $this->file()->getFullUrl(); } } <file_sep>/modules/Frontend/Http/Controllers/Auth/LoginController.php <?php namespace Modules\Frontend\Http\Controllers\Auth; use Illuminate\Http\JsonResponse; use Illuminate\Http\Response; use Modules\Frontend\Http\Controllers\Controller; use App\Models\User; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Route2Class; class LoginController extends Controller { use AuthenticatesUsers { logout as parentLogout; } public function __construct() { $this->middleware('guest')->except('logout'); } public function showLoginForm() { $this->seo()->setTitle(__('meta.login.title')); $this->seo()->setDescription(__('meta.login.description')); Route2Class::addClass('bg-decorative'); return view('frontend::auth.login'); } public function redirectPath(User $user): string { return route('frontend.' . ($user->is_volunteer ? 'vacancies.search' : 'company.board')); } protected function sendLoginResponse(Request $request): JsonResponse { $request->session()->regenerate(); $this->clearLoginAttempts($request); $user = $this->guard()->user(); if ($response = $this->authenticated($request, $user)) { return $response; } return response()->json(['redirect' => $this->redirectPath($user)]); } protected function sendFailedLoginResponse(Request $request): void { $message = trans('auth.failed'); if (($user = User::whereEmail($request->input('email'))->first()) && !$user->has_password) { $message = trans('auth.no_password'); } throw ValidationException::withMessages([ $this->username() => [$message], ]); } public function logout(Request $request): Response { $this->parentLogout($request); return new Response('', 204); } } <file_sep>/app/Models/Volunteers/Surveys/Survey.php <?php namespace App\Models\Volunteers\Surveys; use App\Models\Volunteers\Volunteer; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Survey extends Model { public const UPDATED_AT = null; protected $table = 'volunteer_surveys'; protected $fillable = [ 'source_id', 'specified', 'name', 'email', 'address', 'phone', 'company_name', 'description' ]; public function volunteer(): BelongsTo { return $this->belongsTo(Volunteer::class); } public function source(): BelongsTo { return $this->belongsTo(Source::class); } } <file_sep>/modules/Frontend/Http/Requests/Company/VacancyRequest.php <?php namespace Modules\Frontend\Http\Requests\Company; use App\Models\Jobs\Benefit; use App\Models\Jobs\Hour; use App\Models\Jobs\Incentive; use App\Models\Jobs\Skill; use App\Models\Vacancy; use Illuminate\Foundation\Http\FormRequest; class VacancyRequest extends FormRequest { protected Vacancy $vacancy; public function rules(): array { return [ 'title' => ['required', 'string255'], 'sector_id' => ['required', 'exists:sectors,id'], 'city_id' => ['required', 'exists:us_cities,id'], 'type_id' => ['required', 'exists:job_types,id'], 'hours' => ['required', 'array'], 'hours.*' => ['exists:job_hours,id'], 'description' => ['required', 'string'], 'benefits' => ['required', 'array'], 'benefits.*' => ['exists:job_benefits,id'], 'incentives' => ['nullable', 'array'], 'incentives.*' => ['string'], 'is_relocation' => ['nullable', 'boolean'], 'is_remote_work' => ['nullable', 'boolean'], 'address' => ['nullable', 'string255'], 'skills' => ['nullable', 'array'], 'skills.*' => ['string'], 'company_title' => ['nullable', 'string255'], 'company_description' => ['nullable', 'string255'] ]; } public function syncHours(): array { return $this->vacancy->hours()->sync(Hour::findMany($this->hours)); } public function syncBenefits(): array { return $this->vacancy->benefits()->sync(Benefit::findMany($this->benefits)); } public function syncIncentives(): array { if ($incentives = $this->incentives) { $incentives = Incentive::findOrCreate($incentives); $this->vacancy->incentives()->sync($incentives->pluck('id')->toArray()); } return []; } public function syncSkills(): array { if ($skills = $this->skills) { $skills = Skill::findOrCreate($skills); return $this->vacancy->skills()->sync($skills->pluck('id')->toArray()); } return []; } public function setVacancy(Vacancy $vacancy): void { $this->vacancy = $vacancy; } public function authorize(): bool { return true; } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/ResumeRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer; use Illuminate\Foundation\Http\FormRequest; class ResumeRequest extends FormRequest { public function rules(): array { return [ 'title' => ['required', 'string255'], 'file' => ['required', 'file', 'mimetypes:application/pdf', 'max:1024'] ]; } public function authorize(): bool { return true; } } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/CompanyController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer; use App\Models\Company; use Illuminate\Support\Collection; use Modules\Frontend\Http\Controllers\Controller; use Route2Class; class CompanyController extends Controller { public function __invoke() { $this->seo()->setTitle("Recommended companies"); $companies = Company::query() ->with(['logoMedia', 'size', 'city']) ->select(['id', 'size_id', 'city_id', 'name', 'title']) ->paginate(5); /* @var $companies Collection<Company> */ $companies->transform(function (Company $company) { $company->append(['logo', 'employment', 'location']); return $company; }); if (request()->expectsJson()) { return $companies; } share(compact('companies')); Route2Class::addClass('page-with-search'); return view('frontend::volunteer.companies'); } } <file_sep>/modules/Frontend/Http/Middleware/Searched.php <?php namespace Modules\Frontend\Http\Middleware; use App\Models\SearchQuery; use Auth; use Closure; use Illuminate\Http\Request; class Searched { public function handle($request, Closure $next) { return $next($request); } public function terminate(Request $request, $response): void { if ($request->exists('page')) return; $route = $request->route(); $attributes = [ 'query' => $route->parameter('query'), 'location' => $route->parameter('location'), ]; if ($attributes['query']) { if (($user = Auth::user()) && $client = $user->getClient()) { $client->searchQueries()->create($attributes); } else { SearchQuery::create($attributes); } } } } <file_sep>/modules/Frontend/Http/Controllers/Api/VacancyController.php <?php namespace Modules\Frontend\Http\Controllers\Api; use App\Models\Jobs\Role; use Illuminate\Support\Collection; use Modules\Frontend\Http\Controllers\Controller; class VacancyController extends Controller { public function search(string $query): Collection { return Role::where('name', 'REGEXP', "^.*$query.*$") ->pluck('name'); } } <file_sep>/modules/Frontend/resources/js/plugins/axios.js import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') } axios.interceptors.response.use(function (response) { return response }, function (error) { console.log(error) const {status, data} = error.response if (status === 401) { const login = Vue.options.methods.route('login') Vue.bus.emit('alert', { text: `Your are not unauthenticated. Please <a href="${login}">Sing In.</a>`, variant: 'warning' }) } else if (status === 403) { Vue.bus.emit('alert', {text: 'Your haven\'t permission to do it.', variant: 'danger'}) } else if (status === 419) { Vue.bus.emit('alert', {text: status, variant: 'danger'}) location.reload() } else if (status === 422) { //Vue.bus.emit('alert', {text: 'Validation error. Please check your input data.', variant: 'warning'}) } else if ((status % 500) < 100) { Vue.bus.emit('alert', { text: 'Internal Server Error. The server encountered an internal error or misconfiguration and was unable to complete your request.', variant: 'danger', position: 'top', delay: 12 }) } else { Vue.options.methods.notify(data.message, 'warning') } throw error }) Vue.use(VueAxios, axios) <file_sep>/app/Models/Blog/Category.php <?php namespace App\Models\Blog; use App\Models\Traits\SortableTrait; use Cviebrock\EloquentSluggable\Sluggable; use Illuminate\Database\Eloquent\Model; use Spatie\EloquentSortable\Sortable; class Category extends Model implements Sortable { use Sluggable; use SortableTrait; protected $table = 'article_categories'; protected $fillable = ['name', 'slug', 'is_active']; // FUNCTIONS public function sluggable() { return [ 'slug' => [ 'source' => !empty($this->slug) ? 'slug' : 'name', 'onUpdate' => true, ] ]; } // RELATIONS public function articles() { return $this->hasMany(Article::class); } //SCOPES public function scopeActive($query) { return $query->whereIsActive(true); } // ACCESSORS public function getLinkAttribute() { return route('frontend.articles.category', $this->slug); } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; Route::post( 'stripe/webhook', 'Modules\Frontend\Http\Controllers\Company\Stripe\WebhookController@handleWebhook' )->name('webhook'); <file_sep>/modules/Admin/Repositories/ArticleRepository.php <?php namespace Modules\Admin\Repositories; use App\Models\Blog\Article; use App\Models\Blog\Category; class ArticleRepository { public function shareForCRUD(): void { $categories = Category::ordered() ->pluck('id', 'name') ->map(fn($value, $text) => compact('value', 'text')) ->values(); $statuses = collect(Article::$statuses) ->map(fn($text, $value) => compact('text', 'value')) ->values(); share(compact('categories', 'statuses')); } } <file_sep>/app/Helpers/SimbokPathGenerator.php <?php namespace App\Helpers; use App\Models\Blog\Article; use App\Models\Company; use App\Models\User; use App\Models\Volunteers\Volunteer; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Spatie\MediaLibrary\Support\PathGenerator\PathGenerator; class SimbokPathGenerator implements PathGenerator { public function getPath(Media $media): string { return $this->getBasePath($media) . '/'; } public function getPathForConversions(Media $media): string { return $this->getBasePath($media) . '/conversions/'; } public function getPathForResponsiveImages(Media $media): string { return $this->getBasePath($media) . '/responsive-images/'; } protected function getBasePath(Media $media): string { $folder = ''; $collection = $media->collection_name; switch ($media->model_type) { case Article::class: return "articles/" . $media->model_id . "/$collection"; break; case Volunteer::class: return "volunteers/" . $media->model_id . "/$collection"; break; case Company::class: return "companies/" . $media->model_id . "/$collection"; break; } return "$folder/" . $media->model_id . "/$collection/" . $media->getKey(); } } <file_sep>/modules/Frontend/Http/Controllers/Company/BoardController.php <?php namespace Modules\Frontend\Http\Controllers\Company; use App\Models\Vacancy; use App\Models\Volunteers\Volunteer; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; use Modules\Frontend\Http\Controllers\Controller; use Modules\Frontend\Repositories\VolunteerRepository; class BoardController extends Controller { use HasCompany; protected VolunteerRepository $repository; public function __construct() { $this->repository = app(VolunteerRepository::class); } public function __invoke() { $this->seo()->setTitle("Board | Company"); $company = $this->company()->append('is_subscribed'); $volunteers = collect(); $vacancies = $company->vacancies()->with(['city', 'hours', 'type'])->get(); $titles = $cities = $vacancies->pluck('title')->unique(); $sectors = $cities = $vacancies->pluck('sector_id')->unique(); $cities = $vacancies->pluck('city_id')->unique(); $types = $vacancies->pluck('type_id')->unique(); $hours = $vacancies->pluck('hours')->flatten()->pluck('id')->unique(); $isRelocation = $vacancies->pluck('is_relocation')->flatten()->contains(true); $isRemoteWork = $vacancies->pluck('is_remote_work')->flatten()->contains(true); if ($company->subscribed()) { $volunteers = Volunteer::with(['user', 'types', 'hours', 'roles']) ->when($isRelocation, fn($q) => $q->where('is_relocating', '=', true)) ->when($isRemoteWork, fn($q) => $q->where('is_working_remotely', '=', true)) ->where(function (Builder $q) use ($titles, $sectors, $cities, $types, $hours) { $titles->each(fn($t) => $q->where( 'job_title', 'REGEXP', '[[:<:]]' . $t . '[[:>:]]' )); $q->orWhereHas('roles', fn($q) => $q->whereIn('sector_id', $sectors)); $q->orWhereHas('locations', fn($q) => $q->whereIn('city_id', $cities)); $q->orWhereHas('types', fn($q) => $q->whereIn('id', $types)); $q->orWhereHas('hours', fn($q) => $q->whereIn('id', $hours)); }) ->orderByDesc('completeness') ->paginate(5, ['volunteers.*']); /* @var $volunteers Collection<Volunteer> */ $volunteers->transform([$this->repository, 'transformForIndex']); if ($availableCandidates = $company->getAvailableCandidatesCount()) { $current = $volunteers->currentPage() * $volunteers->perPage(); if ($current >= $availableCandidates) { $volunteers = $volunteers->toArray(); $volunteers['last_page'] = $volunteers['current_page']; } } if (request()->expectsJson()) { return $volunteers; } } $availableVolunteers = $company->getAvailableVolunteersCount(); $resumeViews = [ 'viewed' => $company->resume_views, 'available' => $availableVolunteers === -1 ? '∞' : $availableVolunteers ]; $lastVacancies = $company->vacancies() ->latest() ->limit(3) ->get(['id', 'title', 'status', 'created_at']) ->map(function (Vacancy $vacancy) { $vacancy->days = $vacancy->created_at->diffInDays(); return $vacancy; }); $counts = []; $counts['active'] = $company->vacancies()->active()->count(); $counts['draft'] = $company->vacancies()->draft()->count(); $counts['closed'] = $company->vacancies()->closed()->count(); share(compact('volunteers', 'resumeViews', 'lastVacancies', 'counts')); return view('frontend::company.board'); } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/Survey/CompleteRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer\Survey; use Illuminate\Foundation\Http\FormRequest; class CompleteRequest extends FormRequest { public function rules(): array { return [ 'name' => ['required', 'string255'], 'email' => ['required', 'email'], 'address' => ['required', 'string255'], 'phone' => ['required', 'regex:/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/',/*'phone:US'*/], 'company_name' => ['required', 'string255'], 'description' => ['required', 'string'] ]; } public function authorize(): bool { return true; } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/JobRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer; use Illuminate\Foundation\Http\FormRequest; class JobRequest extends FormRequest { public function rules(): array { return [ 'job_title' => ['required', 'string255'], 'locations' => ['required', 'array'], 'locations.*' => ['exists:us_cities,id', 'distinct'], 'types' => ['required', 'array'], 'types.*' => ['exists:job_types,id'], 'hours' => ['required', 'array'], 'hours.*' => ['exists:job_hours,id'], 'sectors' => ['required', 'array', 'max:10'], 'sectors.*.id' => ['exists:sectors,id', 'distinct'], 'sectors.*.roles' => ['required', 'array', 'max:5'], 'sectors.*.roles.*' => ['exists:sector_roles,id', 'distinct'] ]; } public function attributes(): array { $attributes = parent::attributes(); $attributes['sectors.*.roles'] = 'roles'; return $attributes; } public function messages(): array { $messages = parent::messages(); $messages['sectors.*.roles.required'] = 'Please select :attribute.'; return $messages; } public function authorize(): bool { return true; } } <file_sep>/modules/Admin/Http/Requests/Blog/ArticleRequest.php <?php namespace Modules\Admin\Http\Requests\Blog; use App\Models\Blog\Article; use Illuminate\Foundation\Http\FormRequest; class ArticleRequest extends FormRequest { public function rules() { $update = request()->isMethod('PATCH'); $types = collect(Article::$statuses)->keys()->implode(','); return [ 'category_id' => ['required', 'exists:article_categories,id'], 'title' => ['required', 'string', 'max:255'], 'slug' => ['nullable', 'string', 'max:255'], 'body' => ['required', 'string'], 'excerpt' => ['required', 'string', 'max:510'], 'image' => [$update ? 'nullable' : 'required', 'image', 'mimes:jpg,jpeg,bmp,png'], 'meta_title' => ['nullable', 'string', 'max:255'], 'meta_description' => ['nullable', 'string', 'max:255'], 'status' => ['nullable', "in:$types"], ]; } public function uploadImage(Article $article): bool { if ($this->hasFile('image')) { return $article->uploadImage($this->file('image')) !== null; } return false; } public function authorize() { return true; } } <file_sep>/database/seeds/LanguagesSeeder.php <?php use App\Models\Language; use Illuminate\Database\Seeder; class LanguagesSeeder extends Seeder { public function run() { $languages = [ 'en' => 'English', 'fr' => 'French', 'es' => 'Spanish', 'ar' => 'Arabic', 'cmn' => 'Mandarin', 'ru' => 'Russian', 'pt' => 'Portuguese', 'de' => 'German', 'ja' => 'Japanese', 'hi' => 'Hindi', 'ms' => 'Malay', 'fa' => 'Persian', 'sw' => 'Swahili', 'ta' => 'Tamil', 'it' => 'Italian', 'nl' => 'Dutch', 'bn' => 'Bengali', 'tr' => 'Turkish', 'vi' => 'Vietnamese', 'pl' => 'Polish', 'jv' => 'Javanese', 'pa' => 'Punjabi', 'th' => 'Thai', 'ko' => 'Korean' ]; foreach ($languages as $code => $name) { Language::create(compact('name', 'code')); } } } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/EducationController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Http\Controllers\Controller; use App\Models\Volunteers\Education; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Requests\Volunteer\EducationRequest; class EducationController extends Controller { use HasVolunteer; public function store(EducationRequest $request): JsonResponse { $education = $this->volunteer()->educations()->create($request->validated()); return response()->json(['message' => 'Education has been added.', 'id' => $education->id]); } public function update(EducationRequest $request, Education $education): JsonResponse { $education->update($request->validated()); return response()->json(['message' => 'Education has been updated.', 'id' => $education->id]); } public function destroy(Education $education): JsonResponse { $education->delete(); return response()->json(['message' => 'Education has been deleted.']); } } <file_sep>/modules/Frontend/Providers/FrontendServiceProvider.php <?php namespace Modules\Frontend\Providers; use App\Models\Page; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\View; use Spatie\SchemaOrg\BaseType; use Spatie\SchemaOrg\Schema; class FrontendServiceProvider extends ServiceProvider { protected string $moduleName = 'Frontend'; protected string $moduleNameLower = 'frontend'; public function boot() { $this->registerConfig(); $this->registerViews(); $this->viewComposer(); $this->schema(); $this->directives(); } public function register() { $this->app->register(RouteServiceProvider::class); $this->app->register(BroadcastServiceProvider::class); } public function registerViews() { $sourcePath = module_path($this->moduleName, 'resources/views'); $this->loadViewsFrom($sourcePath, $this->moduleNameLower); } protected function registerConfig() { $this->mergeConfigFrom( module_path($this->moduleName, 'config.php'), $this->moduleNameLower ); } protected function viewComposer() { \View::composer('frontend::layouts.master', function ($view) { $bodyClass = \Route2Class::getClasses()->join(' '); $view->with('bodyClass', $bodyClass); }); } private function schema(): void { View::composer('frontend::layouts.master', function ($view) { $schema = collect(); $page = Page::find(1); $organization = Schema::organization() ->name($page->meta_title ?? $page->title) ->email('<EMAIL>') ->description($page->meta_description) ->logo(asset('dist/img/logo.svg')) ->url(url('/')); $schema->push($organization); $schema = $schema->map(fn(BaseType $item) => $item->toScript()); $view->with('schema', $schema); }); } private function directives(): void { \Blade::directive('schema', function () { return '<?php $schema->each(fn($item)=>print($item)); ?>'; }); } } <file_sep>/modules/Frontend/Http/Middleware/Volunteer.php <?php namespace Modules\Frontend\Http\Middleware; use App\Models\User; use Closure; use Illuminate\Http\Request; class Volunteer { public function handle(Request $request, Closure $next) { if ($request->user()->type !== User::VOLUNTEER) abort(403, 'Only for volunteer'); return $next($request); } } <file_sep>/modules/Frontend/Http/Controllers/Company/UpgradeController.php <?php namespace Modules\Frontend\Http\Controllers\Company; use Exception; use Illuminate\Http\JsonResponse; use Log; use Modules\Frontend\Http\Controllers\Controller; use Stripe\Checkout\Session as CheckoutSession; use Stripe\Stripe; class UpgradeController extends Controller { use HasCompany; public function page() { $this->seo()->setTitle('Subscription'); $company = $this->company(); $subscription = $company->subscription(); $plans = collect(config('simbok.plans')); $plans->transform(function (array $plan) use ($company, $subscription) { $plan['isActive'] = $company->subscribedToPlan($plan['stripe_plan']) && $subscription->valid(); return $plan; }); $card = []; if ($subscription) { $card['brand'] = $company->card_brand; $card['lastFour'] = $company->card_last_four; } share([ 'plans' => $plans, 'hasTrial' => $subscription === null, 'card' => $card, 'stripeAPIToken' => config('services.stripe.key') ]); return view('frontend::company.subscribe.plans'); } public function checkout(string $plan) { Stripe::setApiKey(config('services.stripe.secret')); $company = $this->company(); $subscription = $company->subscription(); if ($company->subscribedToPlan($plan)) { return response()->noContent(403); } $session = CheckoutSession::create([ 'payment_method_types' => ['card'], 'subscription_data' => [ 'items' => [['plan' => $plan]], 'trial_period_days' => !$subscription ? 15 : null, ], 'allow_promotion_codes' => true, 'mode' => 'subscription', 'customer' => $company->createOrGetStripeCustomer()->id, 'success_url' => route('frontend.company.board'), 'cancel_url' => route('frontend.company.upgrade.page'), ]); return response()->json(['session' => $session->id]); } public function cancel(): JsonResponse { $company = $this->company(); if (($subscription = $company->subscription()) && $subscription->valid()) { try { $subscription->noProrate()->cancelNow(); return response()->json(['message' => 'Subscription has been canceled.']); } catch (Exception $e) { Log::error('Can\'t cancel subscription: ' . $e->getMessage() . $e->getTraceAsString()); } } return response()->json(['message' => 'No current subscription was found.'], 404); } /* public function intent(): SetupIntent { return $this->company()->createSetupIntent(); } public function updatePlan(Request $request): JsonResponse { $company = $this->company(); $planID = $request->get('plan'); $paymentID = $request->get('payment'); if (!$company->subscribed()) { $company->newSubscription('default', $planID)->create($paymentID); } else { $company->subscription()->swap($planID); } return response()->json([ 'subscription_updated' => true ]); } public function createPaymentMethod(Request $request): JsonResponse { $company = $this->company(); $paymentMethodID = $request->get('payment_method'); if ($company->stripe_id === null) { $company->createAsStripeCustomer(); } $company->addPaymentMethod($paymentMethodID); $company->updateDefaultPaymentMethod($paymentMethodID); return response()->json(null, 204); } public function getPaymentMethods(Request $request): JsonResponse { $company = $this->company(); $methods = []; if ($company->hasPaymentMethod()) { foreach ($company->paymentMethods() as $method) { $methods[] = [ 'id' => $method->id, 'brand' => $method->card->brand, 'lastFour' => $method->card->last4, 'expMonth' => $method->card->exp_month, 'expYear' => $method->card->exp_year, 'isDefault' => ($company->card_last_four === $method->card->last4) && ($company->card_brand === $method->card->brand) ]; } } return response()->json($methods); } public function removePaymentMethod(Request $request): JsonResponse { $company = $this->company(); $paymentMethodID = $request->get('id'); $paymentMethods = $company->paymentMethods(); foreach ($paymentMethods as $method) { if ($method->id == $paymentMethodID) { $method->delete(); break; } } return response()->json(null, 204); } */ } <file_sep>/database/migrations/2020_09_23_140201_create_volunteer_job_has_types.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerJobHasTypes extends Migration { public function up() { Schema::create('volunteer_job_has_types', function (Blueprint $table) { $table->foreignId('job_id')->constrained('volunteer_jobs')->cascadeOnDelete(); $table->foreignId('type_id')->constrained('job_types')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('volunteer_job_has_types'); } } <file_sep>/modules/Admin/Http/Middleware/Admin.php <?php namespace Modules\Admin\Http\Middleware; use Auth; use Closure; class Admin { public function handle($request, Closure $next) { if (Auth::check() && Auth::getUser()->can('access admin panel')) { return $next($request); } abort(404); } } <file_sep>/modules/Frontend/Http/Resources/ArticleResource.php <?php namespace Modules\Frontend\Http\Resources; use App\Models\Blog\Article; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Pagination\LengthAwarePaginator; class ArticleResource extends JsonResource { public static function collection($resource) { /* @var $collection LengthAwarePaginator */ $collection = parent::collection($resource); return [ 'data' => $collection, 'currentPage' => $collection->currentPage(), 'lastPage' => $collection->lastPage() ]; } public function toArray($request): array { /* @var $article Article */ $article = $this->resource; return [ 'id' => $article->id, 'title' => $article->title, 'excerpt' => $article->excerpt, 'thumbnail' => $article->thumbnail, 'link' => $article->link ]; } } <file_sep>/app/Models/Client.php <?php namespace App\Models; use App\Models\Chats\Chat; use App\Models\Chats\Message; use App\Models\Interfaces\SearchRecordable; use App\Models\Traits\SearchRecording; use App\Models\Volunteers\Volunteer; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasManyThrough; class Client extends Model implements SearchRecordable { use SearchRecording; public function getUnviewedMessages(): int { return $this->incomeMessages()->unviewed()->count(); } /* @return Message|HasManyThrough */ public function incomeMessages(): HasManyThrough { return $this->hasManyThrough(Message::class, Chat::class) ->whereNull($this instanceof Volunteer ? 'chat_messages.volunteer_id' : 'chat_messages.company_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function chats(): HasMany { return $this->hasMany(Chat::class); } public function messages(): HasMany { return $this->hasMany(Message::class); } } <file_sep>/database/migrations/2020_11_04_115325_create_volunteer_has_types.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerHasTypes extends Migration { public function up() { Schema::create('volunteer_has_types', function (Blueprint $table) { $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->foreignId('type_id')->constrained('job_types')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('volunteer_has_types'); } } <file_sep>/modules/Frontend/Providers/BroadcastServiceProvider.php <?php namespace Modules\Frontend\Providers; use Illuminate\Support\Facades\Broadcast; use Illuminate\Support\ServiceProvider; class BroadcastServiceProvider extends ServiceProvider { public function boot(): void { Broadcast::routes(); require module_path('Frontend', 'routes/channels.php'); } } <file_sep>/database/seeds/Jobs/SectorsSeeder.php <?php use App\Models\Jobs\Role; use App\Models\Jobs\Sector; use Illuminate\Database\Seeder; class SectorsSeeder extends Seeder { public function run() { $sectors = [ 'Accountancy' => 2, 'Accountancy (Qualified)' => 100, 'Admin, Secretarial & PA' => 3, 'Apprenticeships' => 1964, 'Banking' => 5, 'Charity & Voluntary' => 500, 'Construction & Property' => 146, 'Customer Service' => 66, 'Education' => 68, 'Energy' => 1961, 'Engineering' => 12, 'Estate Agency' => 1962, 'Financial Services' => 117, 'FMCG' => 1722, 'General Insurance' => 16, 'Graduate Training & Internships' => 169, 'Health & Medicine' => 36, 'Hospitality & Catering' => 6, 'Human Resources' => 24, 'IT & Telecoms' => 52, 'Legal' => 101, 'Leisure & Tourism' => 92, 'Manufacturing' => 168, 'Marketing & PR' => 18, 'Media, Digital & Creative' => 71, 'Motoring & Automotive' => 1700, 'Public Sector' => 501, 'Purchasing' => 27, 'Recruitment Consultancy' => 338, 'Retail' => 90, 'Sales' => 30, 'Scientific' => 89, 'Security & Safety' => 1963, 'Social Care' => 34, 'Strategy & Consultancy' => 1755, 'Training' => 1909, 'Transport & Logistics' => 11, 'Other' => 21, ]; $this->command->getOutput()->progressStart(count($sectors)); \DB::transaction(function () use ($sectors) { foreach ($sectors as $name => $id) { $sector = Sector::create(compact('name')); $response = \Http::get("https://www.reed.co.uk/api/sector/registrationsubsectors?parentSectorId=$id")->body(); $reedRoles = collect(json_decode($response, true))->pluck('Name'); $roles = Role::findOrCreate($reedRoles->toArray()); $sector->roles()->sync($roles->pluck('id')->toArray()); $this->command->getOutput()->progressAdvance(); } }); $this->command->getOutput()->progressFinish(); } } <file_sep>/database/migrations/2020_09_23_140224_create_volunteer_job_has_roles.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerJobHasRoles extends Migration { public function up() { Schema::create('volunteer_job_has_roles', function (Blueprint $table) { $table->foreignId('job_id')->constrained('volunteer_jobs')->cascadeOnDelete(); $table->foreignId('role_id')->constrained('sector_roles')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('volunteer_job_has_roles'); } } <file_sep>/modules/Admin/resources/js/plugins/axios.js import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') } Vue.use(VueAxios, axios) <file_sep>/database/migrations/2021_01_18_183500_create_volunteer_survey_sources_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerSurveySourcesTable extends Migration { public function up(): void { Schema::create('volunteer_survey_sources', function (Blueprint $table) { $table->id(); $table->string('name'); }); } public function down(): void { Schema::dropIfExists('volunteer_survey_sources'); } } <file_sep>/modules/Frontend/Http/Middleware/ServerPush.php <?php namespace Modules\Frontend\Http\Middleware; use Illuminate\Http\Request; use Illuminate\Http\Response; class ServerPush { public function handle(Request $request, \Closure $next) { /* @var $response Response */ $response = $next($request); if ($request->isMethod('GET')) { $response->header('Link', '<' . mix('dist/css/app.css') . '>;rel=preload;as=style', false); } return $response; } } <file_sep>/config/simbok.php <?php return [ 'debugbar_emails' => parse_emails(env('DEBUGBAR_EMAIL', '')), 'plans' => [ [ 'stripe_plan' => env('PLAN_1_ID'), 'name' => 'Starter', 'price' => 11.50, 'advantages' => [ 'Post 1 vacancy', '50 Resume view', '5 candidate recommendations' ], 'limits' => [ 'vacancies' => 1, 'volunteers' => 50, 'recommendations' => 5 ] ], [ 'stripe_plan' => env('PLAN_2_ID'), 'name' => 'Standard', 'price' => 19.50, 'description' => 'Hire easily on a budget', 'advantages' => [ 'Post up to 10 vacancies', 'Up to 100 Resume views', 'Up to 12 candidate recommendations', 'Search the database' ], 'limits' => [ 'vacancies' => 10, 'volunteers' => 100, 'recommendations' => 12 ] ], [ 'stripe_plan' => env('PLAN_3_ID'), 'name' => 'Premium', 'price' => 25.50, 'description' => 'Find qualified candidates fast', 'advantages' => [ 'Post up to 100 vacancies', 'Up to 150 Resume views', 'Up to 20 candidate recommendations', 'Search the database' ], 'limits' => [ 'vacancies' => 100, 'volunteers' => 150, 'recommendations' => 20 ] ], [ 'stripe_plan' => env('PLAN_4_ID'), 'name' => 'Enterprise', 'price' => 65.50, 'advantages' => [ 'Post unlimited vacancies', 'Unlimited Resume views', 'Unlimited candidate recommendations', 'Unlimited Search through our and partner database' ], 'limits' => [ 'vacancies' => -1, 'volunteers' => -1, 'recommendations' => -1 ] ] ] ]; <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/AvatarController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Http\Controllers\Controller; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class AvatarController extends Controller { use HasVolunteer; public function update(Request $request): JsonResponse { ['avatar' => $avatar] = $this->validate($request, [ 'avatar' => ['required', 'image', 'max:2048', 'mimes:jpg,jpeg,bmp,png'] ]); $volunteer = $this->volunteer(); $volunteer->uploadAvatar($avatar); $volunteer->load('avatarMedia'); return response()->json([ 'message' => 'Company logo has been uploaded.', 'avatar' => $volunteer->avatar ]); } public function destroy(): JsonResponse { $volunteer = $this->volunteer(); $volunteer->deleteAvatar(); $volunteer->load('avatarMedia'); return response()->json(['message' => 'Your avatar has been deleted.', 'avatar' => $volunteer->avatar]); } } <file_sep>/modules/Admin/Http/Requests/Jobs/RoleRequest.php <?php namespace Modules\Admin\Http\Requests\Jobs; use App\Models\Jobs\Role; use Illuminate\Foundation\Http\FormRequest; class RoleRequest extends FormRequest { public function rules() { return [ 'name' => ['required', 'string', 'max:255'], 'sectors' => ['required', 'array'], 'sectors.*' => ['exists:sectors,id'] ]; } public function syncSectors(Role $role) { $role->sectors()->sync($this->input('sectors')); } public function authorize() { return true; } } <file_sep>/database/seeds/Jobs/SizesSeeder.php <?php use App\Models\Jobs\Size; use Illuminate\Database\Seeder; class SizesSeeder extends Seeder { public function run() { $sizes = ['Company (1-6 employees)', 'Company (6-10 employees)', 'Company (10-50 employees)', 'Company (50+ employees)']; foreach ($sizes as $name) Size::create(compact('name')); } } <file_sep>/app/Models/Jobs/Skill.php <?php namespace App\Models\Jobs; use App\Models\Traits\IsTag; use Illuminate\Database\Eloquent\Model; class Skill extends Model { use IsTag; const CREATED_AT = null; const UPDATED_AT = null; protected $table = 'job_skills'; protected $fillable = ['name']; } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/CertificateController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Http\Controllers\Controller; use App\Models\Volunteers\Certificate; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Requests\Volunteer\CertificateRequest; class CertificateController extends Controller { use HasVolunteer; public function store(CertificateRequest $request): JsonResponse { $education = $this->volunteer()->certificates()->create($request->validated()); return response()->json(['message' => 'Certificate has been added.', 'id' => $education->id]); } public function update(CertificateRequest $request, Certificate $certificate): JsonResponse { $certificate->update($request->validated()); return response()->json(['message' => 'Certificate has been updated.', 'id' => $certificate->id]); } public function destroy(Certificate $certificate): JsonResponse { $certificate->delete(); return response()->json(['message' => 'Certificate has been deleted.']); } } <file_sep>/modules/Frontend/Http/Controllers/Auth/SocialController.php <?php namespace Modules\Frontend\Http\Controllers\Auth; use Modules\Frontend\Http\Controllers\Controller; use App\Models\User; class SocialController extends Controller { private User $user; public function redirect(string $provider, bool $isCompany = false) { $driver = \Socialite::driver($provider); if ($isCompany) return $driver ->with(['redirect_uri' => url("/social/company/$provider/callback")]) ->redirect(); return $driver->redirect(); } public function callback(string $provider, bool $isCompany = false) { $userSocial = \Socialite::driver($provider)->stateless()->user(); $registered = User::where(['email' => $userSocial->getEmail()]) ->orWhere(['provider_id' => $userSocial->getId()]) ->first(); if ($registered) { \Auth::login($registered); return redirect()->route('frontend.home'); } else { $this->user = User::create([ 'name' => $userSocial->getName(), 'email' => $userSocial->getEmail(), 'provider_id' => $userSocial->getId(), 'provider' => $provider ]); if ($avatar = $userSocial->getAvatar()) { $this->user->addMediaFromUrl($avatar)->toMediaCollection('avatar'); } \Auth::login($this->user); return redirect()->route('frontend.home'); } } public function companyRedirect(string $provider) { return $this->redirect($provider, true); } public function companyCallback(string $provider) { return $this->callback($provider, true); } } <file_sep>/database/seeds/Jobs/SkillsSeeder.php <?php use App\Models\Jobs\Skill; use Illuminate\Database\Seeder; class SkillsSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $skills = [ 'Effective communication', 'Teamwork', 'Responsibility', 'Creativity', 'Problem-solving', 'Leadership', 'Extroversion ', 'People skills', 'Openness', 'Adaptability' ]; foreach ($skills as $name) { Skill::create(compact('name')); } } } <file_sep>/database/migrations/2020_09_20_120134_create_vacancies_table.php <?php use App\Models\Vacancy; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVacanciesTable extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_20_120134_create_vacancies_table.php */ public function up() { $statuses = array_keys(Vacancy::$statuses); Schema::create('vacancies', function (Blueprint $table) use ($statuses) { $table->id(); $table->foreignId('company_id')->constrained(); $table->string('title'); $table->foreignId('sector_id')->constrained('sectors'); $table->foreignId('city_id')->constrained('us_cities'); $table->foreignId('type_id')->constrained('job_types'); $table->text('description'); $table->string('excerpt'); $table->boolean('is_relocation')->default(false); $table->boolean('is_remote_work')->default(false); $table->string('address')->nullable(); $table->string('company_title')->nullable(); $table->string('company_description')->nullable(); $table->enum('status', $statuses)->default(Vacancy::DRAFT); $table->timestamps(); $table->softDeletes(); }); } public function down() { Schema::dropIfExists('vacancies'); } } <file_sep>/database/seeds/ArticlesSeeder.php <?php use App\Models\Blog\Article; use Illuminate\Database\Seeder; class ArticlesSeeder extends Seeder { public function run() { factory(Article::class, 10) ->create() ->each(fn(Article $a) => $a->addMediaFromUrl('https://picsum.photos/750/370') ->toMediaCollection('image')); } } <file_sep>/app/Models/Map/US/City.php <?php namespace App\Models\Map\US; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; class City extends Model { const CREATED_AT = null; const UPDATED_AT = null; protected $table = 'us_cities'; protected $fillable = ['id', 'state_id', 'name', 'county', 'lat', 'lng', 'zips', 'population']; public function scopeBiggest(Builder $query) { return $query->orderByDesc('population'); } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/EducationRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer; use Illuminate\Foundation\Http\FormRequest; class EducationRequest extends FormRequest { public function rules(): array { return [ 'school' => ['required', 'string255'], 'degree' => ['required', 'string255'], 'field' => ['nullable', 'string255'], 'start' => ['required', 'numeric', 'min:1950', 'max:2030'], 'end' => ['required', 'numeric', 'min:1950', 'max:2030', 'gte:start'], 'description' => ['nullable', 'string255'], ]; } public function authorize(): bool { return true; } } <file_sep>/app/Models/Volunteers/Volunteer.php <?php namespace App\Models\Volunteers; use App\Models\Chats\Chat; use App\Models\Client; use App\Models\Interfaces\SearchRecordable; use App\Models\Jobs\Hour; use App\Models\Jobs\Role; use App\Models\Jobs\Skill; use App\Models\Jobs\Type; use App\Models\Language; use App\Models\Map\US\City; use App\Models\Traits\SearchRecording; use App\Models\Traits\SearchTrait; use App\Models\User; use App\Models\Vacancy; use App\Models\Volunteers\Surveys\Survey; use Auth; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\MorphOne; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Http\UploadedFile; use Illuminate\Support\Collection; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; use Spatie\MediaLibrary\MediaCollections\Models\Media; class Volunteer extends Client implements HasMedia { use InteractsWithMedia, SoftDeletes, SearchTrait; public const CREATED_AT = null; public const UPDATED_AT = null; protected $fillable = [ 'is_private', 'phone', 'email', 'social', 'headline', 'city_id', 'zip', 'is_relocating', 'is_working_remotely', 'job_title', 'executive_summary', 'objective', 'achievements', 'associations', 'years_of_experience_id', 'level_of_education_id', 'veteran_status_id', 'cover_letter', 'personal_statement', 'has_driver_license', 'has_car', 'completeness' ]; protected $casts = [ 'social' => 'array', 'is_relocating' => 'boolean', 'is_working_remotely' => 'boolean', 'has_driver_license' => 'boolean', 'has_car' => 'boolean', 'completeness' => 'float' ]; protected array $search = [ 'id', 'job_title' ]; // FUNCTIONS public function registerMediaCollections(): void { $this->addMediaCollection('avatar')->singleFile() ->registerMediaConversions(function (Media $media) { $this->addMediaConversion('icon') ->width(110) ->sharpen(0) ->nonQueued(); }); $this->addMediaCollection('resume')->singleFile(); } public function uploadAvatar(UploadedFile $image = null): void { if ($this->avatarMedia) $this->deleteMedia($this->avatarMedia); $this->addMedia($image)->toMediaCollection('avatar'); } public function deleteAvatar(): bool { return $this->avatarMedia->delete(); } public function getAvatar(string $size = ''): string { if ($this->avatarMedia !== null) { return $this->avatarMedia->getUrl($size); } return asset('dist/img/avatar.svg'); } public function calculateCompleteness(): void { $completeness = 0; $steps = [ 'about' => [ 'value' => ($this->name && $this->headline && $this->city_id), 'cost' => 0.2 ], 'looking' => [ 'value' => $this->roles()->exists(), 'cost' => 0.2 ], 'work_experience' => [ 'value' => $this->workExperiences()->exists(), 'cost' => 0.2 ], 'contact_social' => [ 'value' => ( $this->email && $this->phone && ($this->social !== null && !empty(array_filter($this->social, fn($l) => $l !== null))) ), 'cost' => 0.2 ], 'skills' => [ 'value' => $this->skills()->exists(), 'cost' => 0.2 ], ]; foreach ($steps as $step) { $completeness += $step['value'] ? $step['cost'] : 0; } $this->update(['completeness' => $completeness]); } // RELATIONS public function user(): BelongsTo { return $this->belongsTo(User::class); } public function applies(): BelongsToMany { return $this->belongsToMany(Vacancy::class, 'volunteer_has_applies')->distinct(); } /* @return Vacancy|BelongsToMany */ public function bookmarks(): BelongsToMany { return $this->belongsToMany(Vacancy::class, 'volunteer_has_bookmarks'); } public function city(): BelongsTo { return $this->belongsTo(City::class); } /* @return City[]|Collection|BelongsToMany */ public function locations(): BelongsToMany { return $this->belongsToMany(City::class, 'volunteer_has_locations'); } /* @return City[]|Collection|BelongsToMany */ public function roles(): BelongsToMany { return $this->belongsToMany(Role::class, 'volunteer_has_sectors_with_roles')->withPivot(['sector_id']); } public function types(): BelongsToMany { return $this->belongsToMany(Type::class, 'volunteer_has_types'); } public function hours(): BelongsToMany { return $this->belongsToMany(Hour::class, 'volunteer_has_hours'); } public function workExperiences(): HasMany { return $this->hasMany(WorkExperience::class); } public function educations(): HasMany { return $this->hasMany(Education::class); } /* @return Resume|HasOne */ public function resume(): HasOne { return $this->hasOne(Resume::class); } public function certificates(): HasMany { return $this->hasMany(Certificate::class); } public function skills(): BelongsToMany { return $this->belongsToMany(Skill::class, 'volunteer_has_skills'); } public function languages(): BelongsToMany { return $this->belongsToMany(Language::class, 'volunteer_has_languages')->withPivot(['fluency']); } public function surveys(): HasMany { return $this->hasMany(Survey::class); } public function avatarMedia(): MorphOne { return $this->morphOne(Media::class, 'model')->where('collection_name', 'avatar'); } // SCOPES public function scopePublic(Builder $query): Builder { return $query->where('is_private', '!=', true); } // ACCESSORS public function getAvatarAttribute(): string { return $this->getAvatar(); } public function getIconAttribute(): string { return $this->getAvatar('icon'); } public function getNameAttribute(): ?string { return $this->user->name; } public function getEmailAttribute(string $email = null): string { return $email ?: $this->user->email; } public function getUpdatedAtAttribute(): string { return $this->user->updated_at->diffForHumans(); } //todo refactor to trait HasLocation public function getLocationAttribute(): string { $c = $this->city; if ($c) { $name = $c->name; if ($c->name !== $c->county) { $name .= ", $c->county"; } return "$name $c->state_id"; } return ""; } //todo refactor to trait HasEmployment public function getEmploymentAttribute(): string { return $this->types->implode('name', ', ') . ', ' . $this->hours->implode('name', ', '); } public function getInBookmarksAttribute(): bool { if ($user = Auth::user()) { return $user->company->bookmarks()->where('volunteer_id', $this->id)->exists(); } return false; } public function getIsCompletedAttribute(): bool { return $this->completeness === 1.; } } <file_sep>/modules/Frontend/Http/Controllers/Auth/ChangePasswordController.php <?php namespace Modules\Frontend\Http\Controllers\Auth; use Auth; use Hash; use Illuminate\Http\Request; use Modules\Frontend\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Route2Class; class ChangePasswordController extends Controller { protected $redirectTo = RouteServiceProvider::HOME; public function form() { $this->seo()->setTitle('Change Password'); Route2Class::addClass('bg-decorative'); return view('frontend::auth.passwords.change', [ 'email' => Auth::getUser()->email ]); } public function update(Request $request) { $this->validate($request, [ 'current_password' => ['required', function ($attribute, $value, $fail) { if (!Hash::check($value, Auth::getUser()->password)) $fail('Current password in incorrect.'); }], 'password' => ['required', 'confirmed', 'min:8'] ]); Auth::getUser()->update(['password' => <PASSWORD>::make($request->password)]); return response()->json(['message' => 'Password has been changed.']); } } <file_sep>/modules/Admin/resources/js/helpers/helpers.js export function errors({data, status}) { if (status !== 422) return {} return data.errors } <file_sep>/routes/console.php <?php use Illuminate\Support\Facades\Artisan; <file_sep>/database/migrations/2020_09_23_121458_create_volunteers_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteersTable extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_23_121458_create_volunteers_table.php */ public function up() { Schema::create('volunteers', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->unique()->constrained()->onDelete('cascade'); $table->boolean('is_private')->default(false); $table->string('phone')->nullable(); $table->string('email')->nullable(); $table->json('social')->nullable(); $table->string('headline')->nullable(); $table->foreignId('city_id')->nullable()->constrained('us_cities'); $table->char('zip', 5)->nullable(); $table->boolean('is_relocating')->default(false); $table->boolean('is_working_remotely')->default(false); $table->string('job_title')->nullable(); $table->text('executive_summary')->nullable(); $table->string('objective')->nullable(); $table->string('achievements')->nullable(); $table->string('associations')->nullable(); $table->foreignId('years_of_experience_id')->nullable()->constrained('volunteer_years_of_experience'); $table->foreignId('level_of_education_id')->nullable()->constrained('volunteer_levels_of_education'); $table->foreignId('veteran_status_id')->nullable()->constrained('volunteer_veteran_statuses'); $table->text('cover_letter')->nullable(); $table->string('personal_statement')->nullable(); $table->boolean('has_driver_license')->default(false); $table->boolean('has_car')->default(false); }); } public function down() { Schema::dropIfExists('volunteers'); } } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/LanguageController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Http\Controllers\Controller; use App\Models\Language; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Requests\Volunteer\LanguageRequest; class LanguageController extends Controller { use HasVolunteer; public function store(LanguageRequest $request): JsonResponse { $this->volunteer()->languages()->attach($request->language_id, [ 'fluency' => $request->fluency ]); return response()->json(['message' => 'Language has been added.']); } public function update(LanguageRequest $request, Language $language): JsonResponse { //$certificate->update($request->validated()); return response()->json(['message' => 'Language has been updated.']); } public function destroy(Language $language): JsonResponse { $this->volunteer()->languages()->detach($language->id); return response()->json(['message' => 'Language has been deleted.']); } } <file_sep>/app/Models/Volunteers/Education.php <?php namespace App\Models\Volunteers; use Illuminate\Database\Eloquent\Model; class Education extends Model { const CREATED_AT = null; const UPDATED_AT = null; protected $table = 'volunteer_educations'; protected $fillable = ['school', 'degree', 'field', 'start', 'end', 'description']; } <file_sep>/database/migrations/2020_09_23_121457_create_volunteer_details_tables.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerDetailsTables extends Migration { public function up() { Schema::create('volunteer_years_of_experience', function (Blueprint $table) { $table->id(); $table->string('name'); }); Schema::create('volunteer_levels_of_education', function (Blueprint $table) { $table->id(); $table->string('name'); }); Schema::create('volunteer_veteran_statuses', function (Blueprint $table) { $table->id(); $table->string('name'); }); } public function down() { Schema::dropIfExists('volunteer_years_of_experience'); Schema::dropIfExists('volunteer_levels_of_education'); Schema::dropIfExists('volunteer_veteran_statuses'); } } <file_sep>/modules/Admin/Http/Controllers/Blog/ArticleController.php <?php namespace Modules\Admin\Http\Controllers\Blog; use App\Models\Blog\Article; use Illuminate\Pagination\LengthAwarePaginator; use Modules\Admin\Http\Controllers\Controller; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Requests\Blog\ArticleRequest; use Modules\Admin\Http\Requests\IndexRequest; use Modules\Admin\Repositories\ArticleRepository; class ArticleController extends Controller { use CRUDController; protected ArticleRepository $articleRepository; protected string $resource = 'articles'; public function __construct() { $this->articleRepository = app(ArticleRepository::class); } public function index(IndexRequest $request) { $this->seo()->setTitle('Blog articles'); $sort = $request->get('sortDesc') ?? true; /* @var $articles LengthAwarePaginator */ $articles = Article::with('category') ->when($request->get('searchQuery'), fn($q) => $q->search($request->get('searchQuery'))) ->orderBy($request->get('sortBy') ?? 'id', $sort ? 'desc' : 'asc') ->paginate(10, ['category_id', 'id', 'slug', 'title', 'status', 'created_at', 'updated_at']); $articles->getCollection()->transform(function (Article $article) { $article->append('link'); $article['status'] = Article::$statuses[$article['status']]; return $article; }); if (request()->expectsJson()) { return $articles; } else { share(compact('articles')); } return $this->listing(); } public function create() { $this->seo()->setTitle('Create a new article'); $this->articleRepository->shareForCRUD(); return $this->form(); } public function store(ArticleRequest $request) { $this->seo()->setTitle('Edit an article'); $article = Article::create($request->validated()); if ($request->uploadImage($article)) { $article->load('imageMedia'); $article->append('image'); } return response()->json([ 'status' => 'Article has been created', 'title' => $this->seo()->getTitle(), 'article' => $article ], 201); } public function edit(Article $article) { $this->seo()->setTitle('Edit an article'); $article->append('image'); $this->articleRepository->shareForCRUD(); share(compact('article')); return $this->form(); } public function update(ArticleRequest $request, Article $article) { $article->update($request->validated()); if ($request->uploadImage($article)) { $article->load('imageMedia'); $article->append('image'); } return response()->json(['status' => 'Article has been updated', 'article' => $article]); } public function destroy(Article $article) { $article->delete(); return response()->json(['status' => 'Article has been deleted']); } } <file_sep>/app/Models/Blog/Article.php <?php namespace App\Models\Blog; use App\Models\Traits\SearchTrait; use Cviebrock\EloquentSluggable\Sluggable; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\UploadedFile; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; use Spatie\MediaLibrary\MediaCollections\Models\Media; class Article extends Model implements HasMedia { use Sluggable; use InteractsWithMedia; use SearchTrait; public const DRAFT = 'DRAFT'; public const PUBLISHED = 'PUBLISHED'; public static $statuses = [ self::DRAFT => 'Draft', self::PUBLISHED => 'Published' ]; protected $fillable = [ 'category_id', 'title', 'slug', 'excerpt', 'body', 'meta_title', 'meta_description', 'status' ]; protected $search = [ 'title', 'excerpt' ]; // FUNCTIONS public function registerMediaCollections(): void { $this->addMediaCollection('image') ->singleFile() ->registerMediaConversions(function (Media $media) { $this->addMediaConversion('thumbnail') ->crop('crop-center', 370, 250) ->sharpen(0) ->nonQueued(); }); } public function uploadImage(UploadedFile $image = null): ?Media { if ($this->imageMedia) $this->deleteMedia($this->imageMedia); return $this->addMedia($image)->toMediaCollection('image'); } public function getImage(string $size = ''): string { if ($this->imageMedia !== null) { return url($this->imageMedia->getUrl($size)); } else { return asset('dist/img/no-image.jpg'); } } public function sluggable() { return [ 'slug' => [ 'source' => !empty($this->slug) ? 'slug' : 'title', 'onUpdate' => true, ] ]; } // RELATIONS public function category() { return $this->belongsTo(Category::class); } public function imageMedia() { return $this->morphOne(Media::class, 'model') ->where('collection_name', 'image'); } // SCOPES public function scopePublished($query) { return $query->whereStatus(self::PUBLISHED); } public function scopeWithImage($query) { return $query->with('imageMedia'); } //SETTERS public function setExcerptAttribute(string $excerpt) { $this->attributes['excerpt'] = strip_tags($excerpt); } // ACCESSORS public function getImageAttribute() { return $this->getImage(); } public function getThumbnailAttribute() { return $this->getImage('thumbnail'); } public function getLinkAttribute() { return route('frontend.articles.show', [ 'category' => $this->category->slug, 'article' => $this->slug ]); } public function getDateAttribute() { return $this->created_at->format('d M, Y'); } } <file_sep>/modules/Frontend/resources/js/mixins/form.js import Invalid from "../components/includes/Invalid" import {errors} from "../helpers/helpers" export default { data() { return { errors: {}, isLoading: false } }, methods: { async submit() { this.isLoading = true try { const {status, data} = await this.axios.post(this.route('contact-form'), this.form) try { if (status === 200) { for (let field in this.form) this.form[field] = '' this.errors = {} this.$bus.emit('alert', {text: data.status}) } } catch (e) { console.log(e) } } catch ({response}) { this.wasValidated = true this.errors = errors(response) } this.isLoading = false } }, directives: { valid(el, {modifiers}, {context}) { if (Object.keys(modifiers)[0] in context.errors) { el.classList.remove('is-valid') el.classList.add('is-invalid') } else { el.classList.remove('is-invalid') if (context.wasValidated) { el.classList.add('is-valid') } else if (el.classList.contains('is-valid')) { el.classList.remove('is-valid') } } } }, components: { Invalid } } <file_sep>/modules/Frontend/config.php <?php return [ 'domain' => env('APP_DOMAIN'), 'emails_for_contacts' => parse_emails(env('CONTACT_EMAILS', '')), 'vacancies_company_id' => env('VACANCIES_COMPANY_ID', 1), 'social' => [ 'twitter' => env('SOCIAL_TWITTER'), 'instagram' => env('SOCIAL_INSTAGRAM'), 'linkedin' => env('SOCIAL_LINKEDIN'), 'facebook' => env('SOCIAL_FACEBOOK'), 'youtube' => env('SOCIAL_YOUTUBE'), ] ]; <file_sep>/modules/Frontend/Http/Controllers/ChatController.php <?php namespace Modules\Frontend\Http\Controllers; use App\Models\Chats\Chat; use App\Models\Chats\Message; use App\Models\Client; use Illuminate\Http\JsonResponse; use Modules\Frontend\Events\NewMessage; use Modules\Frontend\Http\Requests\MessageRequest; class ChatController extends Controller { public function page(Chat $chat = null) { $this->seo()->setTitle('Chat'); $user = \Auth::user(); $client = $user->getClient(); $with = [$user->is_volunteer ? 'company.logoMedia' : 'volunteer.avatarMedia']; $chats = $client->chats()->with(['vacancy', ...$with])->get(); $chats = $chats->map(function (Chat $chat) use ($user, $client) { $receiver = $chat->relationLoaded('volunteer') ? $chat->volunteer : $chat->company; $receiver->append(['icon', 'name']); /* @var $lastMessage Message */ $lastMessage = $chat->messages()->latest()->first(); $id = $client->id; if ($user->is_volunteer ? $id === $lastMessage->volunteer_id : $client->id === $lastMessage->company_id) { $lastMessage->isOwner = true; } return [ 'id' => $chat->id, 'jobTitle' => $chat->vacancy->title ?? null, 'name' => $receiver->name, 'avatar' => $receiver->icon, 'lastMessage' => $this->mapMessage($lastMessage) ]; }); share(compact('chats')); if ($chat) { $this->markMessagesAsViewed($client, $chat); share([ 'selectedChatId' => $chat->id, 'messages' => $chat->messages->map(fn(Message $message) => $this->mapMessage($message)), 'unviewedMessages' => $client->getUnviewedMessages() ]); } return view('frontend::pages.chat'); } protected function mapMessage(Message $message): array { $user = \Auth::user(); $client = $user->getClient(); $data = $message->toArray(); $data['isOwner'] = $user->is_volunteer ? $message->volunteer_id === $client->id : $message->company_id === $client->id; return $data; } protected function markMessagesAsViewed(Client $client, Chat $chat) { $client->setRelation('chats', [$chat])->incomeMessages()->unviewed()->update(['is_viewed' => true]); } public function messages(Chat $chat): JsonResponse { $client = \Auth::user()->getClient(); $messages = collect(); $this->markMessagesAsViewed($client, $chat); $messages = $chat->messages->map(function (Message $message) { return $this->mapMessage($message); }); return response()->json([ 'messages' => $messages, 'unviewedMessages' => $client->getUnviewedMessages() ]); } public function send(MessageRequest $request, Chat $chat): JsonResponse { $user = \Auth::user(); /* @var $message Message */ $message = $user->getClient()->messages()->create([ 'chat_id' => $chat->id, 'text' => $request->message ]); broadcast(new NewMessage($message, $chat, $user->getClient())); return response()->json(['message' => $this->mapMessage($message)], 201); } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/WorkExperienceRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer; use Carbon\Carbon; use Illuminate\Foundation\Http\FormRequest; class WorkExperienceRequest extends FormRequest { public function rules(): array { return [ 'title' => ['required', 'string255'], 'company' => ['required', 'string255'], 'start' => ['required', 'date', 'before:now'], 'end' => ['nullable', 'date', 'after_or_equal:start'], 'description' => ['nullable', 'string255'], ]; } public function validated() { $data = parent::validated(); $data['start'] = Carbon::parse($data['start'])->format('Y-m-d H:i'); if ($end = $data['end']) { $data['end'] = Carbon::parse($end)->format('Y-m-d H:i'); } return $data; } public function authorize(): bool { return true; } } <file_sep>/database/migrations/2021_01_18_184156_create_volunteer_surveys_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerSurveysTable extends Migration { public function up(): void { Schema::create('volunteer_surveys', function (Blueprint $table) { $table->id(); $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->foreignId('source_id')->constrained('volunteer_survey_sources'); $table->string('specified')->nullable(); $table->string('name')->nullable(); $table->string('email')->nullable(); $table->string('address')->nullable(); $table->string('phone')->nullable(); $table->string('company_name')->nullable(); $table->text('description')->nullable(); $table->timestamp('created_at')->nullable(); }); } public function down(): void { Schema::dropIfExists('volunteer_surveys'); } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/LanguageRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer; use App\Models\Language; use Illuminate\Foundation\Http\FormRequest; class LanguageRequest extends FormRequest { public function rules(): array { $fluencies = implode(',', array_keys(Language::$fluencies)); return [ 'language_id' => ['required', 'exists:languages,id'], 'fluency' => ['required', "in:$fluencies"] ]; } public function authorize(): bool { return true; } } <file_sep>/app/Helpers/functions.php <?php if (!function_exists('asset_admin')) { function asset_admin($path) { return url("admin/$path"); } } if (!function_exists('form_was_validated')) { function form_was_validated(Illuminate\Support\ViewErrorBag $errors = null): string { if ($errors == null) $errors = Session('errors'); if ($errors && $errors->isNotEmpty()) return $errors->isNotEmpty() ? 'was-validated' : ''; return ''; } } if (!function_exists('valid_class')) { function valid_class(string $name, Illuminate\Support\ViewErrorBag $errors = null): string { if ($errors == null) $errors = Session('errors'); if ($errors && $errors->isNotEmpty()) return !$errors->has($name) ?: 'is-invalid'; return ''; } } if (!function_exists('parse_emails')) { function parse_emails(string $emails): array { return array_map(fn($e) => trim($e), explode(',', $emails)); } } function checked($name, $default = false) { return old($name, $default) ? 'checked' : ''; } function radio_checked($name, $value) { return old($name) == $value ? 'checked' : ''; } function selected($name, $value, $old = null): string { if (old($name) == $value || ($old !== null && $value == $old)) { echo 'selected'; } return ''; } function is_valid(string $name): string { return valid_class($name); } <file_sep>/database/migrations/2020_09_23_142340_create_volunteer_educations_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerEducationsTable extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_23_142340_create_volunteer_educations_table.php */ public function up() { Schema::create('volunteer_educations', function (Blueprint $table) { $table->id(); $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->string('school'); $table->string('degree'); $table->string('field')->nullable(); $table->unsignedSmallInteger('start'); $table->unsignedSmallInteger('end'); $table->string('description')->nullable(); }); } public function down() { Schema::dropIfExists('volunteer_educations'); } } <file_sep>/modules/Frontend/Http/Middleware/SharedData.php <?php namespace Modules\Frontend\Http\Middleware; use Auth; use Closure; use Illuminate\Http\Request; class SharedData { public function handle(Request $request, Closure $next) { $shared = ['social' => config('frontend.social')]; if (!$request->expectsJson() && $request->isMethod('GET') && $user = Auth::user()) { $user->load(['company', 'volunteer'])->append(['is_volunteer']); if ($user->company) { $user->company->append(['logo', 'employment', 'location', 'is_subscribed']); } $userData = $user->toArray(); if ($client = $user->getClient()) { $userData['client'] = $client; $unviewedMessages = $client->getUnviewedMessages(); } share([ 'user' => $userData, 'unviewedMessages' => $unviewedMessages ?? 0 ]); } share($shared); return $next($request); } } <file_sep>/modules/Frontend/resources/js/mixins/validation.js import {ReactiveProvideMixin} from 'vue-reactive-provide' import jsonToForm from "json-form-data" import Invalid from "~/components/includes/Invalid" import {errors} from "~/helpers/helpers" export default { components: { Invalid }, mixins: [ ReactiveProvideMixin({ name: 'errorsInject', include: ['errors'] }), ], data() { return { errors: {}, isLoading: false, wasValidated: false, formConfig: { header: { 'Content-Type': 'multipart/form-data' } } } }, methods: { invalid(field) { if (field in this.errors) return 'has-error' }, async send(url, form) { this.isLoading = true try { const {status, data} = await this.axios.post( url, form, form instanceof FormData ? this.formConfig : null ) this.wasValidated = false this.errors = {} return {status, data} } catch ({response}) { this.wasValidated = true this.$bus.emit('alert', {variant: 'warning', text: response.data.message}) this.errors = errors(response) } finally { this.isLoading = false } }, jtf(json, options = null) { const form = jsonToForm(json, options) if (this.isEdit) form.append('_method', 'PATCH') return form }, } } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/VacancyController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer; use App\Models\Vacancy; use Illuminate\Support\Collection; use Modules\Frontend\Http\Controllers\Controller; use Modules\Frontend\Http\Controllers\Volunteer\Account\HasVolunteer; use Modules\Frontend\Repositories\VacancyRepository; class VacancyController extends Controller { use HasVolunteer; protected VacancyRepository $repository; protected $fields = [ 'id', 'company_id', 'title', 'city_id', 'type_id', 'excerpt', 'company_title', 'status', 'created_at' ]; public function __construct() { $this->repository = app(VacancyRepository::class); } public function saved() { $this->seo()->setTitle("Saved vacancies"); $vacancies = $this->volunteer()->bookmarks() ->active() ->with(['company.logoMedia', 'city', 'type', 'hours']) ->latest() ->paginate(4, $this->fields); /* @var $vacancies Collection<Vacancy> */ $vacancies->transform([$this->repository, 'transformForIndex']); if (request()->expectsJson()) { return $vacancies; } $this->repository->shareForFilter(); share(compact('vacancies')); \Route2Class::addClass('page-with-search'); return view('frontend::volunteer.vacancies.saved'); } public function history() { $this->seo()->setTitle("History apply"); $vacancies = $this->volunteer()->applies() ->with(['company.logoMedia', 'city', 'type', 'hours']) ->latest() ->paginate(4, $this->fields); /* @var $vacancies Collection<Vacancy> */ $vacancies->transform([$this->repository, 'transformForIndex']); if (request()->expectsJson()) { return $vacancies; } $this->repository->shareForFilter(); share(compact('vacancies')); \Route2Class::addClass('page-with-search'); return view('frontend::volunteer.vacancies.history'); } } <file_sep>/modules/Frontend/Repositories/ArticleRepository.php <?php namespace Modules\Frontend\Repositories; use App\Models\Blog\Category; class ArticleRepository { public function getCategories(Category $category = null) { return Category::active()->ordered()->get(['slug', 'name'])->map(function (Category $c) use ($category) { $c->append('link'); $c['is_active'] = $category && $category->slug == $c->slug; return $c; }); } } <file_sep>/database/seeds/PermissionsSeeder.php <?php use Illuminate\Database\Seeder; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; class PermissionsSeeder extends Seeder { public function run(): void { /* Eloquent::unguard(); DB::statement('SET FOREIGN_KEY_CHECKS=0;'); Role::truncate(); Permission::truncate(); DB::statement('SET FOREIGN_KEY_CHECKS=1;'); */ $permissions = [ 'access admin panel', 'edit settings', 'manage pages', 'manage articles', 'manage users', ]; foreach ($permissions as $permission) { if (Permission::where('name', $permission)->first() === null) Permission::create(['name' => $permission]); } $roles = [ 'admin' => $permissions, 'moderator' => [ 'access admin panel', ], 'seo' => [ 'access admin panel', 'manage pages', 'manage articles', ], 'writer' => [ 'access admin panel', 'manage articles' ], ]; foreach ($roles as $name => $permissions) { $role = null; try { $role = Role::findByName($name); } catch (Exception $e) { } if ($role === null) { $role = new Role(['name' => $name]); $role->save(); } $role->syncPermissions($permissions); } } } <file_sep>/database/migrations/2020_11_04_115131_create_volunteer_has_locations.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerHasLocations extends Migration { public function up() { Schema::create('volunteer_has_locations', function (Blueprint $table) { $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->foreignId('city_id')->constrained('us_cities')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('volunteer_has_locations'); } } <file_sep>/modules/Frontend/Http/Controllers/Company/VacancyController.php <?php namespace Modules\Frontend\Http\Controllers\Company; use App\Models\Vacancy; use Auth; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Controllers\Controller; use Modules\Frontend\Http\Requests\Company\VacancyRequest; use Modules\Frontend\Repositories\VacancyRepository; class VacancyController extends Controller { use HasCompany; protected VacancyRepository $repository; protected array $fillable = [ 'title', 'sector_id', 'city_id', 'address', 'type_id', 'description', 'is_relocation', 'is_remote_work', 'company_title', 'company_description' ]; public function __construct() { $this->repository = app(VacancyRepository::class); } public function index(string $status = null) { $this->seo()->setTitle('Vacancies'); $company = Auth::getUser()->company->append('logo'); $vacancies = $company->vacancies() ->when($status, fn($q) => $q->where('status', $status)) ->with(['city', 'type', 'hours']) ->latest() ->get(['id', 'company_id', 'title', 'city_id', 'type_id', 'excerpt', 'company_title', 'status', 'created_at']) ->map(function (Vacancy $vacancy) use ($company) { $vacancy->setRelation('company', $company); $vacancy->append(['employment', 'date', 'location']); $vacancy->company_title = $vacancy->company_title ?? $company->name; $vacancy->days = $vacancy->created_at->diffInDays(); return $vacancy; }); if ($status && !$vacancies->count()) { return redirect()->route('frontend.company.vacancies.index'); } share(compact('vacancies')); $all = $company->vacancies()->count(); $active = $company->vacancies()->active()->count(); $draft = $company->vacancies()->draft()->count(); $closed = $company->vacancies()->closed()->count(); $availableVacancies = 0; if ($plan = $company->getPlan()) { $limit = $plan['limits']['vacancies']; $availableVacancies = $limit === -1 ? '∞' : $limit; } return view('frontend::company.vacancies.index', [ 'counts' => compact('all', 'active', 'draft', 'closed') ], compact('availableVacancies')); } public function create() { if (!$this->company()->subscribed()) { return redirect()->route('frontend.company.upgrade.page'); } $title = 'Post a need'; $this->seo()->setTitle($title); $this->repository->sharedData(); return view('frontend::company.vacancies.form', compact('title')); } public function store(VacancyRequest $request): JsonResponse { $company = Auth::getUser()->company; if (!$company->canPostVacancy()) { return response()->json([ 'message' => 'You have exhausted the vacancy limit. Delete another vacancy or update your plan.' ], 403); } /* @var $vacancy Vacancy */ $vacancy = $company->vacancies()->create($request->only($this->fillable)); $request->setVacancy($vacancy); $request->syncHours(); $request->syncBenefits(); $request->syncIncentives(); $request->syncSkills(); return response()->json(['message' => 'Vacancy has been created.']); } public function edit(Vacancy $vacancy) { $title = 'Edit vacancy'; $this->seo()->setTitle('Edit vacancy'); $this->repository->sharedData(); $vacancy = $this->repository->transformForEdit($vacancy); share(compact('vacancy')); return view('frontend::company.vacancies.form', compact('title')); } public function update(VacancyRequest $request, Vacancy $vacancy): JsonResponse { $vacancy->update($request->only($this->fillable)); $request->setVacancy($vacancy); $request->syncHours(); $request->syncBenefits(); $request->syncIncentives(); $request->syncSkills(); return response()->json(['message' => 'Vacancy has been updated.']); } public function destroy(Vacancy $vacancy): JsonResponse { $vacancy->delete(); return response()->json(['message' => 'The vacancy has been deleted.']); } public function post(Vacancy $vacancy): JsonResponse { //todo check subscription if (!in_array($vacancy->status, [Vacancy::DRAFT])) abort(403); $vacancy->status = Vacancy::ACTIVE; $vacancy->save(); return response()->json(['message' => 'The vacancy has been published.']); } public function stop(Vacancy $vacancy): JsonResponse { $vacancy->status = Vacancy::DRAFT; $vacancy->save(); return response()->json(['message' => 'The vacancy has been stopped.']); } public function close(Vacancy $vacancy): JsonResponse { if (!in_array($vacancy->status, [Vacancy::DRAFT, Vacancy::ACTIVE])) abort(403); $vacancy->status = Vacancy::CLOSED; $vacancy->save(); return response()->json(['message' => 'The vacancy has been closed.']); } public function duplicate(Vacancy $vacancy) { $title = 'Duplicate vacancy'; $this->seo()->setTitle($title); $this->repository->sharedData(); share([ 'vacancy' => $this->repository->transformForEdit($vacancy) ]); return view('frontend::company.vacancies.form', compact('title')); } } <file_sep>/app/Models/User.php <?php namespace App\Models; use App\Models\Interfaces\SearchRecordable; use App\Models\Traits\SearchTrait; use App\Models\Volunteers\Volunteer; use Iatstuti\Database\Support\CascadeSoftDeletes; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\SoftDeletes; use Modules\Frontend\Notifications\ResetPassword as ResetPasswordNotification; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable implements HasMedia { use HasRoles, Notifiable, InteractsWithMedia, SoftDeletes, CascadeSoftDeletes, SearchTrait; protected $fillable = [ 'name', 'email', 'provider', 'provider_id', 'password', 'type' ]; protected $hidden = [ 'password', 'remember_token', ]; protected $cascadeDeletes = ['company', 'volunteer']; protected $search = [ 'email', 'name' ]; public const VOLUNTEER = 'VOLUNTEER'; public const COMPANY = 'COMPANY'; public static $types = [ self::VOLUNTEER => 'Volunteer', self::COMPANY => 'Company' ]; // FUNCTIONS public function sendPasswordResetNotification($token): void { $this->notify(new ResetPasswordNotification($token)); } public function getClient(): ?Client { return $this->is_volunteer ? $this->volunteer : $this->company; } // RELATIONS /* @return Company|HasOne */ public function company(): HasOne { return $this->hasOne(Company::class); } /* @return Volunteer|HasOne */ public function volunteer(): HasOne { return $this->hasOne(Volunteer::class); } // ACCESSORS public function getAvatarAttribute(): ?string { if ($this->type === self::VOLUNTEER) { if ($volunteer = $this->volunteer) { return $this->volunteer->avatar; } } else if ($company = $this->company) { return $this->company->logo; } return null; } public function getHasPasswordAttribute(): bool { return !empty($this->attributes['password']); } public function getIsSuperAdminAttribute(): bool { return $this->id === 1 || $this->email === env('INITIAL_USER_EMAIL'); } public function getIsVolunteerAttribute(): bool { return $this->type === self::VOLUNTEER; } } <file_sep>/database/migrations/2020_09_16_170904_create_us_cities_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsCitiesTable extends Migration { public function up() { Schema::create('us_cities', function (Blueprint $table) { $table->id(); $table->char('state_id', 2); $table->string('name'); $table->string('county'); $table->double('lat'); $table->double('lng'); $table->string('zips', 1900); $table->unsignedInteger('population'); $table->foreign('state_id')->references('id')->on('us_states'); }); } public function down() { Schema::dropIfExists('us_cities'); } } <file_sep>/app/Models/Traits/SearchRecording.php <?php namespace App\Models\Traits; use App\Models\SearchQuery; use Illuminate\Database\Eloquent\Relations\HasMany; trait SearchRecording { public function searchQueries(): HasMany { return $this->hasMany(SearchQuery::class); } } <file_sep>/modules/Frontend/resources/js/pages/index.js export default { RegisterPage: () => import('./auth/Register'), WorkPage: () => import('./static/Work'), HelpPage: () => import('./static/Help'), SitemapPage: () => import('./static/Sitemap'), VolunteerShowPage: () => import('./volunteer/Show'), VolunteerCompaniesPage: () => import('./volunteer/Companies'), VolunteerSavedVacanciesPage: () => import('./volunteer/SavedVacancies'), VolunteerHistoryVacanciesPage: () => import('./volunteer/HistoryVacancies'), VolunteerSurveyPage: () => import('./volunteer/Survey'), CompanyBoardPage: () => import('./company/Board'), CompanyVolunteersIndexPage: () => import('./company/volunteers/Index'), CompanySavedVolunteersPage: () => import('./company/volunteers/Saved'), CompanyCandidatesPage: () => import('./company/volunteers/Candidates'), CompanyUpgradePage: () => import('./company/Upgrade'), ChatPage: () => import('./Chat'), DefaultPage: () => import('./static/Default'), } <file_sep>/modules/Frontend/resources/js/store/modules/volunteer.js import Vue from 'vue' import jsonToForm from 'json-form-data' import {errors} from "~/helpers/helpers" export default { namespaced: true, state: { form: { is_private: false, phone: '', email: '', social: { website: '', linkedin: '', twitter: '', facebook: '', instagram: '', youtube: '', reddit: '', pinterest: '', quora: '', }, name: '', headline: '', city_id: null, zip: '', is_relocating: false, is_working_remotely: false, job_title: '', executive_summary: '', objective: '', achievements: '', associations: '', skills: [], years_of_experience_id: null, level_of_education_id: null, veteran_status_id: null, cover_letter: '', personal_statement: '', has_driver_license: false, has_car: false }, avatar: null, locations: [null], types: [], hours: [], sectors: {}, work_experiences: [], educations: [], resume: null, certificates: [], languages: [] }, mutations: { setup(state, volunteer) { for (let field in state.form) { if (volunteer.hasOwnProperty(field)) { if (field === 'social') { if (volunteer.social !== null) { for (let field in state.form.social) { if (volunteer.social.hasOwnProperty(field)) state.form.social[field] = volunteer.social[field] } } } else { state.form[field] = volunteer[field] } } } state.resume = volunteer.resume || null const relations = [ 'locations', 'types', 'hours', 'sectors', 'work_experiences', 'educations', 'certificates', 'languages' ] for (let relation of relations) if (volunteer[relation].length || Object.values(volunteer[relation]).length) state[relation] = volunteer[relation] }, update(state, form) { for (let field in form) { if (form.hasOwnProperty(field) && state.form.hasOwnProperty(field)) state.form[field] = form[field] } }, updateJob(state, form) { state.form.job_title = form.job_title state.locations = form.locations state.types = form.types state.hours = form.hours state.sectors = {} for (let sector of form.sectors) { state.sectors[sector.id] = sector.roles } }, destroyJob(state) { state.form.job_title = '' state.location = [] state.types = [] state.hours = [] state.sectors = {} }, addWorkExperience(state, experience) { state.work_experiences.push(experience) }, updateWorkExperience(state, experience) { Vue.set(state.work_experiences, state.work_experiences.findIndex(({id}) => id === experience.id), experience) }, destroyWorkExperience(state, id) { state.work_experiences = state.work_experiences.filter(item => item.id !== id) }, addEducation(state, education) { state.educations.push(education) }, updateEducation(state, education) { Vue.set(state.educations, state.educations.findIndex(({id}) => id === education.id), education) }, destroyEducation(state, id) { state.educations = state.educations.filter(item => item.id !== id) }, addResume(state, resume) { state.resume = resume }, destroyResume(state) { state.resume = null }, addCertificate(state, certificate) { state.certificates.push(certificate) }, updateCertificate(state, certificate) { Vue.set(state.certificates, state.certificates.findIndex(({id}) => id === certificate.id), certificate) }, destroyCertificate(state, id) { state.certificates = state.certificates.filter(item => item.id !== id) }, addLanguage(state, language) { state.languages.push(language) }, updateLanguage(state, language) { Vue.set(state.languages, state.languages.findIndex(({id}) => id === language.id), language) }, destroyLanguage(state, id) { state.languages = state.languages.filter(item => item.id !== id) } }, actions: { async updateAbout({commit}, form) { try { const {status, data} = await this.app.axios.post(this.app.route('volunteer.account.update'), form) if (status === 200) { commit('update', form) commit('setErrors', {}, {root: true}) //this.app.notify(data.message) return true } } catch ({response}) { //this.wasValidated = true //this.app.notify(response.data.message, 'warning') commit('setErrors', errors(response), {root: true}) return false } }, async togglePrivacy({state, commit}) { try { const form = {is_private: !state.form.is_private} const {status} = await this.app.axios.post(this.app.route('volunteer.account.update'), form) if (status === 200) { commit('update', form) return true } } catch (e) { console.log(e) return false } }, async updateJob({commit}, form) { try { const {status, data} = await this.app.axios.post(this.app.route('volunteer.account.job.update'), form) if (status === 200) { commit('updateJob', form) commit('setErrors', {}, {root: true}) this.app.notify(data.message) return true } } catch ({response}) { //this.wasValidated = true //this.app.notify(response.data.message, 'warning') commit('setErrors', errors(response), {root: true}) return false } }, async destroyJob({commit}) { try { const { status, data } = await this.app.axios.delete(this.app.route('volunteer.account.job.destroy')) if (status === 200) { commit('destroyJob') this.app.notify(data.message) return true } } catch (e) { console.log(e) return false } }, async updateOrCreateWorkExperience({commit}, {id, form}) { try { const {status, data} = id ? await this.app.axios.patch(this.app.route('volunteer.account.work_experiences.update', id), { ...form, _method: 'PATCH' }) : await this.app.axios.post(this.app.route('volunteer.account.work_experiences.store'), form) if (status === 200) { if (id) { commit('updateWorkExperience', {id, ...form}) } else { commit('addWorkExperience', {id: data.id, ...form}) } this.app.notify(data.message) commit('setErrors', {}, {root: true}) return true } } catch ({response}) { commit('setErrors', errors(response), {root: true}) return false } }, async destroyWorkExperience({commit}, id) { try { const { status, data } = await this.app.axios.delete(this.app.route('volunteer.account.work_experiences.destroy', id)) if (status === 200) { commit('destroyWorkExperience', id) this.app.notify(data.message) return true } } catch (e) { console.log(e) return false } }, async updateOrCreateEducation({commit}, {id, form}) { try { const {status, data} = id ? await this.app.axios.patch(this.app.route('volunteer.account.educations.update', id), { ...form, _method: 'PATCH' }) : await this.app.axios.post(this.app.route('volunteer.account.educations.store'), form) if (status === 200) { if (id) { commit('updateEducation', {id, ...form}) } else { commit('addEducation', {id: data.id, ...form}) } this.app.notify(data.message) commit('setErrors', {}, {root: true}) return true } } catch ({response}) { commit('setErrors', errors(response), {root: true}) return false } }, async destroyEducation({commit}, id) { try { const { status, data } = await this.app.axios.delete(this.app.route('volunteer.account.educations.destroy', id)) if (status === 200) { commit('destroyEducation', id) this.app.notify(data.message) return true } } catch (e) { console.log(e) return false } }, async createResume({commit}, form) { try { const { status, data } = await this.app.axios.post(this.app.route('volunteer.account.resume.store'), jsonToForm(form), { header: { 'Content-Type': 'multipart/form-data' } }) if (status === 200) { commit('addResume', { title: form.title, url: data.url, created_at: data.created_at }) this.app.notify(data.message) commit('setErrors', {}, {root: true}) return true } } catch ({response}) { commit('setErrors', errors(response), {root: true}) return false } }, async destroyResume({commit}) { try { const { status, data } = await this.app.axios.delete(this.app.route('volunteer.account.resume.destroy')) if (status === 200) { commit('destroyResume') this.app.notify(data.message) return true } } catch (e) { console.log(e) return false } }, async updateOrCreateCertificate({commit}, {id, form}) { try { const {status, data} = id ? await this.app.axios.patch(this.app.route('volunteer.account.certificates.update', id), { ...form, _method: 'PATCH' }) : await this.app.axios.post(this.app.route('volunteer.account.certificates.store'), form) if (status === 200) { if (id) { commit('updateCertificate', {id, ...form}) } else { commit('addCertificate', {id: data.id, ...form}) } this.app.notify(data.message) commit('setErrors', {}, {root: true}) return true } } catch ({response}) { commit('setErrors', errors(response), {root: true}) return false } }, async destroyCertificate({commit}, id) { try { const { status, data } = await this.app.axios.delete(this.app.route('volunteer.account.certificates.destroy', id)) if (status === 200) { commit('destroyCertificate', id) this.app.notify(data.message) return true } } catch (e) { console.log(e) return false } }, async updateOrCreateLanguage({commit}, {id, form}) { try { const {status, data} = id ? await this.app.axios.patch(this.app.route('volunteer.account.languages.update', id), { ...form, _method: 'PATCH' }) : await this.app.axios.post(this.app.route('volunteer.account.languages.store'), form) if (status === 200) { if (id) { commit('updateLanguage', {id, ...form}) } else { commit('addLanguage', {id: form.language_id, fluency: form.fluency}) } this.app.notify(data.message) commit('setErrors', {}, {root: true}) return true } } catch ({response}) { commit('setErrors', errors(response), {root: true}) return false } }, async destroyLanguage({commit}, id) { try { const { status, data } = await this.app.axios.delete(this.app.route('volunteer.account.languages.destroy', id)) if (status === 200) { commit('destroyLanguage', id) this.app.notify(data.message) return true } } catch (e) { console.log(e) return false } }, } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/Survey/InitialRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer\Survey; use Illuminate\Foundation\Http\FormRequest; class InitialRequest extends FormRequest { public function rules(): array { return [ 'source_id' => ['required', 'exists:volunteer_survey_sources,id'], 'specified' => ['nullable', 'string255'], ]; } public function authorize(): bool { return true; } } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/SurveyController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer; use App\Models\Volunteers\Surveys\Source; use App\Models\Volunteers\Surveys\Survey; use DB; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Controllers\Controller; use Modules\Frontend\Http\Controllers\Volunteer\Account\HasVolunteer; use Modules\Frontend\Http\Requests\Volunteer\Survey\CompleteRequest; use Modules\Frontend\Http\Requests\Volunteer\Survey\InitialRequest; use Modules\Frontend\Http\Requests\Volunteer\Survey\UpdateJobRequest; class SurveyController extends Controller { use HasVolunteer; public function page() { $this->seo()->setTitle('Short Survey'); $sources = Source::all(); share(compact('sources')); return view('frontend::volunteer.survey'); } public function store(InitialRequest $request): JsonResponse { /* @var $survey Survey */ $survey = $this->volunteer()->surveys()->create([ 'source_id' => $request->source_id, 'specified' => $request->specified ]); return response()->json(['message' => 'Ok.']); } public function updateJob(UpdateJobRequest $request): JsonResponse { $this->volunteer()->workExperiences()->create([ 'title' => $request->job_title, 'company' => $request->company_name, 'start' => DB::raw('NOW()') ]); return response()->json(['message' => 'You profile has been updated.']); } public function complete(CompleteRequest $request): JsonResponse { $survey = $this->volunteer()->surveys()->latest()->first(); if ($survey) { $survey->update([ 'name' => $request->name, 'email' => $request->email, 'address' => $request->address, 'phone' => $request->phone, 'company_name' => $request->company_name, 'description' => $request->description ]); } return response()->json(['message' => 'Thanks you for your apply!']); } } <file_sep>/database/seeds/Jobs/HoursSeeder.php <?php use App\Models\Jobs\Hour; use Illuminate\Database\Seeder; class HoursSeeder extends Seeder { public function run() { $hours = ['Full-time', 'Part-time', 'Per diem']; foreach ($hours as $name) Hour::create(compact('name')); } } <file_sep>/database/migrations/2020_09_08_113654_create_job_details_tables.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateJobDetailsTables extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_08_113654_create_job_details_tables.php */ public function up() { Schema::create('job_hours', function (Blueprint $table) { $table->id(); $table->string('name'); }); Schema::create('job_types', function (Blueprint $table) { $table->id(); $table->string('name'); }); Schema::create('job_company_sizes', function (Blueprint $table) { $table->id(); $table->string('name'); }); Schema::create('job_benefits', function (Blueprint $table) { $table->id(); $table->string('name')->unique(); }); Schema::create('job_incentives', function (Blueprint $table) { $table->id(); $table->string('name')->unique(); }); Schema::create('job_skills', function (Blueprint $table) { $table->id(); $table->string('name')->unique(); }); } public function down() { Schema::dropIfExists('job_hours'); Schema::dropIfExists('job_types'); Schema::dropIfExists('job_company_sizes'); Schema::dropIfExists('job_benefits'); Schema::dropIfExists('job_skills'); } } <file_sep>/modules/Frontend/Http/Controllers/VacancyController.php <?php namespace Modules\Frontend\Http\Controllers; use App\Models\Chats\Chat; use App\Models\Vacancy; use App\Services\LocationService; use Carbon\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\JsonResponse; use Illuminate\Support\Collection; use Modules\Frontend\Http\Controllers\Volunteer\Account\HasVolunteer; use Modules\Frontend\Http\Requests\MessageRequest; use Modules\Frontend\Http\Requests\VacanciesRequest; use Modules\Frontend\Notifications\Company\VacancyApplied; use Modules\Frontend\Repositories\VacancyRepository; class VacancyController extends Controller { use HasVolunteer; protected VacancyRepository $repository; public function __construct() { $this->repository = app(VacancyRepository::class); } public function index( VacanciesRequest $request, LocationService $locationService, string $query = null, string $location = null ) { $title = $query ?? 'Search'; $locations = []; if ($location) { $locations = $locationService->parseLocation($location); } $this->seo()->setTitle(__('meta.vacancies.index.title')); $this->seo()->setDescription(__('meta.vacancies.index.description')); $filters = $request->validated(); $vacancies = Vacancy::active() ->when($query, fn($q) => $q->where('title', 'REGEXP', '[[:<:]]' . $query . '[[:>:]]')) ->when(!empty($locations), fn(Builder $q) => $q->whereIn('city_id', $locations)) ->with(['company.logoMedia', 'city', 'type', 'hours']) ->when(isset($filters['is_relocation']), fn($q) => $q->where('is_relocation', '=', true)) ->when(isset($filters['is_remote_work']), fn($q) => $q->where('is_remote_work', '=', true)) ->when(isset($filters['hours']) && !empty($filters['hours']), fn($q) => $q->whereHas('hours', fn($q) => $q->whereIn('id', $filters['hours']))) ->when(isset($filters['types']) && !empty($filters['types']), fn($q) => $q->whereIn('type_id', $filters['types'])) ->when(isset($filters['sizes']) && !empty($filters['sizes']), fn($q) => $q->whereHas('company', fn($q) => $q->whereIn('size_id', $filters['sizes']))) ->when(isset($filters['sectors']) && !empty($filters['sectors']), fn($q) => $q->whereHas('sector', fn($q) => $q->whereIn('id', $filters['sectors']))) ->when(isset($filters['time']), fn($q) => $q->where('created_at', '>=', Carbon::now()->subDays($filters['time'])->toDateTimeString())) ->latest() ->select([ 'id', 'company_id', 'title', 'city_id', 'address', 'type_id', 'excerpt', 'company_title', 'status', 'created_at' ]) ->paginate(4); /* @var $vacancies Collection<Vacancy> */ $vacancies->transform([$this->repository, 'transformForIndex']); if (request()->expectsJson()) { return $vacancies; } $this->repository->shareForFilter(); share(compact('vacancies', 'query', 'location')); \Route2Class::addClass('page-with-search'); return view('frontend::vacancies.index'); } public function show(Vacancy $vacancy) { if ($vacancy->status !== Vacancy::ACTIVE) { if (($user = \Auth::user()) && !$user->is_volunteer) { abort_if($vacancy->company_id !== $user->company->id, 404); } else { abort(404); } } $this->seo()->setTitle(__('meta.vacancies.show.title', ['name' => $vacancy->title])); $this->seo()->setDescription(__('meta.vacancies.show.description', [ 'name' => $vacancy->title, 'location' => "{$vacancy->city->name}, {$vacancy->city->state_id} " ])); $vacancy->load('company.logoMedia', 'city', 'hours', 'benefits', 'incentives', 'skills'); $vacancy->append(['employment', 'date', 'location', 'is_applied', 'in_bookmarks']); $vacancy->company_title ??= $vacancy->company->name; $vacancy->company_description ??= $vacancy->company->description; $vacancy->company->append('logo'); share(compact('vacancy')); return view('frontend::vacancies.show'); } public function apply(Vacancy $vacancy): JsonResponse { $volunteer = $this->volunteer(); $volunteer->applies()->attach($vacancy->id); $vacancy->company->user->notify(new VacancyApplied($vacancy, $volunteer)); return response()->json(['message' => 'Vacancy has been applied.']); } public function bookmark(Vacancy $vacancy): JsonResponse { $bookmarks = $this->volunteer()->bookmarks()->toggle($vacancy->id); return response()->json([ 'message' => 'Vacancy has been ' . ($bookmarks['attached'] ? 'saved to' : 'removed from') . ' bookmarks.', 'inBookmarks' => in_array($vacancy->id, $bookmarks['attached'], true) ]); } public function chat(MessageRequest $request, Vacancy $vacancy): JsonResponse { $volunteer = $this->volunteer(); /* @var $chat Chat */ $chat = $volunteer->chats()->where('vacancy_id', '=', $vacancy->id)->first(); if (!$chat) { $chat = $volunteer->chats()->create([ 'vacancy_id' => $vacancy->id, 'company_id' => $vacancy->company_id ]); } $chat->messages()->create([ 'volunteer_id' => $volunteer->id, 'text' => $request->input('message') ]); return response()->json(['message' => 'You message has been sent.'], 201); } } <file_sep>/modules/Frontend/resources/js/mixins/vacancies-search.js import locationService from '~/services/location' import {isEmpty} from 'lodash' export default { data() { return { query: '', cityQuery: '', jobs: [], cities: [], } }, watch: { async query(val) { if (this.query.length > 1 && !this.jobs.includes(val)) { const {data: jobs} = await this.axios.get(`/api/vacancies/${this.query}`) if (jobs) this.jobs = jobs } }, async cityQuery(query) { if (query.length && !this.cities.includes(query)) { this.cities = (await locationService.searchLocation(query)).map(({text}) => text) } } }, methods: { submit(filters = null) { this.$refs.query.update.flush() location.href = this.action(filters) }, action(filters = null) { const resource = this.routeIncludes(['volunteers']) ? 'volunteers' : 'vacancies', params = { query: this.query.split(' ').join('-'), } if (this.query && this.cityQuery) { params.location = this.cityQuery.replace(',', '-').split(' ').join('-') } return this.route(`${resource}.search${this.cityQuery ? '.location' : ''}`, params) + (filters !== null ? (!isEmpty(filters) ? `?${filters}` : '') : location.search) } } } <file_sep>/resources/lang/en/meta.php <?php return [ 'login' => [ 'title' => 'Login', 'description' => 'Login - To continue, log in to Simboсk - We are here to make the world a better place - Simbock - Online Volunteering Service' ], 'register' => [ 'title' => 'Sign up (Registration)', 'description' => 'Registration - To continue, Sign up to Simboсk - We are here to make the world a better place - Simbock - Online Volunteering Service' ], 'blog' => [ 'index' => [ 'title' => 'All news (posts)', 'description' => 'Our newsroom - All news and materials about our works - We are here to make the world a better place - Simbock - Online Volunteering Service' ], 'category' => [ 'title' => ':name - all posts', 'description' => 'All post in :name - Let\'s work together with [Simboсk] - Volunteering job any industry, any location, any experience level - We are here to make the world a better place' ], 'show' => [ 'description' => ':name - Let\'s work together with [Simboсk] - Volunteering job any industry, any location, any experience level - We are here to make the world a better place', ] ], 'vacancies' => [ 'index' => [ 'title' => 'All actually vacations on volunteering job', 'description' => 'Actually vacations - Delivery Driver - Full stack- Vue laravel dev and other - We are here to make the world a better place - Simbock - Online Volunteering Service' ], 'show' => [ 'title' => ':name - actually vacancies', 'description' => ':name - :location - Let\'s work together with [Simboсk] - Volunteering job any industry, any location, any experience level' ] ] ]; <file_sep>/modules/Frontend/Http/Middleware/CompleteRegistration.php <?php namespace Modules\Frontend\Http\Middleware; use App\Models\User; use Illuminate\Http\Request; class CompleteRegistration { public function handle(Request $request, \Closure $next) { /* @var $user User */ $user = $request->user(); if (($user !== null) && $user->type === User::COMPANY) { $whitelist = [ 'frontend.company.info.form', 'frontend.company.info.update', 'frontend.api.cities', 'frontend.logout' ]; if ($user->company === null && !$request->routeIs(...$whitelist)) { return redirect(route('frontend.company.info.form')); } } return $next($request); } } <file_sep>/modules/Frontend/Repositories/VacancyRepository.php <?php namespace Modules\Frontend\Repositories; use App\Models\Jobs\Benefit; use App\Models\Jobs\Hour; use App\Models\Jobs\Incentive; use App\Models\Jobs\Sector; use App\Models\Jobs\Size; use App\Models\Jobs\Skill; use App\Models\Jobs\Type; use App\Models\Vacancy; use App\Services\LocationService; class VacancyRepository { public function sharedData(): void { ['sectors' => $sectors, 'types' => $types, 'hours' => $hours] = $this->shareForFilter(true); $benefits = Benefit::all('name', 'id')->map(fn(Benefit $b) => ['text' => $b->name, 'value' => $b->id]); $incentives = Incentive::all(['name', 'id'])->map(fn(Incentive $i) => ['text' => $i->name]); $skills = Skill::all(['name', 'id'])->map(fn(Skill $s) => ['text' => $s->name]); share(compact('sectors', 'types', 'hours', 'benefits', 'incentives', 'skills')); } /* @return void|array */ public function shareForFilter(bool $return = false) { $sectors = Sector::all('name', 'id')->map(fn(Sector $s) => ['text' => $s->name, 'value' => $s->id]); $types = Type::all('name', 'id')->map(fn(Type $t) => ['text' => $t->name, 'value' => $t->id]); $hours = Hour::all('name', 'id')->map(fn(Hour $h) => ['text' => $h->name, 'value' => $h->id]); if ($return) { return compact('sectors', 'types', 'hours'); } $sizes = Size::all('name', 'id')->map(fn(Size $s) => ['text' => $s->name, 'value' => $s->id]); share(compact('sectors', 'types', 'hours', 'sizes')); } public function transformForIndex(Vacancy $vacancy): Vacancy { $vacancy->append(['employment', 'date', 'location', 'is_applied', 'in_bookmarks', 'is_completed']); $vacancy->company_title = $vacancy->company_title ?? $vacancy->company->name; $vacancy->days = $vacancy->created_at->diffInDays(); $vacancy->company->append('logo'); return $vacancy; } public function transformForEdit(Vacancy $vacancy): array { $locationService = app(LocationService::class); $vacancy->load('city', 'hours', 'benefits', 'incentives', 'skills'); $city = $vacancy->city; $vacancy = $vacancy->toArray(); $vacancy['hours'] = collect($vacancy['hours'])->map(fn(array $h) => $h['id']); $vacancy['benefits'] = collect($vacancy['benefits'])->map(fn(array $b) => $b['id']); $vacancy['incentives'] = collect($vacancy['incentives'])->map(fn(array $i) => ['text' => $i['name']]); $vacancy['skills'] = collect($vacancy['skills'])->map(fn(array $s) => ['text' => $s['name']]); $vacancy['city'] = [ 'text' => $locationService->mapCity($city), 'value' => $city->id ]; return $vacancy; } } <file_sep>/modules/Admin/resources/js/app.js import Vue from 'vue' import './plugins' import './filters' import components from './components' import store from './store' const app = new Vue({ el: '#app', data() { return {} }, components, store, mounted() { } }) window.app = app store.app = app require('./helpers/lte') <file_sep>/modules/Frontend/Http/Controllers/PageController.php <?php namespace Modules\Frontend\Http\Controllers; use App\Models\Page; use App\Models\Vacancy; use App\Models\Volunteers\Volunteer; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Requests\ContactFormRequest; use Modules\Frontend\Mail\ContactForm; class PageController extends Controller { public function home() { if ($user = \Auth::user()) { return redirect(route($user->is_volunteer ? 'frontend.vacancies.search' : 'frontend.company.board')); } $page = Page::find(1); $this->seo()->setTitle($page->meta_title ?? $page->title, false); if ($description = $page->meta_description) { $this->seo()->setDescription($description); } \Route2Class::addClass('bg-linear-gradient'); $vacancies = Vacancy::count(); $resumes = Volunteer::count(); return view('frontend::pages.home', compact('vacancies', 'resumes')); } public function work(Page $page) { $vacancies = Vacancy::active() ->where('company_id', '=', 4) ->latest() ->get(['id', 'title', 'city_id', 'created_at']) ->map(function (Vacancy $vacancy) { $vacancy->append(['date', 'location']); return $vacancy; }); share(compact('vacancies')); return view('frontend::pages.work'); } public function show(Page $pageModel) { $page = $pageModel; $this->seo()->setTitle($page->meta_title ?? $page->title, false); if ($description = $page->meta_description) { $this->seo()->setDescription($description); } share([ 'title' => $page->title, 'content' => $page->body ]); $view = 'default'; if ($page->id === 2 || $page->slug === 'our-vacancies') { return $this->work($page); } \Route2Class::addClass('bg-linear-gradient'); if ($page->id === 5 || $page->slug === 'help') { $view = 'help'; } if ($page->slug === 'sitemap') { \Route2Class::addClass('page-sitemap'); $view = 'sitemap'; } if ($page->id === 0) { $view = ''; } return view("frontend::pages.$view"); } public function contactForm(ContactFormRequest $request): JsonResponse { \Mail::to(config('frontend.emails_for_contacts'))->send(new ContactForm($request->validated())); return response()->json(['message' => 'Your message has been sent.']); } } <file_sep>/modules/Frontend/resources/js/mixins/volunteerBlock.js import {mapState} from "vuex" import {ReactiveProvideMixin} from 'vue-reactive-provide' import {BModal} from 'bootstrap-vue' import Invalid from '~/components/includes/Invalid' import ModalHeader from "~/components/volunteer/account/components/ModalHeader" import ModalActions from "~/components/volunteer/account/components/ModalActions" export default { components: { BModal, Invalid, ModalHeader, ModalActions }, mixins: [ ReactiveProvideMixin({ name: 'errorsInject', include: ['errors'] }), ], data() { return { isLoading: false, formConfig: { header: { 'Content-Type': 'multipart/form-data' } } } }, computed: { ...mapState(['errors']) }, created() { this.fill() }, methods: { async update() { if (await this.$store.dispatch('volunteer/updateAbout', this.form)) this.$refs.modal.hide() }, invalid(field) { if (field in this.errors) return 'has-error' }, fill() { for (let field in this.form) { if (this.form.hasOwnProperty(field) && this.$store.state.volunteer.form.hasOwnProperty(field)) this.form[field] = this.$store.state.volunteer.form[field] } }, showModal() { this.$refs.modal.show() }, hideModal() { this.$refs.modal.hide() }, cancel() { this.$refs.modal.hide() this.fill() }, clear() { for (let field in this.form) this.form[field] = null } } } <file_sep>/database/migrations/2020_11_04_120219_create_volunteer_has_sectors_with_roles.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerHasSectorsWithRoles extends Migration { public function up() { Schema::create('volunteer_has_sectors_with_roles', function (Blueprint $table) { $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->foreignId('sector_id')->constrained('sectors')->cascadeOnDelete(); $table->foreignId('role_id')->constrained('sector_roles')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('volunteer_has_sectors_with_roles'); } } <file_sep>/modules/Admin/Http/Controllers/Jobs/RoleController.php <?php namespace Modules\Admin\Http\Controllers\Jobs; use App\Models\Jobs\Role; use App\Models\Jobs\Sector; use Modules\Admin\Http\Controllers\Controller; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Controllers\Traits\SortableController; use Modules\Admin\Http\Requests\Jobs\RoleRequest; use Modules\Admin\Repositories\Jobs\RoleRepository; class RoleController extends Controller { use SortableController; use CRUDController; protected string $modelClass = Role::class; protected string $resource = 'roles'; protected RoleRepository $repository; public function __construct() { $this->repository = app(RoleRepository::class); } public function index(Sector $sector = null) { if ($sector) { $this->seo()->setTitle("Roles of $sector->name sector"); $roles = $sector->roles()->ordered()->get(['id', 'name']); } else { $this->seo()->setTitle('Roles'); $roles = Role::ordered()->get(['id', 'name']); } share(compact('roles')); return view('admin::crud.index', ['resource' => 'roles']); } public function create() { $this->seo()->setTitle('Create a new role'); $this->repository->shareForCRUD(); return $this->form(); } public function store(RoleRequest $request) { $this->seo()->setTitle('Edit a role'); $role = Role::create($request->only('name')); $request->syncSectors($role); return response()->json([ 'status' => 'Role has been created', 'title' => $this->seo()->getTitle(), 'role' => $role ], 201); } public function edit(Role $role) { $this->seo()->setTitle('Edit a role'); $this->repository->shareForCRUD(); $role->load('sectors'); $role->sectors->transform(fn(Sector $s) => $s->id); share(compact('role')); return $this->form(); } public function update(roleRequest $request, Role $role) { $role->update($request->validated()); $request->syncSectors($role); return response()->json(['status' => 'Role has been updated', 'role' => $role]); } public function destroy(Role $role) { $role->delete(); return response()->json(['status' => 'Role has been deleted']); } } <file_sep>/modules/Frontend/Http/Controllers/SitemapController.php <?php namespace Modules\Frontend\Http\Controllers; use App\Http\Controllers\Controller; use App\Models\Blog\Article; use App\Models\Blog\Category; use App\Models\Page; use App\Models\Vacancy; use Spatie\Sitemap\Sitemap; use Spatie\Sitemap\Tags\Url; class SitemapController extends Controller { public function __invoke(): Sitemap { $sitemap = new Sitemap; $links = collect([url('')]); Page::where('slug', '!=', 'home')->get('slug')->each(fn(Page $p) => $links[] = url($p->slug)); $links[] = route('frontend.articles.index'); Category::all('slug')->each(fn(Category $c) => $links[] = route('frontend.articles.category', $c->slug)); Article::all(['category_id', 'slug'])->each(fn(Article $a) => $links[] = $a->link); $links[] = route('frontend.login'); $links[] = route('frontend.register'); $links[] = route('frontend.vacancies.search'); Vacancy::active()->get('id')->each(fn(Vacancy $v) => $links[] = route('frontend.vacancies.show', $v->id)); $links->each(fn(string $link) => $sitemap->add(new Url($link))); return $sitemap; } } <file_sep>/app/Models/Volunteers/Certificate.php <?php namespace App\Models\Volunteers; use Illuminate\Database\Eloquent\Model; class Certificate extends Model { const CREATED_AT = null; const UPDATED_AT = null; protected $table = 'volunteer_certificates'; protected $fillable = ['title', 'issuing_authority', 'year', 'description']; } <file_sep>/app/Models/Traits/IsTag.php <?php namespace App\Models\Traits; use Illuminate\Support\Collection; trait IsTag { /* @return self[]|Collection */ public static function findOrCreate(array $values): Collection { return collect($values)->map(function ($value) { return static::findOrCreateFromString($value); }); } protected static function findOrCreateFromString(string $name) { $tag = static::findFromString($name); if (!$tag) { $tag = static::create(['name' => $name]); } return $tag; } protected static function findFromString(string $name) { return static::query() ->where('name', $name) ->first(); } } <file_sep>/modules/Admin/Http/Controllers/DashboardController.php <?php namespace Modules\Admin\Http\Controllers; use App\Models\Blog\Article; use App\Models\User; class DashboardController extends Controller { public function index() { $this->seo()->setTitle('Dashboard'); $counts = []; $counts['articles'] = Article::count(); $counts['users'] = User::count(); return view('admin::dashboard', $counts); } } <file_sep>/database/migrations/2020_09_07_155706_create_sector_roles_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSectorRolesTable extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_07_155706_create_sector_roles_table.php */ public function up() { Schema::create('sector_roles', function (Blueprint $table) { $table->id(); $table->string('name'); $table->unsignedBigInteger('order')->nullable(); }); } public function down() { Schema::dropIfExists('sector_roles'); } } <file_sep>/app/Services/LocationService.php <?php namespace App\Services; use App\Models\Map\US\City; use App\Models\Map\US\State; class LocationService { protected array $cityFields = ['id', 'name', 'county', 'state_id', 'zips']; protected int $resultsLimit = 8; public function search(string $query): array { $isZip = preg_match('#[0-9]{5}#', $query); if ($isZip) { $cities = City::where('zips', 'LIKE', "% $query %") ->orWhere('zips', 'LIKE', "$query %") ->orWhere('zips', 'LIKE', "$query%") ->orWhere('zips', 'LIKE', "% $query%") ->orWhere('zips', 'LIKE', "% $query") ->orWhere('zips', $query) ->orderByDesc('population') ->limit($this->resultsLimit) ->get($this->cityFields); return $cities->map(function (City $c) use ($query) { $zips = array_filter(explode(' ', $c->zips), fn($zip) => str_contains($zip, $query)); $zip = array_shift($zips); $mapped = $this->mapCity($c); //$mapped = "$zip, $mapped"; //return $mapped; return ['text' => $mapped, 'value' => $c->id]; })->toArray(); } else { if (strlen($query) === 2) { $state = State::find($query); if ($state) { /* @var $cities City */ $cities = $state->cities(); $cities = $cities->biggest() ->limit($this->resultsLimit - 1) ->get($this->cityFields) ->map(fn(City $c) => ['text' => $this->mapCity($c), 'id' => $c->id]); return $cities->toArray(); //return ["$state->name state", ...$cities]; } } else if (strlen($query) > 2) { return $this->searchCity($query); } } return []; } public function parseLocation(string $query): array { $cityName = ''; $countyName = ''; $state = null; $locations = []; $parts = explode('--', $query); if (count($parts) > 1) { [$cityName, $countyState] = $parts; $cityName = implode(' ', explode('-', $cityName)); $words = collect(explode('-', $countyState)); $countyName = $words->reverse()->splice(1, 1)->first(); } else { $words = collect(explode('-', $parts[0])); $cityName = $words->reverse() ->slice(strlen($words->last()) === 2 ? 1 : 0) ->reverse() ->join(' '); } if (strlen($words->last()) === 2) { $state = State::find($words->last()); if ($county = \DB::table('us_cities') ->select('county') ->where('state_id', '=', $state->id) ->where('county', '=', $countyName) ->distinct() ->exists() ) { $locations = City::where('state_id', '=', $state->id) ->where('county', '=', $countyName) ->where('name', '=', $cityName) ->pluck('id'); } else { $locations = City::where('state_id', '=', $state->id) ->where('name', '=', $cityName) ->pluck('id'); } } else { $locations = collect($this->searchCity($words->join(' '))) ->map(fn($c) => $c['value']); } return $locations->toArray(); } public function searchCity(string $query): array { return City::where('name', $query) ->orWhere('name', 'like', "$query%") ->biggest() ->limit($this->resultsLimit) ->get($this->cityFields) ->map(fn(City $c) => ['text' => $this->mapCity($c), 'value' => $c->id, 'zips' => $c->zips]) ->toArray(); } public function mapCity(City $c): string { $name = $c->name; if ( ($c->name !== $c->county) && City::where('name', '=', $c->name) ->where('state_id', '=', $c->state_id) ->count() > 1 ) { $name .= ", $c->county"; } return "$name $c->state_id"; } } <file_sep>/modules/Frontend/Http/Controllers/Auth/ResetPasswordController.php <?php namespace Modules\Frontend\Http\Controllers\Auth; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Modules\Frontend\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\ResetsPasswords; class ResetPasswordController extends Controller { use ResetsPasswords; protected $redirectTo = RouteServiceProvider::HOME; public function showResetForm(Request $request, $token = null) { $this->seo()->setTitle('Password Reset'); \Route2Class::addClass('bg-decorative'); share([ 'email' => $request->email, 'token' => $token ]); return view('frontend::auth.passwords.reset'); } protected function sendResetResponse(Request $request, $response) { return response()->json([ 'message' => trans($response), 'redirect' => route('frontend.home') ]); } protected function sendResetFailedResponse(Request $request, $response) { throw ValidationException::withMessages(['email' => [trans($response)]]); } } <file_sep>/app/Helpers/Accessors/ModelsMultiselect.php <?php namespace App\Helpers\Accessors; class ModelsMultiselect { public function handle($value): array { return array_map(fn($id) => intval($id), explode(',', $value)); } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/AccountRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer; use App\Models\Jobs\Skill; use App\Models\Volunteers\Volunteer; use Illuminate\Foundation\Http\FormRequest; class AccountRequest extends FormRequest { public function rules(): array { return [ 'is_private' => ['nullable', 'boolean'], 'name' => ['nullable', 'string255'], 'headline' => ['nullable', 'string255'], 'city_id' => ['nullable', 'exists:us_cities,id'], 'zip' => ['nullable', 'string', 'max:5'], 'is_relocating' => ['nullable', 'boolean'], 'is_working_remotely' => ['nullable', 'boolean'], 'email' => ['nullable', 'email', 'string255'], 'phone' => ['nullable', 'string255', 'regex:/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/'/*'phone:US'*/], 'social' => ['nullable', 'array'], 'social.website' => ['nullable', 'url'], 'social.linkedin' => ['nullable', 'url'], 'social.twitter' => ['nullable', 'url'], 'social.facebook' => ['nullable', 'url'], 'social.instagram' => ['nullable', 'url'], 'social.youtube' => ['nullable', 'url'], 'social.reddit' => ['nullable', 'url'], 'social.pinterest' => ['nullable', 'url'], 'social.quora' => ['nullable', 'url'], 'executive_summary' => ['nullable', 'string', 'max:512'], 'objective' => ['nullable', 'string', 'max:512'], 'achievements' => ['nullable', 'string', 'max:512'], 'associations' => ['nullable', 'string', 'max:512'], 'skills' => ['nullable', 'array'], 'skills.*' => ['string'], 'years_of_experience_id' => ['nullable', 'exists:volunteer_years_of_experience,id'], 'level_of_education_id' => ['nullable', 'exists:volunteer_levels_of_education,id'], 'veteran_status_id' => ['nullable', 'exists:volunteer_veteran_statuses,id'], 'cover_letter' => ['nullable', 'string', 'max:512'], 'personal_statement' => ['nullable', 'string', 'max:512'], 'has_driver_license' => ['nullable', 'boolean'], 'has_car' => ['nullable', 'boolean'], ]; } public function syncSkills(Volunteer $volunteer): array { if ($this->has('skills')) { $skills = $this->skills; $skills = Skill::findOrCreate($skills); return $volunteer->skills()->sync($skills->pluck('id')->toArray()); } return []; } public function authorize(): bool { return true; } } <file_sep>/modules/Admin/Http/Controllers/Traits/SortableController.php <?php namespace Modules\Admin\Http\Controllers\Traits; use App\Models\Traits\SortableTrait; use Modules\Admin\Http\Requests\SortRequest; /** * @property SortableTrait|string $modelClass */ trait SortableController { public function sort(SortRequest $request) { $order = $request->input('order'); \DB::transaction(fn() => $this->modelClass::setNewOrder($order)); return response()->json(['status' => 'Sectors has been sorted']); } } <file_sep>/modules/Frontend/Events/NewMessage.php <?php namespace Modules\Frontend\Events; use App\Models\Chats\Chat; use App\Models\Chats\Message; use App\Models\Client; use App\Models\User; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class NewMessage implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; protected Message $message; protected Chat $chat; protected Client $sender; public function __construct(Message $message, Chat $chat, Client $sender) { $this->message = $message; $this->chat = $chat; $this->sender = $sender; } public function broadcastOn(): PrivateChannel { $channel = $this->message->volunteer_id ? User::COMPANY : User::VOLUNTEER; $id = $channel === User::COMPANY ? $this->chat->company_id : $this->chat->volunteer_id; return new PrivateChannel("chat.$channel.$id"); } public function broadcastWith(): array { return [ 'message' => $this->message, 'sender' => $this->sender->append('name') ]; } public function broadcastAs(): string { return 'chat.message.created'; } } <file_sep>/app/Providers/AppServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { public function register(): void { // } public function boot(): void { \Validator::extend('string255', function ($attribute, $value, $parameters, $validator) { return is_string($value) && mb_strlen($value) <= 255; }); } } <file_sep>/modules/Admin/Http/Controllers/SurveyController.php <?php namespace Modules\Admin\Http\Controllers; use App\Models\SearchQuery; use App\Models\Volunteers\Surveys\Survey; use Illuminate\Database\Eloquent\Builder; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Requests\IndexRequest; class SurveyController extends Controller { use CRUDController; protected string $resource = 'surveys'; public function index(IndexRequest $request) { $this->seo()->setTitle('Surveys'); $surveys = Survey::with(['volunteer', 'source']) ->when($request->has('sortBy'), function (Builder $users) use ($request) { $users->orderBy($request->get('sortBy'), $request->get('sortDesc') ? 'desc' : 'asc'); }) ->latest() ->paginate(10); $surveys->transform(function (Survey $survey) { $survey->volunteer->append('name'); return $survey; }); if (request()->expectsJson()) { return $surveys; } share(compact('surveys')); return $this->listing(); } } <file_sep>/modules/Frontend/Providers/RouteServiceProvider.php <?php namespace Modules\Frontend\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Modules\Frontend\Http\Middleware\CompleteRegistration; use Modules\Frontend\Http\Middleware\ServerPush; use Modules\Frontend\Http\Middleware\SharedData; class RouteServiceProvider extends ServiceProvider { protected $moduleNamespace = 'Modules\Frontend\Http\Controllers'; public function boot() { parent::boot(); } public function map() { $this->mapApiRoutes(); $this->mapWebRoutes(); } protected function mapWebRoutes() { Route::domain(env('APP_DOMAIN')) ->middleware(['web', CompleteRegistration::class, SharedData::class, ServerPush::class]) ->namespace($this->moduleNamespace) ->as('frontend.') ->group(module_path('Frontend', 'routes/web.php')); } protected function mapApiRoutes() { Route::prefix('api') ->middleware(['web', 'api']) ->namespace($this->moduleNamespace . '\Api') ->group(module_path('Frontend', 'routes/api.php')); } } <file_sep>/database/migrations/2020_09_20_121955_create_vacancy_has_benefits_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVacancyHasBenefitsTable extends Migration { public function up() { Schema::create('vacancy_has_benefits', function (Blueprint $table) { $table->foreignId('vacancy_id')->constrained('vacancies')->cascadeOnDelete(); $table->foreignId('benefit_id')->constrained('job_benefits')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('vacancy_has_benefits'); } } <file_sep>/app/Models/Vacancy.php <?php namespace App\Models; use App\Models\Jobs\Benefit; use App\Models\Jobs\Hour; use App\Models\Jobs\Incentive; use App\Models\Jobs\Sector; use App\Models\Jobs\Skill; use App\Models\Jobs\Type; use App\Models\Map\US\City; use App\Models\Traits\SearchTrait; use App\Models\Volunteers\Volunteer; use Auth; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\SoftDeletes; class Vacancy extends Model { use SoftDeletes; use SearchTrait; public const DRAFT = 'DRAFT'; public const ACTIVE = 'ACTIVE'; public const CLOSED = 'CLOSED'; public static $statuses = [ self::DRAFT => 'Draft', self::ACTIVE => 'Published', self::CLOSED => 'Closed' ]; protected $fillable = [ 'title', 'sector_id', 'city_id', 'type_id', 'description', 'is_relocation', 'is_remote_work', 'address', 'company_title', 'company_description', 'status' ]; protected $casts = [ 'is_applied' => 'bool', 'is_bookmarked' => 'bool' ]; protected array $search = ['title']; // FUNCTIONS public static function boot() { foreach (['creating', 'updating'] as $event) static::$event(fn(self $a) => $a->generateExcerpt()); parent::boot(); } protected function generateExcerpt(): void { $excerpt = mb_substr($this->description, 0, 190); $excerpt = preg_replace('/\W\w+\s*(\W*)$/', '$1', $excerpt); $this->excerpt = $excerpt; } // RELATIONS public function company() { return $this->belongsTo(Company::class); } public function applies(): BelongsToMany { return $this->belongsToMany(Volunteer::class, 'volunteer_has_applies')->distinct(); } public function sector() { return $this->belongsTo(Sector::class); } public function city() { return $this->belongsTo(City::class); } public function type() { return $this->belongsTo(Type::class); } public function hours() { return $this->belongsToMany(Hour::class, 'vacancy_has_hours'); } public function benefits() { return $this->belongsToMany(Benefit::class, 'vacancy_has_benefits'); } public function incentives() { return $this->belongsToMany(Incentive::class, 'vacancy_has_incentives'); } public function skills() { return $this->belongsToMany(Skill::class, 'vacancy_has_skills'); } // SCOPES public function scopeActive(Builder $query) { return $query->where('status', self::ACTIVE); } public function scopeDraft(Builder $query) { return $query->where('status', self::DRAFT); } public function scopeClosed(Builder $query) { return $query->where('status', self::CLOSED); } // ACCESSORS public function getIsAppliedAttribute(): bool { if (($user = Auth::getUser()) && $volunteer = $user->volunteer) { return $user->volunteer->applies()->where('vacancy_id', $this->id)->exists(); } return false; } public function getInBookmarksAttribute(): bool { if (($user = Auth::getUser()) && $volunteer = $user->volunteer) { return $user->volunteer->bookmarks()->where('vacancy_id', $this->id)->exists(); } return false; } public function getEmploymentAttribute(): string { return $this->type->name . ', ' . $this->hours->implode('name', ', '); } public function getDateAttribute(): string { return $this->created_at->diffForHumans(); } //todo refactor to trait HasLocation public function getLocationAttribute(): string { $c = $this->city; $name = $c->name; if ($c->name !== $c->county) $name .= ", $c->county"; return "$name $c->state_id"; } public function getIsCompletedAttribute(): bool { return (bool)$this->address; } } <file_sep>/modules/Admin/Http/Controllers/Jobs/SectorController.php <?php namespace Modules\Admin\Http\Controllers\Jobs; use App\Models\Jobs\Sector; use Modules\Admin\Http\Controllers\Controller; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Controllers\Traits\SortableController; use Modules\Admin\Http\Requests\Jobs\SectorRequest; class SectorController extends Controller { use SortableController; use CRUDController; protected string $modelClass = Sector::class; protected string $resource = 'sectors'; public function index() { $this->seo()->setTitle('Sectors'); $sectors = Sector::ordered()->withCount('roles')->get(['id', 'name']); share(compact('sectors')); return $this->listing(); } public function create() { $this->seo()->setTitle('Create a new sector'); return $this->form(); } public function store(SectorRequest $request) { $this->seo()->setTitle('Edit a sector'); $sector = new Sector($request->validated()); $sector->save(); return response()->json([ 'status' => 'Sector has been created', 'title' => $this->seo()->getTitle(), 'sector' => $sector ], 201); } public function edit(Sector $sector) { $this->seo()->setTitle('Edit a sector'); share(compact('sector')); return $this->form(); } public function update(SectorRequest $request, Sector $sector) { $sector->update($request->validated()); return response()->json(['status' => 'Sector has been updated', 'sector' => $sector]); } public function destroy(Sector $sector) { $sector->delete(); return response()->json(['status' => 'Sector has been deleted']); } } <file_sep>/database/migrations/2020_09_23_140841_create_volunteer_work_experiences.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerWorkExperiences extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_23_140841_create_volunteer_work_experiences.php */ public function up() { Schema::create('volunteer_work_experiences', function (Blueprint $table) { $table->id(); $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->string('title'); $table->string('company'); $table->date('start'); $table->date('end')->nullable(); $table->string('description')->nullable(); }); } public function down() { Schema::dropIfExists('volunteer_work_experiences'); } } <file_sep>/database/seeds/VolunteerMoreInfoSeeder.php <?php use App\Models\Volunteers\MoreInfo\Degree; use App\Models\Volunteers\MoreInfo\VeteranStatus; use App\Models\Volunteers\MoreInfo\YearOfExperience; use Illuminate\Database\Seeder; class VolunteerMoreInfoSeeder extends Seeder { public function run(): void { $years = [ 'Intern', 'Entry Level (0-2 years)', 'Mid Level (3-6 years)', 'Senior Level (7+ years)', 'Director', 'Executive' ]; $degrees = ['High School Diploma/GED', 'Associates Degree', 'Bachelors Degree', 'Masters or Ph.D']; $veterans = ['I am a Veteran', 'I do not wish to specify at this time']; foreach ($years as $name) YearOfExperience::create(compact('name')); foreach ($degrees as $name) Degree::create(compact('name')); foreach ($veterans as $name) VeteranStatus::create(compact('name')); } } <file_sep>/modules/Frontend/Http/Middleware/VolunteerViewed.php <?php namespace Modules\Frontend\Http\Middleware; use Auth; use Closure; use Illuminate\Http\Request; class VolunteerViewed { public function handle($request, Closure $next) { return $next($request); } public function terminate(Request $request, $response): void { $company = Auth::user()->company; if ($company->canSeeVolunteer()) { $company->update(['resume_views' => $company->resume_views + 1]); } } } <file_sep>/database/migrations/2020_09_07_165656_create_sector_has_roles_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSectorHasRolesTable extends Migration { public function up() { Schema::create('sector_has_roles', function (Blueprint $table) { $table->foreignId('sector_id')->constrained('sectors')->cascadeOnDelete(); $table->foreignId('role_id')->constrained('sector_roles')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('sector_has_roles'); } } <file_sep>/app/Models/Jobs/Sector.php <?php namespace App\Models\Jobs; use App\Models\Traits\SortableTrait; use Illuminate\Database\Eloquent\Model; use Spatie\EloquentSortable\Sortable; class Sector extends Model implements Sortable { use SortableTrait; const CREATED_AT = null; const UPDATED_AT = null; protected $fillable = ['name']; protected $table = 'sectors'; // RELATIONS public function roles() { return $this->belongsToMany(Role::class, 'sector_has_roles', 'sector_id', 'role_id'); } } <file_sep>/modules/Admin/Http/Controllers/Users/CompanyController.php <?php namespace Modules\Admin\Http\Controllers\Users; use App\Models\Company; use Illuminate\Database\Eloquent\Builder; use Modules\Admin\Http\Controllers\Controller; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Requests\IndexRequest; class CompanyController extends Controller { use CRUDController; protected string $resource = 'companies'; public function index(IndexRequest $request) { $this->seo()->setTitle('Companies'); $companies = Company::select([ 'id', 'user_id', 'name', 'city_id', 'stripe_id', 'card_brand', 'card_last_four' ]) ->when($request->get('searchQuery'), fn($q) => $q->search($request->get('searchQuery'))) ->when($request->has('sortBy'), function (Builder $users) use ($request) { $users->orderBy($request->get('sortBy'), $request->get('sortDesc') ? 'desc' : 'asc'); }) ->with(['user', 'city']) ->withCount('vacancies') ->paginate(10); $companies->transform(function (Company $company) { $company->plan = $company->subscribed() ? $company->getPlan() : null; return $company; }); if (request()->expectsJson()) { return $companies; } share(compact('companies')); return view('admin::companies.index'); } } <file_sep>/database/seeds/UsCitiesSeeder.php <?php use App\Models\Map\US\City; use Illuminate\Database\Seeder; class UsCitiesSeeder extends Seeder { public function run() { $cities = []; $file_handle = fopen(resource_path('db/us_cities/uscities.csv'), 'r'); while (!feof($file_handle)) { $cities[] = fgetcsv($file_handle, 0, ','); } fclose($file_handle); $columns = array_shift($cities); array_pop($cities); $cities = array_map(function ($city) use ($columns) { $mapped = []; foreach ($city as $key => $value) { $mapped[$columns[$key]] = $value; } return $mapped; }, $cities); \DB::transaction(function () use ($cities) { $this->command->getOutput()->progressStart(count($cities)); foreach ($cities as $data) { City::insert([ 'id' => $data['id'], 'state_id' => $data['state_id'], 'name' => $data['city'], 'county' => $data['county_name'], 'lat' => $data['lat'], 'lng' => $data['lng'], 'zips' => $data['zips'], 'population' => $data['population'] ]); $this->command->getOutput()->progressAdvance(); } $this->command->getOutput()->progressFinish(); }); } } <file_sep>/modules/Frontend/resources/js/app.js import Vue from 'vue' import './plugins' import './filters' import components from './components' import pages from './pages' import store from './store' const app = new Vue({ components: { ...components, ...pages }, el: '#app', store, data() { return { isLargeGrid: false, isMobileGrid: false, isOpenMessage: false, //изначальный скролл = 0 scroll: 0 } }, created() { const user = this.shared('user') if (user) this.$store.commit('setUser', user) }, beforeMount() { window.addEventListener('resize', this.isCheckGrid, false) window.addEventListener('load', this.isCheckGrid, false) }, async mounted() { if (shared('user')) { const {default: VueEcho} = await import('vue-echo') window.Pusher = await require('pusher-js') VueEcho.install(Vue, { broadcaster: 'pusher', key: 'Simbock', wsHost: window.location.hostname, wsPort: 6001, wssPort: 6001, forceTLS: process.env.MIX_APP_ENV !== 'local' }) const {ToastPlugin} = await import('bootstrap-vue') ToastPlugin.install(Vue) setTimeout(() => { this.$bus.emit('broadcasting-ready') }, 1000) const {default: VueSimpleAlert} = await import('vue-simple-alert') VueSimpleAlert.install(Vue) } setTimeout(() => { const adsbygoogle = document.createElement('script') adsbygoogle.setAttribute('data-ad-client', 'ca-pub-2150066652665124') adsbygoogle.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js' document.head.append(adsbygoogle) }, 5000) let links = document.querySelectorAll('.navigate-by-page-link') //якоря для страниц (Policy) links.forEach((link) => { link.addEventListener('click', (e) => { e.preventDefault() let href = link.getAttribute('href').replace('#', '') console.log(href) let scrollTo = document.getElementById(href).getBoundingClientRect().top - 100 window.scrollTo({top: scrollTo, behavior: 'smooth'}) }) }) this.socialPopups() }, methods: { //проверка для размеры для того чтоб скрывать коегде html блоки isCheckGrid() { this.isLargeGrid = window.innerWidth < 1200 this.isMobileGrid = window.innerWidth < 768 }, socialPopups() { const popupSize = { width: 780, height: 550 } const links = document.querySelectorAll('.article-share-item') links.forEach((link) => { link.addEventListener('click', (e) => { const verticalPos = Math.floor((innerWidth - popupSize.width) / 2), horisontalPos = Math.floor((innerHeight - popupSize.height) / 2) const popup = window.open(link.getAttribute('href'), 'social', 'width=' + popupSize.width + ',height=' + popupSize.height + ',left=' + verticalPos + ',top=' + horisontalPos + ',location=0,menubar=0,toolbar=0,status=0,scrollbars=1,resizable=1') if (popup) { popup.focus() e.preventDefault() } }) }) } }, }) store.app = app <file_sep>/database/seeds/Jobs/IncentivesSeeder.php <?php use App\Models\Jobs\Incentive; use Illuminate\Database\Seeder; class IncentivesSeeder extends Seeder { public function run() { $incentives = ['Best', 'work', 'ever']; foreach ($incentives as $name) { Incentive::create(compact('name')); } } } <file_sep>/modules/Frontend/Http/Controllers/Auth/ForgotPasswordController.php <?php namespace Modules\Frontend\Http\Controllers\Auth; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Modules\Frontend\Http\Controllers\Controller; use Illuminate\Foundation\Auth\SendsPasswordResetEmails; class ForgotPasswordController extends Controller { use SendsPasswordResetEmails; public function showLinkRequestForm() { $this->seo()->setTitle('Password Reset'); \Route2Class::addClass('bg-decorative'); return view('frontend::auth.email'); } protected function sendResetLinkResponse(Request $request, $response) { return response()->json(['message' => trans($response)]); } protected function sendResetLinkFailedResponse(Request $request, $response) { throw ValidationException::withMessages([ 'email' => [trans($response)], ]); } } <file_sep>/database/seeds/SurveySourcesSeeder.php <?php use App\Models\Volunteers\Surveys\Source; use Illuminate\Database\Seeder; class SurveySourcesSeeder extends Seeder { public function run(): void { $sources = [ 'Simbok', 'Recruiting or staffing firm', 'Another job site', 'Through someone I know', 'Company site', 'Specify' ]; foreach ($sources as $name) { Source::create(compact('name')); } } } <file_sep>/modules/Admin/resources/js/plugins/ls.js import Vue from 'vue' import Storage from 'vue-ls' const options = { namespace: 'redmedial_admin___', name: 'ls', storage: 'local', }; Vue.use(Storage, options) <file_sep>/database/seeds/ArticleCategoriesSeeder.php <?php use App\Models\Blog\Category; use Illuminate\Database\Seeder; class ArticleCategoriesSeeder extends Seeder { public function run() { $categories = ['Volunteer Job', 'Companies Hiring Volunteer', 'Advice', 'Sports Volunteer', 'Simbok Updates']; foreach ($categories as $category) Category::create(['name' => $category]); } } <file_sep>/modules/Admin/Http/Controllers/Blog/CategoryController.php <?php namespace Modules\Admin\Http\Controllers\Blog; use Modules\Admin\Http\Requests\Blog\CategoryRequest; use App\Models\Blog\Category; use Modules\Admin\Http\Controllers\Controller; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Controllers\Traits\SortableController; class CategoryController extends Controller { use SortableController; use CRUDController; protected $model = Category::class; protected string $modelClass = Category::class; protected string $resource = 'article-categories'; public function index() { $this->seo()->setTitle('Blog categories'); $categories = Category::ordered()->withCount('articles')->get(); share(compact('categories')); return $this->listing(); } public function create() { $this->seo()->setTitle('Create a new category'); return $this->form(); } public function store(CategoryRequest $request) { $this->seo()->setTitle('Edit a category'); $category = Category::create($request->validated()); return response()->json([ 'status' => 'Category has been created', 'title' => $this->seo()->getTitle(), 'category' => $category ], 201); } public function edit(Category $category) { $this->seo()->setTitle('Edit a category'); share(compact('category')); return $this->form(); } public function update(CategoryRequest $request, Category $category) { $category->update($request->validated()); return response()->json(['status' => 'Category has been updated', 'category' => $category]); } public function destroy(Category $category) { $category->delete(); return response()->json(['status' => 'Category has been deleted']); } } <file_sep>/routes/channels.php <?php use App\Models\User; use Illuminate\Support\Facades\Broadcast; Broadcast::channel('chat.{type}.{id}', function (User $user, string $type, int $id) { return $user->type === $type && $user->getClient()->id === $id; }); <file_sep>/modules/Frontend/Http/Controllers/Api/LocationController.php <?php namespace Modules\Frontend\Http\Controllers\Api; use App\Services\LocationService; use Illuminate\Contracts\Support\Renderable; use Illuminate\Http\Request; use Modules\Frontend\Http\Controllers\Controller; class LocationController extends Controller { protected LocationService $service; public function __construct() { $this->service = app(LocationService::class); } public function all(string $query) { return $this->service->search($query); } public function cities(string $query) { return $this->service->searchCity($query); } } <file_sep>/database/seeds/Jobs/TypesSeeder.php <?php use App\Models\Jobs\Type; use Illuminate\Database\Seeder; class TypesSeeder extends Seeder { public function run() { $types = [ 'Permanent', 'Temporary', 'Contract', 'Weekend volunteering Jobs', 'Graduate Jobs (Select if you are a recent graduate)', 'No experience volunteering Jobs', 'Evening volunteering Jobs', 'Sport volunteering']; foreach ($types as $name) Type::create(compact('name')); } } <file_sep>/modules/Admin/Repositories/UserRepository.php <?php namespace Modules\Admin\Repositories; use App\Models\User; use Spatie\Permission\Models\Role; class UserRepository { public function getRoles() { return Role::all()->pluck('name', 'id'); } public function shareForCRUD() { $types = User::$types; $roles = collect($this->getRoles()) ->map(fn($val, $key) => ['value' => $key, 'text' => ucfirst($val)])->values(); share(compact('types', 'roles')); } } <file_sep>/modules/Frontend/Http/Middleware/VacancyOwner.php <?php namespace Modules\Frontend\Http\Middleware; use App\Models\Vacancy; use Illuminate\Http\Request; class VacancyOwner { public function handle(Request $request, \Closure $next) { /* @var $vacancy Vacancy */ $vacancy = $request->vacancy; if ($vacancy->company_id !== $request->user()->company->id) abort(403); return $next($request); } } <file_sep>/modules/Frontend/Http/Requests/Company/InfoRequest.php <?php namespace Modules\Frontend\Http\Requests\Company; use Illuminate\Foundation\Http\FormRequest; class InfoRequest extends FormRequest { public function rules(): array { return [ 'name' => ['required', 'string255'], 'user_name' => ['required', 'string255'], 'title' => ['nullable', 'string255'], 'sector_id' => ['required', 'exists:sectors,id'], 'description' => ['nullable', 'string'], 'size_id' => ['required', 'exists:job_company_sizes,id'], 'address' => ['required', 'string255'], 'address_2' => ['nullable', 'string255'], 'city_id' => ['required', 'exists:us_cities,id'], 'zip' => ['required', 'string', 'max:5'], 'phone' => ['required', 'phone:US'], 'email' => ['nullable', 'email', 'string255'], 'social' => ['nullable', 'array'], 'social.website' => ['nullable', 'url'], 'social.linkedin' => ['nullable', 'url'], 'social.twitter' => ['nullable', 'url'], 'social.facebook' => ['nullable', 'url'], 'social.instagram' => ['nullable', 'url'], 'social.youtube' => ['nullable', 'url'], 'social.reddit' => ['nullable', 'url'], 'social.pinterest' => ['nullable', 'url'], 'social.quora' => ['nullable', 'url'] ]; } public function authorize(): bool { return true; } } <file_sep>/modules/Admin/resources/js/mixins/form.js import Editor from "@/components/includes/forms/Editor" import Invalid from "@/components/includes/forms/Invalid" import CardFooter from "@/components/includes/forms/CardFooter" import vSelect from 'vue-select' import RedCropper from "@/components/includes/forms/RedCropper" import {errors} from "@/helpers/helpers" import {ReactiveProvideMixin} from 'vue-reactive-provide' import jsonToForm from 'json-form-data' export default { components: { Editor, Invalid, CardFooter, vSelect, RedCropper, }, mixins: [ ReactiveProvideMixin({ name: 'errorsInject', include: ['errors'] }), ReactiveProvideMixin({ name: 'footerInject', include: ['resource', 'isEdit', 'isLoading'] }) ], directives: { valid(el, {modifiers}, {context}) { if (Object.keys(modifiers)[0] in context.errors) { el.classList.remove('is-valid') el.classList.add('is-invalid') } else { el.classList.remove('is-invalid') if (context.wasValidated) { el.classList.add('is-valid') } else if (el.classList.contains('is-valid')) { el.classList.remove('is-valid') } } } }, data() { return { id: null, isEdit: false, files: [], errors: {}, isLoading: false, wasValidated: false, formConfig: { header: { 'Content-Type': 'multipart/form-data' } } } }, provide() { return { resource: this.resource, isEdit: this.isEdit, } }, methods: { setupEdit(model) { if (!this.isEdit) this.isEdit = true this.id = model.id for (let field in this.form) { if (model[field] !== undefined && model[field] !== null) this.form[field] = model[field] } }, async send(url, form) { this.isLoading = true try { const {status, data} = await this.axios.post( url, form, form instanceof FormData ? this.formConfig : null ) this.wasValidated = false this.errors = {} return {status, data} } catch ({response}) { this.wasValidated = true this.$bus.emit('alert', {variant: 'warning', text: response.data.message}) this.errors = errors(response) } finally { this.isLoading = false } }, jtf(json, options = null) { const form = jsonToForm(json, options) if (this.isEdit) form.append('_method', 'PATCH') return form }, async easySubmit() { let form = this.form try { if (this.isEdit) { form._method = 'PATCH' const {status, data} = await this.send(this.route(`admin.${this.resource}.update`, this.id), form) if (status === 200) { this.setupEdit(data[this.singular]) this.$bus.emit('alert', {text: data.status}) } } else { const {status, data} = await this.send(this.route(`admin.${this.resource}.store`), form) if (status === 201) { const model = data[this.singular] this.setupEdit(model) document.title = data.title history.pushState( null, data.title, this.route(`admin.${this.resource}.edit`, model.id) ) this.$bus.emit('alert', {text: data.status}) } } } catch (e) { console.log(e) } } } } <file_sep>/README.md <p align="center"> <img src="http://simbock.com/dist/img/logo.svg" width="600"> </p> Let's work together with *Simboсk* - Volunteering job any industry, any location, any experience level - We are here to make the world a better place ---------- ## Installation Please check the official laravel installation guide for server requirements before you start. [Official Documentation](https://laravel.com/docs/master) - Clone the repository `git clone <EMAIL>:Sheshlyuk/simbok.git` - Switch to the repo folder - Install all the dependencies using composer and npm - Copy the example env file and make the required configuration changes in the .env file - Generate a new application key - Run the database migrations (**Set the database connection in .env before migrating**) - Run `npm run prod` - Start the local development server - Run the database seeder and you're done `php artisan db:seed` # Code overview ## Main dependencies ### PHP Name | version --- | --- | laravel/framework | ^7.24 nwidart/laravel-modules | ^7.1 coderello/laravel-shared-data | ^2.0 beyondcode/laravel-websockets | ^1.9 | ### JS Name | version --- | --- | bootstrap-vue | ^2.2.2 vue | ^2.5.17 vue-stripe-checkout | ^3.5.14-beta.0 ## Environment variables - `.env` - Environment variables can be set in this file ***Note*** : You can quickly set the database information and other variables in this file and have the application fully working. <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/AccountController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use Auth; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Controllers\Controller; use Modules\Frontend\Http\Requests\Volunteer\AccountRequest; use Modules\Frontend\Repositories\VolunteerRepository; class AccountController extends Controller { use HasVolunteer; protected VolunteerRepository $repository; public function __construct() { $this->repository = app(VolunteerRepository::class); } public function page() { $this->seo()->setTitle('Your volunteering account'); $volunteer = $this->volunteer(); $volunteer = $this->repository->setupRelations($volunteer); $volunteer = $this->repository->setupAppends($volunteer); $this->repository->shareVolunteer($volunteer); $this->repository->shareForView(); $this->repository->shareForEdit(); return view('frontend::volunteer.account'); } public function update(AccountRequest $request): JsonResponse { $user = Auth::getUser(); $volunteer = $user->volunteer; if ($volunteer->update($request->validated())) { $volunteer->calculateCompleteness(); } $request->syncSkills($volunteer); if ($name = $request->name) { $user->update(compact('name')); } return response()->json(['message' => 'Your account has been updated.']); } } <file_sep>/app/Models/Jobs/Role.php <?php namespace App\Models\Jobs; use App\Models\Traits\IsTag; use App\Models\Traits\SortableTrait; use Illuminate\Database\Eloquent\Model; use Spatie\EloquentSortable\Sortable; class Role extends Model implements Sortable { use IsTag; use SortableTrait; const CREATED_AT = null; const UPDATED_AT = null; protected $fillable = ['name']; protected $table = 'sector_roles'; // RELATIONS public function sectors() { return $this->belongsToMany( Sector::class, 'sector_has_roles', 'role_id', 'sector_id' ); } } <file_sep>/modules/Frontend/Repositories/VolunteerRepository.php <?php namespace Modules\Frontend\Repositories; use App\Models\Jobs\Hour; use App\Models\Jobs\Sector; use App\Models\Jobs\Skill; use App\Models\Jobs\Type; use App\Models\Language; use App\Models\Map\US\City; use App\Models\Volunteers\MoreInfo\Degree; use App\Models\Volunteers\MoreInfo\VeteranStatus; use App\Models\Volunteers\MoreInfo\YearOfExperience; use App\Models\Volunteers\Volunteer; use App\Services\LocationService; use Illuminate\Support\Collection; class VolunteerRepository { public function setupRelations(Volunteer $volunteer): Volunteer { $volunteer->load(['locations', 'roles', 'types', 'hours', 'educations', 'resume', 'skills']); $volunteer->setRelation( 'workExperiences', $volunteer->workExperiences()->orderByDesc('start')->get() ); $volunteer->setRelation('certificates', $volunteer->certificates()->orderByDesc('year')->get()); $volunteer->setRelation( 'languages', $volunteer->languages() ->orderBy('language_id') ->get() ->map(fn(Language $l) => ['id' => $l->id, 'fluency' => $l->pivot->fluency]) ); $volunteer->locations->transform(fn(City $c) => $c->id); $volunteer->types->transform(fn(Type $t) => $t->id); $volunteer->hours->transform(fn(Hour $h) => $h->id); return $volunteer; } public function setupAppends(Volunteer $volunteer): Volunteer { $volunteer->append(['name']); if ($volunteer->avatarMedia) { $volunteer->append(['avatar']); } return $volunteer; } public function shareVolunteer(Volunteer $volunteer): void { $locationService = app(LocationService::class); $volunteerArray = $volunteer->toArray(); /* @var $city City */ if ($city = $volunteer->city) { $volunteerArray['city'] = [ 'text' => $locationService->mapCity($city), 'value' => $city->id, 'zips' => $city->zips ]; } $volunteerArray['skills'] = collect($volunteer['skills'])->pluck('name'); $ids = $volunteer['locations']; $placeholders = implode(',', array_fill(0, count($ids), '?')); $volunteerArray['cities'] = $ids->isNotEmpty() ? City::whereIn('id', $ids) ->orderByRaw("field(id,{$placeholders})", $ids)->get() ->map(fn(City $c) => [[ 'text' => $locationService->mapCity($c), 'value' => $c->id ]]) : []; $volunteerArray['sectors'] = $volunteer->roles() ->select(['sector_id', 'role_id']) ->distinct() ->get() ->groupBy('sector_id') ->map(fn(Collection $items) => $items->map(fn($item) => $item->role_id)->toArray()); share(['volunteer' => $volunteerArray]); } public function shareForView(): void { $types = Type::all('name', 'id')->map(fn(Type $t) => ['text' => $t->name, 'value' => $t->id]); $sectors = Sector::with('roles') ->get(['name', 'id']) ->map(fn(Sector $s) => [ 'text' => $s->name, 'value' => $s->id, 'roles' => $s->roles->chunk(ceil($s->roles->count() / 2))]); $hours = Hour::all('name', 'id')->map(fn(Hour $h) => ['text' => $h->name, 'value' => $h->id]); $yearsOfExperience = YearOfExperience::all(['name', 'id']) ->map(fn(YearOfExperience $y) => ['text' => $y->name, 'value' => $y->id]); $degrees = Degree::all(['name', 'id']) ->map(fn(Degree $d) => ['text' => $d->name, 'value' => $d->id]); $veteranStatuses = VeteranStatus::all(['name', 'id']) ->map(fn(VeteranStatus $s) => ['text' => $s->name, 'value' => $s->id]); $languages = Language::all(['name', 'id'])->map(fn(Language $l) => ['text' => $l->name, 'value' => $l->id]); $fluencies = collect(Language::$fluencies)->map( fn($label, $fluency) => ['text' => $label, 'value' => $fluency] )->values(); share(compact('types', 'sectors', 'hours', 'yearsOfExperience', 'degrees', 'veteranStatuses', 'languages', 'fluencies')); } public function shareForEdit(): void { $skills = Skill::all(['name', 'id'])->map(fn(Skill $s) => ['text' => $s->name]); share( compact('skills') ); } public function transformForIndex(Volunteer $volunteer): Volunteer { $volunteer->append([ 'avatar', 'name', 'location', 'employment', 'updated_at', 'is_completed', 'in_bookmarks' ]); $volunteer->sectors = Sector::findMany( $volunteer->roles->pluck('pivot.sector_id')->unique() )->pluck('name'); return $volunteer; } } <file_sep>/modules/Frontend/routes/api.php <?php Route::get('locations/{query}', 'LocationController@all')->name('api.locations.search'); Route::get('cities/{query}', 'LocationController@cities')->name('api.cities.search'); Route::get('vacancies/{query}', 'VacancyController@search')->name('api.vacancies.search'); <file_sep>/database/migrations/2020_09_16_171841_create_companies_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCompaniesTable extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_16_171841_create_companies_table.php */ public function up() { Schema::create('companies', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->unique()->constrained()->onDelete('cascade'); $table->string('name'); $table->string('title')->nullable(); $table->foreignId('sector_id')->constrained(); $table->text('description')->nullable(); $table->foreignId('size_id')->constrained('job_company_sizes'); $table->string('address'); $table->string('address_2')->nullable(); $table->foreignId('city_id')->constrained('us_cities'); $table->char('zip', 5); $table->string('phone')->nullable(); $table->string('email')->nullable(); $table->json('social')->nullable(); }); } public function down() { Schema::dropIfExists('companies'); } } <file_sep>/database/factories/VacancyFactory.php <?php /** @var Factory $factory */ use App\Models\Company; use App\Models\Jobs\Sector; use App\Models\Jobs\Type; use App\Models\Map\US\City; use App\Models\Vacancy; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(Vacancy::class, function (Faker $faker) { return [ 'company_id' => Company::inRandomOrder()->first()->id, 'title' => $faker->unique()->sentence(3), 'sector_id' => Sector::inRandomOrder()->first()->id, 'city_id' => City::inRandomOrder()->first()->id, 'type_id' => Type::inRandomOrder()->first()->id, 'description' => $faker->realText(512), 'is_relocation' => rand(0, 1) === 1, 'is_remote_work' => rand(0, 1) === 1, 'address' => $faker->address, 'company_title' => $faker->unique()->sentence(6), 'company_description' => $faker->unique()->sentence(16), 'status' => collect(array_keys(Vacancy::$statuses))->random(), ]; }); <file_sep>/app/Models/Chats/Message.php <?php namespace App\Models\Chats; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; class Message extends Model { public const UPDATED_AT = null; protected $table = 'chat_messages'; protected $fillable = ['chat_id', 'volunteer_id', 'company_id', 'text', 'is_viewed']; public function markAsViewed(): bool { $this->is_viewed = true; return $this->save(); } public function scopeUnviewed(Builder $builder): void { $builder->where('is_viewed', '=', false); } } <file_sep>/modules/Admin/Http/Controllers/Users/UserController.php <?php namespace Modules\Admin\Http\Controllers\Users; use App\Models\User; use Hash; use Illuminate\Database\Eloquent\Builder; use Modules\Admin\Http\Controllers\Controller; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Requests\IndexRequest; use Modules\Admin\Http\Requests\UserRequest; use Modules\Admin\Repositories\UserRepository; class UserController extends Controller { use CRUDController; protected UserRepository $userService; protected string $resource = 'users'; public function __construct() { $this->userService = app(UserRepository::class); } public function index(IndexRequest $request) { $this->seo()->setTitle('Users'); $users = User::query()->select(['id', 'email', 'name', 'created_at']) ->when($request->get('searchQuery'), fn($q) => $q->search($request->get('searchQuery'))) ->when($request->has('sortBy'), function (Builder $users) use ($request) { $users->orderBy($request->get('sortBy'), $request->get('sortDesc') ? 'desc' : 'asc'); }) ->with('roles') ->paginate(10); $users->getCollection()->transform(function ($user) { $user['role'] = ucfirst($user->roles->implode('name', ' ')); return $user; }); if (request()->expectsJson()) { return $users; } else { share(compact('users')); } return view('admin::users.index'); } public function create() { $this->seo()->setTitle('Create a new user'); $this->userService->shareForCRUD(); return $this->form(); } public function store(UserRequest $request) { $this->seo()->setTitle('Edit a user'); $password = <PASSWORD>::<PASSWORD>($request->input('password')); $user = User::create(array_merge($request->only('email', 'name', 'type'), compact('password'))); $user->assignRole($request->input('role')); if ($user->is_volunteer) { $user->volunteer()->create(); } return response()->json([ 'status' => 'User has been created', 'title' => $this->seo()->getTitle(), 'user' => $user ], 201); } public function edit(User $user) { $this->seo()->setTitle('Edit a user'); $this->userService->shareForCRUD(); $user->role = $user->roles()->first()->id ?? null; share(compact('user')); return $this->form(); } public function update(UserRequest $request, User $user) { $data = $request->only('email', 'name', 'type'); if ($password = $request->input('password')) { $data['password'] = <PASSWORD>($password); } $user->update($data); $user->syncRoles($request->input('role')); return response()->json(['status' => 'User has been updated', 'user' => $user]); } public function destroy(User $user) { $user->delete(); return response()->json(['status' => 'User has been deleted']); } } <file_sep>/database/migrations/2020_09_23_155402_create_volunteer_has_languages_table.php <?php use App\Models\Language; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerHasLanguagesTable extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2020_09_23_155402_create_volunteer_has_languages_table.php */ public function up() { $fluencies = array_keys(Language::$fluencies); Schema::create('volunteer_has_languages', function (Blueprint $table) use ($fluencies) { $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->foreignId('language_id')->constrained('languages')->cascadeOnDelete(); $table->enum('fluency', $fluencies); }); } public function down() { Schema::dropIfExists('volunteer_has_languages'); } } <file_sep>/modules/Admin/routes.php <?php /** * @routeNamespace("Modules\Admin\Http\Controllers") * @routePrefix("admin.") */ use Modules\Admin\Http\Middleware\Admin; Route::middleware('guest')->group(function () { Route::get('/login', 'LoginController@showLoginForm')->name('login'); Route::post('/login', 'LoginController@login')->name('login.try'); }); Route::middleware(Admin::class)->group(function () { Route::get('/', 'DashboardController@index')->name('dashboard'); Route::resource('/pages', 'PageController', ['names' => 'pages'])->except(['show']); Route::prefix('/blog') ->namespace('Blog') ->as('blog.') ->group(function () { Route::resource('/categories', 'CategoryController'); Route::post('/categories/sort', 'CategoryController@sort')->name('categories.sort'); Route::resource('/articles', 'ArticleController')->except('show'); }); Route::namespace('Users')->group(function () { Route::resource('/users', 'UserController', ['names' => 'users'])->except(['show']); Route::get('/companies', 'CompanyController@index')->name('companies.index'); Route::get('/volunteers', 'VolunteerController@index')->name('volunteers.index'); }); Route::prefix('/jobs')->namespace('Jobs')->group(function () { Route::resource('/sectors', 'SectorController', ['names' => 'sectors'])->except(['show']); Route::get('/sectors/{sector}/roles', 'RoleController@index',)->name('sectors.roles'); Route::post('/sectors/sort', 'SectorController@sort')->name('sectors.sort'); Route::resource('/roles', 'RoleController', ['names' => 'roles'])->except(['show']); Route::post('/roles/sort', 'RoleController@sort')->name('roles.sort'); }); Route::get('/surveys', 'SurveyController@index')->name('surveys.index'); Route::get('/search-queries', 'SearchQueryController@index')->name('search-queries.index'); Route::post('/media', 'MediaController@upload')->name('media.upload'); Route::post('logout', 'LoginController@logout')->name('logout'); }); <file_sep>/modules/Frontend/resources/js/mixins/messages-notifications.js export default { data() { return { unviewedMessages: this.shared('unviewedMessages') } }, mounted() { this.$bus.on('unviewed-messages', unviewedMessages => { this.unviewedMessages = unviewedMessages }) } } <file_sep>/modules/Admin/Http/Controllers/Users/VolunteerController.php <?php namespace Modules\Admin\Http\Controllers\Users; use App\Models\Company; use App\Models\Volunteers\Volunteer; use Illuminate\Database\Eloquent\Builder; use Modules\Admin\Http\Controllers\Controller; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Requests\IndexRequest; class VolunteerController extends Controller { use CRUDController; protected string $resource = 'companies'; public function index(IndexRequest $request) { $this->seo()->setTitle('Volunteers'); $volunteers = Volunteer::select([ 'id', 'user_id', 'city_id', 'job_title', 'completeness' ]) ->when($request->get('searchQuery'), fn($q) => $q->search($request->get('searchQuery'))) ->when($request->has('sortBy'), function (Builder $users) use ($request) { $users->orderBy($request->get('sortBy'), $request->get('sortDesc') ? 'desc' : 'asc'); }) ->with(['user', 'city']) ->paginate(10); $volunteers->transform(fn(Volunteer $volunteer) => $volunteer->append('name')); if (request()->expectsJson()) { return $volunteers; } share(compact('volunteers')); return view('admin::volunteers.index'); } } <file_sep>/database/migrations/2014_10_12_000000_create_users_table.php <?php use App\Models\User; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /* php artisan migrate:refresh --path=/database/migrations/2014_10_12_000000_create_users_table.php */ public function up() { $types = array_keys(User::$types); Schema::create('users', function (Blueprint $table) use ($types) { $table->id(); $table->string('name')->nullable(); $table->string('email')->unique(); $table->string('provider')->nullable(); $table->string('provider_id')->nullable(); $table->timestamp('email_verified_at')->nullable(); $table->string('password')->nullable(); $table->enum('type', $types)->default(User::VOLUNTEER); $table->rememberToken(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('users'); } } <file_sep>/modules/Admin/Providers/RouteServiceProvider.php <?php namespace Modules\Admin\Providers; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Route; class RouteServiceProvider extends ServiceProvider { protected string $moduleNamespace = 'Modules\Admin\Http\Controllers'; public function boot(): void { parent::boot(); } public function map(): void { $this->mapWebRoutes(); } protected function mapWebRoutes(): void { Route::domain(env('ADMIN_DOMAIN')) ->middleware('web') ->namespace($this->moduleNamespace) ->as('admin.') ->group(module_path('Admin', 'routes.php')); } } <file_sep>/database/factories/ArticleFactory.php <?php /** @var Factory $factory */ use App\Models\Blog\Article; use App\Models\Blog\Category; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(Article::class, function (Faker $faker) { return [ 'category_id' => Category::inRandomOrder()->first()->id, 'title' => $faker->unique()->sentence(6), 'body' => $faker->realText(1000), 'excerpt' => $faker->text(140), 'meta_title' => $faker->unique()->sentence(6), 'meta_description' => $faker->unique()->sentence(16), 'status' => Article::PUBLISHED, ]; }); <file_sep>/modules/Frontend/resources/js/components/index.js import Vue from 'vue' export default { App: () => import('./App'), ArticlesList: () => import('./articles/ArticlesList'), CompanyInfoForm: () => import('./company/InfoForm'), CompanyShow: () => import('./companies/Show'), VacancyForm: () => import('./company/vacancies/Form'), CompanyVacanciesList: () => import('./company/vacancies/List'), VacanciesHomeForm: () => import('./vacancies/VacanciesHomeForm'), VacanciesIndex: () => import('./vacancies/VacanciesIndex'), VacancyShow: () => import('./vacancies/Show'), VolunteerAccountPage: () => import('./volunteer/account/AccountPage'), LoginForm: () => import('./auth/Login'), EmailResetForm: () => import('./auth/EmailReset'), PasswordResetForm: () => import('./auth/PasswordReset'), PasswordChangeForm: () => import('./auth/PasswordChange'), SubscriptionManagement: () => import('./company/SubscriptionManagement'), ChatNotifications: () => import('./ChatNotifications'), SeoText: () => import('./SeoText') } Vue.component('SimbokSelect', () => import('./layout/SimbokSelect')) Vue.component('InputMaterial', () => import('./layout/InputMaterial')) <file_sep>/modules/Frontend/Http/Middleware/VacancyNotClosed.php <?php namespace Modules\Frontend\Http\Middleware; use App\Models\Vacancy; use Illuminate\Http\Request; class VacancyNotClosed { public function handle(Request $request, \Closure $next) { /* @var $vacancy Vacancy */ $vacancy = $request->vacancy; if ($vacancy->status === Vacancy::CLOSED || $vacancy->deleted_at) abort(403); return $next($request); } } <file_sep>/modules/Frontend/Http/Controllers/Company/InfoController.php <?php namespace Modules\Frontend\Http\Controllers\Company; use App\Models\Jobs\Sector; use App\Models\Jobs\Size; use App\Services\LocationService; use Illuminate\Http\Request; use Modules\Frontend\Http\Controllers\Controller; use Modules\Frontend\Http\Requests\Company\InfoRequest; class InfoController extends Controller { public function showForm(LocationService $locationService) { $this->seo()->setTitle('Company Info'); $user = \Auth::getUser(); if ($company = $user->company) { if ($company->logoMedia) $company->append('logo'); $city = $company->city; $company = $company->toArray(); $company['city'] = [ 'text' => $locationService->mapCity($city), 'value' => $city->id, 'zips' => $city->zips ]; share(compact('company')); } $sectors = Sector::all('name', 'id')->map(fn(Sector $s) => ['text' => $s->name, 'value' => $s->id]); $sizes = Size::all('name', 'id')->map(fn(Size $s) => ['text' => $s->name, 'value' => $s->id]); share(compact('user', 'sectors', 'sizes')); return view('frontend::company.info'); } public function update(InfoRequest $request) { $data = $request->only([ 'name', 'title', 'sector_id', 'description', 'size_id', 'address', 'address_2', 'city_id', 'zip', 'phone', 'email', 'social' ]); $user = \Auth::getUser(); if ($company = $user->company) { $company->update($data); } else { $user->company()->create($data); } if ($name = $request->user_name) $user->update(compact('name')); return response()->json(['message' => 'Company info has been updated.']); } public function uploadLogo(Request $request) { ['logo' => $logo] = $this->validate($request, [ 'logo' => ['required', 'image', 'max:4096', 'mimes:jpg,jpeg,bmp,png'] ]); $company = \Auth::getUser()->company; $company->uploadLogo($logo); $company->load('logoMedia'); return response()->json([ 'message' => 'Company logo has been uploaded.', 'logo' => $company->logo ]); } public function destroyLogo() { $company = \Auth::getUser()->company; $company->deleteLogo(); return response()->json(['message' => 'Company logo has been deleted.',]); } } <file_sep>/modules/Frontend/Http/Requests/VacanciesRequest.php <?php namespace Modules\Frontend\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class VacanciesRequest extends FormRequest { public function rules(): array { return [ 'is_relocation' => ['nullable'], 'is_remote_work' => ['nullable'], 'hours' => ['nullable'], 'types' => ['nullable'], 'time' => ['nullable'], 'sizes' => ['nullable'], 'sectors' => ['nullable'] ]; } public function all($keys = null): array { $data = parent::all(); foreach (['hours', 'types', 'sizes', 'sectors'] as $filter) { if (isset($data[$filter])) { $data[$filter] = explode('|', $data[$filter]); } } if (isset($data['time'])) { $data['time'] = (int)$data['time']; } return $data; } public function authorize(): bool { return true; } } <file_sep>/database/migrations/2020_12_05_180534_add_completeness_column_to_volunteers.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddCompletenessColumnToVolunteers extends Migration { public function up(): void { Schema::table('volunteers', function (Blueprint $table) { $table->decimal('completeness', 3)->default(0); }); } public function down(): void { Schema::table('volunteers', function (Blueprint $table) { $table->dropColumn('completeness'); }); } } <file_sep>/webpack.config.js /* webpack config for better ide support */ const path = require('path') module.exports = { resolve: { alias: { ziggy: path.resolve('vendor/tightenco/ziggy/dist/js/route.js'), '~': path.resolve('modules/Frontend/resources/js'), '@': path.resolve('modules/Admin/resources/js') }, } } <file_sep>/modules/Admin/Http/Controllers/LoginController.php <?php namespace Modules\Admin\Http\Controllers; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; class LoginController extends Controller { use AuthenticatesUsers; public function __construct() { $this->middleware('guest')->except('logout'); } public function showLoginForm() { $this->seo()->setTitle('Login'); \Route2Class::addClass('blank-page'); \Route2Class::addClass('bg-full-screen-image'); return view('admin::auth.login'); } public function logout(Request $request) { $this->guard()->logout(); $request->session()->invalidate(); return $this->loggedOut($request) ?: redirect()->route('admin.login'); } public function redirectPath() { return route('admin.dashboard'); } } <file_sep>/app/Models/SearchQuery.php <?php namespace App\Models; use App\Models\Volunteers\Volunteer; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class SearchQuery extends Model { public const UPDATED_AT = null; protected $fillable = [ 'query', 'location' ]; public function company(): BelongsTo { return $this->belongsTo(Company::class); } public function volunteer(): BelongsTo { return $this->belongsTo(Volunteer::class); } } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/ResumeController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Http\Controllers\Controller; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Modules\Frontend\Http\Requests\Volunteer\ResumeRequest; class ResumeController extends Controller { use HasVolunteer; public function store(ResumeRequest $request): JsonResponse { $volunteer = $this->volunteer(); $media = $volunteer->addMedia($request->file)->toMediaCollection('resume'); $resume = $this->volunteer()->resume()->create([ 'title' => $request->title, 'file_id' => $media->id ]); return response()->json([ 'message' => 'Resume has been uploaded.', 'url' => $media->getFullUrl(), 'created_at' => $resume->created_at ]); } public function destroy(): JsonResponse { $resume = $this->volunteer()->resume; $resume->file()->delete(); $resume->delete(); return response()->json(['message' => 'Resume has been deleted.']); } } <file_sep>/modules/Admin/Http/Controllers/PageController.php <?php namespace Modules\Admin\Http\Controllers; use App\Models\Page; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Requests\PageRequest; class PageController extends Controller { use CRUDController; protected string $resource = 'pages'; public function index() { $this->seo()->setTitle('Pages'); $pages = Page::all(['id', 'title', 'slug', 'created_at', 'updated_at']); $pages->transform(function ($page) { // $page['link'] = route('frontend.pages.show', $page->slug); return $page; }); share(compact('pages')); return $this->listing(); } public function create() { $this->seo()->setTitle('Create a new page'); return $this->form(); } public function store(PageRequest $request) { $this->seo()->setTitle('Edit a page'); $page = new Page($request->all()); $page->save(); return response()->json([ 'status' => 'Page has been created', 'title' => $this->seo()->getTitle(), 'page' => $page ], 201); } public function edit(Page $page) { $this->seo()->setTitle('Edit a page'); share(compact('page')); return $this->form(); } public function update(PageRequest $request, Page $page) { $page->update($request->all()); return response()->json(['status' => 'Page has been updated', 'page' => $page]); } public function destroy(Page $page) { $page->delete(); return response()->json(['status' => 'Page has been deleted']); } } <file_sep>/modules/Frontend/Http/Controllers/Company/HasCompany.php <?php namespace Modules\Frontend\Http\Controllers\Company; use App\Models\Company; use Auth; trait HasCompany { protected ?Company $company = null; protected function company(): Company { if (!$this->company) { $this->company = Auth::user()->company; } return $this->company; } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/CertificateRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer; use Illuminate\Foundation\Http\FormRequest; class CertificateRequest extends FormRequest { public function rules(): array { return [ 'title' => ['required', 'string255'], 'issuing_authority' => ['nullable', 'string255'], 'year' => ['nullable', 'numeric', 'min:1950', 'max:' . date('Y')], 'description' => ['nullable', 'string255'], ]; } public function authorize(): bool { return true; } } <file_sep>/database/seeds/Jobs/RolesSeeder.php <?php use App\Models\Jobs\Sector; use Illuminate\Database\Seeder; class RolesSeeder extends Seeder { public function run() { $roles = [ "Academic librarian", "Accountant", "Accounting technician", "Actuary", "Adult nurse", "Advertising account executive", "Advertising account planner", "Advertising copywriter", "Advice worker", "Advocate (Scotland)", "Aeronautical engineer", "Agricultural consultant", "Agricultural manager", "Aid worker/humanitarian worker", "Air traffic controller", "Airline cabin crew", "Amenity horticulturist", "Analytical chemist", "Animal nutritionist", "Animator", "Archaeologist", "Architect", "Architectural technologist", "Archivist", "Armed forces officer", "Aromatherapist", "Art therapist", "Arts administrator", "Auditor", "Automotive engineer", "Barrister", "Barrister’s clerk", "Bilingual secretary", "Biomedical engineer", "Biomedical scientist", "Biotechnologist", "Brand manager", "Broadcasting presenter", "Building control officer/surveyor", "Building services engineer", "Building surveyor", "Camera operator", "Careers adviser (higher education)", "Careers adviser", "Careers consultant", "Cartographer", "Catering manager", "Charities administrator", "Charities fundraiser", "Chemical (process) engineer", "Child psychotherapist", "Children's nurse", "Chiropractor", "Civil engineer", "Civil Service administrator", "Clinical biochemist", "Clinical cytogeneticist", "Clinical microbiologist", "Clinical molecular geneticist", "Clinical research associate", "Clinical scientist - tissue typing", "Clothing and textile technologist", "Colour technologist", "Commercial horticulturist", "Commercial/residential/rural surveyor", "Commissioning editor", "Commissioning engineer", "Commodity broker", "Communications engineer", "Community arts worker", "Community education officer", "Community worker", "Company secretary", "Computer sales support", "Computer scientist", "Conference organiser", "Consultant", "Consumer rights adviser", "Control and instrumentation engineer", "Corporate banker", "Corporate treasurer", "Counsellor", "Courier/tour guide", "Court reporter/verbatim reporter", "Credit analyst", "Crown Prosecution Service lawyer", "Crystallographer", "Curator", "Customs officer", "Cyber security specialist", "Dance movement therapist", "Data analyst", "Data scientist", "Data visualisation analyst", "Database administrator", "Debt/finance adviser", "Dental hygienist", "Dentist", "Design engineer", "Dietitian", "Diplomatic service", "Doctor (general practitioner, GP)", "Doctor (hospital)", "Dramatherapist", "Economist", "Editorial assistant", "Education administrator", "Electrical engineer", "Electronics engineer", "Employment advice worker", "Energy conservation officer", "Engineering geologist", "Environmental education officer", "Environmental health officer", "Environmental manager", "Environmental scientist", "Equal opportunities officer", "Equality and diversity officer", "Ergonomist", "Estate agent", "European Commission administrators", "Exhibition display designer", "Exhibition organiser", "Exploration geologist", "Facilities manager", "Field trials officer", "Financial manager", "Firefighter", "Fisheries officer", "Fitness centre manager", "Food scientist", "Food technologist", "Forensic scientist", "Geneticist", "Geographical information systems manager", "Geomatics/land surveyor", "Government lawyer", "Government research officer", "Graphic designer", "Health and safety adviser", "Health and safety inspector", "Health promotion specialist", "Health service manager", "Health visitor", "Herbalist", "Heritage manager", "Higher education administrator", "Higher education advice worker", "Homeless worker", "Horticultural consultant", "Hotel manager", "Housing adviser", "Human resources officer", "Hydrologist", "Illustrator", "Immigration officer", "Immunologist", "Industrial/product designer", "Information scientist", "Information systems manager", "Information technology/software trainers", "Insurance broker", "Insurance claims inspector", "Insurance risk surveyor", "Insurance underwriter", "Interpreter", "Investment analyst", "Investment banker - corporate finance", "Investment banker – operations", "Investment fund manager", "IT consultant", "IT support analyst", "Journalist", "Laboratory technician", "Land-based engineer", "Landscape architect", "Learning disability nurse", "Learning mentor", "Lecturer (adult education)", "Lecturer (further education)", "Lecturer (higher education)", "Legal executive", "Leisure centre manager", "Licensed conveyancer", "Local government administrator", "Local government lawyer", "Logistics/distribution manager", "Magazine features editor", "Magazine journalist", "Maintenance engineer", "Management accountant", "Manufacturing engineer", "Manufacturing machine operator", "Manufacturing toolmaker", "Marine scientist", "Market research analyst", "Market research executive", "Marketing account manager", "Marketing assistant", "Marketing executive", "Marketing manager (social media)", "Materials engineer", "Materials specialist", "Mechanical engineer", "Media analyst", "Media buyer", "Media planner", "Medical physicist", "Medical representative", "Mental health nurse", "Metallurgist", "Meteorologist", "Microbiologist", "Midwife", "Mining engineer", "Mobile developer", "Multimedia programmer", "Multimedia specialists", "Museum education officer", "Museum/gallery exhibition officer", "Music therapist", "Nanoscientist", "Nature conservation officer", "Naval architect", "Network administrator", "Nurse", "Nutritional therapist", "Nutritionist", "Occupational therapist", "Oceanographer", "Office manager", "Operational researcher", "Orthoptist", "Outdoor pursuits manager", "Packaging technologist", "Paediatric nurse", "Paramedic", "Patent attorney", "Patent examiner", "Pension scheme manager", "Personal assistant", "Petroleum engineer", "Pharmacist", "Pharmacologist", "Pharmacovigilance officer", "Photographer", "Physiotherapist", "Picture researcher", "Planning and development surveyor", "Planning technician", "Plant breeder", "Police officer", "Political party agent", "Political party research officer", "Practice nurse", "Press photographer", "Press sub-editor", "Prison officer", "Private music teacher", "Probation officer", "Product development scientist", "Production manager", "Programme researcher", "Project manager", "Psychologist (clinical)", "Psychologist (educational)", "Psychotherapist", "Public affairs consultant (lobbyist)", "Public affairs consultant (research)", "Public house manager", "Public librarian", "Public relations (PR) officer", "QA analyst", "Quality assurance manager", "Quantity surveyor", "Records manager", "Recruitment consultant", "Recycling officer", "Regulatory affairs officer", "Research chemist", "Research scientist", "Restaurant manager", "Retail banker", "Retail buyer", "Retail manager", "Retail merchandiser", "Retail pharmacist", "Sales executive", "Sales manager", "Scene of crime officer", "Secretary", "Seismic interpreter", "Site engineer", "Site manager", "Social researcher", "Social worker", "Software developer", "Soil scientist", "Solicitor", "Speech and language therapist", "Sports coach", "Sports development officer", "Sports therapist", "Statistician", "Stockbroker", "Structural engineer", "Systems analyst", "Systems developer", "Tax inspector", "Teacher (nursery/early years)", "Teacher (primary)", "Teacher (secondary)", "Teacher (special educational needs)", "Teaching/classroom assistant", "Technical author", "Technical sales engineer", "TEFL/TESL teacher", "Television production assistant", "Test automation developer", "Tour operator", "Tourism officer", "Tourist information manager", "Town and country planner", "Toxicologist", "Trade union research officer", "Trader", "Trading standards officer", "Training and development officer", "Translator", "Transportation planner", "Travel agent", "TV/film/theatre set designer", "UX designer", "Validation engineer", "Veterinary nurse", "Veterinary surgeon", "Video game designer", "Video game developer", "Volunteer work organiser", "Warehouse manager", "Waste disposal officer", "Water conservation officer", "Water engineer", "Web designer", "Web developer", "Welfare rights adviser", "Writer", "Youth worker" ]; \DB::transaction(function () use ($roles) { foreach ($roles as $name) { $role = \App\Models\Jobs\Role::create(compact('name')); $limit = rand(1, 5); $role->sectors()->sync(Sector::inRandomOrder()->limit($limit)->pluck('id')); } }); } } <file_sep>/modules/Frontend/Http/Requests/Volunteer/Survey/UpdateJobRequest.php <?php namespace Modules\Frontend\Http\Requests\Volunteer\Survey; use Illuminate\Foundation\Http\FormRequest; class UpdateJobRequest extends FormRequest { public function rules(): array { return [ 'job_title' => ['required', 'string255'], 'company_name' => ['required', 'string255'], ]; } public function authorize(): bool { return true; } } <file_sep>/conf/supervisor.ini [program:simbock-queue] process_name = %(program_name)s command = /opt/php74/bin/php /root/simbock/artisan queue:listen autorestart = true user = root redirect_stderr = true stdout_logfile = /root/simbock/storage/logs/workers/queue.log stopwaitsecs = 3600 [program:simbock-websockets] process_name = %(program_name)s command = /opt/php74/bin/php /root/simbock/artisan websockets:serve --host=172.16.17.32 autorestart = true user = root redirect_stderr = true stdout_logfile = /root/simbock/storage/logs/workers/websockets.log stopwaitsecs = 3600 <file_sep>/modules/Frontend/Http/Controllers/VolunteerController.php <?php namespace Modules\Frontend\Http\Controllers; use App\Models\Chats\Chat; use App\Models\Volunteers\Volunteer; use App\Services\LocationService; use Carbon\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\JsonResponse; use Illuminate\Support\Collection; use Modules\Frontend\Http\Controllers\Company\HasCompany; use Modules\Frontend\Http\Requests\MessageRequest; use Modules\Frontend\Http\Requests\VacanciesRequest; use Modules\Frontend\Repositories\VacancyRepository; use Modules\Frontend\Repositories\VolunteerRepository; class VolunteerController extends Controller { use HasCompany; protected VolunteerRepository $repository; protected VacancyRepository $vacancyRepository; public function __construct() { $this->repository = app(VolunteerRepository::class); $this->vacancyRepository = app(VacancyRepository::class); } public function index( VacanciesRequest $request, LocationService $locationService, string $query = null, string $location = null ) { $title = $query ?? 'Search'; $locations = []; if ($location) { $title .= " in $location"; $locations = $locationService->parseLocation($location); } $this->seo()->setTitle("$title | Volunteers"); $filters = $request->validated(); $volunteers = Volunteer::public() ->select(['id', 'user_id', 'city_id', 'job_title']) ->when( $query, fn(Builder $q) => $q->where('job_title', 'REGEXP', '[[:<:]]' . $query . '[[:>:]]') ->orWhereHas('user', fn(Builder $q) => $q->where('name', 'REGEXP', '[[:<:]]' . $query . '[[:>:]]'))) ->when(!empty($locations), fn(Builder $q) => $q->whereHas('locations', fn(Builder $q) => $q->whereIn('id', $locations))) ->with(['user', 'types', 'hours', 'roles']) ->when(isset($filters['is_relocation']), fn($q) => $q->where('is_relocating', '=', true)) ->when(isset($filters['is_remote_work']), fn($q) => $q->where('is_working_remotely', '=', true)) ->when(isset($filters['hours']) && !empty($filters['hours']), fn($q) => $q->whereHas('hours', fn($q) => $q->whereIn('id', $filters['hours']))) ->when(isset($filters['types']) && !empty($filters['types']), fn($q) => $q->whereHas('types', fn($q) => $q->whereIn('id', $filters['types']))) ->when(isset($filters['sectors']) && !empty($filters['sectors']), fn($q) => $q->whereHas('roles', fn($q) => $q->whereIn('sector_id', $filters['sectors']))) ->when(isset($filters['time']), fn($q) => $q->whereHas('resume', fn($q) => $q->where('created_at', '>=', Carbon::now()->subDays($filters['time'])->toDateTimeString())) ) ->where('completeness', '!=', 0.) ->orderByDesc('completeness') ->paginate(4); /* @var $volunteers Collection<Volunteer> */ $volunteers->transform([$this->repository, 'transformForIndex']); if (request()->expectsJson()) { return $volunteers; } $this->vacancyRepository->shareForFilter(); share(compact('volunteers', 'query', 'location')); \Route2Class::addClass('page-with-search'); return view('frontend::company.volunteers.index'); } public function saved() { $this->seo()->setTitle('Saved Candidates'); $volunteers = Volunteer::with(['user', 'avatarMedia', 'city', 'types', 'hours', 'roles']) ->whereIn('id', \Auth::user()->company->bookmarks()->pluck('id')) ->orderByDesc('completeness') ->paginate(4); /* @var $volunteers Collection<Volunteer> */ $volunteers->transform([$this->repository, 'transformForIndex']); if (request()->expectsJson()) { return $volunteers; } $this->vacancyRepository->shareForFilter(); share(compact('volunteers')); \Route2Class::addClass('page-with-search'); return view('frontend::company.volunteers.saved'); } public function candidates() { $this->seo()->setTitle('View Candidates'); $volunteers = Volunteer::with(['user', 'avatarMedia', 'city', 'types', 'hours', 'roles']) ->whereIn('id', $this->company()->candidates()->pluck('id')) ->orderByDesc('completeness') ->paginate(4); /* @var $volunteers Collection<Volunteer> */ $volunteers->transform([$this->repository, 'transformForIndex']); if (request()->expectsJson()) { return $volunteers; } $this->vacancyRepository->shareForFilter(); share(compact('volunteers')); \Route2Class::addClass('page-with-search'); return view('frontend::company.volunteers.candidates'); } public function show(Volunteer $volunteer) { $company = $this->company(); abort_if( !$company->canSeeVolunteer(), 403, 'You have exhausted the resume views limit. Wait for next monthly payment or update your plan.' ); $this->seo()->setTitle("$volunteer->name | Volunteers"); $volunteer = $this->repository->setupRelations($volunteer); $volunteer = $this->repository->setupAppends($volunteer); $this->repository->shareVolunteer($volunteer); $this->repository->shareForView(); return view('frontend::company.volunteers.show'); } public function self() { return $this->show(\Auth::getUser()->volunteer); } public function bookmark(Volunteer $volunteer): JsonResponse { $bookmarks = \Auth::user()->company->bookmarks()->toggle($volunteer->id); return response()->json([ 'message' => 'Volunteer has been ' . ($bookmarks['attached'] ? 'saved to' : 'removed from') . ' bookmarks.', 'inBookmarks' => in_array($volunteer->id, $bookmarks['attached'], true) ]); } public function contact(Volunteer $volunteer): JsonResponse { $company = $this->company(); if (!$company->canSeeVolunteer()) { return response()->json([ 'message' => 'You have exhausted the resume views limit. Wait for next monthly payment or update your plan.' ], 403); } return response()->json([ 'email' => $volunteer->email, 'phone' => $volunteer->phone ]); } public function chat(MessageRequest $request, Volunteer $volunteer): JsonResponse { $company = $this->company(); /* @var $chat Chat */ $chat = $company->chats()->where('volunteer_id', '=', $volunteer->id)->latest()->first(); if (!$chat) { $chat = $company->chats()->create(['volunteer_id' => $volunteer->id]); } $chat->messages()->create([ 'company_id' => $company->id, 'text' => $request->input('message') ]); return response()->json(['message' => 'You message has been sent.'], 201); } } <file_sep>/modules/Admin/Http/Controllers/SearchQueryController.php <?php namespace Modules\Admin\Http\Controllers; use App\Models\SearchQuery; use Illuminate\Database\Eloquent\Builder; use Modules\Admin\Http\Controllers\Traits\CRUDController; use Modules\Admin\Http\Requests\IndexRequest; class SearchQueryController extends Controller { use CRUDController; protected string $resource = 'search-queries'; public function index(IndexRequest $request) { $this->seo()->setTitle('Search queries'); $searchQueries = SearchQuery::with(['company', 'volunteer']) ->when($request->has('sortBy'), function (Builder $users) use ($request) { $users->orderBy($request->get('sortBy'), $request->get('sortDesc') ? 'desc' : 'asc'); }) ->latest() ->paginate(10); $searchQueries->transform(function (SearchQuery $query) { if ($query->volunteer) { $query->volunteer->append('name'); } return $query; }); if (request()->expectsJson()) { return $searchQueries; } share(compact('searchQueries')); return $this->listing(); } } <file_sep>/modules/Frontend/routes/web.php <?php /** * @routeNamespace("Modules\Frontend\Http\Controllers") * @routePrefix("frontend.") */ use Modules\Frontend\Http\Middleware\Company; use Modules\Frontend\Http\Middleware\Searched; use Modules\Frontend\Http\Middleware\VacancyNotClosed; use Modules\Frontend\Http\Middleware\VacancyOwner; use Modules\Frontend\Http\Middleware\Volunteer; use Modules\Frontend\Http\Middleware\VolunteerViewed; Auth::routes(); Route::middleware('guest')->as('auth.')->group(function () { Route::get('social/company/{provider}', 'Auth\SocialController@companyRedirect')->name('provider_company'); Route::get('social/company/{provider}/callback', 'Auth\SocialController@companyCallback'); Route::get('social/{provider}', 'Auth\SocialController@redirect')->name('provider'); Route::get('social/{provider}/callback', 'Auth\SocialController@callback'); }); Route::get('', 'PageController@home')->name('home'); Route::prefix('newsroom')->as('articles.')->group(function () { Route::get('', 'ArticleController@index')->name('index'); Route::prefix('{category:slug}')->group(function () { Route::get('', 'ArticleController@index')->name('category'); Route::get('{article:slug}', 'ArticleController@show')->name('show'); }); }); Route::as('vacancies.')->group(function () { Route::prefix('vacancies/{query?}') ->middleware(Searched::class) ->as('search') ->group(function () { Route::get('', 'VacancyController@index'); Route::get('{location?}', 'VacancyController@index')->name('.location'); }); Route::prefix('vacancy/{vacancy}')->group(function () { Route::get('', 'VacancyController@show') ->name('show') ->where('vacancy', '[0-9]+'); Route::prefix('') ->middleware(['auth', Volunteer::class]) ->as('actions.') ->group(function () { Route::post('apply', 'VacancyController@apply')->name('apply'); Route::post('bookmark', 'VacancyController@bookmark')->name('bookmark'); Route::post('chat', 'VacancyController@chat')->name('chat'); }); }); }); Route::as('volunteers.')->middleware('auth')->group(function () { Route::prefix('volunteers/{query?}') ->middleware(Searched::class) ->as('search') ->group(function () { Route::get('', 'VolunteerController@index'); Route::get('{location?}', 'VolunteerController@index')->name('.location'); }); Route::prefix('volunteer/{volunteer}')->group(function () { Route::get('', 'VolunteerController@show') ->middleware(VolunteerViewed::class) ->name('show') ->where('volunteer', '[0-9]+'); Route::middleware(Company::class) ->as('actions.') ->group(function () { Route::post('bookmark', 'VolunteerController@bookmark')->name('bookmark'); Route::get('contact', 'VolunteerController@contact') ->middleware(VolunteerViewed::class) ->name('contact'); Route::post('chat', 'VolunteerController@chat')->name('chat'); }); }); }); Route::middleware('auth')->group(function () { Route::prefix('account/change-password') ->namespace('Auth') ->as('auth.change_password.') ->group(function () { Route::get('', 'ChangePasswordController@form')->name('form'); Route::post('', 'ChangePasswordController@update')->name('update'); }); /*Route::prefix('vacancies')->as('vacancies.')->group(function () { Route::prefix('{vacancy}')->group(function () { Route::get('', 'VacancyController@show')->name('show'); }); });*/ Route::as('companies.')->group(function () { Route::get('company/self', 'CompanyController@self') ->middleware(Company::class) ->name('self'); Route::prefix('companies/{company}')->group(function () { Route::get('', 'CompanyController@show')->name('show'); }); }); Route::prefix('company') ->middleware(Company::class) ->as('company.') ->group(function () { Route::as('volunteers.')->group(function () { Route::get('saved', 'VolunteerController@saved')->name('saved'); Route::get('candidates', 'VolunteerController@candidates')->name('candidates'); }); Route::namespace('Company')->group(function () { Route::get('board', 'BoardController')->name('board'); Route::prefix('info')->as('info.')->group(function () { Route::get('', 'InfoController@showForm')->name('form'); Route::post('', 'InfoController@update')->name('update'); Route::prefix('logo')->as('logo.')->group(function () { Route::post('', 'InfoController@uploadLogo')->name('update'); Route::delete('', 'InfoController@destroyLogo')->name('destroy'); }); }); Route::prefix('vacancies')->as('vacancies.')->group(function () { Route::get('{status?}', 'VacancyController@index') ->name('index') ->where('status', '(active|draft|closed)'); Route::get('create', 'VacancyController@create')->name('create'); Route::post('', 'VacancyController@store')->name('store'); Route::prefix('{vacancy}')->middleware(VacancyOwner::class)->group(function () { Route::middleware(VacancyNotClosed::class)->group(function () { Route::get('edit', 'VacancyController@edit')->name('edit'); Route::post('', 'VacancyController@update')->name('update'); }); Route::post('post', 'VacancyController@post')->name('post'); Route::post('stop', 'VacancyController@stop')->name('stop'); Route::post('close', 'VacancyController@close')->name('close'); Route::get('duplicate', 'VacancyController@duplicate')->name('duplicate'); Route::delete('', 'VacancyController@destroy')->name('destroy'); }); }); Route::prefix('upgrade')->as('upgrade.')->group(function () { Route::get('', 'UpgradeController@page')->name('page'); Route::get('checkout/{plan}', 'UpgradeController@checkout')->name('checkout'); Route::post('cancel', 'UpgradeController@cancel')->name('cancel'); /*Route::get('setup-intent', 'UpgradeController@intent')->name('intent'); Route::put('subscription', 'UpgradeController@updatePlan')->name('update'); Route::prefix('payments')->as('payments.')->group(function () { Route::get('', 'UpgradeController@getPaymentMethods')->name('index'); Route::post('', 'UpgradeController@createPaymentMethod')->name('create'); Route::delete('', 'UpgradeController@removePaymentMethod')->name('destroy'); });*/ }); }); }); Route::prefix('volunteer')->as('volunteers.')->group(function () { Route::get('self', 'VolunteerController@self') ->middleware(Volunteer::class) ->name('self'); }); Route::prefix('account') ->middleware(Volunteer::class) ->as('volunteer.') ->namespace('Volunteer') ->group(function () { Route::get('companies', 'CompanyController')->name('vacancies.companies'); Route::get('saved', 'VacancyController@saved')->name('vacancies.saved'); Route::get('history', 'VacancyController@history')->name('vacancies.history'); Route::prefix('info')->as('account.')->namespace('Account')->group(function () { Route::get('', 'AccountController@page')->name('form'); Route::post('', 'AccountController@update')->name('update'); Route::prefix('avatar')->as('avatar.')->group(function () { Route::post('', 'AvatarController@update')->name('update'); Route::delete('', 'AvatarController@destroy')->name('destroy'); }); Route::prefix('job')->as('job.')->group(function () { Route::post('', 'JobController@update')->name('update'); Route::delete('', 'JobController@destroy')->name('destroy'); }); Route::prefix('work_experience')->as('work_experiences.')->group(function () { Route::post('', 'WorkExperienceController@store')->name('store'); Route::prefix('{workExperience}')->group(function () { Route::patch('', 'WorkExperienceController@update')->name('update'); Route::delete('', 'WorkExperienceController@destroy')->name('destroy'); }); }); Route::prefix('education')->as('educations.')->group(function () { Route::post('', 'EducationController@store')->name('store'); Route::prefix('{education}')->group(function () { Route::patch('', 'EducationController@update')->name('update'); Route::delete('', 'EducationController@destroy')->name('destroy'); }); }); Route::prefix('resume')->as('resume.')->group(function () { Route::post('', 'ResumeController@store')->name('store'); Route::delete('', 'ResumeController@destroy')->name('destroy'); }); Route::prefix('certificate')->as('certificates.')->group(function () { Route::post('', 'CertificateController@store')->name('store'); Route::prefix('{certificate}')->group(function () { Route::patch('', 'CertificateController@update')->name('update'); Route::delete('', 'CertificateController@destroy')->name('destroy'); }); }); Route::prefix('language')->as('languages.')->group(function () { Route::post('', 'LanguageController@store')->name('store'); Route::prefix('{language}')->group(function () { Route::patch('', 'LanguageController@update')->name('update'); Route::delete('', 'LanguageController@destroy')->name('destroy'); }); }); }); Route::prefix('survey')->as('survey.')->group(function () { Route::get('', 'SurveyController@page')->name('page'); Route::post('', 'SurveyController@store')->name('create'); Route::post('job', 'SurveyController@updateJob')->name('job'); Route::post('complete', 'SurveyController@complete')->name('complete'); }); }); Route::prefix('chat')->as('chat.')->group(function () { Route::get('{chat?}', 'ChatController@page')->name('page'); Route::get('messages/{chat}', 'ChatController@messages')->name('messages'); Route::post('messages/{chat}', 'ChatController@send')->name('messages.send'); }); }); Route::post('/contact-form', 'PageController@contactForm')->name('contact-form'); Route::get('sitemap.xml', 'SitemapController'); Route::get('/{pageModel:slug}', 'PageController@show')->name('pages.show'); <file_sep>/modules/Frontend/Http/Controllers/Company/Stripe/WebhookController.php <?php namespace Modules\Frontend\Http\Controllers\Company\Stripe; use App\Models\Company; use Carbon\Carbon; use Debugbar; use Exception; use Illuminate\Http\Request; use Laravel\Cashier\Http\Controllers\WebhookController as CashierController; use Log; use Stripe\Exception\ApiErrorException; use Stripe\PaymentMethod; use Stripe\Stripe; use Symfony\Component\HttpFoundation\Response; class WebhookController extends CashierController { public function handleWebhook(Request $request): Response { Debugbar::disable(); $payload = json_decode($request->getContent(), true); Log::debug($payload['type']); return parent::handleWebhook($request); } protected function handleCustomerSubscriptionCreated(array $payload): Response { return $this->createOrUpdateSubscription($payload); } protected function createOrUpdateSubscription(array $payload): Response { /* @var $company Company */ $company = $this->getUserByStripeId($payload['data']['object']['customer']); Log::debug($payload); if ($company) { $data = $payload['data']['object']; if (!$company->subscriptions->contains('stripe_id', $data['id'])) { if (isset($data['trial_end'])) { $trialEndsAt = Carbon::createFromTimestamp($data['trial_end']); } else { $trialEndsAt = null; } $update = [ 'name' => 'default', 'stripe_id' => $data['id'], 'stripe_status' => $data['status'], 'stripe_plan' => $data['plan']['id'] ?? null, 'quantity' => $data['quantity'], 'trial_ends_at' => $trialEndsAt, 'ends_at' => null, ]; $subscription = null; if ($subscription = $company->subscription()) { try { $subscription->noProrate()->cancelNow(); } catch (Exception $e) { Log::error('Can\'t cancel subscription: ' . $e->getMessage() . $e->getTraceAsString()); } $subscription->items()->delete(); $subscription->update($update); } else { $subscription = $company->subscriptions()->create($update); } foreach ($data['items']['data'] as $item) { $subscription->items()->create([ 'stripe_id' => $item['id'], 'stripe_plan' => $item['plan']['id'], 'quantity' => $item['quantity'], ]); } try { Stripe::setApiKey(config('services.stripe.secret')); $paymentMethod = PaymentMethod::retrieve($data['default_payment_method']); $company->update([ 'card_brand' => $paymentMethod->card->brand, 'card_last_four' => $paymentMethod->card->last4 ]); } catch (ApiErrorException $e) { Log::error('Can\'t retrieve payment method: ' . $e->getMessage() . $e->getTraceAsString()); } } } return $this->successMethod(); } protected function handleCustomerSubscriptionUpdated(array $payload): Response { return $this->createOrUpdateSubscription($payload); } protected function handleInvoicePaymentSucceeded($payload): Response { $data = $payload['data']['object']; $company = $this->getUserByStripeId($data['customer']); Log::debug('Invoice for :' . $company->name); if ($company) { Log::debug('Views for :' . $company->resume_views); $company->update(['resume_views' => 0]); } return $this->updateSubscriptionStatus($payload); } protected function updateSubscriptionStatus($payload): Response { $data = $payload['data']['object']; $company = $this->getUserByStripeId($data['customer']); if ($company) { if ($subscription = $company->subscription()) { $subscription->syncStripeStatus(); } } return $this->successMethod(); } protected function handleInvoicePaymentFailed($payload): Response { return $this->updateSubscriptionStatus($payload); } } <file_sep>/modules/Frontend/Http/Requests/ContactFormRequest.php <?php namespace Modules\Frontend\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class ContactFormRequest extends FormRequest { public function rules(): array { return [ 'name' => ['nullable', 'string255'], 'email' => ['required', 'email'], 'comment' => ['nullable', 'string255'], ]; } public function authorize(): bool { return true; } } <file_sep>/database/seeds/UsersSeeder.php <?php use App\Models\Company; use App\Models\User; use Illuminate\Database\Seeder; class UsersSeeder extends Seeder { public function run() { if (User::find(1) === null) { $user = new User([ 'name' => env('INITIAL_USER_NAME'), 'email' => env('INITIAL_USER_EMAIL'), 'password' => env('<PASSWORD>'), ]); $user->save(); $user->assignRole('admin'); } factory(User::class, 1)->create()->each(function (User $user) { $company = factory(Company::class)->make(); $company->user_id = $user->id; $company->save(); }); } } <file_sep>/modules/Admin/Providers/AdminServiceProvider.php <?php namespace Modules\Admin\Providers; use Artesaos\SEOTools\Facades\SEOMeta; use Auth; use Cookie; use Illuminate\Support\ServiceProvider; use View; class AdminServiceProvider extends ServiceProvider { protected string $moduleName = 'Admin'; protected string $moduleNameLower = 'admin'; public function boot(): void { $this->registerConfig(); $this->registerViews(); $this->sharedData(); $this->viewComposer(); } public function register(): void { $this->app->register(RouteServiceProvider::class); } public function registerViews(): void { $sourcePath = module_path($this->moduleName, 'resources/views'); $this->loadViewsFrom($sourcePath, $this->moduleNameLower); } protected function registerConfig() { $this->mergeConfigFrom( module_path($this->moduleName, 'config.php'), $this->moduleNameLower ); } protected function sharedData() { View::composer('admin::layouts.master', function () { share([ 'app' => [ 'name' => config('app.name'), 'env' => config('app.env'), ], 'csrf' => csrf_token() ]); }); } protected function viewComposer() { View::composer('admin::layouts.master', function ($view) { $bodyClass = \Route2Class::generateClassString(); $bodyClass = (string)\Str::of($bodyClass)->replace('login', 'login-page'); $view->with('bodyClass', $bodyClass); }); View::composer(['admin::layouts.base'], function ($view) { \Route2Class::addClass('sidebar-mini'); $title = str_replace(SEOMeta::getTitleSeparator() . SEOMeta::getDefaultTitle(), '', SEOMeta::getTitle()); if ($title) { $view->with('pageTitle', $title); } if (Cookie::get('sidebar-toggle-collapsed')) { \Route2Class::addClass('sidebar-collapse'); } }); View::composer('admin::includes.sidebar', function ($view) { $view->with('name', ucfirst(Auth::getUser()->name)); }); } } <file_sep>/modules/Admin/resources/js/mixins/index-table.js import CreateBtn from '@/components/includes/forms/CreateBtn' import Search from "@/components/includes/forms/Search" import ActionsButtons from "@/components/includes/forms/ActionsButtons" import DragBtn from '@/components/includes/forms/DragBtn' export const index = { data() { return { isBusy: false, } }, provide() { return { resource: this.resource, } }, components: { CreateBtn, ActionsButtons } } export const destroy = { methods: { async destroy(id, provided = false) { try { const destroy = await this.$confirm("Are you sure?") if (destroy) { try { this.isBusy = true const {status, data} = await this.axios.delete(this.route(`admin.${this.resource}.destroy`, id)) if (status === 200) { this.$bus.emit('alert', {text: data.status}) if (!provided) this.items = this.items.filter(item => item.id !== id) return true } } catch (e) { console.log(e) } finally { this.isBusy = false } } } catch (e) { } } } } export const sortable = { methods: { async sort() { const order = this.items.map(({id}) => id) this.isBusy = true try { const {status, data} = await this.axios.post(this.route(`admin.${this.resource}.sort`), {order}) if (status === 200 && data.status) { this.$bus.emit('alert', {text: data.status}) } } catch (e) { console.log(e) } finally { this.isBusy = false } } }, components: { Draggable: () => import( 'vuedraggable'), DragBtn } } export const datatable = { data() { return { initialized: false, isBusy: false, initial: null, searchQuery: '', perPage: null, currentPage: 1, sortBy: 'id', sortDesc: false, total: null, } }, methods: { async items(ctx) { if (!this.initialized) { this.initialized = true return this.initial } this.isBusy = true try { const {data} = await this.axios.get(this.route(`admin.${this.resource}.index`), { params: { searchQuery: this.searchQuery, page: ctx.currentPage, sortBy: ctx.sortBy, sortDesc: +ctx.sortDesc }, }) this.isBusy = false this.perPage = data.per_page this.total = data.total return data.data } catch (error) { this.isBusy = false return [] } }, async destroy(resource, id) { if (await this.$super(destroy).destroy(resource, id, true)) this.$refs.table.refresh() }, search() { if (this.currentPage > 1) { this.resetPage() } else { this.$refs.table.refresh() } }, resetPage() { this.currentPage = 1 } }, watch: { sortBy: 'resetPage', sortDesc: 'resetPage', }, created() { this.initial = this.initialData.data this.perPage = this.initialData.per_page this.total = this.initialData.total }, provide() { return { resource: this.resource, } }, mixins: [index, destroy], components: { Search } } <file_sep>/app/Models/Jobs/Job.php <?php namespace App\Models\Jobs; use Illuminate\Database\Eloquent\Model; class Job extends Model { protected $table = 'volunteer_jobs'; protected $fillable = ['title', 'locations', 'sector_id']; protected $casts = [ 'locations' => 'array' ]; public function types() { return $this->belongsToMany(Type::class, 'volunteer_job_has_types'); } public function hours() { return $this->belongsToMany(Hour::class, 'volunteer_job_has_hours'); } public function roles() { return $this->belongsToMany(Role::class, 'volunteer_job_has_roles'); } } <file_sep>/app/Models/Company.php <?php namespace App\Models; use App\Models\Jobs\Size; use App\Models\Map\US\City; use App\Models\Traits\SearchTrait; use App\Models\Volunteers\Volunteer; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphOne; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Http\UploadedFile; use Illuminate\Support\Collection; use Laravel\Cashier\Billable; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; use Spatie\MediaLibrary\MediaCollections\Models\Media; class Company extends Client implements HasMedia { use InteractsWithMedia, Billable, SoftDeletes, SearchTrait; public const CREATED_AT = null; public const UPDATED_AT = null; protected $fillable = [ 'name', 'title', 'sector_id', 'description', 'size_id', 'address', 'address_2', 'city_id', 'state_id', 'zip', 'phone', 'email', 'social', 'card_brand', 'card_last_four', 'resume_views' ]; protected $casts = [ 'social' => 'array' ]; protected $dates = [ 'trial_ends_at' ]; protected array $search = [ 'id', 'name' ]; // FUNCTIONS public function registerMediaCollections(): void { $this->addMediaCollection('logo')->singleFile() ->registerMediaConversions(function (Media $media) { $this->addMediaConversion('icon') ->width(110) ->sharpen(0) ->nonQueued(); }); } public function uploadLogo(UploadedFile $image = null): void { if ($this->logoMedia) $this->deleteMedia($this->logoMedia); $this->addMedia($image)->toMediaCollection('logo'); } public function deleteLogo(): bool { return $this->logoMedia->delete(); } public function getLogo(string $size = ''): string { if ($this->logoMedia !== null) { return $this->logoMedia->getUrl($size); } return asset('dist/img/avatar.svg'); } public function getPlan(): ?array { $plans = collect(config('simbok.plans')); if ($subscription = $this->subscription()) { return $plans->where('stripe_plan', $subscription->stripe_plan)->first(); } return null; } public function canSeeVolunteer(): bool { if ($this->subscribed() && $plan = $this->getPlan()) { $limit = $this->getAvailableVolunteersCount(); return $limit === -1 || $this->resume_views < $limit; } return false; } public function canPostVacancy(): bool { if ($this->subscribed() && $plan = $this->getPlan()) { $limit = $plan['limits']['vacancies']; return $limit === -1 || $this->vacancies()->count() < $limit; } return false; } public function getAvailableVolunteersCount(): int { if ($this->subscribed() && $plan = $this->getPlan()) { return $plan['limits']['volunteers']; } return 0; } public function getAvailableCandidatesCount(): int { if ($this->subscribed() && $plan = $this->getPlan()) { $recommendations = $plan['limits']['recommendations']; return $recommendations === -1 ? 0 : $recommendations; } return 0; } // RELATIONS public function user(): BelongsTo { return $this->belongsTo(User::class); } /* @return Vacancy|HasMany */ public function vacancies(): HasMany { return $this->hasMany(Vacancy::class); } /* @return Collection<Volunteer> */ public function candidates(): Collection { return $this->vacancies() ->with(['applies' => fn($q) => $q->select('id')]) ->get('id') ->pluck('applies') ->flatten(); } public function bookmarks(): BelongsToMany { return $this->belongsToMany(Volunteer::class, 'company_has_bookmarks'); } public function city(): BelongsTo { return $this->belongsTo(City::class); } public function size(): BelongsTo { return $this->belongsTo(Size::class); } public function logoMedia(): MorphOne { return $this->morphOne(Media::class, 'model')->where('collection_name', 'logo'); } // ACCESSORS public function getLogoAttribute(): string { return $this->getLogo(); } public function getIconAttribute(): string { return $this->getLogo('icon'); } public function getNameAttribute(string $name = null): ?string { return $name ?? $this->user->name; } public function getEmailAttribute(string $email = null): string { return $email ?? $this->user->email; } public function getEmploymentAttribute(): string { return ($this->title ? "$this->title , " : '') . $this->size->name; } public function getLocationAttribute(): string { $c = $this->city; $name = $c->name; if ($c->name !== $c->county) $name .= ", $c->county"; return "$name $c->state_id"; } public function getIsSubscribedAttribute(): bool { return $this->subscribed(); } } <file_sep>/database/migrations/2020_11_27_194510_create_volunteer_has_bookmarks_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVolunteerHasBookmarksTable extends Migration { public function up() { Schema::create('volunteer_has_bookmarks', function (Blueprint $table) { $table->foreignId('volunteer_id')->constrained('volunteers')->cascadeOnDelete(); $table->foreignId('vacancy_id')->constrained('vacancies')->cascadeOnDelete(); }); } public function down() { Schema::dropIfExists('volunteer_has_bookmarks'); } } <file_sep>/modules/Frontend/Http/Controllers/Auth/RegisterController.php <?php namespace Modules\Frontend\Http\Controllers\Auth; use Modules\Frontend\Http\Controllers\Controller; use App\Models\User; use Illuminate\Auth\Events\Registered; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; class RegisterController extends Controller { use RegistersUsers; public function __construct() { $this->middleware('guest'); } public function showRegistrationForm() { $this->seo()->setTitle(__('meta.register.title')); $this->seo()->setDescription(__('meta.register.description')); \Route2Class::addClass('bg-decorative'); return view('frontend::auth.register'); } public function register(Request $request) { $data = $request->all(); $this->validator($data)->validate(); event(new Registered($user = $this->create($data))); $this->guard()->login($user); if ($response = $this->registered($request, $user)) { return $response; } return response()->json(['redirect' => $this->redirectPath($user)]); } public function redirectPath(User $user): string { return route('frontend.' . ($user->is_volunteer ? 'volunteer.account.form' : 'company.info.form')); } protected function validator(array $data) { return Validator::make($data, [ 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], 'is_company' => ['required', 'boolean'] //recaptchaFieldName() => recaptchaRuleName() ]); } protected function create(array $data): User { $user = User::create([ 'email' => $data['email'], 'password' => <PASSWORD>($data['<PASSWORD>']), 'type' => $data['is_company'] ? User::COMPANY : User::VOLUNTEER ]); if (!$data['is_company']) { $user->volunteer()->create(); } return $user; } } <file_sep>/database/migrations/2021_01_15_120015_add_resume_views_to_companies.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddResumeViewsToCompanies extends Migration { public function up(): void { Schema::table('companies', function (Blueprint $table) { $table->unsignedSmallInteger('resume_views')->default(0)->after('trial_ends_at'); }); } public function down(): void { Schema::table('companies', function (Blueprint $table) { $table->dropColumn('resume_views'); }); } } <file_sep>/.env.example APP_NAME=Laravel APP_ENV=local APP_KEY= APP_DEBUG=true APP_DOMAIN=simbok.loc APP_URL=http://localhost ADMIN_DOMAIN="admin.${APP_DOMAIN}" LOG_CHANNEL=daily DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD= BROADCAST_DRIVER=log CACHE_DRIVER=file QUEUE_CONNECTION=database SESSION_DRIVER=file SESSION_LIFETIME=120 SESSION_DOMAIN=".${APP_DOMAIN}" REDIS_HOST=127.0.0.1 REDIS_PASSWORD=<PASSWORD> REDIS_PORT=6379 MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=<PASSWORD> MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=null MAIL_FROM_NAME="${APP_NAME}" AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= AWS_DEFAULT_REGION=us-east-1 AWS_BUCKET= PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= PUSHER_APP_CLUSTER=mt1 MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" GOOGLE_ID= GOOGLE_SECRET= FACEBOOK_ID= FACEBOOK_SECRET= TELESCOPE_ENABLED=false INITIAL_USER_NAME= INITIAL_USER_EMAIL= INITIAL_USER_PASSWORDHASH= VACANCIES_COMPANY_ID= CONTACT_EMAILS= DEBUGBAR_EMAIL= CASHIER_MODEL= CASHIER_CURRENCY= CASHIER_LOGGER= STRIPE_KEY= STRIPE_SECRET= STRIPE_WEBHOOK_SECRET= PLAN_1_ID= PLAN_2_ID= PLAN_3_ID= PLAN_4_ID= <file_sep>/modules/Frontend/Http/Controllers/ArticleController.php <?php namespace Modules\Frontend\Http\Controllers; use App\Models\Blog\Article; use App\Models\Blog\Category; use Modules\Frontend\Http\Resources\ArticleResource; use Modules\Frontend\Repositories\ArticleRepository; use Spatie\SchemaOrg\Schema; class ArticleController extends Controller { protected ArticleRepository $repository; public function __construct() { $this->repository = app(ArticleRepository::class); } public function index(Category $category = null) { $title = __('meta.blog.index.title'); $description = __('meta.blog.index.description'); if ($category) { $title = __('meta.blog.category.title', ['name' => $category->name]); $description = __('meta.blog.category.description', ['name' => $category->name]); } $this->seo()->setTitle($title); $this->seo()->setDescription($description); $query = $category ? $category->articles() : Article::query(); $articles = $query->published() ->withImage() ->with(['category' => fn($q) => $q->select(['id', 'slug'])]) ->orderByDesc('id') ->paginate(6, ['id', 'category_id', 'title', 'slug', 'excerpt']); $articles = ArticleResource::collection($articles); if (request()->expectsJson()) return $articles; share(compact('articles')); $categories = $this->repository->getCategories($category); return view('frontend::articles.index', compact('categories', 'category')); } public function show(Category $category, Article $article) { $this->seo()->setTitle($article->meta_title ?? "$article->title | Simbock", false); $this->seo()->setDescription($article->meta_description ?? __('meta.blog.show.description', ['name' => $article->title])); $articleSchema = Schema::blogPosting() ->headline($article->title) ->image($article->image) ->url($article->link) ->articleBody($article->body) ->datePublished($article->created_at) ->dateModified($article->updated_at) ->author(Schema::person()->name('Simbock')) ->publisher(Schema::organization() ->name('Simbock') ->logo(Schema::imageObject()->url(asset('dist/img/logo.svg')))); $categories = $this->repository->getCategories($category); return view('frontend::articles.show', compact('categories', 'category', 'article', 'articleSchema')); } } <file_sep>/app/Models/Volunteers/Surveys/Source.php <?php namespace App\Models\Volunteers\Surveys; use Illuminate\Database\Eloquent\Model; class Source extends Model { public $timestamps = false; protected $table = 'volunteer_survey_sources'; protected $fillable = ['name']; } <file_sep>/modules/Admin/config.php <?php return [ 'domain' => env('ADMIN_DOMAIN') ]; <file_sep>/webpack.mix.js const mix = require('laravel-mix') const config = require('./webpack.config') require('laravel-mix-svg-vue') require('laravel-mix-merge-manifest') mix.webpackConfig({ output: {chunkFilename: 'dist/js/chunks/[name].js?id=[chunkhash]'}, ...config }) mix.options({processCssUrls: false}) mix.sass('modules/Frontend/resources/scss/app.scss', 'public/dist/css') mix.copy('modules/Frontend/resources/layout/src/img', 'public/dist/img') mix.copy('modules/Frontend/resources/layout/src/favicon', 'public/favicon') mix.copy('modules/Frontend/resources/layout/src/fonts', 'public/dist/fonts') mix.ts('modules/Frontend/resources/js/app.js', 'public/dist/js/').vue() .extract(['vue', 'axios', 'dayjs']) .svgVue({ svgPath: 'modules/Frontend/resources/layout/src/svg', }) if (mix.inProduction()) { mix.version() } else { mix.sourceMaps() } mix.disableNotifications() .mergeManifest() <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/WorkExperienceController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Http\Controllers\Controller; use App\Models\Volunteers\WorkExperience; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Requests\Volunteer\WorkExperienceRequest; class WorkExperienceController extends Controller { use HasVolunteer; public function store(WorkExperienceRequest $request): JsonResponse { $workExperience = $this->volunteer()->workExperiences()->create($request->validated()); $this->volunteer()->calculateCompleteness(); return response()->json(['message' => 'Work experience has been added.', 'id' => $workExperience->id]); } public function update(WorkExperienceRequest $request, WorkExperience $workExperience): JsonResponse { $workExperience->update($request->validated()); $this->volunteer()->calculateCompleteness(); return response()->json(['message' => 'Work experience has been updated.', 'id' => $workExperience->id]); } public function destroy(WorkExperience $workExperience): JsonResponse { $workExperience->delete(); $this->volunteer()->calculateCompleteness(); return response()->json(['message' => 'Work experience has been deleted.']); } } <file_sep>/app/Models/Volunteers/WorkExperience.php <?php namespace App\Models\Volunteers; use Illuminate\Database\Eloquent\Model; class WorkExperience extends Model { const CREATED_AT = null; const UPDATED_AT = null; protected $table = 'volunteer_work_experiences'; protected $fillable = ['title', 'company', 'start', 'end', 'description']; } <file_sep>/modules/Admin/Http/Controllers/Traits/CRUDController.php <?php namespace Modules\Admin\Http\Controllers\Traits; /** * @property string $resource */ trait CRUDController { protected function listing() { return view('admin::crud.index', ['resource' => $this->resource]); } protected function form() { return view('admin::crud.form', ['resource' => $this->resource]); } } <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/HasVolunteer.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Models\Volunteers\Volunteer; use Auth; trait HasVolunteer { protected ?Volunteer $volunteer = null; protected function volunteer(): Volunteer { if (!$this->volunteer) { $this->volunteer = Auth::getUser()->volunteer; } return $this->volunteer; } } <file_sep>/modules/Frontend/Notifications/Company/VacancyApplied.php <?php namespace Modules\Frontend\Notifications\Company; use App\Models\Vacancy; use App\Models\Volunteers\Volunteer; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; class VacancyApplied extends Notification implements ShouldQueue { use Queueable; protected Vacancy $vacancy; protected Volunteer $volunteer; public function __construct(Vacancy $vacancy, Volunteer $volunteer) { $this->vacancy = $vacancy; $this->volunteer = $volunteer; } public function via($notifiable): array { return ['mail']; } public function toMail($notifiable): MailMessage { $name = $this->volunteer->name; $vacancyTitle = $this->vacancy->title; return (new MailMessage) ->line("Volunteer $name has applied your vacancy \"$vacancyTitle\".") ->action('See volunteer\'s account', route('frontend.volunteers.show', $this->volunteer->id)); } } <file_sep>/database/seeds/Jobs/BenefitsSeeder.php <?php use App\Models\Jobs\Benefit; use Illuminate\Database\Seeder; class BenefitsSeeder extends Seeder { public function run() { $benefist = [ 'Medical Insurance', 'Dental Insurance', 'Vision Insurance', '401K', 'Life Insurance' ]; foreach ($benefist as $name) Benefit::create(compact('name')); } } <file_sep>/database/seeds/JobsTablesSeeder.php <?php use Illuminate\Database\Seeder; class JobsTablesSeeder extends Seeder { public function run() { $this->call(SectorsSeeder::class); $this->call(HoursSeeder::class); $this->call(TypesSeeder::class); $this->call(SizesSeeder::class); $this->call(BenefitsSeeder::class); } } <file_sep>/database/seeds/VacanciesSeeder.php <?php use App\Models\Jobs\Benefit; use App\Models\Jobs\Hour; use App\Models\Jobs\Incentive; use App\Models\Jobs\Skill; use App\Models\Vacancy; use Illuminate\Database\Seeder; class VacanciesSeeder extends Seeder { public function run() { factory(Vacancy::class, 10)->create()->each(function (Vacancy $vacancy) { $vacancy->hours()->saveMany(Hour::inRandomOrder()->limit(rand(1, 2))->get()); $vacancy->benefits()->saveMany(Benefit::inRandomOrder()->limit(2)->get()); $vacancy->incentives()->saveMany(Incentive::inRandomOrder()->limit(2)->get()); $vacancy->skills()->saveMany(Skill::inRandomOrder()->limit(3)->get()); }); } } <file_sep>/app/Models/Language.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Language extends Model { const CREATED_AT = null; const UPDATED_AT = null; protected $fillable = ['name', 'code']; public const BASIC = 'BASIC'; public const INTERMEDIATE = 'INTERMEDIATE'; public const FLUENT = 'FLUENT'; public static $fluencies = [ self::BASIC => 'Basic', self::INTERMEDIATE => 'Intermediate', self::FLUENT => 'Fluent' ]; } <file_sep>/modules/Admin/Repositories/Jobs/RoleRepository.php <?php namespace Modules\Admin\Repositories\Jobs; use App\Models\Jobs\Sector; class RoleRepository { public function shareForCRUD() { $sectors = Sector::ordered()->get(['name', 'id'])->values(); share(compact('sectors')); } } <file_sep>/database/factories/CompanyFactory.php <?php /** @var Factory $factory */ use App\Models\Company; use App\Models\Jobs\Sector; use App\Models\Jobs\Size; use App\Models\Map\US\City; use App\Models\Map\US\State; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(Company::class, function (Faker $faker) { return [ 'name' => $faker->unique()->company, 'title' => $faker->unique()->sentence(2), 'sector_id' => Sector::inRandomOrder()->first()->id, 'description' => $faker->unique()->sentence(16), 'size_id' => Size::inRandomOrder()->first()->id, 'address' => $faker->address, 'address_2' => $faker->address, 'city_id' => City::inRandomOrder()->first()->id, 'state_id' => State::inRandomOrder()->first()->id, 'zip' => $faker->numberBetween(0, 99999), 'phone' => $faker->phoneNumber, 'email' => $faker->email, 'social' => [ 'website' => $faker->url, 'linkedin' => $faker->url, 'twitter' => $faker->url, 'facebook' => $faker->url, 'instagram' => $faker->url, 'youtube' => $faker->url, 'reddit' => $faker->url, 'pinterest' => $faker->url, 'quora' => $faker->url ] ]; }); <file_sep>/modules/Frontend/Http/Controllers/Volunteer/Account/JobController.php <?php namespace Modules\Frontend\Http\Controllers\Volunteer\Account; use App\Http\Controllers\Controller; use Illuminate\Http\JsonResponse; use Modules\Frontend\Http\Requests\Volunteer\JobRequest; class JobController extends Controller { use HasVolunteer; public function update(JobRequest $request): JsonResponse { $volunteer = $this->volunteer(); $volunteer->update([ 'job_title' => $request->job_title ]); $volunteer->locations()->sync($request->locations); $volunteer->types()->sync($request->types); $volunteer->hours()->sync($request->hours); $sectors = $request->sectors; $volunteer->roles() ->select(['sector_id', 'role_id']) ->distinct() ->get() ->groupBy('sector_id') ->keys() ->each(function (int $sector) use ($volunteer, $sectors) { if (!array_key_exists($sector, $sectors)) { $volunteer->roles()->where('sector_id', $sector)->detach(); } }); foreach ($sectors as $sector) { $roles = []; foreach ($sector['roles'] as $role) { $roles[$role] = ['sector_id' => $sector['id']]; } $volunteer->roles()->wherePivot('sector_id', $sector['id'])->sync($roles); } $this->volunteer()->calculateCompleteness(); return response()->json([ 'message' => 'Desired job has been saved.', ]); } public function destroy(): JsonResponse { $volunteer = $this->volunteer(); $volunteer->update(['job_title' => null]); $volunteer->locations()->detach(); $volunteer->types()->detach(); $volunteer->hours()->detach(); $volunteer->roles()->detach(); $this->volunteer()->calculateCompleteness(); return response()->json(['message' => 'Desired job has been deleted.']); } } <file_sep>/modules/Frontend/resources/js/store/modules/index.js import volunteer from "./volunteer" export default { volunteer } <file_sep>/app/Models/Chats/Chat.php <?php namespace App\Models\Chats; use App\Models\Company; use App\Models\Vacancy; use App\Models\Volunteers\Volunteer; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; class Chat extends Model { public const UPDATED_AT = null; protected $fillable = ['volunteer_id', 'company_id', 'vacancy_id']; public function messages(): HasMany { return $this->hasMany(Message::class); } public function volunteer(): BelongsTo { return $this->belongsTo(Volunteer::class); } public function company(): BelongsTo { return $this->belongsTo(Company::class); } public function vacancy(): BelongsTo { return $this->belongsTo(Vacancy::class); } } <file_sep>/modules/Frontend/resources/js/plugins/broadcasting.js import Vue from 'vue' import VueEcho from 'vue-echo' window.Pusher = require('pusher-js') Vue.use(VueEcho, { broadcaster: 'pusher', key: 'Simbock', wsHost: window.location.hostname, wsPort: 6001, wssPort: 6001, forceTLS: process.env.MIX_APP_ENV !== 'local' })
9fe0893495e242ec5ab069b6bfc62329ee1a375c
[ "JavaScript", "Markdown", "INI", "PHP", "Shell" ]
196
JavaScript
extrem7/Simbock
6cdcf0d99c7d15c4bfc152159c1b3b1f03423efe
80e37e3bb0e0f3fb71303e5b56e8a7b599787a12
refs/heads/main
<repo_name>codylane/devops-nginx<file_sep>/docker-compose.yml --- version: '3.8' networks: nginx: services: nginx: build: context: '.' dockerfile: 'Dockerfile-nginx' args: LANG: "${LANG}" image: "devops-nginx" hostname: "${NGINX_HOST}" container_name: "${NGINX_HOST}" ports: - "${NGINX_EXPOSED_PORT}:${NGINX_PORT}" - "443:443/tcp" networks: - nginx environment: NGINX_HOST: "${NGINX_HOST}" NGINX_PORT: "${NGINX_PORT}" LANG: "${LANG}" volumes: - './docker/etc/letsencrypt:/etc/letsencrypt' - './docker/etc/nginx/templates:/etc/nginx/templates' - './docker/var/www:/var/www:ro' <file_sep>/docker-entrypoint.d/40-create-openssl-cert-and-key.sh #!/usr/bin/env bash set -e ################################################################### # Script: create-openssl-cert-and-key.sh # Author: <NAME> # # Description: # This creates a self-signed openssl key and certificate to be # used with local development. # # Usage: # The following variables are configurable # # KEY_DIR: # The path where the crt and key will be # enerated. # Default. '.' # # KEY_EXPIRE_AFTER_DAYS: # The number of days that key is valid for # Default: 365 # # KEY_NAME: # The name of the certificate. # Default: FQDN # # KEY_COUNTRY: # The certificates default Country: # Default: US # KEY_STATE: # The certificates default State: # Default: DC # # KEY_LOCATION: # The certificates default Location: # Default: DC # # KEY_ORG: # The certificates default Organization: # Default: HOME # # KEY_ORG_UNIT: # The certificates default Organization Unit: # #Default: IT Department # # KEY_CN: # The certificates Common Name: # Default: FQDN # ################################################################### KEY_DIR="${KEY_DIR:-.}" KEY_EXPIRE_AFTER_DAYS=365 KEY_TYPE="rsa" KEY_BITS=4096 KEY_NAME="${KEY_NAME:-$(hostname -f)}" # KEY_COUNTRY="${KEY_COUNTRY:-US}" # KEY_STATE="${KEY_STATE:-DC}" # KEY_LOCATION="${KEY_LOCATION:-DC}" # KEY_ORG="${KEY_ORG:-HOME}" # KEY_ORG_UNIT="${KEY_ORG:-IT Department}" KEY_CN="${KEY_CN:-${KEY_NAME}}" [ -f "${KEY_DIR}/${KEY_NAME}.crt" ] && exit 0 cd /etc/nginx openssl req \ -x509 \ -nodes \ -days ${KEY_EXPIRE_AFTER_DAYS} \ -newkey "${KEY_TYPE}:${KEY_BITS}" \ -keyout "${KEY_DIR}/${KEY_NAME}.key" \ -out "${KEY_DIR}/${KEY_NAME}.crt" \ -subj "/CN=${KEY_CN}" cat > /etc/nginx/conf.d/ssl.conf <<EOF server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; ssl_certificate /etc/nginx/${HOSTNAME}.crt; ssl_certificate_key /etc/nginx/${HOSTNAME}.key; server_name ${HOSTNAME} localhost; access_log /var/log/nginx/default.access.log main; root /var/www/default; } EOF <file_sep>/Makefile CONTAINER = nginx ENVIRONMENT = common .PHONY: build .PHONY: clean .PHONY: init .PHONY: log .PHONY: run .PHONY: shell .PHONY: status all: clean init build run build: @. envs/$(ENVIRONMENT); \ docker-compose build $(CONTAINER) clean: @. envs/$(ENVIRONMENT); \ docker-compose down --remove-orphans; \ docker-compose rm -fsv $(CONTAINER); \ rm -rf docker/etc/letsencrypt/csr/*.pem init: @. envs/$(ENVIRONMENT); \ ./init.sh; \ mkdir -p $${HOME}/.aws; \ [ -f $${HOME}/.aws/config ] || echo "[default]\nregion = $${AWS_REGION}" > $${HOME}/.aws/config; \ [ -f $${HOME}/.aws/credentials ] || echo "[default]\naws_access_key_id = $${AWS_ACCESS_KEY_ID}\naws_secret_access_key = $${AWS_SECRET_ACCESS_KEY}" > $${HOME}/.aws/credentials; \ chmod 0600 $${HOME}/.aws/* log: @. envs/$(ENVIRONMENT); \ docker-compose logs $(CONTAINER) run: build @. envs/$(ENVIRONMENT); \ docker-compose up -d $(CONTAINER) shell: @. envs/$(ENVIRONMENT); \ docker-compose exec $(CONTAINER) bash status: @. envs/$(ENVIRONMENT); \ docker-compose ps --all prereqs: command -v docker >>/dev/null docker info >>/dev/null command -v docker-compose >>/dev/null command -v dig >>/dev/null command -v aws >>/dev/null aws ec2 describe-instances ## EC2 targets ec2: init ec2_bootstrap ec2_provision ec2_bootstrap: @. envs/$(ENVIRONMENT); \ ansible-playbook -vvv bootstrap.yml ec2_provision: @. envs/$(ENVIRONMENT); \ ansible-playbook -vvv provision.yml <file_sep>/test-requirements.txt -r requirements.txt hacking==4.0.0 <file_sep>/README.md devops-nginx ------------ [![Build Status](https://travis-ci.com/codylane/devops-nginx.svg?branch=main)](https://travis-ci.com/codylane/devops-nginx) # Getting Started - Ensure that you have docker and the docker client libraries installed. - https://docs.docker.com/get-docker/ - Ensure that `docker-compose` is installed. - https://docs.docker.com/compose/install/ - Ensure that `dig` is installed - Ensure awscli is installed - https://aws.amazon.com/cli/ # Environment Variables | Environment variable | Default | Required | Description | | ---------------------- | ------------- | ------------- | ----------------------------------------------------------- | | LANG | en_US.UTF-8 | Y | Locale | | NGINX_HOST | devops-nginx | Y | The DNS hostname to use for serving content | | NGINX_PORT | 80 | Y | The TCP port (inside the container) | | NGINX_EXPOSED_PORT | 80 | Y | The TCP port served via your docker host (external facing) | | EXTERNAL_IP | | N | The external ip address that may be used to serve your content | | AWS_ACCESS_KEY_ID | "${AWS_ACCESS_KEY_ID:-}" | Y | This is your AWS access key id provided in the IAM console | | AWS_SECRET_ACCESS_KEY | "${AWS_SECRET_ACCESS_KEY:-}" | Y | This is your AWS secret access key provided in the IAM console | | AWS_REGION | "${AWS_REGION:-us-east-2}" | N | This is the default AWS region you want to use | | MY_DOMAIN | "${MY_DOMAIN:-codylane-devops.com}" | Y | The domain to use when configuring NGINX. `codylane-devops.com` is a private domain | ## The following variables are customizable outside of [envs/common](envs/common) - `AWS_ACCESS_KEY_ID` - `AWS_SECRET_ACCESS_KEY` - `AWS_REGION` - `MY_DOMAIN` # Usage - Before running the container, we need to first source an environment configuration. - All environment variables for this demo are controlled in an environment directory called `envs` and configuration can be inherited or modified as desired. Please see [Environment Variables](#envrionment-variables) for all the variables you can set. - Once we have the right configuration files in place, we can source that environment. ``` . envs/common ``` - Next, we initialize the awscli to use our AWS account. - **NOTE:** This utility is not smart enough to update AWS credentials if the files already exist on disk. If they do, you will need to modify them by hand. See the [Makefile](Makefile) for details. ``` make init ``` - Then we source source the python environment that will provision our infrastructure in EC2. ``` . ./init.sh ``` ### How to deploy this code to EC2 ``` make ec2 ``` ### How to run the services on your local workstation #### Ensure all the prerequisites are installed ``` make prereqs ``` #### A one-shot command to [clean, init, build, run] the container ``` make ``` #### Build the container - This step creates the base image for serving up our demo via nginx. ``` make build ``` #### Remove and delete the container - **NOTE:** This step does not delete files or directories for the bind mounted storage as noted in the `volumes` section of [docker-compose.yml](docker-compose.yml) ``` make clean ``` #### Show the logs for the running container ``` make log ``` #### Running the container also invokes [build] ``` make run ``` #### Interactively login to the container via a shell - **NOTE:** This step assumes the container is running. ``` make shell ``` #### Show status of the container ``` make status ``` # Validation - If provisioning in EC2 was successful you should be able to open your browser to the following public endpoints assuming this is running from the same workstation that you deployed this code. - **NOTE:** due to time constraints the SSL cert is a self-signed certificate that is generated when the container is started. - https://ec2-nginx-demo.us-east-2.compute.amazonaws.com/ - http://ec2-nginx-demo.us-east-2.compute.amazonaws.com/ <file_sep>/init.sh #!/usr/bin/env bash CMD="${BASH_SOURCE[0]}" BIN_DIR="${CMD%/*}" cd ${BIN_DIR} BIN_DIR="${PWD}" MINICONDA_INSTALL_DIR="${HOME}/miniconda3" export USER_UID=$(id -u $USER) export USER_GID=$(id -g $USER) PROJNAME="${PROJNAME:-${BIN_DIR##*/}}" CONDA_ENV_PYTHON="3.9" CONDA_ENV_NAME="${PROJNAME}-${CONDA_ENV_PYTHON}" OS_TYPE="${OS_TYPE:-}" export PATH="${MINICONDA_INSTALL_DIR}/bin:$PWD/bin:$PWD/:$PATH" BLACK="\033[0;30m" BLACKBOLD="\033[1;30m" RED="\033[0;31m" REDBOLD="\033[1;31m" GREEN="\033[0;32m" GREENBOLD="\033[1;32m" YELLOW="\033[0;33m" YELLOWBOLD="\033[1;33m" BLUE="\033[0;34m" BLUEBOLD="\033[1;34m" PURPLE="\033[0;35m" PURPLEBOLD="\033[1;35m" CYAN="\033[0;36m" CYANBOLD="\033[1;36m" WHITE="\033[0;37m" WHITEBOLD="\033[1;37m" get_os_type() { case "$(uname -s)" in Darwin) OS_TYPE="osx" OS_ARCH="$(uname -m)" return 0 ;; Linux) OS_TYPE="linux" OS_ARCH="$(uname -m)" return 0 ;; *) return 1 ;; esac } has_conda_env() { conda list -n "${1}" 2>&1 >>/dev/null 2>&1 } install_miniconda_linux64() { local MINICONDA_INSTALLER="Miniconda3-latest-Linux-x86_64.sh" local MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh" curl -LO ${MINICONDA_URL} chmod 755 ${MINICONDA_INSTALLER} ./${MINICONDA_INSTALLER} -b- u -p ${MINICONDA_INSTALL_DIR} } install_miniconda_osx64() { local MINICONDA_INSTALLER="Miniconda3-latest-MacOSX-x86_64.sh" local MINICONDA_URL="https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh" curl -LO ${MINICONDA_URL} chmod 755 ${MINICONDA_INSTALLER} ./${MINICONDA_INSTALLER} -b -u -p ${MINICONDA_INSTALL_DIR} } err() { echo "ERR: $* exiting" >&2 exit 1 } info() { local MSG_COLOR="${1:-$WHITE}" shift echo -en "${MSG_COLOR}${@}\033[0m" echo } activate_ci() { info "$GREEN" "Activating CI..." echo run_pip_if_recent_requirements_change "${BIN_DIR}/test-requirements.txt" } activate_prod() { info "$GREEN" "Activating PROD..." echo } activate_env() { local ACTIVATE_ENV="${1}" case "$ACTIVATE_ENV" in prod|production) activate_prod ;; *) activate_ci ;; esac } filetime_last_change_in_seconds() { stat -c %Z "${1}" } get_file_contents() { cat "${1}" 2>>/dev/null || echo "" } get_cache_filename() { local _default_cache="${1}" is_conda_env_active && _default_cache="${1}-${CONDA_DEFAULT_ENV}" || _default_cache="${1}" local CACHE_FILENAME="${BIN_DIR}/.${_default_cache##*/}.lcts" echo "${CACHE_FILENAME}" } update_cache_file() { local DEFAULT_CACHE_FILENAME=$(get_cache_filename "${1}") local CHECK_FILENAME="${1}" local CACHE_FILENAME="${2:-${DEFAULT_CACHE_FILENAME}}" local LAST_CHANGE_TIME_SECS=$(filetime_last_change_in_seconds "${CHECK_FILENAME}") info "$GREEN" "update_cache_file: DEFAULT_CACHE_FILENAME=${DEFAULT_CACHE_FILENAME} CACHE_FILENAME=$CACHE_FILENAME" echo "${LAST_CHANGE_TIME_SECS}" > "${CACHE_FILENAME}" echo $LAST_CHANGE_TIME_SECS } cache_file_last_change_in_seconds() { [ -z "${1}" ] && err "Please pass a filename path as the first argument" local CHECK_FILENAME="${1}" local CACHE_FILENAME=$(get_cache_filename "${1}") # get last change time local LAST_CHANGE_TIME_SECS=$(filetime_last_change_in_seconds "${CHECK_FILENAME}") # if cache file does not exist, display seconds since list last change and return if [ ! -f "${CACHE_FILENAME}" ]; then echo $LAST_CHANGE_TIME_SECS return fi # cache file exists, get cache file last change time stamp (LCTS) local CACHE_FILE_LCTS=$(get_file_contents "${CACHE_FILENAME}") local DELTA_LCTS=$((LAST_CHANGE_TIME_SECS - CACHE_FILE_LCTS)) [ $DELTA_LCTS -lt 0 ] && DELTA_LCTS=$((DELTA_LCTS * -1)) echo $DELTA_LCTS } debug_console() { echo "#############| Entering DEBUG mode |####################"; CMD= set -x while [ "${CMD}" != "exit" ]; do read -p "> " CMD case "${CMD}" in vars) (set -o posix ; set) ;; exit|quit) ;; *) eval "${CMD}" ;; esac done set +x echo "#############| End of DEBUG mode |####################"; } is_conda_env_active() { # If not NULL, environment is active, rc=0, otherwise rc=1 [ -n ${CONDA_DEFAULT_ENV} ] } run_pip_if_recent_requirements_change() { local REQUIREMENTS_FILE="${1}" local CACHE_FILE= info "${GREEN}" "The active conda environment is: '${CONDA_DEFAULT_ENV}'" CACHE_FILE=$(get_cache_filename "${REQUIREMENTS_FILE}") info "${GREEN}" "cache state file: ${CACHE_FILE}" [ -f "${REQUIREMENTS_FILE}" ] || err "The requirements file: ${REQUIREMENTS_FILE} does not exist" info "${GREEN}" "REQUIREMENTS_FILE=$REQUIREMENTS_FILE" local CACHE_FILE_LCTS=$(cache_file_last_change_in_seconds "${REQUIREMENTS_FILE}") info "${GREEN}" "CACHE_FILE_LCTS=$CACHE_FILE_LCTS" if [ ${CACHE_FILE_LCTS} -ne 0 ]; then info "${GREEN}" "Refreshing requirements deps" update_cache_file "${REQUIREMENTS_FILE}" "${CACHE_FILE}" >>/dev/null pip install -r "${REQUIREMENTS_FILE}" [ -f setup.py ] && pip install -e . || true fi } init_osx() { info "$YELLOWBOLD" "WARNING: there is no handler for osx yet" case "${OS_ARCH}" in x86_64) command -v conda >>/dev/null || install_miniconda_osx64 ;; *) info "$REDBOLD" "WARNING: OS arch ${OS_ARCH} is not currently supported" return 1 ;; esac } init_linux() { info "$GREEN" "Initializing linux deps" case "${OS_ARCH}" in x86_64) command -v conda >>/dev/null || install_miniconda_linux64 ;; *) info "$REDBOLD" "WARNING: OS arch ${OS_ARCH} is not currently supported" return 1 ;; esac } coverage_report() { local test_module="${1:-tests/}" [ "$#" -gt 1 ] && shift coverage run -m pytest -vvrs ${@} ${test_module} || true coverage report --show-missing } bandit_report() { bandit --ini tox.ini -r "$@" } create_conda_env() { local NAME="${1}" local PYTHON="${2}" [ -z "${1}" ] && err "Please pass NAME as first argument to create_conda_env" [ -z "${2}" ] && err "Please pass PYTHON as second argument to create_conda_env" conda create -y -n "${NAME}" python="${PYTHON}" # activate conda environment conda activate ${NAME} # remove last change time stamps rm -f .*.lcts run_pip_if_recent_requirements_change "${BIN_DIR}/requirements.txt" conda deactivate } remove_conda_envs() { command -v conda >>/dev/null MINICONDA_INSTALL_DIR="${HOME}/miniconda3" conda deactivate find "${MINICONDA_INSTALL_DIR}/envs" -name "${PROJNAME}*" -type d | sort | while read env_name do rm -rf "${env_name}" done } ## main ## [ -z "${CONDA_ENV_NAME}" ] && err "Please set CONDA_ENV_NAME" [ -z "${PROJNAME}" ] && err "please set PROJNAME" info "$GREEN" "BIN_DIR=${BIN_DIR}" info "$GREEN" "CONDA_ENV_NAME=$CONDA_ENV_NAME" info "$GREEN" "CONDA_ENV_PYTHON=$CONDA_ENV_PYTHON" get_os_type || err "The OS type $OS_TYPE is not supported for local development" eval "init_${OS_TYPE}" [ -f ${MINICONDA_INSTALL_DIR}/etc/profile.d/conda.sh ] && . ${MINICONDA_INSTALL_DIR}/etc/profile.d/conda.sh [ -f /usr/local/miniconda3/etc/profile.d/conda.sh ] && . /usr/local/miniconda3/etc/profile.d/conda.sh [ -f /etc/profile.d/miniconda.sh ] && . /etc/profile.d/miniconda.sh [ -f /usr/local/Caskroom/miniconda/base/etc/profile.d/conda.sh ] && . /usr/local/Caskroom/miniconda/base/etc/profile.d/conda.sh [ $(find . -maxdepth 1 -name '*.lcts' -type f -print | wc -l) -eq 0 ] && remove_conda_envs || true has_conda_env "${CONDA_ENV_NAME}" || create_conda_env "${CONDA_ENV_NAME}" "${CONDA_ENV_PYTHON}" conda activate ${CONDA_ENV_NAME} run_pip_if_recent_requirements_change "${BIN_DIR}/requirements.txt" activate_env "${1:-ci}" export PATH="${CONDA_PREFIX}/bin:${PATH}" <file_sep>/requirements.txt ansible==3.2.0 boto3==1.17.53
a052bfdf59b4c492bea6614ded7555398280309f
[ "YAML", "Markdown", "Makefile", "Text", "Shell" ]
7
YAML
codylane/devops-nginx
bbbeabdbe544a2d004a9123679e2d7b6de90502d
8d7da8e5db2c3846987e2daa3765b324f094a1a9
refs/heads/master
<repo_name>agencyy/ads<file_sep>/back/routes/api.php <?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ // Route::middleware('auth:api')->get('/user', function (Request $request) { // return $request->user(); // }); Route::post('/user/signup', [ 'uses' => 'AuthController@signup' ]); //socialite Route::get('/login/{service}', [ 'uses' => 'AuthController@redirect' ]); Route::get('/login/{service}/callback', [ 'uses' => 'AuthController@callback' ]); //////////// Route::post('/user/signin', [ 'uses' => 'AuthController@signin' ]); Route::post('/user/test', function(){ return 'test'; }); Route::group(['middleware'=>['auth.jwt']], function(){ //token authentication Route::post('/test', function(){ return response()->json(['test']); }); Route::post('/user', [ 'uses' => 'UserController@index' ]); });<file_sep>/back/app/Models/User.php <?php namespace App\Models; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'first_name', 'last_name', 'email', 'password', 'picture_url', 'birthday', 'gender', 'slug' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function social(){ return $this->hasMany(UserSocial::class); } public function adAccount(){ return $this->hasMany(AdAccount::class); } public function business(){ return $this->hasMany(Business::class); } public function hasSocialLinked($service){ return (bool) $this->social->where('service', $service)->count(); } public function hasAdAccountLinked($ad_account_id){ return (bool) $this->adAccount->where('ad_account_id', $ad_account_id)->count(); } public function hasBusinessLinked($business_id){ return (bool) $this->business->where('business_id', $business_id)->count(); } } <file_sep>/client/src/app/services/http.service.ts import { Injectable } from '@angular/core'; import { Http, Headers, Response } from '@angular/http'; import { DataService } from './data.service'; @Injectable() export class HttpService { server_url = "http:\/\/back.dev/"; constructor(private http:Http) { } post(uri, data, callback){ var url = this.server_url+uri; var headers = { headers: new Headers({ // 'X-Requested-With':'XMLHttpRequest', // 'Content-Type':'application/json', // 'Accept':'application/json', 'Authorization': 'Bearer '+ this.getAuthToken(), }) //this doest work from tutorial } this.http.post(url, data, headers).subscribe( (res: any) => { // var data = JSON.stringify(res._body); var data = JSON.parse(res._body); callback(data) } ); } get(uri, callback){ var url = this.server_url+uri; this.http.get(url).subscribe( (res: any) => { var data = JSON.parse(res._body); callback(data) } ); } getAuthToken(){ return localStorage.getItem('token'); } } <file_sep>/client/src/app/services/auth.service.ts import { Injectable } from '@angular/core'; import { HttpService } from './http.service'; import { DataService } from './data.service'; import { UtilService } from './util.service'; @Injectable() export class AuthService { constructor(private dataService: DataService, private httpService: HttpService, private utilService: UtilService){} decodeAuthToken(){ var token = this.dataService.auth_token; var base64Url = token.split('.')[1]; var base64 = base64Url.replace('-','+').replace('_', '/'); return JSON.parse(window.atob(base64)); } login(email, password){ return new Promise(resolve => { this.httpService.post('api/user/signin', {email:email, password:<PASSWORD>}, (data)=>{ this.dataService.auth_token = data.token; localStorage.setItem('token', data.token); resolve(); }); }) } testAuth(){ console.log('testing auth'); return new Promise(resolve => { this.httpService.post('api/test', {}, (data)=>{ console.log(data); resolve(); }); }) } getToken(){ return localStorage.getItem('token'); } getSocialRedirectUrl(service){ var uri = 'api/login/'+service; return new Promise(resolve => { this.httpService.get(uri, (data)=>{ resolve(data); }); }); } loginFacebook(){ this.getSocialRedirectUrl('facebook').then((data: any)=>{ window.location.href = data.redirect_url; //this will redirect the the specified url that is in the backend as client url }) } } <file_sep>/client/src/app/services/util.service.ts import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { HttpService } from './http.service'; import { DataService } from './data.service'; @Injectable() export class UtilService { constructor(private router: Router, private dataService: DataService, private httpService: HttpService){} route(url){ this.router.navigate([url]); } returnGetParameter(parameterName) { var result = null, tmp = []; location.search .substr(1) .split("&") .forEach((item) => { tmp = item.split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); }); return result; } } <file_sep>/back/app/Facades/Facebook.php <?php namespace App\Facades; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Client; class Facebook { public static function getLongFacebookToken($short_token){ //this converts the short lived facebook token gotten from login to a long lived token $url = config('services.facebook.graph_url').'/oauth/access_token?grant_type=fb_exchange_token&client_id='.config('services.facebook.client_id').'&client_secret='.config('services.facebook.client_secret').'&fb_exchange_token='.$short_token; $client = new Client(); $res = $client->request('GET', $url); $body = json_decode($res->getBody()); $access_token = $body->access_token; return $access_token; } public static function getAdAccountsArray($service_user){ $accounts = $service_user->user['adaccounts']['data']; return $accounts; } public static function getBusinessesArray($service_user){ $accounts = $service_user->user['businesses']['data']; return $accounts; } }<file_sep>/client/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MdGridListModule, MdInputModule, MdButtonModule, MdCheckboxModule, MdSidenavModule} from '@angular/material'; import { routing } from './app.routing'; import { AppComponent } from './app.component'; //services import { HttpService } from './services/http.service'; import { UtilService } from './services/util.service'; import { DataService } from './services/data.service'; import { AuthService } from './services/auth.service'; //Components import { TestComponent } from './test/test.component'; import { HomeComponent } from './basic/home/home.component'; import { MainMenuComponent } from './partials/main-menu/main-menu.component'; @NgModule({ declarations: [ AppComponent, TestComponent, HomeComponent, MainMenuComponent ], imports: [ BrowserModule, HttpModule, FormsModule, routing, BrowserAnimationsModule, MdGridListModule, MdButtonModule, MdCheckboxModule, MdSidenavModule, MdInputModule, ], providers: [ HttpService, UtilService, DataService, AuthService, ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/back/app/Http/Controllers/AuthController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use App\Models\AdAccounts; use JWTAuth; use Carbon\Carbon; use Socialite; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Client; use Facebook; class AuthController extends Controller { public function signup(Request $request){ $this->validate($request, [ 'name' =>'required', 'email'=> 'required | email | unique:users', 'password'=> '<PASSWORD>' ]); User::create([ 'name' => $request->input('name'), 'email'=> $request->input('email'), 'password'=><PASSWORD>($request->input('password')) ]); } public function signin(Request $request){ $credentials = $request->only('email', 'password'); $expire = ['exp'=> Carbon::now()->addWeek()->timestamp]; try { if (!$token = JWTAuth::attempt($credentials,$expire)){ return response()->json([ 'error' => 'invalid-creds' ], 401); } } catch (JWTException $e) { return response()->json([ 'error' => 'Could not create token' ],500); } return response()->json(compact('token')); } public function redirect($service){ if($service == 'facebook'){ $redirect_url = Socialite::with($service)->fields([ 'first_name', 'last_name', 'email', 'gender', 'birthday', 'adaccounts', 'businesses']) ->scopes([ 'email', 'user_birthday', 'ads_management', 'business_management']) ->stateless()->redirect()->getTargetUrl(); //this allows the transaction to be stateless which will make it work as an api }else{ $redirect_url = Socialite::with($service)->stateless()->redirect()->getTargetUrl(); } return response()->json(['redirect_url'=>$redirect_url]); } public function callback($service, Request $request){ $flow = ''; $long_token = NULL; $error = $request->input('error'); if($error == 'access_denied'){ $flow = $error; return redirect()->to(config('app.client_url') . '?' . 'flow='.$flow);#redirect to angular } $flow = "login"; if($service == 'facebook'){ $serviceUser = Socialite::driver($service)->stateless()->fields(['name','first_name','last_name','email', 'gender','verified','birthday', 'posts','adaccounts', 'businesses'])->user(); $token = $serviceUser->token; $long_token = Facebook::getLongFacebookToken($token); }else{ $serviceUser = Socialite::driver($service)->user(); } $user = $this->getExistingUser($serviceUser, $service); if(!$user){ $flow = "registered"; if($service = 'facebook'){ $user = User::create([ 'email'=> $serviceUser->getEmail(), 'name' => $serviceUser->getName(), 'first_name' => $serviceUser->user['first_name'], 'last_name' => $serviceUser->user['last_name'], 'picture_url' => $serviceUser->avatar, 'gender' => $serviceUser->user['gender'], 'active' => true, 'slug' => str_random(10) ]); }else{ $user = User::create([ 'email'=> $serviceUser->getEmail(), 'name' => $serviceUser->getName(), 'picture_url' => $serviceUser->avatar, 'active' => true, 'slug' => str_random(10), ]); } } if ($this->needsToCreateSocial($user, $service)){ $user->social()->create([ 'social_id' => $serviceUser->getId(), 'service' => $service, 'picture_url' => $serviceUser->avatar ]); } $user->social()->first()->update(['access_token'=>$long_token]); //ad accounts $ad_accounts = Facebook::getAdAccountsArray($serviceUser); foreach($ad_accounts as $ad_account){ $account_id = $ad_account['account_id']; if ($this->needsToCreateAdAccount($user, $account_id)){ $user->adAccount()->create([ 'ad_account_id' => $account_id, 'service'=>$service, ]); } } //Bussiness Accounts $businesses = Facebook::getBusinessesArray($serviceUser); foreach($businesses as $business){ $name = $business['name']; $business_id = $business['id']; if ($this->needsToCreateBusiness($user, $account_id)){ $user->business()->create([ 'business_id' => $business_id, 'name'=>$name, 'service'=>$service, ]); } } $jwt_token = JWTAuth::fromUser($user);//gets the JWT token from the user model json web token for authenticating on the front end return redirect()->to(config('app.client_url') . '?' . 'token=' . $jwt_token . '&flow='.$flow);#redirect to angular client side // return response()->json(['flow'=>$flow, 'token'=>$token, 'URL'=> config('app.client_url')]); } protected function needsToCreateSocial($user, $service){ return !$user->hasSocialLinked($service); } protected function needsToCreateAdAccount($user, $ad_account_id){ return !$user->hasAdAccountLinked($ad_account_id); } protected function needsToCreateBusiness($user, $business_id){ return !$user->hasBusinessLinked($business_id); } public function getExistingUser($serviceUser, $service){ return User::where('email', $serviceUser->getEmail())->orWhereHas('social', function($q) use ($serviceUser, $service){ $q->where('social_id', $serviceUser->getId())->where('service', $service); })->first(); } }
d1a18bbf928dafb1e8509b37bb954916f895d4a4
[ "TypeScript", "PHP" ]
8
PHP
agencyy/ads
0ff4ecdd7b052c9dc20204b9d248ce02f8a6c6db
6cee125cfa5200ffb9942ce459b626d85069b5d1
refs/heads/master
<repo_name>WideChat/hubot-rocketchat-boilerplate<file_sep>/all_scripts/yandex-translator.js 'use strict'; function yandexTranslate (robot) { var pattern = '(?!(@[a-z]*)) (.*)' var rparts = new RegExp(pattern, 'i'); robot.respond(rparts, request); function request (command) { var input = command.match[2].trim(); // Query to detect which language the message is in, either spanish or english var q_detect = { key: process.env.YANDEX_TRANSLATE_API_KEY, text: input, hint: ['es', 'en'] }; command .http('https://translate.yandex.net/api/v1.5/tr.json/detect') .query(q_detect) .header('User-Agent', 'Mozilla/5.0') .get()(detect); function detect (err, res, body) { var parsed = parse(body); if (parsed) { console.log("this is the parsed body: " + JSON.stringify(parsed)); var origin = parsed.lang; } else { command.send("Sorry, could not detect the language of origin."); } var target = ( origin == 'en' ? 'es' : 'en'); var lang = origin + '-' + target var q = { key: process.env.YANDEX_TRANSLATE_API_KEY, lang: lang, text: input }; command .http('https://translate.yandex.net/api/v1.5/tr.json/translate') .query(q) .header('User-Agent', 'Mozilla/5.0') .get()(response); } //var origin = 'en'; //var target = 'es'; function response (err, res, body) { var parsed = parse(body); if (parsed) { command.send(parsed.text); } } } } function parse (json) { try { return JSON.parse(json); } catch (e) { return { text: 'No.' }; } } module.exports = yandexTranslate;
020fa7ab91b4602771ff72d77ebf39a391584a14
[ "JavaScript" ]
1
JavaScript
WideChat/hubot-rocketchat-boilerplate
d4d8daeb193491b10e83ee8627070fabd9dffe0a
4786a146f5e715aa3e0f792ed167ff5a8781b11e
refs/heads/master
<file_sep>import Vue from 'vue' // 直接在组件使用时import UserTool from '@/router/UserTool'引用 let user={} user.saveUser=function(userobj){ // window.sessionStorage.setItem('User',JSON.stringify(userobj)); window.localStorage.setItem('User',JSON.stringify(userobj)); } user.getUser=function(){ // return JSON.parse(window.sessionStorage.getItem('User')||'{}'); return JSON.parse(window.localStorage.getItem('User')||'{}'); } user.deleteUser=function(){ // window.sessionStorage.removeItem('User'); window.localStorage.removeItem('User'); } user.addUser=function(obj){ let user=this.getUser(); //注册时插入 Vue.set(user,'userName',obj.name); Vue.set(user,'userTele',obj.tele); Vue.set(user,'userPassWord',obj.password); Vue.set(user,'userImg',obj.img); Vue.set(user,'userId',obj.id); Vue.set(user,'userLoginTip',obj.logintip); //修改个人信息插入 Vue.set(user,'userSex',obj.sex); Vue.set(user,'userBirthday',obj.birthday); Vue.set(user,'userInterest',obj.interest); Vue.set(user,'userWork',obj.work); Vue.set(user,'userMyself',obj.myself); Vue.set(user,'userStar',obj.star); this.saveUser(user); } //要抛出user对象 export default user; <file_sep><?php //要在C:\wamp64\www\user.php中调用, // 且打开wampserver,运行网址在http://localhost:8085/user.php header("Content-type: text/html; charset=utf-8"); header('Access-Control-Allow-Origin:http:*'); //写监听端口文件,还在调试中,目标限制特定端口访问,提高安全性 $ro =file_get_contents('php://input'); //获取json文件 $user=json_decode($ro,true); //将json转为PHP数组,供操作 $name=$user['Name']; $userPwd=$user['userPwd']; // 操作数据库 //1.连接数据库 $conn = mysqli_connect('localhost:3300','root','123456','test'); // 检查连接 if (!$conn) { die("连接错误: " . mysqli_connect_error()); } $sql="select * from user where (name='$name') and (password='$<PASSWORD>')"; //查询用户表是否存在该用户 $result = mysqli_query($conn,$sql) ; //执行数据库 if (!$result) { printf("Error: %s\n", mysqli_error($conn)); exit(); } //返回结果集的函数,若存在则返回1(一行结果集) // if (mysqli_num_rows($result) > 0) { // // 输出数据 // while($row = mysqli_fetch_assoc($result)) { // echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["password"]. "<br>"; // print_r($row); // } // } else { // echo "0 结果"; // } $re = mysqli_num_rows($result); //返回结果集的函数,若存在则返回1(一行结果集) //判断结果集,返回相应的查询结果给前端 if($re!=0){ $row['status']="1"; $row['err']="0"; }else{ $row['status']="0"; $row['err']="fail"; } echo(json_encode($row)); mysqli_free_result($result); //释放查询结果内存(养成良好习惯) //官网对这个用法解释:mysql_free_result() 仅需要在考虑到返回很大的结果集时会占用多少内存时调用。在脚本结束后所有关联的内存都会被自动释放。 mysqli_close($conn);//关闭数据库 ?> <file_sep>import Vue from 'vue' import Router from 'vue-router' // 引入模块,自定义组件 import Life from '@/components/life/PhotosList' import Technology from '@/components/technology/NewsList' import Shop from '@/components/shop/Goods' import Mine from '@/components/mine/Mine' import Publish from '@/components/publish/Publish' //以上是底部栏模块 // import NewsList from '@/components/news/NewsList' import NewsDetail from '@/components/technology/NewsDetail' // import PhotosList from '@/components/photo/PhotosList' import PhotosDetail from '@/components/life/PhotosDetail' // import Goods from '@/components/Goods/Goods' import GoodsDetail from '@/components/shop/GoodsDetail' import GoodsComment from '@/components/shop/GoodsComment' import Car from '@/components/shop/Car' // 以下是用户信息和关于项目解说模块 import Login from '@/components/mine/Login' import Register from '@/components/mine/Register' import Install from '@/components/mine/Install' import Message from '@/components/mine/Message' import Password from '@/components/mine/Password' import Secret from '@/components/mine/Secret' import About from '@/components/mine/About' // 使用vue-router插件,相当于Vue.prototype.$route=Router; Vue.use(Router) // 根据匹配路由规则,加载对应的组件 export default new Router({ routes: [ { path:'/', redirect:'/life/旅行'//将初始页面重定向 }, { //动态路由匹配 path: '/life/:categoryTitle', name: 'life',//命名路由 component: Life, meta:{keepAlive:true}//需要缓存的视图组件 }, { path: '/technology', name: 'technology',//命名路由 component:Technology, meta:{keepAlive:true} }, { path: '/publish', name: 'publish',//命名路由 component: Publish, meta:{auto:true}//路由元信息 }, { // path: '/shop/:categoryTitle/:page', path: '/shop/:categoryTitle', name: 'shop',//命名路由 component: Shop, meta:{keepAlive:true} }, { path: '/mine', name: 'mine',//命名路由 component: Mine }, //以上是底部栏的路由设置 //新闻列表 { path:'/news/detail', name:'detail', component:NewsDetail }, //图文分享 { //先params后query,?id= path:'/photos/detail/:categoryTitle', name:'photos.detail', component:PhotosDetail }, //商品列表 { //query,?id= path:'/goods/detail', name:'goods.detail', component:GoodsDetail, meta:{keepAlive:true} }, { //query,?id= path:'/goods/comment', name:'goods.comment', component:GoodsComment }, //购物车 { path:'/shop/car', name:'shop.car', component:Car, meta:{auto:true} }, //用户信息 { path:'/install', name:'install', component:Install }, { path:'/install/message', name:'install.message', component:Message, meta:{auto:true}//路由元信息 }, { path:'/login', name:'login', component:Login }, { path:'/register', name:'register', component:Register }, { path:'/install/password', name:'install.password', component:Password, meta:{auto:true}//路由元信息 },{ path:'/install/secret', name:'install.secret', component:Secret },{ path:'/install/about', name:'install.about', component:About } ] }); <file_sep>import Vue from "vue" import Axios from 'axios' import store from '@/store' // 配置axios,每一个文件对axios发起请求,要挂载到vue实例化对象上 Vue.prototype.$axios=Axios let time={}; //php取出来的是一个个对象,需要转换成对象数组 //缺点:对于只有一条数据,无法进行转换 time.ToArray=function(objs){ let note=[]; let a=objs.split('}');//将多个对象转化为数组 let l=a.join('}},');//将数组转换为字符串 let b=l.split('},');//再将字符串转换为标准的数组对象 b.pop();//多出了一个空元素,删除 b.forEach(item=>{ if(JSON.parse(item)){ note.push(JSON.parse(item));//将每个元素的json格式转换为对象 } }); return note; } //用于笔记的封面列表,获取单张图片作为封面 time.hasImgs=function(objs){ //将多个对象转化为数组 let note=this.ToArray(objs); //处理图片格式,有的是一张,有的是多张 let note_img=[]; note.forEach(item=>{ let reg=/[-]{3}/; if(reg.test(item.img)){ let k=item.img.split("---");//对应public.vue里pics转成字符串的方式,把字符串转回一组图片数组 note_img.push(k[0]); }else{ note_img.push(item.img);//用一个数组吧所有封面图片装起来 } }) return note_img; } //提取公共的删除和修改加入购物车商品的PHP连接操作(car.vue) time.updateGoods=function(cz,id,c){ Vue.prototype.$axios.post('/api/updateGoods.php',{ caozuo:cz, goods_id:id, category:c }) .then(res=>{ console.log(res.data); }) .catch(err=>{ console.log(err); }) } //对于购物车小图标的小球里面的数量(fixcar.vue和goodsdetail.vue) time.getGoodsNum=function(telephone){ let products=[]; var num=0; // this.$axios这里的this错误 Vue.prototype.$axios.post('/api/checkGoods.php', {tele:telephone}) .then(res=>{ if(res.data instanceof Object){ products=res.data; num=parseInt(products.num); } else{ products=this.ToArray(res.data); products.forEach((item,index)=>{ num+=parseInt(item.num); }) } //当页面进行刷新会清空,要想商品数量保留则调用action(vuex)获取总数量重新赋值 // 同样,this.$store的this也错误,正确的是store store.dispatch('changeGoodsNum',num); }) .catch(err=>{ console.log(err); }) } time.updateStar=function(noteId,caoZuo,ad){ //提取共同连接PHP,点赞与收藏数+或-1(photosdetail.vue) Vue.prototype.$axios.post('/api/updateNoteLike.php',{ note_id:noteId, caozuo:caoZuo, AD:ad }) .then(res=>{ console.log(res.data); }) .catch(err=>{ console.log("修改点赞数失败",err); }) } //提取公共的删除和修改商品的PHP连接操作(goodsdetail.vue) time.updateShop=function(cz,id,number){ Vue.prototype.$axios.post('/api/deleteGoods.php',{ caozuo:cz, goods_id:id, num:number }) .then(res=>{ console.log(res.data); }) .catch(err=>{ console.log(err); }) } time.geto=function(num){ return num<0?'0'+num:num; } // 转换时间格式符合数据库datetime格式,用momentjs.cn库代替了 time.changeTime=function(){ const date=new Date(); const ymd=date.getFullYear()+'-'+this.geto(date.getMonth()+1)+'-'+this.geto(date.getDate()); const time=this.geto(date.getHours())+':'+this.geto(date.getMinutes())+':'+this.geto(date.getSeconds()); return ymd.concat('-',time); } //抛出去obj对象 export default time; <file_sep>import Vue from 'vue' let obj={} //保存商品 obj.saveGoods=function(goodsList){ window.localStorage.setItem('goodsList',JSON.stringify(goodsList)); } // 获取商品 obj.getGoodsList=function(){ return JSON.parse(window.localStorage.getItem('goodsList')||'{}'); } //因为属性+i,所以需要全局变量i,进行增删操作是获取最后的i //但是不能用全局变量,获取的i到后面不准确 // let goodsList=obj.getGoodsList(); // let k=Object.keys(goodsList);//获取对象的所有属性组成数组 // let i=k.length/6-1;因为一次循环有6个不同的对象属性,为虚拟数组的长度 //添加商品 // goods参数是一个对象,{加入购物车商品id,商品数量} obj.addGoods=function(goods){ let goodsList=this.getGoodsList(); let k=Object.keys(goodsList);//获取对象的所有属性组成数组 let i=k.length/6-1; i++; //不是刷新后从0开始,从数组长度-1开始 //2,因为obj是一个对象,不是一个数组,所以要不同的属性名才可以存进去, // if(goods.num!=0){因为在数量为0不进入小球动漫触发后,即不调用添加方法 // goodsList['id'+i]=goods.id; Vue.set(goodsList,'id'+i,goods.id); Vue.set(goodsList,'title'+i,goods.title); Vue.set(goodsList,'price'+i,goods.price); Vue.set(goodsList,'img'+i,goods.img); Vue.set(goodsList,'num'+i,goods.num); Vue.set(goodsList,'category'+i,goods.category); // 保存一下 this.saveGoods(goodsList); } //删除商品,删除对象属性 obj.deleteGoods=function(index){ let goodsList=this.getGoodsList(); let k=Object.keys(goodsList);//获取对象的所有属性组成数组 let i=k.length/6-1; // 删除对象属性,且不占位置Vue.delete(obj,key); //删除相应的商品数据,而不是删除标签节点,可以存储 Vue.delete(goodsList,'id'+index); Vue.delete(goodsList,'title'+index); Vue.delete(goodsList,'price'+index); Vue.delete(goodsList,'img'+index); Vue.delete(goodsList,'num'+index); Vue.delete(goodsList,'category'+index); // 删了index的数据后,后面的i要往前自动改变, // 不然在car.vue中无法遍历获取数据 for(let j=index;j<i;j++){ //想过设置删除的那些属性,(对象,属性,属性值) // Vue.set(goodsList,'id'+j,goodsList['id'+(j+1)]); //直接用后面覆盖前面的方法,认真分析过j<i还是j<i-1, // i-1不行,这样就只可获取长度-2,不可,只能再删除最后一个元素 goodsList['id'+j]=goodsList['id'+(j+1)] goodsList['title'+j]=goodsList['title'+(j+1)] goodsList['img'+j]=goodsList['img'+(j+1)] goodsList['num'+j]=goodsList['num'+(j+1)] goodsList['price'+j]=goodsList['price'+(j+1)] goodsList['category'+j]=goodsList['category'+(j+1)] } // 再删除最后一个元素 Vue.delete(goodsList,'id'+i); Vue.delete(goodsList,'title'+i); Vue.delete(goodsList,'price'+i); Vue.delete(goodsList,'img'+i); Vue.delete(goodsList,'num'+i); Vue.delete(goodsList,'category'+i); //存储改变 // console.log("删除后的数组长度"+i); this.saveGoods(goodsList); } //修改加入购物车的商品,传入对象要修改的属性和值 obj.updataGoods=function(key,value){ let goodsList=this.getGoodsList(); goodsList[key]=value; // console.log(key,value); this.saveGoods(goodsList); } //获取购物车的总数量 obj.getTotalCount=function(){ let sum=0; let goodsList=this.getGoodsList(); let k=Object.keys(goodsList);//获取对象的所有属性组成数组 let i=k.length/6-1; // 因为i此时已经是长度-1 for(let j=0;j<=i;j++){ let values=goodsList['num'+j]; sum+=values; } return sum; } //抛出去obj对象 export default obj; //在GoodsDetail.vue中的购入购物车事件中, //调用js添加到购物车页面的数据,保存到本地数据方法 // id:this.goods.item.itemId, // GoodsTool.addGoods({ // title:this.goods.item.title, // price:this.goods.item.priceRange, // id:this.$route.query.id, // num:parseInt(parseInt(this.num)),//因为number类型的input返回值是string // img:this.changeUrl,//更新的图片 // category:this.changeTitle//更新的名字 // }); <file_sep>import Vue from 'vue' const EventBus=new Vue(); // bus组件传值 export default EventBus; // 挂载到main.js的vue实例上 <file_sep>// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. // 入口文件 import Vue from 'vue' import App from './App' import router from './router' import Axios from 'axios' //引入vuex仓库,还要在实例中挂载 import store from './store' // 配置axios,每一个文件对axios发起请求,要挂载到vue实例化对象上 Vue.prototype.$axios=Axios; //基本地址 // Axios.defaults.baseURL='https://api03.6bqb.com/xhs/'; // 引入mint-ui import Mint from 'mint-ui'; Vue.use(Mint); // 全局引入样式,公司项目建议不要全局引入,占内存,建议有序引入 import 'mint-ui/lib/style.css' // 引入element-ui import ElementUI from 'element-ui'; Vue.use(ElementUI); import 'element-ui/lib/theme-chalk/index.css'; //引入图片查看器,查看放大图 import VuePreview from 'vue2-preview' Vue.use(VuePreview);//内部会运行Vue.component('vue2-preview',{})的组件 //引入rem适配移动端方案还有一个在build的utils.js中配置 import 'lib-flexible/flexible.js'; // 引入时间库 import Moment from 'moment'; // 时间显示是中文 // Moment.locale('zh-ch'); Moment.lang('zh-cn'); //自定义全局时间过滤器 Vue.filter('coverTime',function(data,formatStr){//data要格式化时间,formatStr要格式化的格式 // return Moment(data).format(formatStr); return Moment(data, formatStr).fromNow(); }) //控制显示字数 Vue.filter('Tolength',function(str,num){ //如果字符串小于num,则原型返回 if(str.length<=num){ return str; } // 否则截取长度为num的字符串 else{ return str.substr(0,num-1)+'...' } }); //axios拦截器在请求或响应被 then 或 catch 处理前拦截它们。 // 添加请求拦截器,在数据加载完前加loading动画 Axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 //加载提示框 Mint.Indicator.open({ text: 'Loading...' }); return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 var myInterceptor =Axios.interceptors.response.use(function (response) { // 对响应数据做点什么 //关闭加载框 Mint.Indicator.close(); return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); }); //移除拦截器 // Axios.interceptors.request.eject(myInterceptor); //引入自己写的全局css样式 import '../static/css/global.css' //引入字体图标的css,在toast中使用自定义图标 // 若需在文字上方显示一个 icon 图标,可以将图标的类名作为 iconClass 的值传给 Toast(图标需自行准备) import '../static/iconfont/iconfont.css' import '../static/iconfont/iconfont.js' //注册全局的导航栏子组件 import TopBar from '@/components/comment/TopBar' Vue.component(TopBar.name,TopBar);//(自定义组件名,TopBar.vue的组件名) //注册信息设置顶部栏 import TopUser from '@/components/comment/TopUser' Vue.component(TopUser.name,TopUser); // 注册全局搜索子组件 import Search from '@/components/comment/Search' Vue.component(Search.name,Search); //注册全局的轮播图子组件 import MySwipper from '@/components/comment/MySwipper' Vue.component(MySwipper.name,MySwipper); //注册全局购物车组件 import fixCar from '@/components/comment/fixCar' Vue.component(fixCar.name,fixCar); Vue.config.productionTip = false // 将bus总线对象挂载到vue实例上 import EventBus from './router/EventBus' Vue.prototype.$bus=EventBus; import Time from '@/router/time' import UserTool from '@/router/UserTool' //注册全局路由守卫,进行路由权限控制 router.beforeEach((to,from,next)=>{ //判断是否登录,在index.js的path中设置meta:{auto:true} if(to.meta.auto){ if(UserTool.getUser().userName){ next();//如果本地存储有用户信息放行,UserTool.getUser() console.log(UserTool.getUser()); } else{ next({ path:'/login', query: { redirect: to.fullPath } }) } }//meta为false,就是已经登陆,就不需要跳转登陆页面 else{//必须有else //必須要有next()方法進行放行 next(); } }); /* eslint-disable no-new */ new Vue({ el: '#app', router, //挂载vuex仓库 store, components: { App }, template: '<App/>' })
a44d9d627e6220f84fa52e52f61caef284cd38ac
[ "JavaScript", "PHP" ]
7
JavaScript
xuannuan/warn
a4494fdb5c144e8baaf136e81c96d0a263b75cbe
150d294fd924855190896c26eb6bbe3fee918301
refs/heads/master
<repo_name>Sougandika/Different-Projects<file_sep>/passwordGenerator.js //DOM elements const resultsEl = document.getElementById('result'); const lengthEl = document.getElementById('length'); const uppercaseEl = document.getElementById('upperCase'); const lowercaseEl = document.getElementById('lowerCase'); const numbersEl = document.getElementById('numbers'); const symbolsEl = document.getElementById('symbols'); const generateEl = document.getElementById('generate'); //Putting all these functions in an object const randomFunc={ lower:getRandomLower, upper:getRandUpper, number:getRandNumber, symbol:getRandSymbol }; // Generate event listen generateEl.addEventListener('click', () =>{ const length = +lengthEl.value; const hasLower = lowercaseEl.checked; const hasUpper = uppercaseEl.checked; const hasNumber = numbersEl.checked; const hasSymbol = symbolsEl.checked; resultsEl.innerText = generatePassword( hasLower, hasUpper, hasNumber, hasSymbol, length ); }); // Generate Password function function generatePassword(lower, upper, number, symbol, length){ // Initialize password variable // Allow only checked // loop over length call generator function for ech type // Add final pw to pw var and return let generatedPassword = ''; const typesCount = lower + upper +number + symbol; console.log('typeCount:', typesCount); const typesArr = [ {lower}, {upper}, {number},{symbol}].filter { item =>Object.values(item)[0] }; // console.log('typesArr: ', typesArr); if(typesCount === 0) { return '' ; } for(let i=0; i< length; i+= typesCount){ typesArr.forEach(type => { const funcName = Object.keys(type)[0] ; generatedPassword += randomFunc[funcName](); }); } const finalPassword = generatedPassword.slice(0,length); return finalPassword; } //Generate functions // 4 different functions needed to generate random numbers, symbols,upperCase and lowerCase // Getting lowerCase letters function getRandomLower() { return String.fromCharCode(Math.floor(Math.random() *26)+ 97); //97-120 ASCII values of lowerCase } //Getting upperCase letters function getRandUpper(){ return String.fromCharCode(Math.floor(Math.random()* 26)+ 65); } //Geting Numbers function getRandNumber(){ return Math.floor(Math.random()*10 +48); } //Getting Symbols function getRandSymbol(){ const symbols='!@#$%^&*(){}[]=<>/,.'; return symbols[Math.floor(Math.random()*symbols.length)]; }
4e2009e3807c03ba9b0e56b404902f7712701e83
[ "JavaScript" ]
1
JavaScript
Sougandika/Different-Projects
311770c6bfe88459eb7086c84adb6473a66eebb1
afde6e1343d4256ed787bfbdb6b0d1353a3eb07e
refs/heads/master
<file_sep>import Vue from "vue"; import VueRouter from "vue-router"; import EnterPassword from "../views/EnterPassword"; import PasswordChangedPopUp from "../views/PasswordChangedPopUp"; // import Recovery from '../views/Recovery' Vue.use(VueRouter); const routes = [ { path: "/recovery", name: "EmailRecovery", meta: { layout: "empty" }, component: () => import("../views/EmailRecovery.vue") }, { path: "/menu", name: "Menu", meta: { layout: "empty" }, component: () => import("../views/Menu.vue") }, { path:"/menuform", name:"MenuForm", // meta:{layout: "main"}, component:()=>import("../views/MenuForm.vue") }, { path: "/createform", name:"CreateForm", meta:{layout:"main"}, component: ()=>import("../views/CreateForm.vue") }, { path: "/createtable", name:"CreateTablePU2a", meta:{layout:"main"}, component: ()=>import("../views/CreateTablePU2a.vue") }, { path: "/", name: "Login", meta: { layout: "empty" }, component: () => import("../views/Login.vue") }, { path: "/enterpassword", name: "EnterPassword", component: EnterPassword }, { path: "/passwordchangedpopup", name: "PasswordChangedPopUp", component: PasswordChangedPopUp } ]; const router = new VueRouter({ mode: "history", base: process.env.BASE_URL, routes }); export default router;
4adb05f9fc3849d54197992f0af1cc63df446db5
[ "JavaScript" ]
1
JavaScript
inessa65/beljd-main
aab737bce72991528308c9d79c571afb14423951
c0c8d6bca0e41bf000d538de0b75564fd22d0921
refs/heads/master
<file_sep>using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using static SightBraille.BrailleEditor; using static SightBraille.SightBrailleApp; namespace SightBraille { /// <summary> /// Logique d'interaction pour MainWindow.xaml /// </summary> public partial class EditorWindow : Window { public static RoutedCommand DictionnaryCommand = new RoutedCommand(); private BrailleEditor _editor; public EditorWindow() { InitializeComponent(); this._editor = new BrailleEditor(this, this.MainEditorContainer); CommandBinding dictionnaryCommandBinding = new CommandBinding(DictionnaryCommand, ExecuteDictionnary, CanExecuteDictionnary); this.CommandBindings.Add(dictionnaryCommandBinding); this.DictionnaryButton.Command = DictionnaryCommand; this.SymbolMenu.Command = DictionnaryCommand; this.SerialPortsComboBox.ItemsSource = (Application.Current as SightBrailleApp).ConnectionManager.SerialPorts; this.SerialPortsComboBox.SelectionChanged += SelectedPortChanged; } public void AddCharacter(char c) { this._editor.AttemptWriteChar(c); } private void SelectedPortChanged(object obj, SelectionChangedEventArgs e) { if(this.SerialPortsComboBox.SelectedItem != null && (this.SerialPortsComboBox.SelectedItem as SerialPortConnection).State == PortConnectionState.CONNECTED) { this.PrintBrailleButton.IsEnabled = true; } else { this.PrintBrailleButton.IsEnabled = false; } } private void CanExecuteDictionnary(object obj, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void ExecuteDictionnary(object obj, ExecutedRoutedEventArgs e) { Window symbols = new BrailleSymbolListWindow(); symbols.Show(); } private void NewCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e) { (Application.Current as SightBrailleApp).Document.NewDocument(); this._editor.LoadNewData((Application.Current as SightBrailleApp).Document.Characters); } private void OpenCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e) { Open(); } private void Open() { List<BrailleCharacter>[] data = (Application.Current as SightBrailleApp).Document.OpenDocument(); if(data != null) { this._editor.LoadNewData(data); } } private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e) { (Application.Current as SightBrailleApp).Document.SaveDocument(this._editor.Characters); } private void PrintCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void PrintCommand_Executed(object sender, ExecutedRoutedEventArgs e) { printDocument(); } private void SaveAsCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void SaveAsCommand_Executed(object sender, ExecutedRoutedEventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Fichier braille (*.braille)|*.braille|Tous les fichiers (*.*)|*.*"; } public void AutoSelectSerialPort(int recommendedPort) { if(this.SerialPortsComboBox.SelectedItem == null) { this.SerialPortsComboBox.SelectedIndex = recommendedPort; } } private void printDocument() { PrintDialog printDialog = new PrintDialog(); bool? result = printDialog.ShowDialog(); if(result == true) { double docWidth = printDialog.PrintableAreaWidth; double docHeight = printDialog.PrintableAreaHeight; FlowDocument document = new FlowDocument(); document.Background = Brushes.White; Section main = new Section(); main.FontSize = docWidth / A4_WIDTH * 10.5; main.FontFamily = new FontFamily("Courier New"); main.FontStretch = FontStretches.UltraExpanded; document.PagePadding = new Thickness(docWidth / A4_WIDTH * MARGIN_WIDTH, docWidth / A4_WIDTH * MARGIN_HEIGHT, docWidth / A4_WIDTH * MARGIN_WIDTH, docWidth / A4_WIDTH * MARGIN_HEIGHT); List<String> text = new List<String>(); foreach (List<BrailleSymbolSlotPosition> line in this._editor.Symbols) { string txtLine = ""; foreach (BrailleSymbolSlotPosition s in line) { txtLine += s.Symbol.DisplayLettter; } text.Add(txtLine); } foreach (string line in text) { Paragraph p = new Paragraph(new Run(line)); p.Margin = new Thickness(0); p.LineHeight = docWidth / A4_WIDTH * 10.25; p.LineStackingStrategy = LineStackingStrategy.BlockLineHeight; main.Blocks.Add(p); } document.Blocks.Add(main); document.PageHeight = docHeight; document.PageWidth = docWidth; document.ColumnGap = 0; document.ColumnWidth = printDialog.PrintableAreaWidth; IDocumentPaginatorSource idpSource = document; printDialog.PrintDocument(idpSource.DocumentPaginator, "Braille"); } } private void PrintBrailleButton_Click(object sender, RoutedEventArgs e) { Document document = (Application.Current as SightBrailleApp).Document; document.UpdateDocument(_editor.Characters); (Application.Current as SightBrailleApp).ConnectionManager.PrintBrailleDocument(this.SerialPortsComboBox.SelectedIndex); } private void InstructionsOutput_Click(object sender, RoutedEventArgs e) { Document document = (Application.Current as SightBrailleApp).Document; document.UpdateDocument(_editor.Characters); MessageBox.Show(string.Join("\n", document.GetInstructions().Split('\n').ToArray()), "Instructions"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Media; using System.Windows; using System.Windows.Media.Effects; using System.Windows.Input; using System.IO; using static SightBraille.SightBrailleApp; using System.Windows.Shapes; using System.Windows.Media.Animation; using static SightBraille.SightBrailleApp.BrailleCharacter; namespace SightBraille { class BrailleEditor { private EditorWindow window; private Viewbox _parent; public StackPanel EditorContainer; public Style LetterStyle = new Style(typeof(TextBlock)); public Style DotStyle = new Style(typeof(Ellipse)); public BrailleEditor(EditorWindow window, Viewbox panel) { this.LetterStyle.Setters.Add(new Setter(TextBlock.FontFamilyProperty, new FontFamily("Courier New"))); this.LetterStyle.Setters.Add(new Setter(TextBlock.FontSizeProperty, 9 * FACTOR)); this.LetterStyle.Setters.Add(new Setter(TextOptions.TextRenderingModeProperty, TextRenderingMode.Aliased)); this.DotStyle.Setters.Add(new Setter(Ellipse.FillProperty, Brushes.Transparent)); this.DotStyle.Setters.Add(new Setter(Ellipse.WidthProperty, 3 * FACTOR)); this.DotStyle.Setters.Add(new Setter(Ellipse.HeightProperty, 3 * FACTOR)); this.EditorContainer = new StackPanel() { Background = Brushes.White, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Effect = new DropShadowEffect() { BlurRadius = 15, ShadowDepth = 5, Opacity = 0.3 }, UseLayoutRounding = true, Margin = new Thickness(0, 15, 0, 15), Focusable = false }; this._parent = panel; this._parent.Child = (this.EditorContainer); this.window = window; InitCanavas(); } private void DataChanged() { (Application.Current as SightBrailleApp).Document.DocumentChanged(); } public void KeyPressed(object sender, KeyEventArgs args) { Key k = args.Key; if (k == Key.Back) { handeled(args); AttemptEraseBack(); } else if (k == Key.Up) { handeled(args); AttemptCursorPositionOffset(-1, 0); } else if (k == Key.Down) { handeled(args); AttemptCursorPositionOffset(1, 0); } else if (k == Key.Left) { handeled(args); AttemptCursorPositionOffsetChangeLine(-1); } else if (k == Key.Right) { handeled(args); AttemptCursorPositionOffsetChangeLine(1); }else if(k == Key.Enter) { handeled(args); AttemptSplitLine(); } } private void handeled(KeyEventArgs args) { args.Handled = true; } public void TextInput(object sender, TextCompositionEventArgs args) { string txt = args.Text; if(txt != null && txt.Length > 0) { foreach(char c in txt) { AttemptWriteChar(c); } args.Handled = true; } } public void LeftMouseButtonPressed(object sender, MouseButtonEventArgs args) { Point clickPos = args.GetPosition(Canvas); int row = (int)(clickPos.Y / BRAILLE_HEIGHT_DISP); int column = (int)(Math.Round(clickPos.X / BRAILLE_WIDTH_DISP)); AttemptCursorPositionChange(row, column); } private int inRange(int max, int a) { return Math.Max(0, Math.Min(max, a)); } public void SetSymbolAtPosition(int row, int column, BrailleSymbolSlotPosition symbol) { if(symbol != null) { BrailleSymbolSlot slot = symbol.Symbol; setLetter(row, column, slot.DisplayLettter); setFillerCase(row, column, slot.Filler); } else { setLetter(row, column, ' '); setFillerCase(row, column, false); } } private void setLetter(int row, int column, char c) { Letters[row, column].Text = c.ToString(); } private void setFillerCase(int row, int column, bool filler) { Dots[row, column].Fill = filler ? Brushes.LightGray : Brushes.Transparent; } public List<BrailleCharacter>[] Characters = new List<BrailleCharacter>[CHARACTER_ROWS]; public List<BrailleSymbolSlotPosition>[] Symbols = new List<BrailleSymbolSlotPosition>[CHARACTER_ROWS]; public Canvas Canvas; public TextBlock[,] Letters = new TextBlock[CHARACTER_ROWS, CHARACTER_COLUMNS]; public Ellipse[,] Dots = new Ellipse[CHARACTER_ROWS, CHARACTER_COLUMNS]; public EditorCursor Cursor; public void LoadNewData(List<BrailleCharacter>[] data) { Characters = data; for(int i = 0; i < CHARACTER_ROWS; i++) { RecalculateSymbolSlots(i); } AttemptCursorPositionChange(0, 0); } public void AttemptCursorPositionOffset(int offsetRow, int offsetColumn) { AttemptCursorPositionChange(Cursor.Row + offsetRow, Cursor.Column + offsetColumn); } public void AttemptCursorPositionOffsetChangeLine(int offsetColumn) { if(offsetColumn + Cursor.Column > Symbols[Cursor.Row].Count && Cursor.Row + 1 < CHARACTER_ROWS) { AttemptCursorPositionChange(Cursor.Row + 1, 0); }else if(offsetColumn + Cursor.Column < 0 && Cursor.Row > 0) { AttemptCursorPositionChange(Cursor.Row - 1, CHARACTER_COLUMNS); } else { AttemptCursorPositionOffset(0, offsetColumn); } } public void AttemptCursorPositionChange(int row, int column) { int outputRow = inRange(CHARACTER_ROWS - 1, row); int outputColumn = inRange(CHARACTER_COLUMNS, column); //One position added to column to account for the cursor's mecanics int length = Symbols[outputRow].Count; if(outputColumn >= length) { outputColumn = length; } int offset = outputRow != Cursor.Row ? 0 : outputColumn - Cursor.Column; int p = 0; while(IsSymbolOffsetFiller(p - 1, outputRow, outputColumn)) { if(offset >= 0) { p++; } else { p--; } } Cursor.SetPosition(outputRow, outputColumn + p); } private bool IsSymbolOffsetFiller(int o, int row, int column) { BrailleSymbolSlotPosition s = getSymbolSlotPosition(o, row, column); return s == null ? false : s.Symbol.Filler; } public void AttemptSplitLine() { //If last line empty bool isLastEmpty = true; foreach (BrailleCharacter c in Characters[CHARACTER_ROWS - 1]) { if(c.Type != BrailleCharacterType.WHITESPACE) { isLastEmpty = false; break; } } if (isLastEmpty && Cursor.Row < CHARACTER_ROWS - 1) { List<BrailleCharacter> remaining = Characters[Cursor.Row]; List<BrailleCharacter> cut = new List<BrailleCharacter>(); //If cursor is at eol BrailleSymbolSlotPosition s = GetSymbolSlotPositionCurrent(); if (s != null) { int characterIndex = s.i; remaining = Characters[Cursor.Row].GetRange(0, s.i); cut = Characters[Cursor.Row].GetRange(s.i, Characters[Cursor.Row].Count - s.i); } for(int i = CHARACTER_ROWS - 1; i > Cursor.Row; i--) { Characters[i] = Characters[i - 1]; } Characters[Cursor.Row] = remaining; Characters[Cursor.Row + 1] = cut; AttemptCursorPositionChange(Cursor.Row + 1, 0); for(int i = 0; i < CHARACTER_ROWS; i++) { RecalculateSymbolSlots(i); } DataChanged(); } } public void AttemptWriteChar(char c) { int row = Cursor.Row; int column = Cursor.Column; BrailleCharacter newChar = GetBrailleCharacter(c); if (newChar != null) { int symbolCount = Symbols[row].Count; //Primary check if room available if (symbolCount < CHARACTER_COLUMNS) { //Find current character index or select last one List<BrailleCharacter> characters = Characters[row]; if (characters.Count == 0) { characters.Add(newChar); RecalculateSymbolSlots(row); AttemptCursorPositionOffset(0, newChar.GetSymbols(BlankCharacter, BlankCharacter, BlankCharacter).Count); DataChanged(); return; } else { BrailleSymbolSlotPosition previous = GetSymbolSlotPositionBefore(); //Calculate new list of symbol slot position and check if it fits List<BrailleCharacter> newCharacters = characters.ToList(); int index = previous != null ? previous.i + 1 : 0; newCharacters.Insert(index, newChar); int newSymbolsCount = GetNewSymbolSlots(newCharacters).Count; if (newSymbolsCount <= CHARACTER_COLUMNS) { Characters[row] = newCharacters; RecalculateSymbolSlots(row); AttemptCursorPositionChange(row, GetLastSymbolFromCharacterColumn(index, row)); DataChanged(); return; } } } } } private int GetLastSymbolFromCharacterColumn(int charPos, int row) { int j = 0; int newColumn = 0; foreach (BrailleSymbolSlotPosition s in Symbols[row]) { if (s.i == charPos) { newColumn = j; } j++; } return newColumn + 1; } private List<BrailleSymbolSlotPosition> GetNewSymbolSlots(List<BrailleCharacter> characters) { List<BrailleSymbolSlotPosition> symbols = new List<BrailleSymbolSlotPosition>(); int i = 0; int length = characters.Count; BrailleCharacter before = BlankCharacter; BrailleCharacter beforebefore = BlankCharacter; BrailleCharacter after; foreach (BrailleCharacter character in characters) { if (i < length - 1) { after = characters[i + 1]; } else { after = BlankCharacter; } foreach (BrailleSymbolSlot slot in character.GetSymbols(beforebefore, before, after)) { BrailleSymbolSlotPosition s = new BrailleSymbolSlotPosition(slot, 0, i); symbols.Add(s); } //Next beforebefore = before; before = character; i++; } return symbols; } private void RecalculateSymbolSlots(int row) { List<BrailleCharacter> characters = Characters[row]; List<BrailleSymbolSlotPosition> symbols = new List<BrailleSymbolSlotPosition>(); int i = 0; int length = characters.Count; BrailleCharacter before = BlankCharacter; BrailleCharacter beforebefore = BlankCharacter; BrailleCharacter after; int symbolCountBefore = Symbols[row].Count; int k = 0; foreach(BrailleCharacter character in characters) { if(i < length - 1) { after = characters[i + 1]; } else { after = BlankCharacter; } foreach(BrailleSymbolSlot slot in character.GetSymbols(beforebefore, before, after)) { BrailleSymbolSlotPosition s = new BrailleSymbolSlotPosition(slot, row, i); symbols.Add(s); //Directly update graphics for performance SetSymbolAtPosition(row, k, s); k++; } //Next beforebefore = before; before = character; i++; } Symbols[row] = symbols; for(int j = k; j < symbolCountBefore; j++) { SetSymbolAtPosition(row, j, null); } } public void AttemptEraseBack() { BrailleSymbolSlotPosition symbol = GetSymbolSlotPositionBefore(); if(symbol != null && symbol.Symbol.Filler) { AttemptCursorPositionOffset(0, -1); }else if(symbol == null && Cursor.Row > 0) { if (Symbols[Cursor.Row - 1].Count == 0) { for (int i = Cursor.Row - 1; i < CHARACTER_ROWS - 1; i++) { Characters[i] = Characters[i + 1]; } Characters[CHARACTER_ROWS - 1] = new List<BrailleCharacter>(); AttemptCursorPositionChange(Cursor.Row - 1, CHARACTER_COLUMNS); for (int i = Cursor.Row; i < CHARACTER_ROWS; i++) { RecalculateSymbolSlots(i); } } else if (Symbols[Cursor.Row].Count == 0) { for (int i = Cursor.Row; i < CHARACTER_ROWS - 1; i++) { Characters[i] = Characters[i + 1]; } AttemptCursorPositionChange(Cursor.Row - 1, CHARACTER_COLUMNS); for (int i = Cursor.Row; i < CHARACTER_ROWS; i++) { RecalculateSymbolSlots(i); } } DataChanged(); } else if(symbol != null) { int row = symbol.row; Characters[row].RemoveAt(symbol.i); RecalculateSymbolSlots(row); if(symbol.i == 0) { AttemptCursorPositionChange(row, 0); } else if(Characters[row].Count >= symbol.i) { AttemptCursorPositionChange(row, GetLastSymbolFromCharacterColumn(symbol.i - 1, row)); }else if(Characters[row].Count > 0) { AttemptCursorPositionChange(row, Characters[row].Count); } DataChanged(); } } private BrailleSymbolSlotPosition GetSymbolSlotPositionBefore() { return GetSymbolSlotPosition(-1); } private BrailleSymbolSlotPosition GetSymbolSlotPositionBeforeBefore() { return GetSymbolSlotPosition(-2); } private BrailleSymbolSlotPosition GetSymbolSlotPositionCurrent() { return GetSymbolSlotPosition(0); } private BrailleSymbolSlotPosition GetSymbolSlotPosition(int o) { return getSymbolSlotPosition(o, Cursor.Row, Cursor.Column); } private BrailleSymbolSlotPosition getSymbolSlotPosition(int o, int row, int column) { if (Symbols[row].Count <= column + o || column + o < 0) { return null; } else { return Symbols[row][column + o]; } } public class EditorCursor { public int Row; public int Column; private Canvas editorCanvas; private Rectangle cursor; private Storyboard cursorStoryBoard = new Storyboard(); public EditorCursor(EditorWindow window, Canvas canvas) { this.cursor = new Rectangle() { Width = 0.5 * FACTOR, Height = BRAILLE_HEIGHT_DISP * 0.7, Fill = Brushes.Black }; this.editorCanvas = canvas; this.editorCanvas.Children.Add(this.cursor); this.cursorStoryBoard = (Storyboard)window.FindResource("AnimateFlicker"); foreach (DoubleAnimation a in this.cursorStoryBoard.Children) { Storyboard.SetTarget(a, this.cursor); } this.cursor.Loaded += new RoutedEventHandler((object sender, RoutedEventArgs args) => { this.cursorStoryBoard.Begin(); }); } public void SetPosition(int row, int column) { this.Row = row; this.Column = column; Canvas.SetLeft(cursor, column * BRAILLE_WIDTH_DISP); Canvas.SetTop(cursor, row * BRAILLE_HEIGHT_DISP + 2 * FACTOR); this.cursorStoryBoard.Begin(); } } public void InitCanavas() { this.Canvas = new Canvas() { Width = CHARACTER_COLUMNS * BRAILLE_WIDTH_DISP, Height = CHARACTER_ROWS * BRAILLE_HEIGHT_DISP, Margin = new Thickness(MARGIN_WIDTH_DISP, MARGIN_HEIGHT_DISP, MARGIN_WIDTH_DISP, MARGIN_HEIGHT_DISP), Background = Brushes.Transparent, UseLayoutRounding = true, Cursor = Cursors.IBeam, IsEnabled = true }; window.PreviewKeyDown += new KeyEventHandler(KeyPressed); window.TextInput += new TextCompositionEventHandler(TextInput); Canvas.MouseLeftButtonDown += new MouseButtonEventHandler(LeftMouseButtonPressed); this.EditorContainer.Children.Add(Canvas); for (int i = 0; i < CHARACTER_ROWS; i++) { for(int j = 0; j < CHARACTER_COLUMNS; j++) { double xPos = j * BRAILLE_WIDTH_DISP + BRAILLE_WIDTH_DISP / 4; double yPos = i * BRAILLE_HEIGHT_DISP + BRAILLE_HEIGHT_DISP / 2; TextBlock letter = new TextBlock(); letter.UseLayoutRounding = true; letter.Text = " "; Ellipse dot = new Ellipse(); dot.Style = DotStyle; letter.Style = LetterStyle; Canvas.SetLeft(letter, xPos); Canvas.SetTop(letter, yPos - 3 * FACTOR); Canvas.SetLeft(dot, xPos); Canvas.SetTop(dot, yPos); Letters[i,j] = letter; Dots[i,j] = dot; Canvas.Children.Add(dot); Canvas.Children.Add(letter); } } for(int i = 0; i < CHARACTER_ROWS; i++) { Symbols[i] = new List<BrailleSymbolSlotPosition>(); Characters[i] = new List<BrailleCharacter>(); } Cursor = new EditorCursor(window, Canvas); } public class BrailleSymbolSlotPosition { public BrailleSymbolSlot Symbol; public int row; public int i; public BrailleSymbolSlotPosition(BrailleSymbolSlot symbol, int row, int i) { this.Symbol = symbol; this.row = row; this.i = i; } } public void SaveEdits() { Document doc = (SightBrailleApp.Current as SightBrailleApp).Document; doc.Characters = (List<BrailleCharacter>[])Characters.Clone(); doc.IsSaved = false; } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SightBraille { public class SerialPortConnectionManager { public ObservableCollection<SerialPortConnection> SerialPorts = new ObservableCollection<SerialPortConnection>(); public void InitPortManager() { SerialPortService.PortsChanged += new EventHandler<PortsChangedArgs>(SerialPortChanged); SerialPortChanged(null, null); } public SerialPortConnectionManager() { } public void PrintBrailleDocument(int index) { if(SerialPorts[index] != null && SerialPorts[index].State == PortConnectionState.CONNECTED) { SerialPorts[index].SendInstructions(); } } private void SerialPortChanged(object obj, PortsChangedArgs e) { List<string> newPorts = new List<string>(SerialPort.GetPortNames()); foreach (string port in SerialPort.GetPortNames()) { foreach (SerialPortConnection connection in SerialPorts) { if (connection.PortName == port) { newPorts.Remove(port); } } } foreach (string newPort in newPorts) { SightBrailleApp.Current.Dispatcher.Invoke(() => { this.SerialPorts.Add(new SerialPortConnection(newPort)); }); } List<SerialPortConnection> toRemove = new List<SerialPortConnection>(); foreach (SerialPortConnection actualConnection in SerialPorts) { bool isStillConnected = false; foreach (string port in SerialPort.GetPortNames()) { if (actualConnection.PortName == port) { isStillConnected = true; break; } } if (!isStillConnected) { toRemove.Add(actualConnection); } } foreach (SerialPortConnection remove in toRemove) { SightBrailleApp.Current.Dispatcher.Invoke(() => { SerialPorts.Remove(remove); remove.Disconnect(); }); } foreach (SerialPortConnection connection in SerialPorts) { connection.UpdateConnectionAsync(); } } } } <file_sep>using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; using System.Windows; using static SightBraille.SightBrailleApp; namespace SightBraille { public class Document { public SightBrailleApp app; public bool IsSaved = false; public string FilePath = null; public List<BrailleCharacter>[] Characters = new List<BrailleCharacter>[CHARACTER_ROWS]; public Document(SightBrailleApp app) { this.app = app; } public void DocumentChanged() { this.IsSaved = false; app.ChangeEditorWindowTitleStatus(FilePath != null ? FilePath + " (modifié)" : "Nouveau fichier (modifié)"); } public void DocumentUnchanged() { this.IsSaved = true; app.ChangeEditorWindowTitleStatus(FilePath != null ? FilePath : "Nouveau fichier"); } public void UpdateDocument(List<BrailleCharacter>[] data) { this.Characters = data; } public void SaveDocument(List<BrailleCharacter>[] data) { this.Characters = data; if(FilePath == null) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Fichier braille (*.braille)|*.braille|Tous les fichiers (*.*)|*.*"; if (saveFileDialog.ShowDialog() == true) { this.FilePath = saveFileDialog.FileName; } else { return; } } try { Stream stream = File.Open(FilePath, FileMode.Create); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(stream, Characters); DocumentUnchanged(); }catch(Exception e) { Console.WriteLine("Error happened " + e.Message); } } private bool CheckConfirmation() { if (!this.IsSaved) { MessageBoxResult result = MessageBox.Show("Les modifications apportées au document actuel n'ont pas été enregistrées. Etes-vous sur de vouloir continuer?", "Confirmation", MessageBoxButton.YesNo); if (result == MessageBoxResult.No) { return false; } } return true; } public List<BrailleCharacter>[] OpenDocument() { if (!CheckConfirmation()) { return null; } OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Fichier braille (*.braille)|*.braille|Tous les fichiers (*.*)|*.*"; if(openFileDialog.ShowDialog() == true) { string newFilePath = openFileDialog.FileName; try { Stream stream = File.Open(newFilePath, FileMode.Open); BinaryFormatter binaryFormatter = new BinaryFormatter(); List<BrailleCharacter>[] data = (List<BrailleCharacter>[])binaryFormatter.Deserialize(stream); if(data != null) { this.FilePath = newFilePath; DocumentUnchanged(); Characters = data; return data; } } catch (Exception e) { Console.WriteLine("Error happened " + e.Message); } } return null; } public void NewDocument() { this.FilePath = null; DocumentUnchanged(); Characters = new List<BrailleCharacter>[CHARACTER_ROWS]; for(int i = 0; i < CHARACTER_ROWS; i++) { Characters[i] = new List<BrailleCharacter>(); } } public string GetInstructions() { List<String> instructions = new List<string>(); instructions.Add("START_PRINT"); Document document = this; for (int i = 0; i < SightBrailleApp.CHARACTER_ROWS; i++) { List<BrailleSymbol> symbols = CalculateSymbols(document, i); for (int j = 0; j < 3; j++) { List<String> dotLine = new List<String>(); dotLine.Add("BEGIN_LINE"); int horizontalPosition = 0; foreach (BrailleSymbol symbol in symbols) { for (int k = 0; k < 2; k++) { if (symbol.Points[j, k]) { dotLine.Add((horizontalPosition + k).ToString()); } } horizontalPosition += 2; } dotLine.Add("STOP_LINE"); instructions.AddRange(dotLine); } } instructions.Add("END_OF_PRINT"); return string.Join("\n", instructions.ToArray()); } private List<BrailleSymbol> CalculateSymbols(Document document, int row) { List<BrailleCharacter> characters = document.Characters[row]; List<BrailleSymbol> symbols = new List<BrailleSymbol>(); int i = 0; int length = characters.Count; BrailleCharacter before = BlankCharacter; BrailleCharacter beforebefore = BlankCharacter; BrailleCharacter after; //int symbolCountBefore = Symbols[row].Count; foreach (BrailleCharacter character in characters) { if (i < length - 1) { after = characters[i + 1]; } else { after = BlankCharacter; } foreach (BrailleSymbolSlot slot in character.GetSymbols(beforebefore, before, after)) { symbols.Add(slot.GetSymbol()); } //Next beforebefore = before; before = character; i++; } return symbols; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration; using System.Data; using System.IO; using System.IO.Ports; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using System.Windows.Threading; namespace SightBraille { /// <summary> /// Logique d'interaction pour App.xaml /// </summary> /// public partial class SightBrailleApp : Application { public SerialPortConnectionManager ConnectionManager = new SerialPortConnectionManager(); public Document Document; public SightBrailleApp() { ConnectionManager.InitPortManager(); this.MainWindow = new EditorWindow(); this.MainWindow.Show(); this.Document = new Document(this); this.Document.NewDocument(); } public const double A4_WIDTH = 210; public const double A4_LENGTH = 297; public const double MARGIN_WIDTH = 15; public const double MARGIN_HEIGHT = 10; public const double USEABLE_A4_WIDTH = A4_WIDTH - 2 * MARGIN_WIDTH; public const double USEABLE_A4_LENGTH = A4_LENGTH - 2 * MARGIN_HEIGHT; public const double BRAILLE_WIDTH = 6.25; public const double BRAILLE_HEIGHT = 10; public const int CHARACTER_ROWS = (int)(USEABLE_A4_LENGTH / BRAILLE_HEIGHT); public const int CHARACTER_COLUMNS = (int)(USEABLE_A4_WIDTH / BRAILLE_WIDTH); public const double FACTOR = 5; public const double BRAILLE_WIDTH_DISP = BRAILLE_WIDTH * FACTOR; public const double BRAILLE_HEIGHT_DISP = BRAILLE_HEIGHT * FACTOR; public const double MARGIN_WIDTH_DISP = MARGIN_WIDTH * FACTOR; public const double MARGIN_HEIGHT_DISP = MARGIN_HEIGHT * FACTOR; public void ChangeEditorWindowTitleStatus(string text) { this.MainWindow.Title = "SightBraille - " + text; } public class BrailleSymbol : IEnumerable { public bool[,] Points = new bool[3, 2]; public BrailleSymbol(string character) { Points = GetBrailleFromString(character); } public bool[,] GetBrailleFromString(string text) { bool[,] braille = new bool[3, 2]; if (text.Length != 6) { return braille; } else { int i = 0; int j = 0; foreach (char c in text) { braille[i, j] = c == '#'; j++; if (j > 1) { j = 0; i++; } } return braille; } } public IEnumerator GetEnumerator() { return Points.GetEnumerator(); } } public class BrailleSymbolSlot { private BrailleSymbol Symbol; public char DisplayLettter; public bool Filler; public BrailleSymbolSlot(char c, BrailleSymbol symbol, bool filler) { this.DisplayLettter = c; this.Symbol = symbol; this.Filler = filler; } public BrailleSymbol GetSymbol() { return Symbol; } } public static Dictionary<char, BrailleSymbol> BrailleDictionary = new Dictionary<char, BrailleSymbol> { {'a', new BrailleSymbol("#-----") }, {'b', new BrailleSymbol("#-#---") }, {'c', new BrailleSymbol("##----") }, {'d', new BrailleSymbol("##-#--") }, {'e', new BrailleSymbol("#--#--") }, {'f', new BrailleSymbol("###---") }, {'g', new BrailleSymbol("####--") }, {'h', new BrailleSymbol("#-##--") }, {'i', new BrailleSymbol("-##---") }, {'j', new BrailleSymbol("-###--") }, {'k', new BrailleSymbol("#---#-") }, {'l', new BrailleSymbol("#-#-#-") }, {'m', new BrailleSymbol("##--#-") }, {'n', new BrailleSymbol("##-##-") }, {'o', new BrailleSymbol("#--##-") }, {'p', new BrailleSymbol("###-#-") }, {'q', new BrailleSymbol("#####-") }, {'r', new BrailleSymbol("#-###-") }, {'s', new BrailleSymbol("-##-#-") }, {'t', new BrailleSymbol("-####-") }, {'u', new BrailleSymbol("#---##") }, {'v', new BrailleSymbol("#-#-##") }, {'w', new BrailleSymbol("-###-#") }, {'x', new BrailleSymbol("##--##") }, {'y', new BrailleSymbol("##-###") }, {'z', new BrailleSymbol("#--###") }, {'à', new BrailleSymbol("#-####") }, {'â', new BrailleSymbol("#----#") }, {'ç', new BrailleSymbol("###-##") }, {'è', new BrailleSymbol("-##-##") }, {'ê', new BrailleSymbol("#-#--#") }, {'ë', new BrailleSymbol("###--#") }, {'é', new BrailleSymbol("######") }, {'î', new BrailleSymbol("##---#") }, {'ï', new BrailleSymbol("####-#") }, {'ô', new BrailleSymbol("##-#-#") }, {'œ', new BrailleSymbol("-##--#") }, {'ù', new BrailleSymbol("-#####") }, {'û', new BrailleSymbol("#--#-#") }, {'ü', new BrailleSymbol("#-##-#") }, //Number {'1', new BrailleSymbol("#----#") }, {'2', new BrailleSymbol("#-#--#") }, {'3', new BrailleSymbol("##---#") }, {'4', new BrailleSymbol("##-#-#") }, {'5', new BrailleSymbol("#--#-#") }, {'6', new BrailleSymbol("###--#") }, {'7', new BrailleSymbol("####-#") }, {'8', new BrailleSymbol("#-##-#") }, {'9', new BrailleSymbol("-##--#") }, {'0', new BrailleSymbol("-#-###") }, {'+', new BrailleSymbol("--###-") }, {'-', new BrailleSymbol("----##") }, {'×', new BrailleSymbol("---##-") }, {'÷', new BrailleSymbol("--##--") }, {'=', new BrailleSymbol("--####") }, {',', new BrailleSymbol("--#---") }, {';', new BrailleSymbol("--#-#-") }, {':', new BrailleSymbol("--##--") }, {'.', new BrailleSymbol("--##-#") }, {'?', new BrailleSymbol("--#--#") }, {'!', new BrailleSymbol("--###-") }, {'"', new BrailleSymbol("--####") }, {'(', new BrailleSymbol("--#-##") }, {')', new BrailleSymbol("---###") }, {'\'', new BrailleSymbol("----#-") }, {'*', new BrailleSymbol("---##-") }, {'/', new BrailleSymbol("-#--#-") }, {'@', new BrailleSymbol("-#-##-") }, //Symbol {'§', new BrailleSymbol("###-#-") }, {'&', new BrailleSymbol("######") }, {'©', new BrailleSymbol("##----") }, {'®', new BrailleSymbol("#-###-") }, {'™', new BrailleSymbol("-####-") }, {'%', new BrailleSymbol("-#--##") }, //Currency {'¥', new BrailleSymbol("##-###") }, {'€', new BrailleSymbol("#--#--") }, {'$', new BrailleSymbol("-##-#-") }, {'£', new BrailleSymbol("#-#-#-") }, }; public static Dictionary<String, BrailleSymbol> BrailleSpecialDictionary = new Dictionary<string, BrailleSymbol> { {NUMBER, new BrailleSymbol("-----#") }, {WHITESPACE, new BrailleSymbol("------") }, {UPPERCASE, new BrailleSymbol("-#---#") }, {SYMBOL, new BrailleSymbol("---#--") }, {CURRENCY, new BrailleSymbol("-#-#--") }, }; public static List<char> WhitespaceChars = new List<char> {' '}; public static List<char> LowercaseChars = new List<char> {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','à','â','ç','è','ê','ë','é','î','ï','ô','œ','ù','û','ü',',',';',':','.','?','!','"','(',')','\'','-','*','/','@'}; public static List<char> UppercaseChars = new List<char> {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','À', 'Â', 'Ç', 'È', 'Ê', 'Ë', 'É', 'Î', 'Ï', 'Ô', 'Œ', 'Ù', 'Û', 'Ü'}; public static List<char> NumberChars = new List<char> {'1','2','3','4','5','6','7','8','9','0','+','-','×','÷','='}; public static List<char> SymbolChars = new List<char> {'§','&','©','®','™','%'}; public static List<char> CurrencyChars = new List<char> {'¥','€','$','£'}; private const string WHITESPACE = "whitespace"; private const string NUMBER = "number"; private const string UPPERCASE = "uppercase"; private const string SYMBOL = "symbol"; private const string CURRENCY = "currency"; public static BrailleCharacter BlankCharacter = new BrailleCharacter(' ', BrailleCharacterType.WHITESPACE); public static BrailleCharacter GetBrailleCharacter(char c) { if(c == ' ') { return BlankCharacter; }else if (LowercaseChars.Contains(c)) { return new BrailleCharacter(c, BrailleCharacterType.LOWERCASE); }else if (UppercaseChars.Contains(c)) { return new BrailleCharacter(c, BrailleCharacterType.UPPERCASE); }else if (NumberChars.Contains(c)) { return new BrailleCharacter(c, BrailleCharacterType.NUMBER); }else if (SymbolChars.Contains(c)) { return new BrailleCharacter(c, BrailleCharacterType.SYMBOL); }else if (CurrencyChars.Contains(c)) { return new BrailleCharacter(c, BrailleCharacterType.CURRENCY); } else { return null; } } [Serializable] public class BrailleCharacter { public char Letter; public BrailleCharacterType Type; [NonSerialized] private List<BrailleSymbolSlot> symbolSlots; public BrailleCharacter(char c, BrailleCharacterType type) { this.Letter = c; this.Type = type; } public List<BrailleSymbolSlot> GetSymbols(BrailleCharacter beforebefore, BrailleCharacter before, BrailleCharacter after) { this.symbolSlots = new List<BrailleSymbolSlot>(); if(Type == BrailleCharacterType.WHITESPACE) { AddSymbolSlotSpecial(WHITESPACE, false); }else if(Type == BrailleCharacterType.LOWERCASE) { if(before.Type == BrailleCharacterType.NUMBER || (beforebefore.Type == BrailleCharacterType.UPPERCASE && before.Type == BrailleCharacterType.UPPERCASE)) { AddSymbolSlotSpecial(WHITESPACE); } AddSymbolSlot(Letter); }else if(Type == BrailleCharacterType.UPPERCASE) { if(before.Type != BrailleCharacterType.UPPERCASE) { if (!IsIndependantCharacter(before)) { AddSymbolSlotSpecial(WHITESPACE); } //If the previous char is not uppercase, then add uppercase mark. If the character after it is also uppercase, then add a second mark. AddSymbolSlotSpecial(UPPERCASE); if(after.Type == BrailleCharacterType.UPPERCASE) { AddSymbolSlotSpecial(UPPERCASE); } } AddSymbolSlot(Letter); }else if(Type == BrailleCharacterType.NUMBER) { //Add number mark if character before is not number if(before.Type != BrailleCharacterType.NUMBER) { AddSymbolSlotSpecial(NUMBER); } AddSymbolSlot(Letter); } else { //Handles both money and special symbols if (!IsIndependantCharacter(before)) { AddSymbolSlotSpecial(WHITESPACE); } if(Type == BrailleCharacterType.CURRENCY) { AddSymbolSlotSpecial(CURRENCY); AddSymbolSlot(Letter); }else if(Type == BrailleCharacterType.SYMBOL) { AddSymbolSlotSpecial(SYMBOL); AddSymbolSlot(Letter); } } return symbolSlots; } private bool IsIndependantCharacter(BrailleCharacter c) { return c.Type == BrailleCharacterType.WHITESPACE || c.Type == BrailleCharacterType.LOWERCASE || c.Type == BrailleCharacterType.SYMBOL || c.Type == BrailleCharacterType.CURRENCY; } private void AddSymbolSlotSpecial(string s, bool filler = true) { this.symbolSlots.Add(new BrailleSymbolSlot(' ', BrailleSpecialDictionary[s], filler)); } private void AddSymbolSlot(char c) { this.symbolSlots.Add(new BrailleSymbolSlot(c, BrailleDictionary[c.ToString().ToLower()[0]], false)); } } public enum BrailleCharacterType { LOWERCASE, UPPERCASE, NUMBER, WHITESPACE, SYMBOL, CURRENCY } } }<file_sep> # <img src="SightBraille/logo.ico" alt="Logo sightbraille" width="35"/> SightBraille Logiciel de contrôle d'un projet d'imprimante à braille *Développé sous WPF en C#* <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using static SightBraille.BrailleEditor; using static SightBraille.SightBrailleApp; namespace SightBraille { public class SerialPortConnection : INotifyPropertyChanged { public string PortName { get; set; } public SerialPort Port; public PortConnectionState State = PortConnectionState.CLOSED; private bool isBusy = false; public Brush DotColor { get { if (State == PortConnectionState.CONNECTED) { return Brushes.Green; } else if (State == PortConnectionState.CHECKING) { return Brushes.Coral; } return Brushes.Gray; } set { } } public SerialPortConnection(string portName) { this.PortName = portName; this.Port = new SerialPort(PortName, 9600, Parity.None, 8, StopBits.One); NotifyPropertyChanged("PortName"); } public void UpdateConnectionAsync() { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (object sender, DoWorkEventArgs e) => { UpdateConnection(); }; worker.RunWorkerAsync(10000); } public void UpdateConnection() { if (!isBusy) { isBusy = true; if (State == PortConnectionState.CLOSED) { if (!Port.IsOpen) { Console.WriteLine("Checking for port " + PortName); setConnectionState(PortConnectionState.CHECKING); try { Port.Open(); if (checkIsBraillePrinter()) { setConnectionState(PortConnectionState.CONNECTED); TriggerAutoSelect(); } else { setConnectionState(PortConnectionState.CLOSED); this.Disconnect(); } } catch (Exception) { } } else { Console.WriteLine(PortName + " is already opened"); setConnectionState(PortConnectionState.CLOSED); } } else if (State == PortConnectionState.CONNECTED) { if (!checkIsBraillePrinter()) { setConnectionState(PortConnectionState.CLOSED); } } } isBusy = false; } private void TriggerAutoSelect() { int i = 0; foreach (SerialPortConnection connection in ((SightBrailleApp.Current as SightBrailleApp).ConnectionManager.SerialPorts)) { if (connection.State == PortConnectionState.CONNECTED) { ((SightBrailleApp.Current as SightBrailleApp).MainWindow as EditorWindow).AutoSelectSerialPort(i); } i++; } } public void SendInstructions() { if (!isBusy) { this.isBusy = true; //Send instructions string instructions = (Application.Current as SightBrailleApp).Document.GetInstructions(); Port.Write(instructions); } this.isBusy = false; } private List<BrailleSymbol> CalculateSymbols(Document document, int row) { List<BrailleCharacter> characters = document.Characters[row]; List<BrailleSymbol> symbols = new List<BrailleSymbol>(); int i = 0; int length = characters.Count; BrailleCharacter before = BlankCharacter; BrailleCharacter beforebefore = BlankCharacter; BrailleCharacter after; //int symbolCountBefore = Symbols[row].Count; foreach (BrailleCharacter character in characters) { if (i < length - 1) { after = characters[i + 1]; } else { after = BlankCharacter; } foreach (BrailleSymbolSlot slot in character.GetSymbols(beforebefore, before, after)) { symbols.Add(slot.GetSymbol()); } //Next beforebefore = before; before = character; i++; } return symbols; } private bool checkIsBraillePrinter() { try { Port.DiscardInBuffer(); Port.DiscardOutBuffer(); Port.WriteLine("IsBraillePrinterCheck"); Port.ReadTimeout = 5000; string response = Port.ReadLine(); Console.WriteLine("Response: " + response); if (response.Contains("IsBraillePrinterConfirmation")) { setConnectionState(PortConnectionState.CONNECTED); Console.WriteLine("Connected!"); return true; } } catch (Exception e) { try { Port.Close(); } catch (IOException) { } Console.WriteLine("An error occured while checking port"); Console.WriteLine(e.Message); } return false; } public void Disconnect() { this.Port.Close(); } private void setConnectionState(PortConnectionState state) { this.State = state; this.NotifyPropertyChanged("State"); this.NotifyPropertyChanged("DotColor"); } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } public enum PortConnectionState { CLOSED, CHECKING, CONNECTED } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using static SightBraille.SightBrailleApp; namespace SightBraille { /// <summary> /// Logique d'interaction pour Window1.xaml /// </summary> public partial class BrailleSymbolListWindow : Window { public SymbolDots firstSymbol = new SymbolDots(); public SymbolDots secondSymbol = new SymbolDots(); public BrailleSymbolListWindow() { InitializeComponent(); List<char> allChars = new List<char>(); allChars.AddRange(SightBrailleApp.LowercaseChars); allChars.AddRange(SightBrailleApp.UppercaseChars); allChars.AddRange(SightBrailleApp.CurrencyChars); allChars.AddRange(SightBrailleApp.NumberChars); allChars.AddRange(SightBrailleApp.SymbolChars); foreach (char c in allChars) { ListViewItem item = new ListViewItem(); item.Content = c; this.CharacterList.Items.Add(item); } this.CharacterList.SelectedIndex = 0; this.SymbolsPanel.Children.Add(firstSymbol.DotCanvas); this.SymbolsPanel.Children.Add(secondSymbol.DotCanvas); this.secondSymbol.DotCanvas.Margin = new Thickness(20, 0, 0, 0); this.CharacterList.MouseDoubleClick += DoubleClick; } private void DoubleClick(object obj, MouseEventArgs args) { if(CharacterList.SelectedIndex != -1) { ((SightBrailleApp.Current as SightBrailleApp).MainWindow as EditorWindow).AddCharacter((char)((ListViewItem)CharacterList.SelectedItem).Content); this.Close(); } } private void CharacterList_SelectionChanged(object sender, SelectionChangedEventArgs e) { char character = ((char)((ListViewItem)CharacterList.SelectedItem).Content); this.Character.Text = character.ToString(); BrailleCharacter braille = GetBrailleCharacter(character); List<BrailleSymbolSlot> slots = braille.GetSymbols(BlankCharacter, BlankCharacter, BlankCharacter); if (slots.Count == 1) { this.firstSymbol.UpdateDots(slots[0].GetSymbol().Points); this.secondSymbol.DotCanvas.Visibility = Visibility.Collapsed; } if (slots.Count == 2) { this.firstSymbol.UpdateDots(slots[0].GetSymbol().Points); this.secondSymbol.DotCanvas.Visibility = Visibility.Visible; this.secondSymbol.UpdateDots(slots[1].GetSymbol().Points); } } } public class SymbolDots { public Canvas DotCanvas; public Ellipse[,] Dots = new Ellipse[3,2]; public SymbolDots() { DotCanvas = new Canvas(); for(int i = 0; i < 3; i++) { for(int j = 0; j < 2; j++) { Dots[i, j] = AddDotAtPos(j, i); } } DotCanvas.Width = 60; DotCanvas.Height = 90; DotCanvas.HorizontalAlignment = HorizontalAlignment.Center; DotCanvas.VerticalAlignment = VerticalAlignment.Center; } public void UpdateDots(bool[,] state) { Brush black = Brushes.Black; Brush empty = Brushes.LightGray; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { Dots[i, j].Fill = state[i, j] ? black : empty; } } } public Ellipse AddDotAtPos(int x, int y) { Ellipse dot = new Ellipse(); dot.Width = 20; dot.Height = 20; dot.Fill = Brushes.Black; Canvas.SetLeft(dot, x * 35); Canvas.SetTop(dot, y * 35); DotCanvas.Children.Add(dot); return dot; } } }
fc9edcb9d390d5d83cf1f8b2e1c2ab2b62c33cbc
[ "Markdown", "C#" ]
8
C#
grandgibus/SightBraille
d7a664654b7e31b82d2ff397730a0224794eaff2
b512b179ccdceab5c541dda41ba1b8f7d145cbb6
refs/heads/master
<repo_name>samimsu/chess.com-games<file_sep>/chess_com_archives.py # chess.com API -> https://www.chess.com/news/view/published-data-api # The API has been used to download monthly archives for a user using a Python3 program. # This program works as of 26/09/2018 import urllib import urllib.request def main(username, directory): baseUrl = f"https://api.chess.com/pub/player/{username}/games/" archivesUrl = baseUrl + "archives" #read the archives url and store in a list f = urllib.request.urlopen(archivesUrl) archives = f.read().decode("utf-8") archives = archives.replace('{"archives":["', '","') archives = archives.rstrip('"]}') archivesList = archives.split(f'","{baseUrl}') #download all the archives for i in range(len(archivesList)-1): url = f"{baseUrl}{archivesList[i+1]}/pgn" filename = f"{archivesList[i+1].replace('/', '-')}" urllib.request.urlretrieve(url, f"{directory}{filename}.pgn") print(f"{filename}.pgn has been downloaded.") print("All files have been downloaded.") main("magnuscarlsen", f"/Users/Magnus/Desktop/THINGS/My Chess Games/") <file_sep>/README.md # chess.com games This [program](chess_com_archives.py) downloads all the chess games of any user from chess.com in monthly archives. Code output: ![Code Output](code-output.bmp) Downloaded files: ![Downloaded Files](downloaded-files.bmp)
2ec61863b8040fdf9fdbb0bc22d518b20c927ed1
[ "Markdown", "Python" ]
2
Python
samimsu/chess.com-games
e9e563d50d81a01aaaf483f2f4926544cb07f786
7cad7134c72c5cd04addea683c9de5ed2feb5cac
refs/heads/master
<file_sep>package com.example.jitendra.newsapp.adapter; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.jitendra.newsapp.R; import com.example.jitendra.newsapp.activities.SavedPagesActivity; import com.example.jitendra.newsapp.databasehandler.SavedPagesHelper; import com.example.jitendra.newsapp.fragment.FullDescriptionFragment; import com.example.jitendra.newsapp.model.UtilSavedPage; import java.util.ArrayList; /** * Created by jitendra on 16/05/2017. */ public class SavedPageAdapter extends RecyclerView.Adapter<SavedPageAdapter.pageViewHolder> { private ArrayList<UtilSavedPage> listSavedPage=new ArrayList<UtilSavedPage>(); private Context context; public SavedPageAdapter(ArrayList<UtilSavedPage> listSavedPage,Context context) { this.listSavedPage = listSavedPage; this.context=context; } @Override public pageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout,parent,false); pageViewHolder holder=new pageViewHolder(view); return holder; } @Override public void onBindViewHolder(final pageViewHolder holder, int position) { final UtilSavedPage page=listSavedPage.get(position); holder.list.setText(page.getTitle()); holder.list.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SavedPagesActivity activity=(SavedPagesActivity)v.getContext(); //hiding all previous content of recyclerview before showing fragment activity.hideRecycer(); ArrayList<String> listOfPages=new ArrayList<String>(); listOfPages.clear(); SavedPagesHelper helper=new SavedPagesHelper(context,null,null,1); listOfPages=(ArrayList<String>) helper.getPage(page.getTitle()).clone(); Bundle bundle=new Bundle(); bundle.putString("cardTitle",listOfPages.get(1)); bundle.putString("cardDiscription",listOfPages.get(2)); bundle.putString("cardImageURL",listOfPages.get(0)); FullDescriptionFragment fragment=new FullDescriptionFragment(); fragment.setArguments(bundle); activity.getSupportFragmentManager().beginTransaction().add(R.id.rl_boolmark,fragment).commit(); } }); } @Override public int getItemCount() { return listSavedPage.size(); } public static class pageViewHolder extends RecyclerView.ViewHolder{ private TextView list; public pageViewHolder(View itemView) { super(itemView); list=(TextView)itemView.findViewById(R.id.tv_titeList); } } } <file_sep>package com.example.jitendra.newsapp.model; /** * Created by jitendra on 11/05/2017. */ public class UtilFragmentCard { private String ImageURL; private String Title; private String Discription; public UtilFragmentCard(String imageURL, String title, String discription) { ImageURL = imageURL; Title = title; Discription = discription; } public UtilFragmentCard() { } public String getImageURL() { return ImageURL; } public void setImageURL(String imageURL) { ImageURL = imageURL; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getDiscription() { return Discription; } public void setDiscription(String discription) { Discription = discription; } } <file_sep>package com.example.jitendra.newsapp.firebase; import android.app.Application; import com.firebase.client.Firebase; /** * Created by jitendra on 11/05/2017. */ public class NewsApp extends Application{ @Override public void onCreate() { super.onCreate(); Firebase.setAndroidContext(this); } } <file_sep>package com.example.jitendra.newsapp.fragment; //Fagment for showing List of news in form of cards import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.jitendra.newsapp.R; import com.example.jitendra.newsapp.adapter.NewsAdapter; import com.example.jitendra.newsapp.model.UtilFragmentCard; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; public class FragmentCardView extends Fragment { private RecyclerView recyclerView; private NewsAdapter adapter; private RecyclerView.LayoutManager layoutManager; private String address; private FirebaseDatabase database; private DatabaseReference mRef; private ArrayList<UtilFragmentCard> cardInfo = new ArrayList<UtilFragmentCard>(); public FragmentCardView() { // Required empty public constructor } //constructor with address of firebase newsFeed /*@SuppressLint("ValidFragment") public FragmentCardView(String address) { this.address = address; }*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @RequiresApi(api = Build.VERSION_CODES.N) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //inflating view View view = inflater.inflate(R.layout.fragment_fragment_card_view, container, false); address=getArguments().getString("address"); recyclerView = (RecyclerView) view.findViewById(R.id.rv_NewsRecycler); layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); database = FirebaseDatabase.getInstance(); mRef = database.getReferenceFromUrl(address); //Adding listener to database references mRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() { @Override public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) { for (com.google.firebase.database.DataSnapshot postSnapShot : dataSnapshot.getChildren()) { cardInfo.add(postSnapShot.getValue(UtilFragmentCard.class)); if (adapter == null) { adapter = new NewsAdapter(cardInfo); } recyclerView.setAdapter(adapter); adapter.notifyDataSetChanged(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); // Inflate the layout for this fragment return view; } } <file_sep> public class Manager extends Employee { private String designation; private int teamSize; //size of team //default constructor to assign default values public Manager(){ super(); designation=""; teamSize=0; } //parametarized constructor public Manager(int id,String Name,int Sal,String designation, int size) { super(id,Name,Sal); this.designation = designation; teamSize = size; } @Override public String toString() { return super.toString()+"\nDesignation=" + designation + "\nSize of team=" + teamSize; } public static void main(String[] args) { int id; //Manager's id String name; //Manager's name int sal; //Manager's salary int size; String Desig; id=001; name="Jitendra"; sal=50000; Desig="Manager"; size=50; Manager M=new Manager(id,name,sal,Desig,size); System.out.println(M); } }<file_sep>package com.example.jitendra.newsapp.databasehandler; //Sqlite helper class to define whole structure of database import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.jitendra.newsapp.model.SavedPages; import java.util.ArrayList; public class SavedPagesHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION=1; private static final String DATABASE_NAME="savedpages.db"; private static final String TEXT=" TEXT "; public static final String TABLE_NAME=" pages "; public static final String COLUMN_TITLE=" title "; public static final String COLUMN_DESCRIPTION =" description "; public static final String COLUMN_IMAGESTRING=" imagestring "; public SavedPagesHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, DATABASE_VERSION); } //creating table in db @Override public void onCreate(SQLiteDatabase db) { String query="CREATE TABLE "+ TABLE_NAME + "(" + COLUMN_TITLE+TEXT+"PRIMARY KEY"+","+ COLUMN_DESCRIPTION +TEXT+","+ COLUMN_IMAGESTRING+TEXT+");"; db.execSQL(query); } //recreating table in db @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME); onCreate(db); } //adding new page to db public void addPage(SavedPages pages){ ContentValues values=new ContentValues(); values.put(COLUMN_TITLE,pages.getTitle()); values.put(COLUMN_DESCRIPTION,pages.getDescription()); values.put(COLUMN_IMAGESTRING,pages.getImageString()); SQLiteDatabase db=getWritableDatabase(); db.insert(TABLE_NAME,null,values); db.close(); } //method returning saved page to display public ArrayList<String> getPage(String pageTitle){ SQLiteDatabase db=getWritableDatabase(); String query="SELECT * FROM "+TABLE_NAME+"WHERE title='"+pageTitle+"'"; //Setting cursor Cursor cursor=db.rawQuery(query,null); ArrayList<String> getPageList=new ArrayList<String>(); /*getPageList.clear();*/ cursor.moveToFirst(); if(cursor.getString(cursor.getColumnIndex("title")).equals(pageTitle)){ getPageList.add(cursor.getString(cursor.getColumnIndex("imagestring"))); getPageList.add(cursor.getString(cursor.getColumnIndex("title"))); getPageList.add(cursor.getString(cursor.getColumnIndex("description"))); } db.close(); return getPageList; } //Accessing page title to display in saved pages tab public ArrayList<String> getPageTitle() { SQLiteDatabase db = getWritableDatabase(); String query = "SELECT * FROM " + TABLE_NAME + "WHERE 1"; //Setting cursor Cursor cursor = db.rawQuery(query, null); //moving cursor to first position ArrayList<String> alTitle=new ArrayList<String>(); while (cursor.moveToNext()) { if (cursor.getString(cursor.getColumnIndex("title")) != null) { alTitle.add(cursor.getString(cursor.getColumnIndex("title"))); } } db.close(); return alTitle; } } <file_sep>package com.example.jitendra.newsapp.activities; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.jitendra.newsapp.R; public class BaseActivity extends AppCompatActivity { @Override protected void onStart() { super.onStart(); SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String fontSize=preferences.getString("fontsizechecked", "SMALL"); //code to apply font size if (fontSize.equals("LARGE")) { setTheme(R.style.Theme_Large); }else if(fontSize.equals("MEDIUM")){ setTheme(R.style.Theme_Medium); }else{ setTheme(R.style.Theme_Small); } //code to toggle imageLoading if (preferences.getBoolean("ImageLoadingOn", false)) { setTheme(R.style.Theme3_Enable); } else { setTheme(R.style.Theme3_Disable); } //code to toggle Night Mode if (preferences.getBoolean("nightModeOn", false)) { setTheme((R.style.Theme2_NightMode)); }else{ setTheme((R.style.Theme2_DayMode)); } } } <file_sep>package com.example.jitendra.newsapp.model; /** * Created by jitendra on 16/05/2017. */ public class UtilSavedPage { private String title; public UtilSavedPage(String title) { this.title = title; } public UtilSavedPage() { } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } <file_sep>package com.example.jitendra.newsapp.activities; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.Switch; import android.widget.Toast; import com.example.jitendra.newsapp.R; import com.jakewharton.processphoenix.ProcessPhoenix; public class SettingActivity extends BaseActivity { private RadioButton largeText; private RadioButton smallText; private RadioButton mediumText; private Switch nightModeSwitch; private Switch imageLoadingSwitch; public SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); largeText = (RadioButton) findViewById(R.id.rb_textSizeLarge); smallText = (RadioButton) findViewById(R.id.rb_textSizeSmall); mediumText = (RadioButton) findViewById(R.id.rb_textSizeMedium); nightModeSwitch = (Switch) findViewById(R.id.s_nightModeEnable); imageLoadingSwitch = (Switch) findViewById(R.id.rg_imageLoading); String fontSize=preferences.getString("fontsizechecked", "SMALL"); //retriving previous state of Setting Activity if (fontSize.equals("LARGE")) { largeText.setChecked(true); }else if(fontSize.equals("MEDIUM")){ mediumText.setChecked(true); }else{ smallText.setChecked(true); } nightModeSwitch.setChecked(preferences.getBoolean("nightModeOn", false)); imageLoadingSwitch.setChecked(preferences.getBoolean("ImageLoadingOn", false)); //onclickListener for large text size largeText.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { largeText.setChecked(true); preferences.edit().putString("fontsizechecked", "LARGE").apply(); } }); //onclickListener for small text size smallText.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { smallText.setChecked(true); preferences.edit().putString("fontsizechecked", "SMALL").apply(); } }); //onclickListener for medium text size mediumText.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mediumText.setChecked(true); preferences.edit().putString("fontsizechecked", "MEDIUM").apply(); } }); //onclickListener for NightMode nightModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked == true) { buttonView.setChecked(true); preferences.edit().putBoolean("nightModeOn", true).apply(); } else { buttonView.setChecked(false); preferences.edit().putBoolean("nightModeOn", false).apply(); } } }); //onclickListener for ImageLoading imageLoadingSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked == true) { buttonView.setChecked(true); preferences.edit().putBoolean("ImageLoadingOn", true).apply(); } else { buttonView.setChecked(false); preferences.edit().putBoolean("ImageLoadingOn", false).apply(); } } }); } } <file_sep> public class Developer extends Employee{ private String languageUsed; // language on which Developer is working private String empDesignation; //default constructor to assign default values public Developer(){ super(); //calling default constructor of parent class languageUsed=""; empDesignation=""; } //parametarized constructor public Developer(int id,String name,int sal,String designation,String language) { super(id,name,sal); languageUsed =language; empDesignation=designation; } @Override public String toString() { return super.toString()+"\nDesignation="+empDesignation+"\nLanguage=" +languageUsed; } public static void main(String[] args) { int id; //dev's id String name; //dev's name int sal; //dev's salary String lang; String desig; id=001; name="Jitendra"; sal=20000; lang="JAVA"; desig="Developer"; Developer dev=new Developer(id,name,sal,desig,lang); System.out.println(dev); } } <file_sep>package com.example.jitendra.newsapp.model; /** * Created by jitendra on 16/05/2017. */ public class SavedPages { private String title; private String description; private String imageString; public SavedPages(String title, String description, String imageString) { this.title = title; this.description = description; this.imageString = imageString; } public SavedPages() { } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getImageString() { return imageString; } public void setImageString(String imageString) { this.imageString = imageString; } }
694e1714cd930d82a9add5b1921ff07f9f76ff64
[ "Java" ]
11
Java
jitendrapurohit12/Assignment1
adc91642ea79166e6ca104f5349923e7bd0d57cd
08e940d76d762d9c94685f6a5b79383ae7a6ed27
refs/heads/master
<repo_name>liuchunhong/Fiter<file_sep>/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-Fiter.build/DerivedSources/Pods_Fiter_vers.c extern const unsigned char Pods_FiterVersionString[]; extern const double Pods_FiterVersionNumber; const unsigned char Pods_FiterVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:Pods_Fiter PROJECT:Pods-1" "\n"; const double Pods_FiterVersionNumber __attribute__ ((used)) = (double)1.; <file_sep>/Build/Intermediates/Fiter.build/Debug-iphoneos/Fiter.build/Script-CA681DF415EA26E43EEA618B.sh #!/bin/sh "${SRCROOT}/Pods/Target Support Files/Pods-Fiter/Pods-Fiter-frameworks.sh" <file_sep>/Podfile use_frameworks! target 'Fiter' do pod 'JSONModel' pod 'Masonry' end
5c7cd45324f57b6b2ee02be6d5e5ad5dda88f301
[ "C", "Ruby", "Shell" ]
3
C
liuchunhong/Fiter
648ff2fd3e98d4fdf40a513a0047b286da29eaee
7d2287eb5811de4a142dcf282586f90ec08ca2c4
refs/heads/master
<file_sep>from GeometricObject import GeometricObject from Circle import Circle from Rectangle import Rectangle c_radius = int(input()) r_width = int(input()) r_height = int(input()) c_color = str(input()) c_filled = bool(input()) r_color = str(input()) r_filled = bool(input()) c = Circle(c_radius,c_color,c_filled) r = Rectangle(r_width,r_height,r_color,r_filled) print("Circle:") print("Radius is ", c.getRadius()) print("Diameter is ", c.getDiameter()) print("Area is ", c.getArea()) print("Perimeter is ", c.getPerimeter()) print("color: ", c.getColor(), " and filled: ", c.isFilled()) print() print("Rectangle:") print("Width is ", r.getWidth()) print("Height is ", r.getHeight()) print("Area is ", r.getArea()) print("Perimeter is ", r.getPerimeter()) print("color: ", r.getColor(), " and filled: ", r.isFilled())<file_sep>from Date import Date from Student import Student s1 = Student("John", 6, 1, 1999, 90) s2 = Student("Marry", 10, 8, 1997, 80) name = str(input()) month = int(input()) day = int(input()) year = int(input()) s1.setName(name) s2.setDate(month,day,year) s1.toString() s2.toString() <file_sep>#ifndef BMI_h #define BMI_h class BMI { public: BMI(double, double); double getBMI(); private: double weight, height; }; #endif <file_sep>#include<iostream> #include<iomanip> #include<string> #include "BMI.h" using namespace std; int main() { string name; double w, h; cin >> name >> w >> h; BMI BMI(w, h); cout << setprecision(2) << fixed << name << BMI.getBMI() << endl; system("pause"); return 0; }<file_sep>from Date import Date class Student(Date): def __init__(self, name, month, day, year, score): super().__init__(month,day,year) self.__date = Date(month,day,year) self.__name = name #self.__date = date self.__score = score def setName(self, name): self.__name = name def setDate(self, month, day, year): self.__date = Date(month,day,year) def setScore(self, score): self.__score = score def getName(self): return self.__name def getDate(self): return self.__date.toString() def getScore(self): return self.__score def toString(self): print(self.__name, self.__date.toString(), self.__score )<file_sep>##西元年份除以4不可整除,為平年。 ##西元年份除以4可整除,且除以100不可整除,為閏年。 ##西元年份除以100可整除,且除以400不可整除,為平年 ##西元年份除以400可整除,為閏年。 def isLeapYear(newYear): if (newYear % 400 == 0) or (newYear % 100 != 0 and newYear % 4 == 0): return True else: return False for i in range(3): day=input() day=int(day) if(isLeapYear(day) == True): print("The",day,"is leap year.") else:print("The",day,"isn't leap year.") <file_sep>from Rectangle import Rectangle l1 = int(input()) l2 = int(input()) w1 = int(input()) w2 = int(input()) r1 = Rectangle(l1, w1) r2 = Rectangle(l2, w2) print(r1.getArea(), " ", r1.getPerimeter()) print(r2.getArea(), " ", r2.getPerimeter()) r2.setLength(50) r2.setWidth(25) print(r2.getArea(), " ", r2.getPerimeter())
3c1f8a7199268cb611f8ab330e8437fe7447679a
[ "Python", "C++" ]
7
Python
peipei0w0/108-2
efa6e20a87bc78aa4862a348dd112461ce838c13
6928d203e09aaf5753114c0154c85fe0d71b1ff8
refs/heads/master
<repo_name>yukihatake1804/Exercise05<file_sep>/Exercise5a/Exercise5a/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercise5a { class Program { static void Main(string[] args) { PrintAtoZ(); PrintAtoZ2(); while (true) { char c = Console.ReadKey().KeyChar; Console.WriteLine(" " + Char2Code(c)); Console.WriteLine("Is Upper? = " + IsUpper(c)); } } static void PrintAtoZ() { for (int i = 65;i < 91; i++) { Console.Write((char)i + " "); } Console.WriteLine(" "); } static void PrintAtoZ2() { for (int i = 90; i > 64; i--) { Console.Write((char)i + " "); } Console.WriteLine(" "); } public static int Char2Code(char c) { return (int)c; } public static bool IsUpper(char c) { if ((int)c > (int)64 && (int)c < (int)91) { return true; } return false; } public static bool IsLower(char c) { if ((int)c > (int)96 && (int)c < (int)123) { return true; } return false; } public static char ToUpper(char c) { return c; } } }
40ff6c7880e303dda7f3022b001512cdc99833b3
[ "C#" ]
1
C#
yukihatake1804/Exercise05
62e04d0d13bb1ca3ce6463c782d86cb8a92e640f
80c1af312328b0d91d6e00024b36ae3b27a6ce52
refs/heads/main
<repo_name>Timoideas/CamiBase<file_sep>/README.md # CamiBase # CamiBase <file_sep>/pages/404.js export default function Error() { return <div>Error el buscar</div>; } <file_sep>/pages/index.js import style from '../styles/Index.module.css'; import Head from '../heads/Head'; export default function Home() { return ( <> <Head /> <div className={style.Title}>H<NAME></div> </> ); }
ceff0bbaf347bc0878e588c94be13440e5349015
[ "Markdown", "JavaScript" ]
3
Markdown
Timoideas/CamiBase
d4361149a636539646ba6295713b1917f1db300a
548fd0f21fb183a8348f95c080eb9d539dbf0555
refs/heads/master
<repo_name>BYU-IS-Media/sass-compass_HSSuiteStyles<file_sep>/qualtrics.php <?php header("access-control-allow-origin:*"); $form_id = 'SV_d5U4bk8YUwDOpFP'; $request_type = 'GET'; $data = array(); foreach(array_merge($_GET,$_POST) AS $key=>$value) { switch($key) { case "form_id": $form_id = $value; break; case "request_type": $request_type = $value; break; default: $data[$key] = $value; break; } } $url = 'https://byu.az1.qualtrics.com/jfe/form/'.$form_id; if(strtoupper($request_type) == "GET"){ $url .= "?"; foreach($data as $key=>$value) { $url .= $key."=".$value."&"; } $url = substr($url,0,strlen($url)-1); } $data_string = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); if(strtoupper($request_type) == "POST") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); } else if(strtoupper($request_type) != "GET") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_type); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); } curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $result=curl_exec ($ch); echo $result; echo curl_error($ch); curl_close ($ch); ?><file_sep>/temp.html <p>Subject to change</p> <h4><span style="font-size:20px">Sunday (July 10)</span></h4> <ul class="schedule"> <li><span>5:30-6:45 p.m.</span><ul><li>Check-in</li><li>Location TBA</li></ul></li> <li><span>7:00-7:45 p.m.</span><ul><li>Welcome/Joe </li><li>Location TBA</li></ul></li> <li><span>7:45-8:00 p.m.</span><ul><li>Orientation</li><li>Location TBA</li></ul></li> <li><span>8:00-8:30 p.m.</span><ul><li>Ice Cream Social</li><li>Location TBA</li></ul></li> <li><span>8:30-10:00 p.m.</span><ul><li>Counselor Activities</li><li>Heleman Halls</li></ul></li> <li><span>10:30 p.m.</span><ul><li>Lights Out</li><li>Heleman Halls</li></ul></li> </ul> <h4><span style="font-size:20px">Monday (July 11)</span></h4> <ul class="schedule"> <li><span>6:30-7:30 a.m.</span><ul><li>Breakfast</li><li>Cannon Center</li></ul></li> <li><span>8:00-8:50 a.m.</span><ul><li>Class (English)</li><li>JKB</li></ul></li> <li><span>9:00-9:50</span><ul><li>Class (Math)</li><li>JKB</li></ul></li> <li><span>10:00-10:50 a.m.</span><ul><li>Class (Science)</li><li>JKB</li></ul></li> <li><span>11:00 am - 12:30 p.m.</span><ul><li>Lunch</li><li>Cannon Center</li></ul></li> <li><span>12:30-1:30 p.m.</span><ul><li>Class (English)</li><li>JKB</li></ul></li> <li><span>1:40-2:40 p.m.</span><ul><li>Class (Math)</li><li>JKB</li></ul></li> <li><span>2:40-3:00 p.m.</span><ul><li>Snack Break</li><li>Snack Tree</li></ul></li> <li><span>3:00-4:00 p.m.</span><ul><li>Class (Science)</li><li>JKB</li></ul></li> <li><span>4:00-6:00 p.m.</span><ul><li>Free Time</li></ul></li> <li><span>6:00-9:00 p.m.</span><ul><li>BBQ Dinner, Games, &amp; Lesson by <NAME></li><li>Helaman Halls</li></ul></li> <li><span>9:00-10:00 p.m.</span><ul><li>Counselor Activities</li><li>Helaman Halls</li></ul></li> <li><span>10:30 p.m.</span><ul><li>Lights Out</li><li>Helaman Halls</li></ul></li> </ul> <h4><span style="font-size:20px">Tuesday (July 12)</span></h4> <ul class="schedule"> <li><span>6:30-7:30 a.m.</span><ul><li>Breakfast</li><li>Cannon Center</li></ul></li> <li><span>8:00-10:00 a.m.</span><ul><li>Camp Photo and Campus Tours</li><li></li></ul></li> <li><span>10:00-12:00 p.m.</span><ul><li>Service Project</li><li>WSC</li></ul></li> <li><span>12:00-1:30 p.m.</span><ul><li>Lunch</li><li>Cannon Center</li></ul></li> <li><span>1:30-2:40 p.m.</span><ul><li>Class (English)</li><li>JKB</li></ul></li> <li><span>2:40-3:00 p.m.</span><ul><li>Snack Break</li><li>Snack Tree</li></ul></li> <li><span>3:00-4:00 p.m.</span><ul><li>Class (Math)</li><li>JKB</li></ul></li> <li><span>4:00-4:50 p.m.</span><ul><li>Class (Science)</li><li>JKB</li></ul></li> <li><span>5:00-6:45 p.m.</span><ul><li>Dinner/Free Time</li><li>Cannon Center</li></ul></li> <li><span>7:00-8:00 p.m.</span><ul><li>Picture Scavenger Hunt</li><li></li></ul></li> <li><span>8:00-10:00 p.m.</span><ul><li>Counselor Activities</li><li>Helaman Halls</li></ul></li> <li><span>10:30 p.m.</span><ul><li>Lights Out</li><li></li></ul></li> </ul> <h4><span style="font-size:20px">Wednesday (July 13)</span></h4> <ul class="schedule"> <li><span>6:30-7:30 a.m.</span><ul><li>Breakfast</li><li>Cannon Center</li></ul></li> <li><span>8:00-8:50 a.m.</span><ul><li>Class (English)</li><li>JKB</li></ul></li> <li><span>9:00-9:50 a.m.</span><ul><li>Class (Math)</li><li>JKB</li></ul></li> <li><span>10:00-10:50 a.m.</span><ul><li>Class (Science)</li><li>JKB</li></ul></li> <li><span>11:00-12:00 p.m.</span><ul><li>Lunch</li><li>Cannon Center</li></ul></li> <li><span>12:00-12:50 p.m.</span><ul><li>Class (English)</li><li>JKB</li></ul></li> <li><span>1:00-1:50 p.m.</span><ul><li>Class (Math)</li><li>JKB</li></ul></li> <li><span>2:00-3:15 p.m.</span><ul><li>Travis B (Admissions)</li><li>TBD</li></ul></li> <li><span>3:15-4:00 p.m.</span><ul><li>Get Ready for 7 Peaks</li><li>JKB</li></ul></li> <li><span>4:00-8:00 p.m.</span><ul><li>7 Peaks</li><li></li></ul></li> <li><span>8:00-10:00 p.m.</span><ul><li>Counselor Activities</li><li>Heleman Halls</li></ul></li> <li><span>10:30 p.m.</span><ul><li>Lights Out</li><li><NAME></li></ul></li> </ul> <h4><span style="font-size:20px">Thursday (July 14)</span></h4> <ul class="schedule"> <li><span>6:30-7:30 a.m.</span><ul><li>Breakfast</li><li>Cannon Center</li></ul></li> <li><span>8:00-8:50 a.m.</span><ul><li>Class (Science)</li><li>JKB</li></ul></li> <li><span>9:00-9:50 p.m.</span><ul><li>ACT Test Orientation (Sue&nbsp;W.)</li><li>JKB</li></ul></li> <li><span>10:00-10:50 a.m.</span><ul><li>Class (English)</li><li>JKB</li></ul></li> <li><span>11:00-11:50 a.m.</span><ul><li>Class (Math)</li><li>JKB</li></ul></li> <li><span>12:00-1:30 p.m.</span><ul><li>Lunch</li><li>Cannon Center</li></ul></li> <li><span>1:30-2:30 p.m.</span><ul><li>Class (Science)</li><li>JKB</li></ul></li> <li><span>2:40-3:40 p.m.</span><ul><li>Class (English)</li><li>JKB</li></ul></li> <li><span>3:40-4:00 p.m.</span><ul><li>Snack Break</li><li>Snack Tree</li></ul></li> <li><span>4:00-5:00 p.m.</span><ul><li>Class (Math)</li><li>JKB</li></ul></li> <li><span>5:00-8:00 p.m.</span><ul><li>Dinner/Free Time</li><li>Heleman Halls</li></ul></li> <li><span>8:00-10:00 p.m.</span><ul><li>Dance/Activity</li><li>TBA</li></ul></li> <li><span>10:30 p.m.</span><ul><li>Lights Out</li><li></li></ul></li> </ul> <h4><span style="font-size:20px">Friday (July 15)</span></h4> <ul class="schedule"> <li><span>6:30-7:30 a.m.</span><ul><li>Breakfast</li><li>Cannon Center</li></ul></li> <li><span>8:00-8:50 a.m.</span><ul><li>Review English</li><li>JKB</li></ul></li> <li><span>9:00-9:50 p.m.</span><ul><li>Review Math</li><li>JKB</li></ul></li> <li><span>10:00-10:50 a.m.</span><ul><li>Review Science</li><li>JKB</li></ul></li> <li><span>11:00-12:30 p.m.</span><ul><li>Lunch</li><li>Cannon Center</li></ul></li> <li><span>12:30-4:00 p.m.</span><ul><li>ACT Test</li><li></li></ul></li> <li><span>4:00-5:00 p.m.</span><ul><li>Tripp G.</li><li>TBD</li></ul></li> <li><span>5:00-7:00 p.m.</span><ul><li>Free Time</li><li>Heleman Halls</li></ul></li> <li><span>7:00-9:00 p.m.</span><ul><li>Pizza Party and Carnival</li><li>Conference Center Patio</li></ul></li> <li><span>9:00-10:00 p.m.</span><ul><li>Counselor Activities</li><li>Heleman Halls</li></ul></li> <li><span>10:30 p.m.</span><ul><li>Lights Out</li><li></li></ul></li> </ul> <h4><span style="font-size:20px">Saturday (July 16)</span></h4> <ul class="schedule"> <li><span>6:30-7:30 a.m.</span><ul><li>Breakfast</li><li>Cannon Center</li></ul></li> <li><span>8:30-9:00 a.m.</span><ul><li>Dorm Check-out</li><li>Heleman Halls</li></ul></li> <li><span>9:15-10:30 a.m.</span><ul><li>BYU Admissions (Travis&nbsp;B.)</li><li>JKB</li></ul></li> </ul> <style type="text/css"> .schedule,.schedule ul { list-style-type:none; margin:0 3em 0.125em 1em; } @media screen and (min-width:530px) { .schedule li { flex-direction:row; } .schedule ul { flex-direction:column; } .schedule li,.schedule ul { display:flex; align-items:left; align-content:stretch; } .schedule > li > *:first-child { width:9.9em; } .schedule ul li:first-child { width:10em; } } @media screen and (min-width:700px) { .schedule li,.schedule ul { flex-direction:row; } .schedule ul li:first-child { margin:0 1em 0.125em 1em; } } </style> <file_sep>/ReadMe.md # BYU HSS Styles creation tool! ## Installation You'll need to install: * [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) or [GitHub](https://help.github.com/desktop/guides/getting-started/installing-github-desktop/) * [Ruby (This link is for Windows)](http://www.ruby-lang.org/en/documentation/installation/#rubyinstaller) and [SASS and Compass](http://compass-style.org/install/) * [Apache (webserver)](https://httpd.apache.org/docs/2.4/platform) This install is slightly more complicated, because it is best run as a system service. The commands are listed here, but I'd recommend additionally adding the ApacheMonitor program to your system startup. This way you can easily turn it on and off. * Alternatively you can use a "stack manager" or other tool: * [XAMPP](https://www.apachefriends.org/index.html) * [bitnami](https://bitnami.com/stack/wamp) * [WAMPP](http://www.wampserver.com/) * I'm sure there are more... * Also, [ApacheHaus](http://www.apachehaus.com/cgi-bin/download.plx) or [Apache Lounge](https://www.apachelounge.com/download/) have the Visual Studio components baked-in... * An editor of your choice * [Eclipse](https://www.eclipse.org/downloads/) * [Sublime](https://www.sublimetext.com/download) * [Brackets](http://brackets.io/) * [Notepad++](https://notepad-plus-plus.org/download) ## Customizing the styles!! ### Files everywhere!!? the folder structure might be a little weird at first, but here's the basics: ``` Top Level │ index.html │ test.html <-- This is the file you can test your styles with locally! │ test2.html <-- These files are links at the bottom right, so no need to remember where │ test3.html they are or how they are named. │ test4.html │ test5.html │ └───HS Suite Files │ │ enroll.html <-- these two files were created for garfield and are a sort of semi- │ │ index.html catalog, which helps them form an email request to their counselor │ │ │ └───CSS <-- This is the output from "compass watch" or "compass compile" │ │ │ somedomain-styles.css │ │ │ [...] | | │ └───Images <-- This is the place you put the images for the school's branding! │ │ somedomain-logo.svg <-- This is what you should call your logo. It makes it | | easier to find what you're looking for if you retain | | consistent naming style. | | [...] <-- lots of images here... | | | └───Common Images <-- This is a folder containing all the images used for | | [...] every domain. Upload all of these to the "Content" for | the domain. │ └───scss │ generic-styles.scss <-- This is the file you copy to create new styles for a domain! │ somedomain-styles.scss <-- this is a made-up file to indicate that this folder also | contains the styles for all existing domains. │ [...] ``` ### Understanding where to start The styles are set up with defaults which you can change to match the school's colors and fit their logo image in. The available defaults and default values are: * ```$theme-color3: rgba(255, 255, 255,.7);``` Background color for the bar at the top of the screen (pre-login only) * ```$school-name: "Placeholder High School";``` * ```$school-name-color: rgb(13, 71, 161);``` * ```$school-logo-filename1: "placeholder-logo.svg";``` * ```$show-school-name: false;``` Pre-login, show the school name? * ```$school-logo-largesize-top-bar-logo-height: 38px;``` This changes the height of the entire top bar stripe on the login page only * ```$school-logo-largesize: 350px;``` logo width * ```$school-logo-largesize-vertical: 160px;``` logo height * ```$school-logo-largesize-position:0 0;``` logo position (within the box provided by the height and width, how is the image positioned. This goes y x, which can be confusing) * ```$school-logo-largesize-top:15px;``` * ```$school-logo-largesize-horizontal:20px;``` * ```$school-logo-largesize-padding:5px 5px 0 5px;``` Padding for the school name text block. * ```$vendor-name: "BYU Independent Study";``` * ```$vendor-logo-largesize: 890x;``` * ```$vendor-logo-mediumsize: 300px;``` * ```$vendor-logo-show: true;``` * ```$theme-color1: rgb(255, 255, 255);``` Background color for the bar at the top post-login * ```$theme-color1-2: rgb(255, 255, 255);``` Background color for the sub-bar at the top post-login * ```$theme-color2: $school-name-color; // rgb(124, 124, 124);``` border color top * ```$school-logo-mediumsize-padding:0 65px 5px 50px;``` This changes the padding on the school text block. * ```$show-school-name-again: false;``` Post-login, show the school name? * ```$school-logo-filename2: "placeholder-logo.svg";``` If this is left to default, it inherits from ```$school-logo-filename1``` * ```$school-logo-mediumsize: 50px;``` This changes the horizontal size of the background image displayed with the school name in the top bar. * ```$school-logo-mediumsize-position:98% 50%;``` This changes where in the bar the logo is displayed (x then y) * ```$theme-color4: rgba(204, 204, 204, 1);``` highlight color, syllabus "left of module contents" background (grey text), "info page" top area background color, gradebook bottom bar background color, mouse hover color, and focus color * ```$theme-color7: rgb(174, 49, 31);``` highlight header color, syllabus "module title bar" background (white text), and focus color * ```$theme-color8: $school-name-color;//rgb(204, 204, 204);``` the "real" highlight color, also the "this item has been clicked on" color * ```$theme-color5: rgb(221, 221, 221);``` highlight dark color, and focus color * ```$theme-color6: rgb(186, 186, 186);``` highlight medium color, headings (white text), and focus color ### Domain isn't using the new styles!!? You need to add this to the "Domain Customization" thing... ``` <files> <file type="style" path="CSS/somedomain-styles.css" /> </files> ```
6357b47f4c20a7d08fec33b8d096c0a63d3585f2
[ "Markdown", "HTML", "PHP" ]
3
PHP
BYU-IS-Media/sass-compass_HSSuiteStyles
137ea893efb87ce6247a0e4ff3074a8b900560a5
20a0a41b7c2192f64cfa8bf49614aa67db84e519
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PairWithMe.Models { public class PairingUser { public string UserName { get; set; } public TimeZone UsersTimeZone { get; set; } public List<string> FavoriteGitHubRepos { get; set; } public PairingUser(string userName, TimeZone usersTimeZone) { UserName = userName; UsersTimeZone = usersTimeZone; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Moq; using NUnit.Framework; using PairWithMe.Controllers; using PairWithMe.Models; namespace PairWithMe.Tests.Controllers { [TestFixture] public class SearchUserAPITest { [Test] public void SearchForCSharpUsers() { //// arrange //var searchCriteria = new SearchCriteria() // { // FavoriteLanguages // = new List<SearchCriteria.ProgrammingLanguages> {SearchCriteria.ProgrammingLanguages.CSharp} // }; //var mock = new Mock<SearchUserController>(); //mock.Setup(x => x.Get(It.IsAny<SearchCriteria>())) // .Returns(new List<PairingUser> { new PairingUser("anotheruser") }); //var controller = mock.Object; //// act //var result = controller.Get(searchCriteria); //// assert //Assert.That(result.Count > 0, "UserCollection Should Contain More than One"); } } }<file_sep>using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Web; using System.Web.Mvc; using PairWithMe.Models; namespace PairWithMe.Controllers { public class PairingUsersController : Controller { private readonly IPairingUserRepository pairinguserRepository; // If you are using Dependency Injection, you can delete the following constructor public PairingUsersController() : this(new PairingUserRepository()) { } public PairingUsersController(IPairingUserRepository pairinguserRepository) { this.pairinguserRepository = pairinguserRepository; ViewBag.Options = new NameValueCollection { { "C++", "SeePlusPlus" }, { "Linux", "Blimix" } }; } // // GET: /PairingUsers/ public ViewResult Index() { return View(pairinguserRepository.All); } // // GET: /PairingUsers/Details/5 public ViewResult Details(int id) { return View(pairinguserRepository.Find(id)); } // // GET: /PairingUsers/Create public ActionResult Create() { return View(); } // // POST: /PairingUsers/Create [HttpPost] public ActionResult Create(PairingUser pairinguser) { if (!ModelState.IsValid) { return View(); } pairinguserRepository.InsertOrUpdate(pairinguser); pairinguserRepository.Save(); return RedirectToAction("Index"); } // // GET: /PairingUsers/Edit/5 public ActionResult Edit(int id) { return View(pairinguserRepository.Find(id)); } // // POST: /PairingUsers/Edit/5 [HttpPost] public ActionResult Edit(PairingUser pairinguser) { if (ModelState.IsValid) { pairinguserRepository.InsertOrUpdate(pairinguser); pairinguserRepository.Save(); return RedirectToAction("Index"); } else { return View(); } } // // GET: /PairingUsers/Delete/5 public ActionResult Delete(int id) { return View(pairinguserRepository.Find(id)); } // // POST: /PairingUsers/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { pairinguserRepository.Delete(id); pairinguserRepository.Save(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { pairinguserRepository.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PairWithMe.Models { public class SearchCriteria { public List<ProgrammingLanguages> FavoriteLanguages; public enum ProgrammingLanguages { CSharp, Java } } }<file_sep>using System.Web.Mvc; using Moq; using NUnit.Framework; using PairWithMe.Controllers; using PairWithMe.Models; namespace PairWithMe.Tests.Controllers { [TestFixture] public class PairingUsersControllerTest { [Test] public void CreatePairingUserTest() { // Arrange var pairingUser = new PairingUser(); var _repository = new Mock<IPairingUserRepository>(); var controller = new PairingUsersController(_repository.Object) { ControllerContext = new Mock<ControllerContext>().Object }; // Act var result = controller.Create(pairingUser) as ActionResult; // Assert Assert.IsNotNull(result, "Cannot Create PairingUser"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using PairWithMe.Models; namespace PairWithMe.Controllers { public class SearchUserController : ApiController { public IList<PairingUser> Get() { throw new NotImplementedException(); } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } public virtual List<PairingUser> Get(SearchCriteria searchCriteria) { throw new NotImplementedException(); } } //public interface ISearchUser //{ // IList<PairingUser> FindUsersByInterest(PairingUser currentUser); // IList<PairingUser> FindUsersByExactTimeZone(TimeZoneInfo pst); //} } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Web; namespace PairWithMe.Models { public class PairingUserRepository : IPairingUserRepository { PairWithMeContext context = new PairWithMeContext(); public IQueryable<PairingUser> All { get { return context.PairingUsers; } } public IQueryable<PairingUser> AllIncluding(params Expression<Func<PairingUser, object>>[] includeProperties) { IQueryable<PairingUser> query = context.PairingUsers; foreach (var includeProperty in includeProperties) { query = query.Include(includeProperty); } return query; } public PairingUser Find(int id) { return context.PairingUsers.Find(id); } public void InsertOrUpdate(PairingUser pairinguser) { if (pairinguser.PairingUserId == default(int)) { // New entity context.PairingUsers.Add(pairinguser); } else { // Existing entity context.Entry(pairinguser).State = EntityState.Modified; } } public void Delete(int id) { var pairinguser = context.PairingUsers.Find(id); context.PairingUsers.Remove(pairinguser); } public void Save() { context.SaveChanges(); } public void Dispose() { context.Dispose(); } } public interface IPairingUserRepository : IDisposable { IQueryable<PairingUser> All { get; } IQueryable<PairingUser> AllIncluding(params Expression<Func<PairingUser, object>>[] includeProperties); PairingUser Find(int id); void InsertOrUpdate(PairingUser pairinguser); void Delete(int id); void Save(); } }
ff818eb87474797582c2c99156f489e36c8b69e5
[ "C#" ]
7
C#
JohnCSimon/PairWithMe
8141a094375530bd63bce05ecd807713b228d451
1c9c1eb63f0de7b96cf81ea1d8d933a720dd690d
refs/heads/master
<repo_name>kuritka/Int.Parse<file_sep>/StringParseSpecs.cs using System; using System.Globalization; using NUnit.Framework; namespace Int.Parse { public partial class StringParseSpecs { [Test] public void CorrectInvariantInput() { Assert.AreEqual(Parse("100"), 100); Assert.AreEqual(Parse("10501"), 10501); } [Test] public void WrongInvariantInput() { ArgumentNullInput(string.Empty); ArgumentNullInput(null); ArgumentInput("100as0"); ArgumentInput("+ 100000 0000 "); ArgumentInput("528.22.12"); ArgumentInput("528..11"); } [Test] public void CorrectInvariantDecimalInput() { Assert.AreEqual(Parse("100.0"), 100); Assert.AreEqual(Parse("15142.2"), 15142); } [Test] public void WrongInvariantDecimalNumberWithThreeDecimalDigits() { Assert.Throws<ArgumentException>(() => Parse("15142.005")); } [Test] public void WrongInvariantDecimalNumberWithWrongDecimalSeparator() { Assert.Throws<ArgumentException>(() => Parse("15142,05")); } [Test] public void CorrectCzechDecimalNumberWithRightDecimalSeparator() { Assert.AreEqual(Parse("15142,05",CultureInfo.GetCultureInfo("cs-CZ")),15142); } [Test] public void WrongCzechDecimalNumberWithWrongCountOfDecimalDigits() { Assert.Throws<ArgumentException>(() => Parse("15142,005", CultureInfo.GetCultureInfo("cs-CZ"))); } [Test] public void InvariantGroupedNumberWithWrongGroupedSeparators() { Assert.Throws<ArgumentException>(() => Parse("15.142.005")); } [Test] public void InputWithGroupedInvarintNumber() { Assert.AreEqual(Parse("11,001.02"), 11001); Assert.AreEqual(Parse("11,001,001.02"), 11001001); } [Test] public void CorrectNegativeInput() { Assert.AreEqual(Parse("-100"), -100); } [Test] public void CorrectPositiveInput() { Assert.AreEqual(Parse("+100"), +100); } [Test] public void TooBigPositiveInput() { Assert.Throws<OverflowException>(() => Parse("1000000000000000000000")); } [Test] public void TooLowNegativeInput() { Assert.Throws<OverflowException>(() => Parse("-1000000000000000000000")); } } } <file_sep>/Parser.cs using System; using System.Globalization; using System.Linq; using System.Runtime.Remoting.Contexts; namespace Int.Parse { [Synchronization] public class Parser : ContextBoundObject { public int ParseInvariant(string number) { return Parse(number, CultureInfo.InvariantCulture); } public int Parse(string number, CultureInfo cultureInfo) { var decimalCounter = 1; var result = 0; if (string.IsNullOrEmpty(number)) { throw new ArgumentNullException(); } number = ProcessDecimalSeparator(number, cultureInfo); number = ProcessGroupSeparators(number, cultureInfo); if (number.StartsWith("-")) { decimalCounter *= -1; number = number.Substring(1); } else if (number.StartsWith("+")) { number = number.Substring(1); } foreach (var charValue in number.Select(c => c - 48)) { if (charValue < 0 || charValue > 9) { throw new ArgumentException("Argument contains invalid characters"); } checked { result = 10*result + charValue; } } return result * decimalCounter; } private static string ProcessDecimalSeparator(string number, CultureInfo cultureInfo) { if (number.Contains(cultureInfo.NumberFormat.NumberDecimalSeparator)) { var decimalParts = number.Split(cultureInfo.NumberFormat.NumberDecimalSeparator.ToCharArray()); if (decimalParts.Count() != 2) { throw new ArgumentException("Invalid input"); } if (decimalParts[1].Length > cultureInfo.NumberFormat.NumberDecimalDigits) { throw new ArgumentException("Invalid input"); } number = number.Split(cultureInfo.NumberFormat.NumberDecimalSeparator.ToCharArray())[0]; } return number; } private static string ProcessGroupSeparators(string number, CultureInfo cultureInfo) { if (number.Contains(cultureInfo.NumberFormat.NumberGroupSeparator)) { var groupParts = number.Split(cultureInfo.NumberFormat.NumberGroupSeparator.ToCharArray()); if (groupParts.Skip(1).All(d => d.Count() == 3)) { number = number.Replace(cultureInfo.NumberFormat.NumberGroupSeparator, string.Empty); if (number == string.Empty) { throw new ArgumentNullException(); } } } return number; } } } <file_sep>/StringParseSpecs.Infrastructure.cs using System; using System.Globalization; using NUnit.Framework; namespace Int.Parse { partial class StringParseSpecs { private void ArgumentInput(string input) { Assert.Throws<ArgumentException>(() => Parse(input)); } private void ArgumentNullInput(string input) { Assert.Throws<ArgumentNullException>(() => Parse(input)); } private int Parse(string number) { return new Parser().ParseInvariant(number); } private int Parse(string number, CultureInfo cultureInfo) { return new Parser().Parse(number, cultureInfo); } } }
8cdc9e45d799bb781ad901939860d5de7676c74d
[ "C#" ]
3
C#
kuritka/Int.Parse
0a6696893546828ad6f2bb9db1c637abde732f48
7eaddbac644bef5a6263699c8d392752b995bb5b