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/master
<repo_name>KyloRen444/DragonSurge1.14.4<file_sep>/src/main/java/net/mcreator/dragonsurge/world/biome/TESTBiome.java package net.mcreator.dragonsurge.world.biome; import net.minecraftforge.registries.ObjectHolder; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraft.world.gen.surfacebuilders.SurfaceBuilderConfig; import net.minecraft.world.gen.surfacebuilders.SurfaceBuilder; import net.minecraft.world.gen.placement.Placement; import net.minecraft.world.gen.placement.FrequencyConfig; import net.minecraft.world.gen.placement.AtSurfaceWithExtraConfig; import net.minecraft.world.gen.feature.MultipleRandomFeatureConfig; import net.minecraft.world.gen.feature.IFeatureConfig; import net.minecraft.world.gen.feature.GrassFeatureConfig; import net.minecraft.world.gen.feature.Feature; import net.minecraft.world.gen.GenerationStage; import net.minecraft.world.biome.DefaultBiomeFeatures; import net.minecraft.world.biome.Biome; import net.minecraft.block.Blocks; import net.mcreator.dragonsurge.block.YellowOreBlock; import net.mcreator.dragonsurge.block.LightdragonsurgegrassBlock; import net.mcreator.dragonsurge.DragonSurgeElements; @DragonSurgeElements.ModElement.Tag public class TESTBiome extends DragonSurgeElements.ModElement { @ObjectHolder("dragonsurge:test") public static final CustomBiome biome = null; public TESTBiome(DragonSurgeElements instance) { super(instance, 138); } @Override public void initElements() { elements.biomes.add(() -> new CustomBiome()); } @Override public void init(FMLCommonSetupEvent event) { } static class CustomBiome extends Biome { public CustomBiome() { super(new Biome.Builder().downfall(0.5f).depth(0.1f).scale(0.2f).temperature(0.5f).precipitation(Biome.RainType.RAIN) .category(Biome.Category.NONE).waterColor(4159204).waterFogColor(329011).parent("dragonsurge:test") .surfaceBuilder(SurfaceBuilder.DEFAULT, new SurfaceBuilderConfig(LightdragonsurgegrassBlock.block.getDefaultState(), YellowOreBlock.block.getDefaultState(), YellowOreBlock.block.getDefaultState()))); setRegistryName("test"); DefaultBiomeFeatures.addCarvers(this); DefaultBiomeFeatures.addStructures(this); DefaultBiomeFeatures.addMonsterRooms(this); DefaultBiomeFeatures.addOres(this); DefaultBiomeFeatures.addLakes(this); addFeature(GenerationStage.Decoration.VEGETAL_DECORATION, Biome.createDecoratedFeature(Feature.DEFAULT_FLOWER, IFeatureConfig.NO_FEATURE_CONFIG, Placement.COUNT_HEIGHTMAP_32, new FrequencyConfig(4))); addFeature(GenerationStage.Decoration.VEGETAL_DECORATION, Biome.createDecoratedFeature(Feature.GRASS, new GrassFeatureConfig(Blocks.GRASS.getDefaultState()), Placement.COUNT_HEIGHTMAP_DOUBLE, new FrequencyConfig(4))); addFeature(GenerationStage.Decoration.VEGETAL_DECORATION, Biome.createDecoratedFeature(Feature.RANDOM_SELECTOR, new MultipleRandomFeatureConfig(new Feature[]{Feature.BIRCH_TREE, Feature.FANCY_TREE}, new IFeatureConfig[]{IFeatureConfig.NO_FEATURE_CONFIG, IFeatureConfig.NO_FEATURE_CONFIG}, new float[]{0.2F, 0.1F}, Feature.NORMAL_TREE, IFeatureConfig.NO_FEATURE_CONFIG), Placement.COUNT_EXTRA_HEIGHTMAP, new AtSurfaceWithExtraConfig(4, 0.1F, 1))); } } }
2d5542cd213183e65343b0fb0b3ef5a78b736b21
[ "Java" ]
1
Java
KyloRen444/DragonSurge1.14.4
3ea74b6c35965a0f06b521ae25d7bda1852349d7
584b77ef0a77bc2950a828a83af102562a81215b
refs/heads/master
<file_sep>package com.natlus.yarsi import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ArrayAdapter import androidx.databinding.DataBindingUtil import com.natlus.yarsi.databinding.ActivityParentFormBinding import com.natlus.yarsi.databinding.ActivitySchoolFormBinding import com.natlus.yarsi.models.Parent import com.natlus.yarsi.models.Pribadi import com.natlus.yarsi.models.School class SchoolFormActivity : AppCompatActivity() { private val DATA_PRIBADI = "DATA_PRIBADI" private val DATA_PARENT = "DATA_PARENT" private val DATA_SCHOOL = "DATA_SCHOOL" private lateinit var binding: ActivitySchoolFormBinding private lateinit var dataProvinsi: Array<String> private lateinit var dataKota: Array<String> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_school_form) setUp() loadDataSpinner() binding.btnGoToResult.setOnClickListener { intentToResult() } } private fun setUp() { dataProvinsi = resources.getStringArray(R.array.dataProvinsi) dataKota = resources.getStringArray(R.array.dataKota) } private fun loadDataSpinner() { val adapterProvinsi = ArrayAdapter(this, android.R.layout.simple_spinner_item, dataProvinsi) val adapterKota = ArrayAdapter(this, android.R.layout.simple_spinner_item, dataKota) adapterProvinsi.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) adapterKota.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) binding.spinnerProvinsiUnivAsal.adapter = adapterProvinsi binding.spinnerKotaUnivAsal.adapter = adapterKota } private fun intentToResult() { val dataSchool = School( namaUnivAsal = binding.editTextUnivAsal.text.toString(), namaFakultasAsal = binding.editTextFakultasAsal.text.toString(), namaProdiAsal = binding.editTextProdiAsal.text.toString(), provinsiUnivAsal = binding.spinnerProvinsiUnivAsal.selectedItem.toString(), kotaUnivAsal = binding.spinnerKotaUnivAsal.selectedItem.toString(), alamatUnivAsal = binding.editTextAlamatUnivAsal.text.toString(), kodePosUnivAsal = binding.editTextKodePos.text.toString(), akreditasiUnivAsal = binding.editTextAkreditasiUnivAsal.text.toString(), nilaiIPK = binding.editTextNilaiIPK.text.toString(), ) val dataParent = intent.getParcelableExtra<Parent>(DATA_PARENT)!! val dataPribadi = intent.getParcelableExtra<Pribadi>(DATA_PRIBADI)!! val resultIntent = Intent(this, ResultFormActivity::class.java) resultIntent.putExtra(DATA_SCHOOL, dataSchool) resultIntent.putExtra(DATA_PARENT, dataParent) resultIntent.putExtra(DATA_PRIBADI, dataPribadi) startActivity(resultIntent) } }<file_sep>package com.natlus.yarsi import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import com.natlus.yarsi.databinding.ActivityResultFormBinding import com.natlus.yarsi.models.Parent import com.natlus.yarsi.models.Pribadi import com.natlus.yarsi.models.School class ResultFormActivity : AppCompatActivity() { private val DATA_PRIBADI = "DATA_PRIBADI" private val DATA_PARENT = "DATA_PARENT" private val DATA_SCHOOL = "DATA_SCHOOL" private lateinit var binding: ActivityResultFormBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_result_form) binding.school = intent.getParcelableExtra<School>(DATA_SCHOOL)!! binding.parent = intent.getParcelableExtra<Parent>(DATA_PARENT)!! binding.pribadi = intent.getParcelableExtra<Pribadi>(DATA_PRIBADI)!! } }<file_sep>package com.natlus.yarsi import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.databinding.DataBindingUtil import com.natlus.yarsi.databinding.ActivityMainBinding import com.natlus.yarsi.databinding.ActivityParentFormBinding import com.natlus.yarsi.models.Parent import com.natlus.yarsi.models.Pribadi class ParentFormActivity : AppCompatActivity() { private val DATA_PRIBADI = "DATA_PRIBADI" private val DATA_PARENT = "DATA_PARENT" private lateinit var binding: ActivityParentFormBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_parent_form) binding.btnParenttoSchool.setOnClickListener { intentToSchool() } } private fun intentToSchool() { val dataParent = Parent( namaAyah = binding.editTextNamaAyah.text.toString(), nikAyah = binding.editTextNikAyah.text.toString(), namaIbu = binding.editTextNamaIbu.text.toString(), nikIbu = binding.editTextNikIbu.text.toString(), tanggalLahirAyah = binding.editTextLahirAyah.text.toString(), tanggalLahirIbu = binding.editTextLahirIbu.text.toString(), alamatParent = binding.editTextAlamat.text.toString(), phoneOrtu = binding.editTextPhone.text.toString(), emailParent = binding.editTextEmail.text.toString(), pendidikanAyah = binding.editTextPendidikanAyah.text.toString(), pendidikanIbu = binding.editTextPendidikanIbu.text.toString(), pekerjaanAyah = binding.editTextPekerjaanAyah.text.toString(), pekerjaanIbu = binding.editTextPekerjaanIbu.text.toString(), ) val dataPribadi = intent.getParcelableExtra<Pribadi>(DATA_PRIBADI)!! val resultIntent = Intent(this, SchoolFormActivity::class.java) resultIntent.putExtra(DATA_PARENT, dataParent) resultIntent.putExtra(DATA_PRIBADI, dataPribadi) startActivity(resultIntent) } }
b0d23913e32d5e3e71fff4600b884c3126493f24
[ "Kotlin" ]
3
Kotlin
SultanKs4/yarsi
e40335be2ca2368787eb07327ec6699afbf5ac89
e7930959150bf3cdc65f933a88bbee513bcb2c4f
refs/heads/main
<file_sep>const Engine = Matter.Engine; const Render = Matter.Render; const World = Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint; const Body = Matter.Body; const Composites = Matter.Composites; const Composite = Matter.Composites; let engine; let world; var ground; var con; function setup() { createCanvas(400,400); engine = Engine.create(); world = engine.world; con = Matter.Constraint.create({ pointA:{x:200,y:20}, bodyB:ball, pointB:{x:0,y:0}, length:100, stiffness:0.1 }); World.add(world,con); rectMode(CENTER); ellipseMode(RADIUS); } function draw() { background(51); Engine.update(engine); ellipse(ball.position.x,ball.position.y,10); ellipse(ball2.position.x,ball2.position.y,20) push(); strokeWeight(2); stroke(255); line(con.pointA.x,con.pointA.y,ball.position.x,ball.position.y); line(ball.position.x,ball.position.y,ball2.position.x,ball2.position.y); pop(); }
32491dcf8db766bddc919277e3e531db51374809
[ "JavaScript" ]
1
JavaScript
samuraivai2007/bp
01ebaf498500943853addccb4161a8be7dee1f2d
c37fda883c8b4824934a2afc1570901a9619336b
refs/heads/master
<repo_name>noahcas25/MobileUtilities<file_sep>/Assets/Scripts/StoreController.cs using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using UnityEngine; using Button = UnityEngine.UI.Button; public class StoreController : MonoBehaviour { // Global Variables private int diceCount = 7; private int diceIndex = 0; private int newIndex = 0; private GameObject bg; private GameObject selectedText; private string materialName; // variables that are set when application is started void Start() { Application.targetFrameRate = 60; diceCount = transform.childCount; // Sets dice positions for the camera to track when the dice buttons are clicked for(int i = 0; i < diceCount - 1; i++) { transform.GetChild(i).GetComponent<StartMenuRotator>().setPosX(((-145*i)+(-3))); } } // PlayerSettings that are loaded on enable of the scene void OnEnable() { bg = GameObject.FindWithTag("Backgrounds"); selectedText = GameObject.FindWithTag("SelectedDiceText"); if(PlayerPrefs.HasKey("diceIndex")) this.newIndex = PlayerPrefs.GetInt("diceIndex"); if(PlayerPrefs.HasKey("BgColor")) BackgroundChange(PlayerPrefs.GetString("BgColor")); if(PlayerPrefs.HasKey("materialName")) ChangeMaterial(PlayerPrefs.GetString("materialName")); else materialName = "WhiteOnBlackMatte"; ButtonClicked(newIndex); } // PlayerSettings that are saved on disable of the scene void OnDisable() { PlayerPrefs.SetInt("diceIndex", diceIndex); PlayerPrefs.SetString("materialName", materialName); PlayerPrefs.Save(); } // Sets the selected dice as the active one private void SetDice() { // turns on the indicator for the selected dice transform.GetChild(6).transform.GetChild(diceIndex).gameObject.SetActive(false); transform.GetChild(6).transform.GetChild(newIndex).gameObject.SetActive(true); diceIndex = newIndex; } // Disables all backgrounds and enables the selected one through a switch statement private void BackgroundChange(string color) { bg.transform.GetChild(0).gameObject.SetActive(false); bg.transform.GetChild(1).gameObject.SetActive(false); bg.transform.GetChild(2).gameObject.SetActive(false); switch(color) { case "red": bg.transform.GetChild(0).gameObject.SetActive(true); break; case "green": bg.transform.GetChild(1).gameObject.SetActive(true); break; default: bg.transform.GetChild(2).gameObject.SetActive(true); break; } } // Function that sets the selected dice and changes camera position public void ButtonClicked(int index) { int buttonPosition = transform.GetChild(index).GetComponent<StartMenuRotator>().getPosX(); transform.parent.gameObject.GetComponent<RectTransform>().localPosition = new Vector3(buttonPosition, 289, 0); newIndex = index; SetDice(); // Updates SelectedDiceText selectedText.GetComponent<TMPro.TextMeshProUGUI>().text = SelectedDiceInfo(); } // Handles the MaterialButton Function public void ChangeMaterial(string matName) { for(int i = 0; i < (diceCount - 1); i++) { transform.GetChild(i).GetComponent<MeshRenderer>().material = Resources.Load(matName + "/" + transform.GetChild(i).gameObject.name + "_" + matName + "Material", typeof(Material)) as Material; } materialName = matName; } // Changes the text above the roll button based on which dice is chosen public string SelectedDiceInfo(){ switch(newIndex){ case 0: return "Round"; break; case 1: return "Square"; break; case 2: return "8 Sided"; break; case 3: return "10 Sided"; break; case 4: return "12 Sided"; break; case 5: return "20 Sided"; break; default: return "Rounded"; } } }<file_sep>/Assets/Scripts/TextUpdater.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using InnerDriveStudios.DiceCreator; using TMPro; public class TextUpdater : MonoBehaviour { // Global variables private string diceSideUp; private GameObject dice; private bool landed; // On start save the closestMatching diceSideUp to a variable void Start() { dice = GameObject.FindWithTag("Dice"); diceSideUp = dice.GetComponent<DieSides>().GetDieSideMatchInfo().closestMatch.ToString(); } // Updates the diceSideUp variable when the dice lands and changes the result text based on the result void Update() { if(dice.GetComponent<Dice>().GetLanded() && diceSideUp != dice.GetComponent<DieSides>().GetDieSideMatchInfo().closestMatch.ToString()) { diceSideUp = dice.GetComponent<DieSides>().GetDieSideMatchInfo().closestMatch.ToString(); GetComponent<TMPro.TextMeshProUGUI>().text = "" + diceSideUp[8]; if(diceSideUp.Length > 9) { GetComponent<TMPro.TextMeshProUGUI>().text += diceSideUp[9]; } } } }<file_sep>/Assets/Scripts/HomeScreen.cs using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class HomeScreen : MonoBehaviour { // Global Variables public GameObject diceOverlay; private GameObject canvasOverlay; private GameObject volumeSlider; private GameObject bg; private Animator anim; private float volume = 0; private int diceIndex = 0; private int newIndex = 0; private string color; // variables that are set when application is started public void Start() { Application.targetFrameRate = 60; anim = GameObject.FindWithTag("TransitionImage").GetComponent<Animator>(); canvasOverlay = GameObject.FindWithTag("CanvasOverlay"); anim.CrossFade("SceneSwitchInHomeScreen", 0, 0, 0, 0); volume = GetComponent<AudioSource>().volume; volumeSlider = transform.GetChild(1).GetChild(0).GetChild(3).gameObject; } // PlayerSettings that are loaded on enable of the scene void OnEnable() { bg = GameObject.FindWithTag("Backgrounds"); if(PlayerPrefs.HasKey("diceIndex")) this.newIndex = PlayerPrefs.GetInt("diceIndex"); if(PlayerPrefs.HasKey("Volume")) { volume = PlayerPrefs.GetFloat("Volume"); GetComponent<AudioSource>().volume = volume; } if(PlayerPrefs.HasKey("BgColor")) { BackgroundChange(PlayerPrefs.GetString("BgColor")); } if(PlayerPrefs.HasKey("materialName")) ChangeMaterial(PlayerPrefs.GetString("materialName")); setDice(); } // Player settings that are saved on disable of the scene void OnDisable() { PlayerPrefs.SetFloat("Volume", volume); PlayerPrefs.Save(); } // Sets the selected dice as the active one private void setDice() { diceOverlay.transform.GetChild(diceIndex).gameObject.SetActive(false); diceOverlay.transform.GetChild(newIndex).gameObject.SetActive(true); diceIndex = newIndex; } // Function used by the volumeSlider to adjust audiosource's volume public void UpdateVolume() { volume = volumeSlider.GetComponent<Slider>().value; GetComponent<AudioSource>().volume = volume; } // Disables all backgrounds and enables the selected one through a switch statement public void BackgroundChange(string color) { bg.transform.GetChild(0).gameObject.SetActive(false); bg.transform.GetChild(1).gameObject.SetActive(false); bg.transform.GetChild(2).gameObject.SetActive(false); switch(color) { case "red": bg.transform.GetChild(0).gameObject.SetActive(true); break; case "green": bg.transform.GetChild(1).gameObject.SetActive(true); break; default: bg.transform.GetChild(2).gameObject.SetActive(true); break; } PlayerPrefs.SetString("BgColor", color); } // Changes the ActiveDices Material public void ChangeMaterial(string matName) { diceOverlay.transform.GetChild(newIndex).GetComponent<MeshRenderer>().material = Resources.Load(matName + "/" + diceOverlay.transform.GetChild(newIndex).gameObject.name + "_" + matName + "Material", typeof(Material)) as Material; } // Function that sets the option canvas as the active canvas on screen and disables the start canvas public void Options() { diceOverlay.SetActive(false); canvasOverlay.transform.GetChild(0).gameObject.SetActive(false); canvasOverlay.transform.GetChild(1).gameObject.SetActive(true); volumeSlider.GetComponent<Slider>().value = volume; } // Function that sets the start canvas as the active canvas on screen and disables the option canvas public void Back() { diceOverlay.SetActive(true); canvasOverlay.transform.GetChild(0).gameObject.SetActive(true); canvasOverlay.transform.GetChild(1).gameObject.SetActive(false); } // Transitions to the dice rolling scene public void DiceRoll() { StartCoroutine(Transition("3D Dice")); } // Transitions to the shop scene public void Shop() { StartCoroutine(Transition("Shop")); } // Function that handles the transition animations and loads a new scene private IEnumerator Transition(string scene) { anim.CrossFade("SceneSwitchOutHomeScreen", 0, 0, 0, 0); yield return new WaitForSeconds((float) 0.5); SceneManager.LoadScene(scene); } } <file_sep>/Assets/Scripts/AdsManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Advertisements; public class AdsManager : MonoBehaviour, IUnityAdsListener { // Changes the gameId and type string if IOS or Android #if UNITY_IOS string gameId = "4395794"; string type = "iOS"; #else string gameId = "4395795"; string type = "Android"; #endif // Initialize advertisements void Start() { Advertisement.Initialize(gameId); } // Plays Interstitial ad; Quick Ad public void PlayAd() { if(Advertisement.IsReady("Interstitial_" + type)) { Advertisement.Show("Interstitial_" + type); } else Debug.Log("Ads not ready"); } // Plays Reward ad; Longer Ad public void PlayRewardAd() { if(Advertisement.IsReady("Rewarded_" + type)) { Advertisement.Show("Rewarded_" + type); } else Debug.Log("Ads not ready"); } // Necessary Methods for Ads public void OnUnityAdsReady(string placementId) { throw new System.NotImplementedException(); } public void OnUnityAdsDidError(string message) { Debug.Log("ERROR: " + message); } public void OnUnityAdsDidStart(string placementId) { Debug.Log("VIDEO STARTED"); } public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) { if(placementId == "Reward" && showResult == ShowResult.Finished) { Debug.Log("PLAYER REWARDED"); } } } <file_sep>/Assets/Scripts/StartMenuRotator.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class StartMenuRotator : MonoBehaviour { public bool isShop = false; private int posX; // Update is called once per frame void Update() { // Rotates the dice depending on which scene its in if(isShop) this.transform.Rotate(new Vector3(0, 30, 0) * (float) 2 * Time.deltaTime); else this.transform.Rotate(new Vector3(0, 0, 20) * (float) 2 * Time.deltaTime); } // Sets the dices world position in Shop scene public void setPosX(int value) { if(value > -730 && value < 1) { posX = value; } } // Gets the dices world position in Shop scene public int getPosX() { return posX; } } <file_sep>/Assets/Scripts/Menu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using TMPro; public class Menu : MonoBehaviour { // Global Variables private GameObject dice; private Vector3 dicePosition; private GameObject rollButton; private GameObject rollButtonChild; private GameObject bg; private GameObject volumeSlider; private float volume = 0; private int diceIndex = 0; private int newIndex = 0; public GameObject diceOverlay; private GameObject pauseMenu; private Animator anim; // Ad variables public AdsManager ads; private int adCounter; // Start is called before the first frame update void Start() { Application.targetFrameRate = 60; pauseMenu = GameObject.FindWithTag("PauseMenu"); rollButton = GameObject.FindWithTag("RollButton"); rollButtonChild = rollButton.transform.GetChild(1).gameObject; volumeSlider = pauseMenu.transform.GetChild(1).GetChild(2).gameObject; anim = GameObject.FindWithTag("TransitionImage").GetComponent<Animator>(); anim.CrossFade("SceneSwitchInDice", 0, 0, 0, 0); adCounter = 0; } // PlayerSettings that are loaded on enable of the scene * void OnEnable() { bg = GameObject.FindWithTag("Backgrounds"); // Load playerPrefs on startUp if(PlayerPrefs.HasKey("diceIndex")) this.newIndex = PlayerPrefs.GetInt("diceIndex"); if(PlayerPrefs.HasKey("Volume")) { volume = PlayerPrefs.GetFloat("Volume"); GetComponent<AudioSource>().volume = volume; } if(PlayerPrefs.HasKey("BgColor")) BackgroundChange(PlayerPrefs.GetString("BgColor")); // Load the selected dice, save the position and turn off gravity settings for dice and its overlay SetDice(); dice = GameObject.FindWithTag("Dice"); dicePosition = dice.transform.parent.transform.position; dice.GetComponent<Rigidbody>().useGravity = false; diceOverlay.GetComponent<Rigidbody>().useGravity = false; if(PlayerPrefs.HasKey("materialName")) ChangeMaterial(PlayerPrefs.GetString("materialName")); } // Player settings that are saved on disable of the scene void OnDisable() { PlayerPrefs.SetFloat("Volume", volume); PlayerPrefs.Save(); } // Sets the selected dice as the active one void SetDice() { diceOverlay.transform.GetChild(diceIndex).gameObject.SetActive(false); diceOverlay.transform.GetChild(newIndex).gameObject.SetActive(true); } // Function that rolls the dice public void Roll() { if(dice.GetComponent<Dice>().GetCanRoll()) { adCounter++; // Plays ad every 10th roll if(adCounter%10==0) { ads.PlayAd(); } // adjusts dice physics on roll diceOverlay.transform.rotation = Quaternion.identity; dice.GetComponent<Rigidbody>().useGravity = true; diceOverlay.GetComponent<Rigidbody>().useGravity = true; diceOverlay.GetComponent<Rigidbody>().AddForce(35, -20, 35, ForceMode.Impulse); dice.GetComponent<Rigidbody>().AddForce(35, -20, 35, ForceMode.Impulse); // disable roll buttons rollButton.GetComponent<Button>().enabled = false; rollButtonChild.GetComponent<TMPro.TextMeshProUGUI>().enabled = false; // position the dice and disable roll function SetPositions(); dice.GetComponent<Dice>().SetCanRoll(false); dice.GetComponent<Dice>().SetLanded(false); StartCoroutine(RollTimer()); } } // Timer that reinstates the roll function after 4 seconds private IEnumerator RollTimer() { yield return new WaitForSeconds((float) 4); rollButton.GetComponent<Button>().enabled = true; rollButtonChild.GetComponent<TMPro.TextMeshProUGUI>().enabled = true; dice.GetComponent<Dice>().SetCanRoll(true); } // Function that prepares dice for roll private void SetPositions() { dice.GetComponent<Dice>().Randomize(); diceOverlay.transform.position = dicePosition; dice.transform.position = dicePosition; dice.GetComponent<Rigidbody>().velocity = Vector3.zero; dice.GetComponent<Rigidbody>().angularVelocity = Vector3.zero; diceOverlay.GetComponent<Rigidbody>().velocity = Vector3.zero; diceOverlay.GetComponent<Rigidbody>().angularVelocity = Vector3.zero; } // Function used by the volumeSlider to adjust audiosource's volume public void UpdateVolume() { volume = volumeSlider.GetComponent<Slider>().value; GetComponent<AudioSource>().volume = volume; } // Disables all backgrounds and enables the selected one through a switch statement * public void BackgroundChange(string color) { bg.transform.GetChild(0).gameObject.SetActive(false); bg.transform.GetChild(1).gameObject.SetActive(false); bg.transform.GetChild(2).gameObject.SetActive(false); switch(color) { case "red": bg.transform.GetChild(0).gameObject.SetActive(true); break; case "green": bg.transform.GetChild(1).gameObject.SetActive(true); break; default: bg.transform.GetChild(2).gameObject.SetActive(true); break; } PlayerPrefs.SetString("BgColor", color); } // Changes the ActiveDices Material public void ChangeMaterial(string matName) { dice.GetComponent<MeshRenderer>().material = Resources.Load(matName + "/" + dice.gameObject.name + "_" + matName + "Material", typeof(Material)) as Material; } // Calls the pausemenu switcher method that pauses the game public void PauseMenu() { volumeSlider.GetComponent<Slider>().value = volume; pauseMenu.GetComponent<PauseMenu>().Switcher(anim); } // Transitions to the HomeScreen scene public void Back() { StartCoroutine(Transition("HomeScreen")); } // Function that handles the transition animations and loads a new scene private IEnumerator Transition(string scene) { anim.CrossFade("SceneSwitchOutDice", 0, 0, 0, 0); yield return new WaitForSeconds((float) 0.5); SceneManager.LoadScene(scene); } } <file_sep>/Assets/Scripts/SettingsMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SettingsMenu : MonoBehaviour { // Function that changes the active canvas to the pauseMenuCanvas; public void Back() { transform.GetChild(0).gameObject.SetActive(true); transform.GetChild(1).gameObject.SetActive(false); } } <file_sep>/Assets/Scripts/ShopMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class ShopMenu : MonoBehaviour { private Animator animator; private GameObject selectedDiceText; private GameObject palletCanvas; // PlayerSettings that are loaded on enable of the scene public void OnEnable() { animator = GameObject.FindWithTag("TransitionImage").GetComponent<Animator>(); animator.CrossFade("SceneSwitchInShop", 0, 0, 0, 0); palletCanvas = GameObject.FindWithTag("PauseMenu"); palletCanvas.SetActive(false); if(PlayerPrefs.HasKey("Volume")) { GetComponent<AudioSource>().volume = PlayerPrefs.GetFloat("Volume"); } } // Transitions to the HomeScreen public void Back() { // Time.timeScale = 1f; StartCoroutine(Transition("HomeScreen")); } // Activates the pallet canvas in the shop public void MaterialPallet() { if(!palletCanvas.activeSelf) palletCanvas.SetActive(true); else palletCanvas.SetActive(false); } // Transitions to the Roll Scene public void RollButton() { // Time.timeScale = 1f; StartCoroutine(Transition("3D Dice")); } // Function that handles the transition animations and loads a new scene private IEnumerator Transition(string scene) { animator.CrossFade("SceneSwitchOutShop", 0, 0, 0, 0); yield return new WaitForSeconds((float) 0.5); SceneManager.LoadScene(scene); } } <file_sep>/Assets/Scripts/Dice.cs // using System.Runtime; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Dice : MonoBehaviour { // Global Variables private bool landed = false; private bool canRoll = true; private string DiceSideUp; private bool selected; // random #s for new dice angle private int rand1; private int rand2; private int rand3; private System.Random random = new System.Random(); // Update is called once per frame void Update() { if(!canRoll) { this.transform.parent.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None; this.transform.parent.transform.Rotate(new Vector3(45, 0, -45) * (float) 6 * Time.deltaTime); } } // Function that randomizes the dices angle public void Randomize() { rand1 = (int) random.Next(1, 120); rand2 = (int) random.Next(1, 120); rand3 = (int) random.Next(1, 120); this.transform.Rotate(new Vector3(rand1, rand2, rand3)); } // Trigger for collision with table, sets variables true private void OnTriggerEnter(Collider other) { if(other.CompareTag("Table")) { this.transform.parent.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezePositionZ; canRoll = true; landed = true; } } // Function that sets variable canRoll public void SetCanRoll(bool value) { this.canRoll = value; } // Function that sets variable landed public void SetLanded(bool value) { this.landed = value; } // returns canRoll variable public bool GetCanRoll() { return canRoll; } // returns landed variable public bool GetLanded() { return landed; } } <file_sep>/Assets/Scripts/PauseMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PauseMenu : MonoBehaviour { private bool paused = false; private Animator animator; // Function that switches between pause and resume public void Switcher(Animator animIn) { this.animator = (Animator) animIn; if(paused) Resume(); else Pause(); } // Function that "Pauses" the game, sets the pauseCanvas active and timeScale to 0 public void Pause() { transform.GetChild(0).gameObject.SetActive(true); Time.timeScale = 0f; paused = true; } // Function that "Resumes" the game, disables the pauseCanvas and sets timeScale to 1 public void Resume() { transform.GetChild(0).gameObject.SetActive(false); Time.timeScale = 1f; paused = false; } // Function that changes the active canvas to the settingsCanvas; SettingsMenu brings pauseCanvas back public void Settings() { transform.GetChild(0).gameObject.SetActive(false); transform.GetChild(1).gameObject.SetActive(true); } // Function that changes the active canvas to the pauseMenuCanvas; public void ReturnFromSettings() { transform.GetChild(0).gameObject.SetActive(true); transform.GetChild(1).gameObject.SetActive(false); } // Transitions to the shop scene public void Shop() { Time.timeScale = 1f; StartCoroutine(Transition("Shop")); } // Transitions to the HomeScreen scene public void Back() { Time.timeScale = 1f; StartCoroutine(Transition("HomeScreen")); } // Function Exits the application public void Quit() { Time.timeScale = 1f; Application.Quit(); } // Function that handles the transition animations and loads a new scene private IEnumerator Transition(string scene) { animator.CrossFade("SceneSwitchOutDice", 0, 0, 0, 0); yield return new WaitForSeconds((float) 0.5); SceneManager.LoadScene(scene); } }
fa5802a1368bcb9eade765100c96cf5b90aded76
[ "C#" ]
10
C#
noahcas25/MobileUtilities
ae1b4c32a4849b832dc6e24946472c8e343a5ac0
c7ea2647fbac4b75c0ffc7fa7f7ab368e967a929
refs/heads/master
<repo_name>bearloga/wmf-pai-test<file_sep>/plumber.R library(plumber) library(glue) library(magrittr) library(knitr) library(kableExtra) library(htmltools) log_filename <- "/usr/local/plumber/test/requests.log" style <- '<style type="text/css"> body { padding: 15px; font-family: sans-serif; font-size: 14px; text-align: left; } pre { font-size: 12px; padding: 5px; } td { padding: 0 20px; } .table-striped>tbody>tr:nth-child(odd)>td { background-color: #f9f8f7; } </style>' html <- '<!DOCTYPE html> <html> <head> <title>Logged requests | Product Analytics Infrastructure</title> {style} </head> <body> {table} </body> </html>' #* @apiTitle Test API #* Log the request to a file #* @post /events function(req) { # write(paste0(Sys.time(), ": ", req), "~/Desktop/test/requests.log", append = TRUE) sink(file = log_filename, append = TRUE) cat(as.character(Sys.time()), "\t", urltools::url_decode(req$HTTP_USER_AGENT), "\t", req$postBody, "\n", sep = "") sink() } #* View logged requests #* @get /view #* @html function() { if (file.exists(log_filename)) { reqs <- log_filename %>% readr::read_tsv(col_names = c("timestamp", "user_agent", "post_body"), col_types = "Tcc") %>% dplyr::mutate( deserialized_json = purrr::map(post_body, jsonlite::fromJSON, simplifyVector = FALSE), deserialized_json = purrr::map(deserialized_json, ~ .x[sort(names(.x))]), client_dt = purrr::map_chr(deserialized_json, ~ .x[["client_dt"]]), post_body = paste0("<pre>", htmlEscape(purrr::map_chr(deserialized_json, jsonlite::toJSON, pretty = TRUE, auto_unbox = TRUE)), "</pre>") ) %>% dplyr::arrange(dplyr::desc(timestamp), dplyr::desc(client_dt)) %>% dplyr::select(-c(deserialized_json, client_dt)) table <- reqs %>% kable("html", escape = FALSE, col.names = c("Received (UTC, DESC)", "UserAgent", "POST body")) %>% kable_styling(bootstrap_options = c("striped"), position = "left", full_width = TRUE) %>% column_spec(1, width = "180px") %>% column_spec(2, width = "380px") } else { table <- "<p>Request log empty</p>" } return(glue(html)) } #* Clear request log #* @get /clear function() { if (file.exists(log_filename)) { file.remove(log_filename) } } #* Clear logged requests but retain some #* @get /retain/<leave> function(leave) { leave <- as.integer(leave) if (file.exists(log_filename) && leave > 0) { reqs <- read.delim(log_filename, header = FALSE, col.names = c("timestamp", "user_agent", "post_body"), stringsAsFactors = FALSE) write.table(tail(reqs, leave), log_filename, row.names = FALSE, col.names = FALSE, sep = "\t") } } #* Fetch stream configuration #* @get /streams #* @serializer unboxedJSON function() { if (file.exists("stream-config.json")) { return(jsonlite::read_json("stream-config.json")) } } <file_sep>/run.R #!/usr/bin/env Rscript pr <- plumber::plumb("plumber.R") pr$run(host = "172.16.7.127", port = 8000) <file_sep>/README.md # Test endpoint This repository contains code and instructions for setting up a web API for testing Product Analytics Infrastructure working group's Event Platform Client libraries. It relies on the [{plumber}](https://www.rplumber.io/) package for [R](https://www.r-project.org/). It makes the following endpoints available at `BASE_URL="https://pai-test.wmflabs.org/"`: - `/events`: records `POST` body in a log file - `/view`: displays logged requests as a table in a web page - `/clear`: empties the requests log - `/retain/n`: clears the log except the most recent `n` requests - `/streams`: returns the latest version of [streams configuration](stream-config.yaml) as JSON For example, to log an event from the browser: ```JS var url = BASE_URL + "/events", event = { action: "start", }; navigator.sendBeacon(url, JSON.stringify(event)) ``` ## Setup ### Instance Create a new Debian Buster instance on [CloudVPS](https://wikitech.wikimedia.org/wiki/Portal:Cloud_VPS) using the [Horizon UI](https://horizon.wikimedia.org/). `m1.small` flavor is fine. Make sure the `default` [security group](https://horizon.wikimedia.org/project/security_groups/) has a rule for Ingress Port 8000 CIDR 0.0.0.0/0 (`ALLOW IPv4 8000/tcp from 0.0.0.0/0`), then set up a DNS hostname in the [web proxies section of Horizon](https://horizon.wikimedia.org/project/proxy/) for the instance and be sure to change the port from 80 (default) to 8000. ### Dependencies `sudo` while SSH'd to the instance (e.g. `test-endpoint-01.eqiad.wmflabs`): ```bash deb http://cran.r-project.org/bin/linux/debian buster-cran35/ >> /etc/apt/sources.list apt-key adv --keyserver keys.gnupg.net --recv-key 'E19F5F87128899B192B1A2C2AD5F960A256A04AF' apt-get update apt-get install r-base r-base-dev libcurl4-openssl-dev libxml2-dev libssl-dev nodejs npm npm install -g pm2 ``` **Note**: see [this page](https://cran.r-project.org/bin/linux/debian/) for more information about installing R on Debian. Then, in R: ```R install.packages(c("plumber", "urltools", "yaml", "tidyverse")) ``` ### Service `mkdir /usr/local/plumber` (`chown` if necessary), clone this repo, register the service with pm2, and save the settings in case of reboot: ```bash git clone https://github.com/bearloga/wmf-pai-test.git /usr/local/plumber/test pm2 start --interpreter="Rscript" /usr/local/plumber/test/run.R pm2 save ``` For more information, refer to [pm2 section](https://www.rplumber.io/docs/hosting.html#pm2) in [Plumber's docs](https://www.rplumber.io/docs/). **Note**: The instance's routable IP is hardcoded in [run.R](run.R). It would need to be changed in case of a new instance. In the future we may want to add an nginx config that reverse proxies from the routable ip to the local service and change the host in run.R back to the default of 127.0.0.1 #### Maintainance ``` cd /usr/local/plumber/test pm2 restart run.R ``` To schedule `crontab`: ``` */15 * * * * cd /usr/local/plumber/test && git pull ``` **Note**: may want to consider Puppetizing this so we could use the `notify` metaparameter with a `git` resource to automatically trigger `pm2` to restart if the repository was updated. For now we need to do this manually. ## CloudVPS [Help:MediaWiki-Vagrant in Cloud VPS](https://wikitech.wikimedia.org/wiki/Help:MediaWiki-Vagrant_in_Cloud_VPS)
69cbf863756b251c8e6376e82304c61fda072c2a
[ "Markdown", "R" ]
3
R
bearloga/wmf-pai-test
7f1ab17a6a4fb41fd7334ed5e7cebfb7104dfd13
541748ca5d6fa7c968b5beed40c05008e163969a
refs/heads/master
<repo_name>YanjieHe/AutoGrader<file_sep>/src/main/resources/application.properties spring.datasource.url=jdbc:mysql://localhost:3306/grader?useSSL=false&serverTimezone=UTC spring.datasource.username=spring-user spring.datasource.password=<PASSWORD> spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect spring.jpa.properties.hibernate.id.new_generator_mappings=false spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl <file_sep>/src/main/java/com/company/grader/controller/TestCaseController.java package com.company.grader.controller; import com.company.grader.model.TestCase; import com.company.grader.model.TestCaseCompositeKey; import com.company.grader.repository.TestCaseRepository; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.ArrayList; import javax.persistence.Query; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @RestController @RequestMapping({"/test_cases"}) public class TestCaseController { private TestCaseRepository repository; TestCaseController(TestCaseRepository testCaseRepository) { this.repository = testCaseRepository; } // CRUD methods here @GetMapping public List findAll(){ List<TestCase> testCases = repository.findAll(); return testCases; } @PersistenceContext private EntityManager entityManager; @GetMapping(path = {"/all_test_cases/{problemID}"}) public ResponseEntity<List<?>> getAllTestCasesByProblem(@PathVariable Integer problemID){ String queryStr = "SELECT Problem_ID, Order_ID, Pre_Code, After_Code, Parameters, Expected FROM Test_Cases WHERE Problem_ID = ?1"; try { Query query = entityManager.createNativeQuery(queryStr); query.setParameter(1, problemID); List<Object[]> result = (List<Object[]>) query.getResultList(); List<TestCase> testCases = new ArrayList<TestCase>(); for(Object[] row : result) { TestCase testCase = new TestCase(); testCase.setProblemID((Integer)row[0]); testCase.setOrderID((Integer)row[1]); testCase.setPreCode((String)row[2]); testCase.setAfterCode((String)row[3]); testCase.setParameters((String)row[4]); testCase.setExpected((String)row[5]); testCases.add(testCase); } return ResponseEntity.ok().body(testCases); } catch (Exception e) { e.printStackTrace(); throw e; } } @GetMapping(path = {"/test_case/{problemID}/{order}"}) public ResponseEntity<TestCase> findById(@PathVariable Integer problemID, @PathVariable Integer order){ return repository.findById(new TestCaseCompositeKey(problemID, order)) .map(record -> { return ResponseEntity.ok().body(record); }) .orElse(ResponseEntity.notFound().build()); } } <file_sep>/README.md # AutoGrader The back-end of an auto grader. <file_sep>/src/main/java/com/company/grader/repository/ProblemRepository.java package com.company.grader.repository; import com.company.grader.model.Problem; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ProblemRepository extends JpaRepository<Problem, Integer> { } <file_sep>/src/main/java/com/company/grader/model/SubmissionCompositeKey.java package com.company.grader.model; import javax.persistence.Embeddable; import java.io.Serializable; import java.sql.Timestamp; @Embeddable public class SubmissionCompositeKey implements Serializable { private static final long serialVersionUID = -7081335288545850506L; private String email; private Integer problemID; private Timestamp submittedTime; public SubmissionCompositeKey(){ } public SubmissionCompositeKey(String email, Integer problemID, Timestamp submittedTime){ this.setEmail(email); this.setProblemID(problemID); this.setSubmittedTime(submittedTime); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getProblemID() { return problemID; } public void setProblemID(Integer problemID) { this.problemID = problemID; } public Timestamp getSubmittedTime() { return submittedTime; } public void setSubmittedTime(Timestamp submittedTime) { this.submittedTime = submittedTime; } } <file_sep>/src/main/java/com/company/grader/model/Problem.java package com.company.grader.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @AllArgsConstructor @NoArgsConstructor @Data @Entity @Table(name = "Problems") public class Problem { @Id @Column(name = "Problem_ID") private Integer problemID; @Column(name = "Header") private String header; @Column(name = "Description") private String Description; @Column(name = "Rich_Text_Description") private String richTextDescription; @Column(name = "Template") private String template; } <file_sep>/sql/drop_tables.sql DROP TABLE User_Problems; DROP TABLE Submissions; DROP TABLE Tests; DROP TABLE Test_Cases; DROP TABLE Problems; DROP TABLE Users; <file_sep>/src/main/java/com/company/grader/model/Test.java package com.company.grader.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; @AllArgsConstructor @NoArgsConstructor @Data @Entity @IdClass(UserProblemCompositeKey.class) @Table(name = "Tests") public class Test { @Id @Column(name = "User_Email") private String email; @Id @Column(name = "Problem_ID") private Integer problemID; @Column(name = "Code") private String code; } <file_sep>/sql/create_tables.sql CREATE TABLE Problems ( Problem_ID INT PRIMARY KEY, Header TEXT NOT NULL, Description TEXT NOT NULL, Rich_Text_Description TEXT NOT NULL, Template TEXT NOT NULL ) CHARSET=UTF8; CREATE TABLE Test_Cases ( Problem_ID INT NOT NULL, Order_ID INT NOT NULL, Pre_Code TEXT NOT NULL, After_Code TEXT NOT NULL, Parameters TEXT NOT NULL, Expected TEXT NOT NULL, FOREIGN KEY (Problem_ID) REFERENCES Problems(Problem_ID) ON DELETE CASCADE, PRIMARY KEY (Problem_ID, Order_ID) ) CHARSET=UTF8; CREATE TABLE Users ( User_Email VARCHAR(255) PRIMARY KEY, Password VARCHAR(255) NOT NULL, First_Name VARCHAR(100) NOT NULL, Last_Name VARCHAR(100) NOT NULL, GWID INT NOT NULL ) CHARSET=UTF8; CREATE TABLE User_Problems ( User_Email VARCHAR(255) NOT NULL, Problem_ID INT NOT NULL, Status VARCHAR(10) NOT NULL, FOREIGN KEY (User_Email) REFERENCES Users(User_Email) ON DELETE CASCADE, FOREIGN KEY (Problem_ID) REFERENCES Problems(Problem_ID) ON DELETE CASCADE, PRIMARY KEY (User_Email, Problem_ID) ) CHARSET=UTF8; CREATE TABLE Submissions ( User_Email VARCHAR(255) NOT NULL, Problem_ID INT NOT NULL, Code TEXT NOT NULL, Passed BOOLEAN NOT NULL, Submitted_Time TIMESTAMP NOT NULL, FOREIGN KEY (User_Email) REFERENCES Users(User_Email) ON DELETE CASCADE, FOREIGN KEY (Problem_ID) REFERENCES Problems(Problem_ID) ON DELETE CASCADE, PRIMARY KEY (User_Email, Problem_ID, SUBMITTED_TIME) ) CHARSET=UTF8; CREATE TABLE Tests ( User_Email VARCHAR(255) NOT NULL, Problem_ID INT NOT NULL, Code TEXT NOT NULL, FOREIGN KEY (User_Email) REFERENCES Users(User_Email) ON DELETE CASCADE, FOREIGN KEY (Problem_ID) REFERENCES Problems(Problem_ID) ON DELETE CASCADE, PRIMARY KEY (User_Email, Problem_ID) ) CHARSET=UTF8;
a94fc800c36a9184d709da7236a1ff6272ac2e52
[ "Markdown", "Java", "SQL", "INI" ]
9
INI
YanjieHe/AutoGrader
92dee8ed6b0b7e4378711442c68ff95d40c96c53
cf713fc0f1e0dd561c1ccd0996a0f81fb890a469
refs/heads/master
<repo_name>abulanadi/Lab4<file_sep>/NaiveQuick.cs using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab4 { class NaiveQuick { static int MAXVALUE = 50000; static int MINVALUE = -50000; static int MININPUT = 1; static int MAXINPUT = Convert.ToInt32(Math.Pow(2, 15)); static int numberOfTrials = 10000; Random random = new Random(); static string resultsFolderPath = "C:\\Users\\Adria\\School Stuff\\CSC482\\Lab4"; public void Sort(int[] arr, int left, int right) { if (left < right) { int pivot = Partition(arr, left, right); if (pivot > 1) { Sort(arr, left, pivot - 1); } if (pivot + 1 < right) { Sort(arr, pivot + 1, right); } } } public int Partition(int[] arr, int left, int right) { int pivot = arr[left]; while (true) { while (arr[left] < pivot) { left++; } while (arr[right] > pivot) { right--; } if (left < right) { if (arr[left] == arr[right]) return right; int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } else { return right; } } } public int[] CreateRandomListOfInts(int size) { int[] newList = new int[size]; for (int i = 0; i < size; i++) { newList[i] = random.Next(MINVALUE, MAXVALUE); } return newList; } public void checkSortCorrect() { Console.WriteLine("Testing naive quicksort..."); int[] testList1 = CreateRandomListOfInts(5); Console.WriteLine("Test list 1 pre sort:"); foreach (int x in testList1) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList1, 0, testList1.Length - 1); Console.WriteLine("Sorted list 1:"); foreach (int y in testList1) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList2 = CreateRandomListOfInts(10); Console.WriteLine("Test list 2 pre sort:"); foreach (int x in testList2) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList2, 0, testList2.Length - 1); Console.WriteLine("Sorted list 2:"); foreach (int y in testList2) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList3 = CreateRandomListOfInts(15); Console.WriteLine("Test list 3 pre sort:"); foreach (int x in testList3) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList3, 0, testList3.Length - 1); Console.WriteLine("Sorted list 3:"); foreach (int y in testList3) { Console.Write("{0} ", y); } Console.WriteLine(); } public void RunFullNaiveQuick(string resultFile) { Stopwatch stopwatch = new Stopwatch(); double previousTime = 0; double doubleRatio = 0; Console.WriteLine("Input Size\tAvg Time (ns)\tDoubling Ratio"); for (int inputSize = MININPUT; inputSize <= MAXINPUT; inputSize += inputSize) { double nanoSecs = 0; //System.GC.Collect(); for (long trial = 0; trial < numberOfTrials; trial++) { int[] testList = CreateRandomListOfInts(inputSize); stopwatch.Restart(); Sort(testList, 0, testList.Length - 1); stopwatch.Stop(); nanoSecs += stopwatch.Elapsed.TotalMilliseconds * 1000000; } double averageTrialTime = nanoSecs / numberOfTrials; if (previousTime > 0) { doubleRatio = averageTrialTime / previousTime; } previousTime = averageTrialTime; Console.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); using (StreamWriter outputFile = new StreamWriter(Path.Combine(resultsFolderPath, resultFile), true)) { outputFile.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); } } } public void RunFullNaiveQuickSorted(string resultFile) { Stopwatch stopwatch = new Stopwatch(); Merge merge = new Merge(); double previousTime = 0; double doubleRatio = 0; Console.WriteLine("Input Size\tAvg Time (ns)\tDoubling Ratio"); for (int inputSize = MININPUT; inputSize <= MAXINPUT; inputSize += inputSize) { double nanoSecs = 0; //System.GC.Collect(); for (long trial = 0; trial < numberOfTrials; trial++) { int[] testList = CreateRandomListOfInts(inputSize); merge.Sort(testList); stopwatch.Restart(); Sort(testList, 0, testList.Length - 1); stopwatch.Stop(); nanoSecs += stopwatch.Elapsed.TotalMilliseconds * 1000000; } double averageTrialTime = nanoSecs / numberOfTrials; if (previousTime > 0) { doubleRatio = averageTrialTime / previousTime; } previousTime = averageTrialTime; Console.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); using (StreamWriter outputFile = new StreamWriter(Path.Combine(resultsFolderPath, resultFile), true)) { outputFile.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); } } } } } <file_sep>/Insertion.cs using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Insertion { static int MAXVALUE = 50000; static int MINVALUE = -50000; static int MININPUT = 1; static int MAXINPUT = Convert.ToInt32(Math.Pow(2, 10)); static int numberOfTrials = 10000; Random random = new Random(); static string resultsFolderPath = "C:\\Users\\Adria\\School Stuff\\CSC482\\Lab4"; public int[] Sort(int[] arrayToSort) { int n = arrayToSort.Length; for (int i = 1; i < n; ++i) { int key = arrayToSort[i]; int j = i - 1; while (j >= 0 && arrayToSort[j] > key) { arrayToSort[j + 1] = arrayToSort[j]; j = j - 1; } arrayToSort[j + 1] = key; } return arrayToSort; } public int[] CreateRandomListOfInts(int size) { int[] newList = new int[size]; for (int i = 0; i < size; i++) { newList[i] = random.Next(MINVALUE, MAXVALUE); } return newList; } public void checkSortCorrect() { Console.WriteLine("Testing insertion sort..."); int[] testList1 = CreateRandomListOfInts(5); Console.WriteLine("Test list 1 pre sort:"); foreach (int x in testList1) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList1); Console.WriteLine("Sorted list 1:"); foreach (int y in testList1) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList2 = CreateRandomListOfInts(10); Console.WriteLine("Test list 2 pre sort:"); foreach (int x in testList2) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList2); Console.WriteLine("Sorted list 2:"); foreach (int y in testList2) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList3 = CreateRandomListOfInts(15); Console.WriteLine("Test list 3 pre sort:"); foreach (int x in testList3) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList3); Console.WriteLine("Sorted list 3:"); foreach (int y in testList3) { Console.Write("{0} ", y); } Console.WriteLine(); } public void RunFullInsertion(string resultFile) { Stopwatch stopwatch = new Stopwatch(); double previousTime = 0; double doubleRatio = 0; Console.WriteLine("Input Size\tAvg Time (ns)\tDoubling Ratio"); for (int inputSize = MININPUT; inputSize <= MAXINPUT; inputSize += inputSize) { double nanoSecs = 0; //System.GC.Collect(); for (long trial = 0; trial < numberOfTrials; trial++) { int[] testList = CreateRandomListOfInts(inputSize); stopwatch.Restart(); Sort(testList); stopwatch.Stop(); nanoSecs += stopwatch.Elapsed.TotalMilliseconds * 1000000; } double averageTrialTime = nanoSecs / numberOfTrials; if (previousTime > 0) { doubleRatio = averageTrialTime / previousTime; } previousTime = averageTrialTime; Console.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); using (StreamWriter outputFile = new StreamWriter(Path.Combine(resultsFolderPath, resultFile), true)) { outputFile.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); } } } }<file_sep>/Bubble.cs using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Bubble { static int MAXVALUE = 50000; static int MINVALUE = -50000; static int MININPUT = 1; static int MAXINPUT = Convert.ToInt32(Math.Pow(2, 10)); static int numberOfTrials = 10000; Random random = new Random(); static string resultsFolderPath = "C:\\Users\\Adria\\School Stuff\\CSC482\\Lab4"; public void Sort(int[] arrayToSort) { int temp; for(int i = 0; i < arrayToSort.Length - 1; i++) { for(int j = 0; j < arrayToSort.Length - i - 1; j++) { if(arrayToSort[j] > arrayToSort[j + 1]) { temp = arrayToSort[j]; arrayToSort[j] = arrayToSort[j+1]; arrayToSort[j+1] = temp; } } } } public int[] CreateRandomListOfInts(int size) { int[] newList = new int[size]; for (int i = 0; i < size; i++) { newList[i] = random.Next(MINVALUE, MAXVALUE); } return newList; } public void checkSortCorrect() { Console.WriteLine("Testing bubble sort..."); int[] testList1 = CreateRandomListOfInts(5); Console.WriteLine("Test list 1 pre sort:"); foreach (int x in testList1) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList1); Console.WriteLine("Sorted list 1:"); foreach (int y in testList1) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList2 = CreateRandomListOfInts(10); Console.WriteLine("Test list 2 pre sort:"); foreach (int x in testList2) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList2); Console.WriteLine("Sorted list 2:"); foreach (int y in testList2) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList3 = CreateRandomListOfInts(15); Console.WriteLine("Test list 3 pre sort:"); foreach (int x in testList3) { Console.Write("{0} ", x); } Console.WriteLine(); Sort(testList3); Console.WriteLine("Sorted list 3:"); foreach (int y in testList3) { Console.Write("{0} ", y); } Console.WriteLine(); } public void RunFullBubble(string resultFile) { Stopwatch stopwatch = new Stopwatch(); double previousTime = 0; double doubleRatio = 0; Console.WriteLine("Input Size\tAvg Time (ns)\tDoubling Ratio"); for (int inputSize = MININPUT; inputSize <= MAXINPUT; inputSize += inputSize) { double nanoSecs = 0; //System.GC.Collect(); for (long trial = 0; trial < numberOfTrials; trial++) { int[] testList = CreateRandomListOfInts(inputSize); stopwatch.Restart(); Sort(testList); stopwatch.Stop(); nanoSecs += stopwatch.Elapsed.TotalMilliseconds * 1000000; } double averageTrialTime = nanoSecs / numberOfTrials; if (previousTime > 0) { doubleRatio = averageTrialTime / previousTime; } previousTime = averageTrialTime; Console.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); using (StreamWriter outputFile = new StreamWriter(Path.Combine(resultsFolderPath, resultFile), true)) { outputFile.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); } } } }<file_sep>/Program.cs using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab4 { class Program { static void Main(string[] args) { Insertion insertion = new Insertion(); NaiveQuick naiveQuick = new NaiveQuick(); Merge merge = new Merge(); Bubble bubble = new Bubble(); Quick quick = new Quick(); /*naiveQuick.checkSortCorrect(); Console.WriteLine(); insertion.checkSortCorrect(); Console.WriteLine(); merge.checkSortCorrect(); Console.WriteLine(); bubble.checkSortCorrect(); Console.WriteLine(); quick.checkSortCorrect();*/ //bubble.RunFullBubble("BubbleTest1.txt"); //naiveQuick.RunFullNaiveQuick("NaiveQuickTest2.txt"); //merge.RunFullMerge("MergeTest2.txt"); //quick.RunFullQuick("QuickTest1.txt"); //insertion.RunFullInsertion("InsertionTest1.txt"); //naiveQuick.RunFullNaiveQuickSorted("NaiveSorted.txt"); //quick.RunFullQuickSorted("QuickSorted.txt"); } } } <file_sep>/Merge.cs using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Merge { static int MAXVALUE = 50000; static int MINVALUE = -50000; static int MININPUT = 1; static int MAXINPUT = Convert.ToInt32(Math.Pow(2, 15)); static int numberOfTrials = 10000; Random random = new Random(); static string resultsFolderPath = "C:\\Users\\Adria\\School Stuff\\CSC482\\Lab4"; public int[] Sort(int[] arrayToSort) { int[] left; int[] right; int[] result = new int[arrayToSort.Length]; if(arrayToSort.Length <= 1) { return arrayToSort; } int midPoint = arrayToSort.Length / 2; left = new int[midPoint]; if(arrayToSort.Length % 2 == 0) { right = new int[midPoint]; } else { right = new int[midPoint + 1]; } for(int i = 0; i < midPoint; i++) { left[i] = arrayToSort[i]; } int x = 0; for(int i = midPoint; i < arrayToSort.Length; i++) { right[x] = arrayToSort[i]; x++; } left = Sort(left); right = Sort(right); result = Combine(left, right); return result; } public int[] Combine(int[] left, int[] right) { int resultLength = right.Length + left.Length; int[] result = new int[resultLength]; int indexLeft = 0, indexRight = 0, indexResult = 0; while(indexLeft < left.Length || indexRight < right.Length) { if(indexLeft < left.Length && indexRight < right.Length) { if(left[indexLeft] <= right[indexRight]) { result[indexResult] = left[indexLeft]; indexLeft++; indexResult++; } else { result[indexResult] = right[indexRight]; indexRight++; indexResult++; } } else if(indexLeft < left.Length) { result[indexResult] = left[indexLeft]; indexLeft++; indexResult++; } else if(indexRight < right.Length) { result[indexResult] = right[indexRight]; indexRight++; indexResult++; } } return result; } public int[] CreateRandomListOfInts(int size) { int[] newList = new int[size]; for (int i = 0; i < size; i++) { newList[i] = random.Next(MINVALUE, MAXVALUE); } return newList; } public void checkSortCorrect() { Console.WriteLine("Testing merge sort..."); int[] testList1 = CreateRandomListOfInts(5); Console.WriteLine("Test list 1 pre sort:"); foreach (int x in testList1) { Console.Write("{0} ", x); } Console.WriteLine(); int[] sortedList1 = Sort(testList1); Console.WriteLine("Sorted list 1:"); foreach (int y in sortedList1) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList2 = CreateRandomListOfInts(10); Console.WriteLine("Test list 2 pre sort:"); foreach (int x in testList2) { Console.Write("{0} ", x); } Console.WriteLine(); int[] sortedList2 = Sort(testList2); Console.WriteLine("Sorted list 2:"); foreach (int y in sortedList2) { Console.Write("{0} ", y); } Console.WriteLine(); int[] testList3 = CreateRandomListOfInts(15); Console.WriteLine("Test list 3 pre sort:"); foreach (int x in testList3) { Console.Write("{0} ", x); } Console.WriteLine(); int[] sortedList3 = Sort(testList3); Console.WriteLine("Sorted list 3:"); foreach (int y in sortedList3) { Console.Write("{0} ", y); } Console.WriteLine(); } public void RunFullMerge(string resultFile) { Stopwatch stopwatch = new Stopwatch(); double previousTime = 0; double doubleRatio = 0; Console.WriteLine("Input Size\tAvg Time (ns)\tDoubling Ratio"); for (int inputSize = MININPUT; inputSize <= MAXINPUT; inputSize += inputSize) { double nanoSecs = 0; //System.GC.Collect(); for (long trial = 0; trial < numberOfTrials; trial++) { int[] testList = CreateRandomListOfInts(inputSize); stopwatch.Restart(); Sort(testList); stopwatch.Stop(); nanoSecs += stopwatch.Elapsed.TotalMilliseconds * 1000000; } double averageTrialTime = nanoSecs / numberOfTrials; if (previousTime > 0) { doubleRatio = averageTrialTime / previousTime; } previousTime = averageTrialTime; Console.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); using (StreamWriter outputFile = new StreamWriter(Path.Combine(resultsFolderPath, resultFile), true)) { outputFile.WriteLine("{0,-10} {1,16} {2,10:N2}", inputSize, averageTrialTime, doubleRatio); } } } }
52555195f3b58bc45c5ecf400e4816c86e2eb08a
[ "C#" ]
5
C#
abulanadi/Lab4
9f753ffc430178e33b6cea259c6b860b481e77a6
412a5239ee36e9300571533211c75865a50464ad
refs/heads/master
<file_sep>// Coding reference has been taken from the demo provided by the professor in class lectures. (function($){ //console.log('js loaded....'); //creating database var database; //database open request var openRequest = indexedDB.open("notelist",1); openRequest.onupgradeneeded = function(e) { console.log("Upgrading DATABASE..."); var thisDB = e.target.result; if(!thisDB.objectStoreNames.contains("noteliststore")) { thisDB.createObjectStore("noteliststore", { autoIncrement : true }); } } openRequest.onsuccess = function(e) { console.log("Open Success!"); database = e.target.result; var name = document.getElementById('nameList').value; document.getElementById('add-btn').addEventListener('click', function(){ // add note button on click function var name = document.getElementById('nameList').value; var sub = document.getElementById('subjectList').value; var text = document.getElementById('textList').value; // input validation if(name == '' && sub == '' && text == ''){ swal({ title: "Please fill up all the text fields.", text: "Thankyou.", imageUrl: "images/warning.png" }); } else if(sub == '' && text == ''){ swal({ title: "Please enter subject and message fields.", text: "Thankyou.", imageUrl: "images/warning.png" }); } else if(name == '' && sub == ''){ swal({ title: "Please enter name and subject.", text: "Thankyou.", imageUrl: "images/warning.png" }); } else if(name == '' && text == ''){ swal({ title: "Please enter name and message.", text: "Thankyou.", imageUrl: "images/warning.png" }); } else if(name == ''){ swal({ title: "Hey, Please enter valid name.", text: "Thankyou.", imageUrl: "images/warning.png" }); } else if(sub == ''){ swal({ title: "Please enter subject.", text: "Thankyou.", imageUrl: "images/warning.png" }); } else if(text == ''){ swal({ title: "Please enter message.", text: "Thankyou.", imageUrl: "images/warning.png" }); } else if (!name.trim()) { //empty } else { addNote(); //addSubject(subject); //addWord(text); } });noteList(); } openRequest.onerror = function() { console.log("Open Error!"); console.dir(e); } function addNote() { //fetching data from database var transaction = database.transaction(["noteliststore"],"readwrite"); var store = transaction.objectStore("noteliststore"); var name = document.getElementById('nameList').value; var sub = document.getElementById('subjectList').value; var text = document.getElementById('textList').value; var date = new Date(); console.log('adding ' +name ); // storing data var request = store.add({ name, sub, text, date }); request.onerror = function(e) { console.log("Error",e.target.error.name); //some type of error handler } request.onsuccess = function(e) { console.log("added " + name); noteList(); document.getElementById('nameList').value = ''; document.getElementById('subjectList').value = ''; document.getElementById('textList').value = ''; } } function noteList(){ $('#viewDetails').empty(); $('#viewDetails').html('<table class="table table-hover"><tr><th>Key</th><th>Text</th></tr></table>'); //Count Objects var transaction = database.transaction(['noteliststore'], 'readonly'); var store = transaction.objectStore('noteliststore'); //var care = addName.store.request.result.date; var countRequest = store.count(); //console.log(countRequest.result); countRequest.onsuccess = function(){ console.log(countRequest.result); // displaying all the notes added to the database in table $('#viewDetails').html('</br><table><caption><h3>VIEW NOTE(S)&nbsp;<img src="images/view.png"/></h3></caption><thead><tr><th colspan="4">TOTAL' +' ( '+countRequest.result+' ) '+'NOTES &nbsp;<img src="images/square.png"/></th></tr><tr><th> ID<img src="images/key.png"/></th><th>SUBJECT&nbsp;<img src="images/paper.png"/></th><th>DATE&nbsp;<img src="images/clock.png"/></th><th>COUNT&nbsp;<img src="images/hand.png"/></th></tr></thead></table>'); }; // Get all Objects var objectStore = database.transaction("noteliststore").objectStore("noteliststore"); objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { var $link = $('<button class="btn btn-warning" href="#" data-key="' + cursor.key + '">' + cursor.value.sub + '&nbsp;<img src="images/arrow.png"/></button>'); $link.click(function(){ //alert('Clicked ' + $(this).attr('data-key')); loadTextByKey(parseInt($(this).attr('data-key'))); }); // displaying all the notes added to the database by appending it to the view notes table var $row = $('<tr> The no of notes is :' +IDBRequest.result+'</tr>'); var $keyCell = $('<tbody><tr><td> ID '+cursor.key+'</td>'); var $textCell = $('<td></td>').append($link); var $data= $('<td>' + cursor.value.date +'</td>'); var $count = $('<td> ' +cursor.value.text.length + ' characters </td>'); $row.append($keyCell); $row.append($textCell); $row.append($data); $row.append($count); $('#viewDetails table').append($row); cursor.continue(); } else { //no more entries } }; } function loadTextByKey(key){ var transaction = database.transaction(['noteliststore'], 'readonly'); var store = transaction.objectStore('noteliststore'); var request = store.get(key); request.onerror = function(event) { // Handle errors! }; request.onsuccess = function(event) { //Do something with the request.result! console.log(request.result.date); // note details are shown (name,subject,message, date and message character count) $('#noteDetails').html('<div id="corner"><p><h2>Hello' +' '+ '<font color="#6C2DC7">'+ request.result.name + '!</font></h2></p><p><font color="gray">Date: '+ ' '+request.result.date+ '</font></p><p><h3>Subject:' +' '+' <font color="1F45FC">'+ request.result.sub + ' </font></p><p>Message:'+' '+' <font color="#4CC552">' +request.result.text+'</font></h3></p><p>('+ ' '+request.result.text.length+'&nbsp; characters count )</p></div><br>'); // delete button to delete the notes created var $deleteButton = $('<center><button class="btn btn-danger">Delete Note &nbsp;<img src="images/delete.png"/></button></center>'); $deleteButton.click(function(){ console.log('Delete' + key); deleteWord(key); }); $('#noteDetails').append($deleteButton); }; } function deleteWord(key) { var transaction = database.transaction(['noteliststore'], 'readwrite'); var store = transaction.objectStore('noteliststore'); var request = store.delete(key); request.onsuccess = function(evt){ noteList(); $('#noteDetails').empty(); }; } })(jQuery);
77ac5a50ebaa7f09ffe6db43320618f8ab2759a4
[ "JavaScript" ]
1
JavaScript
rudra28/JavaScript_NoteMaking_App
7ad411c2eabdd14c284b018184dbec41c16b09f6
66e7f94ea9e64568ac4306d723206707a3f2def3
refs/heads/master
<file_sep>let keys = require('./keys.js'); let request = require('request'); let fs = require('fs'); let spotify = require('spotify'); let ombd = require ('omdb'); let command = process.argv[2]; let mediaName = ""; for (let i = 3; i < process.argv.length; i++) { mediaName += "+" + process.argv[i]; } let Twitter = require('twitter'); let client = new Twitter(keys.twitterKeys); let params = {screen_name: 'SamanthaCoke_'} function liri (command) { switch (command) { case "my-tweets": grabTweets(); break; case "spotify-this-song": spotifyThis(); break; case "movie-this": movieThis(); break; case "do-what-it-says": default: console.log("Samantha, you forgot to add a liri command!") } } function grabTweets() { client.get('statuses/user_timeline',params, function(error, tweets, response) { if (!error) { let tweetAmount = 0; if(tweets.legnth < 20) { tweetAmount = tweets.length; } else { tweetAmount = 20; } for (let i = 0; i < tweetAmount ; i++) { console.log(twwets[i].text); } } }); } function spotifyThis() { spotify.search({ type: 'track', query:mediaName || "sce of base - the sign"}, function(err, data) { if ( err ) { console.log ('Error occurred: ' + err); return; } console.log("Artist: " + data.tracks.items[0].artists[0].name); console.log("Name: " + data.tracks.items[0].name); console.log("Link: " + data.tracks.items[0].preview_url); console.log("Album: " + data.tracks.items[0].album.name); }); function movieThis() { ombd.get ({ title: mediaName }, true, function(err, movie) { if (err) { return console.error(err); } if (!movie) { return console.log ('Movie not found!'); } console.log("Title: " + movie.title); console.log("Year: " + movie.year); console.log(IMDB Rating: " + movie.imdb.rating); console.log("Produced in: " + movie.counties); console.log("Plot: " + movie.plot); console.log("Actors: " + movie.actors); function doThis() { fs.readFile("random.txt", "utf8", function(err,data){ if (err) { return; } let output = data.splot(','); command = output[0]; mediaName = output [1]; liri(command); }); } liri(command);
a72db8a254e0bbc414743e1fdcf28ece28ef9bb8
[ "JavaScript" ]
1
JavaScript
SamanthaCoke/liri-node-app
7d5cf32568f8bd8023d3f76b0ea21a8ed3bdc891
8cb55eb1a8f387bfab252a145b6b6687572db308
refs/heads/master
<repo_name>praveenpatil05/SharedCode<file_sep>/BlogPosts/2015/03/Sharing Memcache/api_go/service.go /* Copyright 2015, Google, Inc. 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 hello import ( "fmt" "log" "net/http" "appengine" "appengine/memcache" ) func init() { http.HandleFunc("/", handler) http.HandleFunc("/json", jsonHandler) } func handler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) item, err := memcache.Get(c, "secret") if err != nil { handleError(w, err) } fmt.Fprint(w, string(item.Value)) } type Location struct { Name string `json:"name"` City string `json:"city"` State string `json:"state"` Lat float32 `json:"latitude"` Lon float32 `json:"longitude"` } func jsonHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) var item Location key := "secret2" _, err := memcache.JSON.Get(c, key, &item) if err != nil { handleError(w, err) } fmt.Fprintf(w, "%+v\n", item) } func handleError(w http.ResponseWriter, err error) { log.Print("Yo") log.Printf("%v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) } <file_sep>/Presos/Intro To Go/gosamples/09_helloworld/main.go /* Copyright 2015, Google, Inc. 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 main import ( "fmt" "log" "sync" "time" ) import ( "github.com/tpryan/gosamples/helloworld" ) // func main() { // defer un(trace("main")) // greetLocal() // greetMexico() // greetFrance() // greetChina() // } // func main() { // defer un(trace("main")) // go greetLocal() // go greetMexico() // go greetChina() // go greetFrance() // time.Sleep(time.Second * 7) // } func main() { defer un(trace("main")) var wg sync.WaitGroup wg.Add(4) go func() { greetLocal() wg.Done() }() go func() { greetMexico() wg.Done() }() go func() { greetFrance() wg.Done() }() go func() { greetChina() wg.Done() }() wg.Wait() } func greetLocal() { defer un(trace("greetLocal")) greet, _ := helloworld.Greet("English") fmt.Printf("Here we say: %v\n", greet) } func greetMexico() { defer un(trace("greetMexico")) time.Sleep(time.Millisecond * 1877) greet, _ := helloworld.Greet("Spanish") fmt.Printf("In Mexico City (1877 miles away), they say: %v\n", greet) } func greetFrance() { defer un(trace("greetFrance")) time.Sleep(time.Millisecond * 5560) greet, _ := helloworld.Greet("French") fmt.Printf("In France (5560 miles away) they say: %v\n", greet) } func greetChina() { defer un(trace("greetChina")) time.Sleep(time.Millisecond * 5901) greet, _ := helloworld.Greet("Chinese") fmt.Printf("In China (5901 miles away) they say: %v\n", greet) } func trace(s string) (string, time.Time) { return s, time.Now() } func un(s string, startTime time.Time) { endTime := time.Now() log.Println(s, "ElapsedTime in seconds:", endTime.Sub(startTime)) } <file_sep>/Presos/Intro To Go/gosamples/05_helloworld/main.rb greet_list = { 'Chinese' => "你好世界", 'Dutch' => "Hello wereld", 'English' => "Hello world", 'French' => "Bonjour monde", 'German' => "<NAME>", 'Greek' => "γειά σου κόσμος", 'Italian' => "Ciao mondo", 'Japanese' => "こんにちは世界", 'Korean' => "여보세요 세계", 'Portuguese' => "Olá mundo", 'Russian' => "Здравствулте мир", 'Spanish' => "Hola mundo" } lang = ARGV[0] lang = "English" if lang == nil response = greet_list[lang] if response == nil puts "The language you selected is not valid." else puts greet_list[lang] end <file_sep>/Presos/Intro To Go/gosamples/10_helloworld/main.go /* Copyright 2015, Google, Inc. 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 main import ( "fmt" "log" "sync" "time" ) import ( "github.com/tpryan/gosamples/helloworld" ) type Destination struct { Name string Language string Country string Distance int } func main() { defer un(trace("main")) des := []Destination{ {"San Francisco", "English", "USA", 0}, {"Mexico City", "Spanish", "Mexico", 1877}, {"Bejing", "Chinese", "China", 5901}, {"Montreal", "French", "Canada", 2535}, {"Paramaribo", "Dutch", "Suriname", 4728}, {"Windhoek", "German", "Namibia", 9819}, {"Moscow", "Russian", "Russia", 5865}, {"Tokyo", "Japanese", "Japan", 5136}, {"Athens", "Greek", "Greece", 6772}, {"Rome", "Italian", "Italy", 6239}, {"Seoul", "Korean", "South Korea", 5607}, {"São Paulo", "Portuguese", "Brazil", 6479}, } var wg sync.WaitGroup for _, d := range des { wg.Add(1) go func(d Destination) { defer wg.Done() greet(d) }(d) } wg.Wait() } func greet(d Destination) { time.Sleep(time.Duration(d.Distance) * time.Millisecond) greet, _ := helloworld.Greet(d.Language) fmt.Printf("In %s (%d miles away), they say: %s\n", d.Name, d.Distance, greet) } func trace(s string) (string, time.Time) { return s, time.Now() } func un(s string, startTime time.Time) { endTime := time.Now() log.Println(s, "ElapsedTime in seconds:", endTime.Sub(startTime)) } <file_sep>/Presos/Intro To Go/gosamples/05_helloworld/main.go /* Copyright 2015, Google, Inc. 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 main import ( "flag" "fmt" "log" ) func main() { lang := flag.String("lang", "English", "a language in which to get greeting.") flag.Parse() greetings := map[string]string{ "Chinese": "你好世界", "Dutch": "Hello wereld", "English": "Hello world", "French": "Bonjour monde", "German": "<NAME>", "Greek": "γειά σου κόσμος", "Italian": "Ciao mondo", "Japanese": "こんにちは世界", "Korean": "여보세요 세계", "Portuguese": "<NAME>", "Russian": "Здравствулте мир", "Spanish": "Hola mundo", } if r, ok := greetings[*lang]; ok { fmt.Printf("%s\n", r) } else { log.Fatal("The language you selected is not valid.") } } <file_sep>/README.md # SharedCode Code that I am sharing in various forms. <file_sep>/BlogPosts/2016/04/Autoscale Disk/autoscale-disk #!/bin/bash # Copyright 2015, Google, Inc. # 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. # Usage info show_help() { cat << EOF Usage: ${0##*/} -d CLOUDDISK [-t THRESHOLD] [-f FACTOR] [-m MAX] Checks the disk utilization of CLOUDDISK and if it is over the THRESHOLD increase the disk size by multiplying current size by FACTOR as long as it does not exceed MAX. -c Check to make sure you have properly authorized service account. SUCCESS = display from gcloud compute disks list FAILURE = ERROR - Insufficient Permission -h Display this help and exit -d CLOUDDISK The Google Cloud Disk name to check. This name can be seen running 'gcloud compute disks list' -t THRESHOLD The percentage (0-100) above which to resize the disk. DEFAULT 90 -f FACTOR The multiplier to resize the disk by. A 1GB disk with a factor of 2 will be resized to 2GB. DEFAULT 2. -m MAX The limit in GB beyond which we will not resize a disk. DEFAULT 6400GB. Examples: Run with defaults on a disk named 'storage' - ${0##*/} -d storage Check if the disk 'storage' is more than 50% usage, if so quadruple the disk to a limit of 1000GB ${0##*/} -d storage - t 50 -f 4 -m 1000 EOF } check_perms() { /usr/local/bin/gcloud compute disks list } # Initialize our own variables: THRESHOLD=90 FACTOR=2 MAX=64000 while getopts "d:t:m:f:hc" opt; do case "$opt" in h) show_help >&2 exit ;; c) check_perms >&2 exit ;; d) CLOUDDISK=$OPTARG ;; t) THRESHOLD=$OPTARG ;; m) MAX=$OPTARG ;; f) FACTOR=$OPTARG ;; esac done if [ "$CLOUDDISK" = "" ] then echo "You must set a CLOUDDISK using -d option. Run ${0##*/} -h for more help. " exit fi # Get variables for scale parameters LOCALDISK=`readlink -f /dev/disk/by-id/google-$CLOUDDISK` # Get current usage in percentage expressed as a number between 1-100 tmp=`df $LOCALDISK | awk '{ print $5 }' | tail -n 1` USAGE="${tmp//%}" # Check to see if disk is over threshold. if [ $USAGE -lt $THRESHOLD ] then echo "Disk is within threshold" exit else echo "Disk is over threshold, attempting to resize" fi # Get Current size of disk tmp2=`df -BG $LOCALDISK | awk '{ print $2 }' | tail -n 1` CURRENTSIZE="${tmp2//G}" # Compute next size of disk. PROPOSEDSIZE=$(( CURRENTSIZE * FACTOR )) if [ $PROPOSEDSIZE -gt $MAX ] then echo "Proposed disk size ($PROPOSEDSIZE)GB is higher than the max allowed ($MAX)GB." exit else echo "Proposed disk size acceptable, attempting to resize" fi # RESIZE IT ZONE=`/usr/local/bin/gcloud compute disks list $CLOUDDISK | awk '{ print $2 }' | tail -n 1` /usr/local/bin/gcloud compute disks resize $CLOUDDISK --size "$PROPOSEDSIZE"GB --zone $ZONE --quiet # Tell the OS that the disk has been resized. sudo resize2fs /dev/disk/by-id/google-"$CLOUDDISK"<file_sep>/BlogPosts/2016/02/Cloud Vision PHP/README.MD # Cloud Vision PHP Example. ## Prereqisites 1. Sign up for Google Cloud Platform Account http://cloud.google.com 2. Enable Cloud Vision API https://cloud.google.com/vision/docs/getting-started "This is not an official Google product."<file_sep>/BlogPosts/2016/04/Migrating SQL/sync.sh # Copyright 2015, Google, Inc. # 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. PROJECT=[Project ID] SRC_INSTANCE=[Name of source Cloud SQL instance to target] DES_INSTANCE=[Name of destination Cloud SQL instance to target] BUCKET=gs://[Name of Bucket set aside for temporarily storing mysqldump] DATABASE=[MySQL Database name] # Export source SQL to SQL file gcloud sql instances export $SRC_INSTANCE $BUCKET/sql/export.sql \ --database $DATABASE --project $PROJECT # Import SQL file to destination SQL gcloud sql instances import $DES_INSTANCE $BUCKET/sql/export.sql \ --project $PROJECT # Delete SQL file and export logs. gsutil rm $BUCKET/sql/export.sql*<file_sep>/Presos/Intro To Go/gosamples/08_helloworld/main.go /* Copyright 2015, Google, Inc. 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 main import ( "encoding/json" "fmt" "log" "net/http" "github.com/tpryan/gosamples/helloworld" ) func main() { http.HandleFunc("/get", HandleGet) http.HandleFunc("/list", HandleList) log.Print(http.ListenAndServe(":8080", nil)) } func HandleList(w http.ResponseWriter, r *http.Request) { list := helloworld.Langauges() json, err := json.Marshal(list) if err != nil { handleError(w, err) return } sendJSON(w, string(json)) } func HandleGet(w http.ResponseWriter, r *http.Request) { lang := r.FormValue("language") greet, err := helloworld.Greet(lang) if err != nil { handleError(w, err) return } sendJSON(w, greet) } func handleError(w http.ResponseWriter, err error) { http.Error(w, err.Error(), http.StatusInternalServerError) log.Print(err) } func sendJSON(w http.ResponseWriter, content string) { w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, content) } <file_sep>/Presos/Intro To Firebase/lab/11_styleself.js /* Copyright 2015, Google, Inc. 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. */ myFirebase.on('child_added', function(snapshot) { var msg = snapshot.val(); displayMessage(msg.name,msg.text); checkSelf(); }); function checkSelf(){ var self = document.querySelector("#name").value; if (self.length == 0){ return; } [].forEach.call( document.querySelectorAll('.msg'), function(el) { if (el.innerHTML.indexOf('<div class="name">'+self) > -1){ el.classList.add("self"); } else{ el.classList.remove("self"); } }, false); } <file_sep>/Presos/Intro To Go/gosamples/helloworld/hellowworld_test.go /* Copyright 2015, Google, Inc. 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 helloworld import ( "errors" "testing" ) func TestGreet(t *testing.T) { cases := []struct { input string s string err error }{ {"", "", errors.New(ErrorNotFound)}, {"English", "Hello world", nil}, } for _, c := range cases { got_s, got_err := Greet(c.input) if got_s != c.s { t.Errorf("Validate(%q) == %q, want %q", c.input, got_s, c.s) } if got_err != nil && got_err.Error() != c.err.Error() { t.Errorf("Validate(%q) == %q, want %q", c.input, got_err, c.err) } } } <file_sep>/BlogPosts/2015/03/Sharing Memcache/api_php/json.php <!-- Copyright 2015, Google, Inc. 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. --> <?php $memcache = new Memcache; $info['name'] = "hometown"; $info['city'] = "Philadelphia"; $info['state'] = "PA"; $info['latitude'] = "39.995664772727"; $info['longitude'] = "-75.138788636364"; $secret = json_encode($info,JSON_NUMERIC_CHECK); $memcache->set("secret2", $secret); $value = $memcache->get("secret2"); echo $value ?><file_sep>/Presos/Intro To Firebase/lab/08_makehtmlforobject.js /* Copyright 2015, Google, Inc. 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. */ function displayMessage(name,text){ var html = '<div class="msg"><div class="name">' + name + '</div><div class="text">' + text + "</div></div>"; document.querySelector("#results").innerHTML += html; <file_sep>/Presos/Intro To Go/gosamples/helloworld/hellowworld.go /* Copyright 2015, Google, Inc. 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 helloworld import "errors" const ( ErrorNotFound = "The language you selected is not valid." ) var greetings = map[string]string{ "Chinese": "你好世界", "Dutch": "Hello wereld", "English": "Hello world", "French": "Bonjour monde", "German": "<NAME>", "Greek": "γειά σου κόσμος", "Italian": "Ciao mondo", "Japanese": "こんにちは世界", "Korean": "여보세요 세계", "Portuguese": "Olá mundo", "Russian": "Здравствулте мир", "Spanish": "Hola mundo", } func Greet(language string) (string, error) { if _, ok := greetings[language]; ok { return greetings[language], nil } else { return "", errors.New(ErrorNotFound) } } func Langauges() []string { var response []string for l := range greetings { response = append(response, l) } return response }
8f8dd5df832ad13a7860368a6f8d78aa1f54c1f3
[ "Ruby", "Markdown", "JavaScript", "PHP", "Go", "Shell" ]
15
Go
praveenpatil05/SharedCode
ffaf65ffcd493be2d20b7b2ec8e45fe24c119cb9
90b65cf742198cd828a92c156aeaaa315d742bb7
refs/heads/main
<repo_name>jflow415/mycode<file_sep>/lab_input/iptaker03.py name= input ("What is your name?") day= input("what day is today?") print("Hello, " + name + "! Happy " + day + "!") print("Hello, {}! Happy {}!".format(name,day)) <file_sep>/gotRuler.01 #!/usr/bin/python3 #Four rounds to get <file_sep>/dict01/marvelchar01.py #!/usrbin/env python3 marvelchars = { "Starlord": {"real name": "<NAME>", "powers": "dance moves", "archenemy": "Thanos"}, "Mystique": {"real name": "<NAME>", "powers": "shape shifter", "archenemy": "Professor X"}, "She-Hulk":{ "real name": "<NAME>", "powers": "super strength & intelligence", "archenemy": "Titania"} } char_name = input("Which character do you want to know about? (starlord, mystique, she-hulk)").title() char_stat = input("What statistic do you want to know about? (real name, powers, archenemy)").lower() #print(marvelchars, sep= ", ") print(char_name,"s", char_stat, "is:", marvelchars[char_name][char_stat]) # notice that when you put the cursor over the last parens, it doesn't highlight the FIRST one next to print at the beginning of the line # shows that you're missing an ending parenthesis at the end of line 21 :) #would the get method give the current power of the chosen character? # as written, no I don't believe so... the first argument is the key being "get"ted, the second argument is what gets returned if no key is found. #Ok. I'll do some more digging . Ok cool! Let me know if you need any help! <file_sep>/animedata/anime01.py import pandas as pd pd.read_csv('anime.csv') #exampleFile = open('anime.csv','r') #exampleReader= exampleFile.readlines() #exampleData = list(exampleReader) #print(exampleData) #exampleFile.close() <file_sep>/moveplease01.py #!/usr/bin/env python3 # standard library imports import shutil import os import shutil import os #called at runtime os.chdir("/home/student/mycode/") shutil.move("raynor.obj", "ceph_storage/") # program will pause while we accept input xname = input('What is the new name for kerrigan.obj? ') # collect string input from the user shutil.move('ceph_storage/kerrigan.obj', 'ceph_storage/' + xname) # moving kerrigan.obj into # ceph_storage/ with new name # this calls our main function <file_sep>/challenges/challenge01.py #!/usr/bin/env python3 import random #create our first list icecream= ["flavors", "salty"] #create our second list of names tlgclass= ["Adrian","Bikash","Chas","Chathula","Chris","Hongyi","Jauric","<NAME>.","<NAME>.","Josh","Justin","Karlo","Kerri-Leigh","Jason","Nicholas","Peng","Philippe","Pierre","Stephen","Yun"] #append the integer 99 to the list of icecream icecream.append(99) # ask for user input number = input("Choose a number between 0 and 19.") print(icecream[2], icecream[0], "and ", tlgclass[int(number)], " chooses to be ", icecream[1]) print(icecream[2], icecream[0], "and ", random.choice(tlgclass), "chooses to be ", icecream[1]) <file_sep>/mix-list/mixlist01.py #!/usr/bin/env python3 #create a list with three items my_list = [ "192.168.0.5", 5060, "UP" ] #display the first item print("The first item in the list (IP): " + my_list[0]) #display the second item and convert to a string print("The second item in the list (port): " + str(my_list[1]) ) #display the third item print("The last item in the list (state): " + my_list[2] ) iplist = [5060, "80", 55, "10.0.0.1","10.20.30.1","ssh"] print(f"Display only the IP at position 3,4: {iplist[3]}, and { iplist[4]}") <file_sep>/demofunc/function01.py #write a function that accepts 1 argument. #arg = name def namechanger(n): # code goes here return n + " is a wild and crazy guy!" names= ["Jauric","Chas","Chathula","Bikash"] for name in names: print(namechanger(name))
82def635efeded80741b6ba6fdb2172bbfa63d5a
[ "Python" ]
8
Python
jflow415/mycode
1274e1436825bd58c9d02e1ac05d548f550a6d0a
96163e97e17b61f055fcf333b0caf4f7660f003a
refs/heads/master
<repo_name>hughiednguyen/applied_hw7_multithread_matrix_calc<file_sep>/controller.cpp #include "controller.h" Controller::Controller(QObject *parent) : QObject(parent) {} Controller::~Controller() {} void Controller::compute() { computeThread(); // Compute QRunnable // Restart timer QElapsedTimer timer2; timer2.start(); // Create M*P QRunnables // Join M*P QRunnables // stop timer // emit notifyComputeComplete(x, y) /* for (size_t i = 0; i < size; i++) { multiply *t = new multiply(data); QThreadPool globalInstance()->start(+); globalInstance->notifyDone(xy) emit qRunnbleCompleted }*/ emitQRunnableProgress(100); int time = timer2.elapsed(); emitPthreadTime(time); } void Controller::computeThread() { pthread_t controllerThread; struct PathArgs *computeStruct = new PathArgs(); computeStruct->controller = this; pthread_create(&controllerThread, NULL, computeThreads, (void *)computeStruct); pthread_join(controllerThread, NULL); delete computeStruct; } QString Controller::getMatrixAPath() { return filePathA; } QString Controller::getMatrixBPath() { return filePathB; } QString Controller::getMatrixCPath() { return filePathC; } int Controller::getPThreadProgress() { return TotalPThreadProgress; } void Controller::emitRWError(QString errorMessage) { emit readWriteError(errorMessage); } void Controller::emitPthreadTime(int PThreadTime) { TotalPThreadTime = PThreadTime; emit notifyComputeCompleted(PThreadTime, TotalQRunnableTime); } void Controller::emitQRunnableTime(int QRunnableTime) { TotalQRunnableTime = QRunnableTime; emit notifyComputeCompleted(QRunnableTime, TotalQRunnableTime); } void Controller::emitPThreadProgress(int PThreadProgress) { TotalPThreadProgress = PThreadProgress; emit notifyProgressCompleted(TotalPThreadProgress, TotalQRunnableProgress); } void Controller::emitQRunnableProgress(int QRunnableProgress) { TotalQRunnableProgress = QRunnableProgress; emit notifyProgressCompleted(TotalPThreadProgress, TotalQRunnableProgress); } void Controller::getPaths(QString pathA, QString pathB, QString pathC) { filePathA = pathA; filePathB = pathB; filePathC = pathC; } // *************THREADING ***************** // void *Controller::computeThreads(void *arg) { // Start timer QElapsedTimer timer; timer.start(); struct PathArgs *computeStruct = (struct PathArgs *)arg; // Create 2 read threads pthread_t readA, readB; struct ReadArgs readStructA, readStructB; readStructA.filepath = computeStruct->controller->getMatrixAPath(); readStructB.filepath = computeStruct->controller->getMatrixBPath(); pthread_create(&readA, NULL, read, (void *)&readStructA); pthread_create(&readB, NULL, read, (void *)&readStructB); // Join for both pthread_join(readA, NULL); pthread_join(readB, NULL); // Handling for individual error found during read if (readStructA.error) { computeStruct->controller->emitRWError(readStructA.errorMessage); pthread_exit(0); } if (readStructB.error) { computeStruct->controller->emitRWError(readStructB.errorMessage); pthread_exit(0); } if (readStructA.type != readStructB.type) { computeStruct->controller->emitRWError( "Data format disagreement between matrices"); pthread_exit(0); } MATRIX_TYPE type = readStructA.type; // Check for inter-matrices dimension mismatch // A's columns has to be equal to B's rows // Total threads = total output elements (A's row times B's column) // + 2 read + 1 write int totalThreads = 3; if (type == INT) { if (readStructA.intMatrix[0].size() != readStructB.intMatrix.size()) { computeStruct->controller->emitRWError("Matrix inner dimension mismatch"); pthread_exit(0); } totalThreads += readStructA.intMatrix.size() * readStructB.intMatrix[0].size(); } else if (type == DOUBLE) { if (readStructA.decMatrix[0].size() != readStructB.decMatrix.size()) { computeStruct->controller->emitRWError("Matrix inner dimension mismatch"); pthread_exit(0); } totalThreads += readStructA.decMatrix.size() * readStructB.decMatrix[0].size(); } // Emit to update progress bar int PThreadProgress = 2 / totalThreads; computeStruct->controller->emitPThreadProgress(PThreadProgress); // Create write struct for multiply and write pthread_t writer; struct WriteArgs writeStruct; writeStruct.filepath = computeStruct->controller->getMatrixCPath().trimmed(); writeStruct.type = type; writeStruct.decMatrixA = readStructA.decMatrix; writeStruct.decMatrixB = readStructB.decMatrix; writeStruct.intMatrixA = readStructA.intMatrix; writeStruct.intMatrixB = readStructB.intMatrix; if (type == INT) { for (int i = 0; i < writeStruct.intMatrixA.size(); i++) { QVector<int> row; for (int j = 0; j < writeStruct.intMatrixB[0].size(); j++) { row.append(0); } writeStruct.intMatrixC.append(row); writeStruct.locks.append( QBitArray(writeStruct.intMatrixB[0].size(), false)); } } else if (type == DOUBLE) { for (int i = 0; i < writeStruct.decMatrixA.size(); i++) { QVector<double> row; for (int j = 0; j < writeStruct.decMatrixB[0].size(); j++) { row.append(0); } writeStruct.decMatrixC.append(row); writeStruct.locks.append( QBitArray(writeStruct.decMatrixB[0].size(), false)); } } // Create M * P threads int totalItems = totalThreads - 3; pthread_t multiplies[totalItems]; int count = 0; if (type == INT) { for (int i = 0; i < writeStruct.intMatrixA.size(); i++) { for (int j = 0; j < writeStruct.intMatrixB[0].size(); j++) { struct MultArgs multStruct; multStruct.write = &writeStruct; multStruct.i = i; multStruct.j = j; multStruct.totalThreads = totalThreads; pthread_create(&multiplies[count], NULL, multiply, (void *)&multStruct); count++; } } // Join M * P threads for (int i = 0; i < totalItems; i++) { pthread_join(multiplies[i], NULL); } } else if (type == DOUBLE) { for (int i = 0; i < writeStruct.decMatrixA.size(); i++) { for (int j = 0; j < writeStruct.decMatrixB[0].size(); j++) { struct MultArgs multStruct; multStruct.write = &writeStruct; multStruct.paths = computeStruct; multStruct.totalThreads = totalItems; multStruct.i = i; multStruct.j = j; pthread_create(&multiplies[count], NULL, multiply, (void *)&multStruct); count++; } } // Join M * P threads for (int i = 0; i < totalItems; i++) { // TODO: Distinguish between QRunnable and PThread // Update progress bar incrementally int currentProgress = computeStruct->controller->getPThreadProgress(); int increment = (1 / (totalThreads)); computeStruct->controller->emitPThreadProgress(currentProgress + increment); pthread_join(multiplies[i], NULL); } } // Create write thread pthread_create(&writer, NULL, write, (void *)&writeStruct); // Join write thread pthread_join(writer, NULL); // Set max progress bar computeStruct->controller->emitPThreadProgress(100); // Set elapsed time int PThreadTime = timer.elapsed(); computeStruct->controller->emitPthreadTime(PThreadTime); pthread_exit(0); } void *Controller::read(void *arg) { struct ReadArgs *readStruct = (struct ReadArgs *)arg; QString path = readStruct->filepath; // Open QFile datFile(path); datFile.open(QIODevice::ReadOnly); QString line; QStringList dataList; // Read until end of file while (!datFile.atEnd()) { line = datFile.readLine().trimmed(); // Add the line to private list dataList << line; } QVector<QStringList> test; for (int i = 0; i < dataList.size(); i++) { QStringList list = dataList[i].split(QRegExp("\\s+"), QString::SkipEmptyParts); test << list; } // Handling for empty matrix if (test.size() == 0) { readStruct->error = true; readStruct->errorMessage = "Empty matrix is not acceptable"; pthread_exit(0); } // To keep track of data consistency within matrix int intCount = 0; int doubleCount = 0; int totalConversions = 0; // Conversion things + Data format checks bool okInt = false, okDouble = false; // This regex checks if the decimal number has 4 decimal values QRegularExpression doubleMatch("^-?[0-9]\\d*(\\.\\d{1,4})$", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match; for (int i = 0; i < test.size(); i++) { // Temp rows for insertions IntegerRow rowi; DecimalRow rowd; for (int j = 0; j < test[i].size(); j++) { rowi.append(test[i][j].toInt(&okInt)); //^-?[0-9]\d*(\.\d{1,4})$ match = doubleMatch.match(test[i][j]); okDouble = match.hasMatch(); double toAppend = okDouble ? test[i][j].toDouble() : 0.0; rowd.append(toAppend); // Increment for each successful conversion intCount = okInt ? intCount + 1 : intCount; doubleCount = okDouble ? doubleCount + 1 : doubleCount; // Increment for each attempted conversions totalConversions++; } // Insert into vectors readStruct->decMatrix.append(rowd); readStruct->intMatrix.append(rowi); } // Data format check based on count variables if (!((intCount == totalConversions && doubleCount == 0) || (doubleCount == totalConversions && intCount == 0))) { readStruct->error = true; readStruct->errorMessage = "Data format disagreement within matrix"; pthread_exit(0); } // Determine readStruct->type of Matrix readStruct->type = intCount == totalConversions ? INT : DOUBLE; // Check for multiple-length rows for a single matrix // Row length consistency comparisons with first row length int currentRowCount = 0; int firstRowCount = 0; bool consistency = true; if (readStruct->type == INT) { firstRowCount = readStruct->intMatrix.first().size(); for (int i = 0; i < readStruct->intMatrix.size(); i++) { currentRowCount = readStruct->intMatrix.at(i).size(); consistency = consistency && (currentRowCount == firstRowCount); } } else if (readStruct->type == DOUBLE) { firstRowCount = readStruct->decMatrix.first().size(); for (int i = 0; i < readStruct->decMatrix.size(); i++) { currentRowCount = readStruct->decMatrix.at(i).size(); consistency = consistency && (currentRowCount == firstRowCount); } } // Error for the consistency flag if (!consistency) { readStruct->error = true; readStruct->errorMessage = "Multiple-length rows for a single matrix"; } pthread_exit(0); } void *Controller::write(void *arg) { struct WriteArgs *writeStruct = (struct WriteArgs *)arg; QString path = writeStruct->filepath; QFile out(path); out.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text); // Open as textstream QTextStream outs(&out); if (writeStruct->type == DOUBLE) { // For decimals outs.setRealNumberPrecision(4); outs.setRealNumberNotation(QTextStream::FixedNotation); for (int i = 0; i < writeStruct->decMatrixC.size(); i++) { for (int j = 0; j < writeStruct->decMatrixC[i].size(); j++) { outs << writeStruct->decMatrixC[i][j] << " "; } outs << "\n"; } } else if (writeStruct->type == INT) { for (int i = 0; i < writeStruct->intMatrixC.size(); i++) { for (int j = 0; j < writeStruct->intMatrixC[i].size(); j++) { outs << writeStruct->intMatrixC[i][j] << " "; } outs << "\n"; } } out.close(); pthread_exit(0); } void *Controller::multiply(void *arg) { struct MultArgs *multStruct = (struct MultArgs *)arg; int total = 0; if (multStruct->write->type == INT) { for (int i = 0; i < multStruct->write->intMatrixA[0].size(); i++) { total += multStruct->write->intMatrixA[multStruct->i][i] * multStruct->write->intMatrixB[i][multStruct->j]; } multStruct->write->intMatrixC[multStruct->i][multStruct->j] = total; } else if (multStruct->write->type == DOUBLE) { for (int i = 0; i < multStruct->write->decMatrixA[0].size(); i++) { total += multStruct->write->decMatrixA[multStruct->i][i] * multStruct->write->decMatrixB[i][multStruct->j]; } multStruct->write->decMatrixC[multStruct->i][multStruct->j] = total; } // Set QBitArray to indicate success multStruct->write->locks[multStruct->i][multStruct->j] = true; pthread_exit(0); } <file_sep>/ui_mainwindow.h /******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.7.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QProgressBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *CentralWidget; QWidget *layoutWidget; QGridLayout *Grid; QLabel *MatrixALabel; QLineEdit *MatrixALineEdit; QPushButton *MatrixAButton; QLabel *MatrixBLabel; QLineEdit *MatrixBLineEdit; QPushButton *MatrixBButton; QLabel *MatrixCLabel; QLineEdit *MatrixCLineEdit; QPushButton *MatrixCButton; QLabel *pThreadLabel; QProgressBar *pThreadProgressBar; QLabel *pThreadValueLabel; QLabel *QRunnableLabe1; QProgressBar *QRunnableProgressBaR; QLabel *QRunnableValueLabel; QPushButton *ComputeButton; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(500, 300); CentralWidget = new QWidget(MainWindow); CentralWidget->setObjectName(QStringLiteral("CentralWidget")); CentralWidget->setMinimumSize(QSize(400, 0)); layoutWidget = new QWidget(CentralWidget); layoutWidget->setObjectName(QStringLiteral("layoutWidget")); layoutWidget->setGeometry(QRect(20, 10, 461, 231)); Grid = new QGridLayout(layoutWidget); Grid->setSpacing(6); Grid->setContentsMargins(11, 11, 11, 11); Grid->setObjectName(QStringLiteral("Grid")); Grid->setContentsMargins(0, 0, 0, 0); MatrixALabel = new QLabel(layoutWidget); MatrixALabel->setObjectName(QStringLiteral("MatrixALabel")); Grid->addWidget(MatrixALabel, 0, 0, 1, 1); MatrixALineEdit = new QLineEdit(layoutWidget); MatrixALineEdit->setObjectName(QStringLiteral("MatrixALineEdit")); MatrixALineEdit->setEnabled(false); MatrixALineEdit->setReadOnly(true); Grid->addWidget(MatrixALineEdit, 0, 1, 1, 1); MatrixAButton = new QPushButton(layoutWidget); MatrixAButton->setObjectName(QStringLiteral("MatrixAButton")); Grid->addWidget(MatrixAButton, 0, 2, 1, 1); MatrixBLabel = new QLabel(layoutWidget); MatrixBLabel->setObjectName(QStringLiteral("MatrixBLabel")); Grid->addWidget(MatrixBLabel, 1, 0, 1, 1); MatrixBLineEdit = new QLineEdit(layoutWidget); MatrixBLineEdit->setObjectName(QStringLiteral("MatrixBLineEdit")); MatrixBLineEdit->setEnabled(false); MatrixBLineEdit->setReadOnly(true); Grid->addWidget(MatrixBLineEdit, 1, 1, 1, 1); MatrixBButton = new QPushButton(layoutWidget); MatrixBButton->setObjectName(QStringLiteral("MatrixBButton")); Grid->addWidget(MatrixBButton, 1, 2, 1, 1); MatrixCLabel = new QLabel(layoutWidget); MatrixCLabel->setObjectName(QStringLiteral("MatrixCLabel")); Grid->addWidget(MatrixCLabel, 2, 0, 1, 1); MatrixCLineEdit = new QLineEdit(layoutWidget); MatrixCLineEdit->setObjectName(QStringLiteral("MatrixCLineEdit")); MatrixCLineEdit->setReadOnly(false); Grid->addWidget(MatrixCLineEdit, 2, 1, 1, 1); MatrixCButton = new QPushButton(layoutWidget); MatrixCButton->setObjectName(QStringLiteral("MatrixCButton")); Grid->addWidget(MatrixCButton, 2, 2, 1, 1); pThreadLabel = new QLabel(layoutWidget); pThreadLabel->setObjectName(QStringLiteral("pThreadLabel")); Grid->addWidget(pThreadLabel, 3, 0, 1, 1); pThreadProgressBar = new QProgressBar(layoutWidget); pThreadProgressBar->setObjectName(QStringLiteral("pThreadProgressBar")); pThreadProgressBar->setValue(0); Grid->addWidget(pThreadProgressBar, 3, 1, 1, 1); pThreadValueLabel = new QLabel(layoutWidget); pThreadValueLabel->setObjectName(QStringLiteral("pThreadValueLabel")); pThreadValueLabel->setAlignment(Qt::AlignCenter); Grid->addWidget(pThreadValueLabel, 3, 2, 1, 1); QRunnableLabe1 = new QLabel(layoutWidget); QRunnableLabe1->setObjectName(QStringLiteral("QRunnableLabe1")); Grid->addWidget(QRunnableLabe1, 4, 0, 1, 1); QRunnableProgressBaR = new QProgressBar(layoutWidget); QRunnableProgressBaR->setObjectName(QStringLiteral("QRunnableProgressBaR")); QRunnableProgressBaR->setValue(0); Grid->addWidget(QRunnableProgressBaR, 4, 1, 1, 1); QRunnableValueLabel = new QLabel(layoutWidget); QRunnableValueLabel->setObjectName(QStringLiteral("QRunnableValueLabel")); QRunnableValueLabel->setAlignment(Qt::AlignCenter); Grid->addWidget(QRunnableValueLabel, 4, 2, 1, 1); ComputeButton = new QPushButton(CentralWidget); ComputeButton->setObjectName(QStringLiteral("ComputeButton")); ComputeButton->setGeometry(QRect(20, 240, 461, 40)); ComputeButton->setFlat(false); MainWindow->setCentralWidget(CentralWidget); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR)); MatrixALabel->setText(QApplication::translate("MainWindow", "Matrix A", Q_NULLPTR)); MatrixAButton->setText(QApplication::translate("MainWindow", "....", Q_NULLPTR)); MatrixBLabel->setText(QApplication::translate("MainWindow", "Matrix B", Q_NULLPTR)); MatrixBButton->setText(QApplication::translate("MainWindow", "....", Q_NULLPTR)); MatrixCLabel->setText(QApplication::translate("MainWindow", "Matrix C", Q_NULLPTR)); MatrixCButton->setText(QApplication::translate("MainWindow", "....", Q_NULLPTR)); pThreadLabel->setText(QApplication::translate("MainWindow", "PThread", Q_NULLPTR)); pThreadValueLabel->setText(QApplication::translate("MainWindow", "0", Q_NULLPTR)); QRunnableLabe1->setText(QApplication::translate("MainWindow", "QRunnable", Q_NULLPTR)); QRunnableValueLabel->setText(QApplication::translate("MainWindow", "0", Q_NULLPTR)); ComputeButton->setText(QApplication::translate("MainWindow", "COMPUTE", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H <file_sep>/mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "controller.h" #include <QFile> #include <QFileDialog> #include <QFileInfo> #include <QMainWindow> #include <QMessageBox> #include <QObject> #include <QString> #include <QTextStream> #include <QVector> #include <pthread.h> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); signals: // Send the filepath names void sendPaths(QString pathA, QString pathB, QString pathC); public slots: // Display completion message box void allThreadsCompleted(); // Update progress bar value void progressDone(int PThreadProgress, int QRunnableProgress); // Update the timer (ms) void computeDone(int PThreadTime, int QRunnableTime); // Display error message boxes void errorReceived(QString errorMessage); private slots: // Buttons click/edit void on_MatrixAButton_clicked(); void on_MatrixBButton_clicked(); void on_MatrixCButton_clicked(); void on_MatrixCLineEdit_editingFinished(); void on_ComputeButton_clicked(); // Progress Bars updates void updatePThreadProgressBar(int value); void updateQRunnableProgressBar(int value); private: Ui::MainWindow *ui; QString filenameA, filenameB, filenameC; // Error handling for paths validation bool filenameCheck(const QString filename) const; Controller m_controller; }; #endif // MAINWINDOW_H <file_sep>/mainwindow.cpp #include "mainwindow.h" #include "controller.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("Matrix Multiplier"); // Connect the path send functions QObject::connect(this, SIGNAL(sendPaths(QString, QString, QString)), &m_controller, SLOT(getPaths(QString, QString, QString))); // Connect the error handlers QObject::connect(&m_controller, SIGNAL(readWriteError(QString)), this, SLOT(errorReceived(QString))); // Connect the compute notifications QObject::connect(&m_controller, SIGNAL(notifyComputeCompleted(int, int)), this, SLOT(computeDone(int, int))); QObject::connect(&m_controller, SIGNAL(notifyProgressCompleted(int, int)), this, SLOT(progressDone(int, int))); // Connect the final thread QObject::connect(&m_controller, SIGNAL(notifyTotalThreads(void)), this, SLOT(allThreadsCompleted(void))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::allThreadsCompleted() { QMessageBox::information(this, "Done", "Done compute"); } void MainWindow::progressDone(int PThreadProgress, int QRunnableProgress) { ui->QRunnableProgressBaR->setValue(QRunnableProgress); ui->pThreadProgressBar->setValue(PThreadProgress); } void MainWindow::computeDone(int PThreadTime, int QRunnableTime) { ui->pThreadValueLabel->setText(QString::number(PThreadTime)); ui->QRunnableValueLabel->setText(QString::number(QRunnableTime)); } void MainWindow::errorReceived(QString errorMessage) { QMessageBox::critical(this, "Error", errorMessage); } void MainWindow::on_MatrixAButton_clicked() { // Get path from file selection dialog filenameA = QFileDialog::getOpenFileName(this, "/home"); // Set field text to selected path ui->MatrixALineEdit->setText(filenameA); } void MainWindow::on_MatrixBButton_clicked() { // Get path from file selection dialog filenameB = QFileDialog::getOpenFileName(this, "/home"); // Set field text to selected path ui->MatrixBLineEdit->setText(filenameB); } void MainWindow::on_MatrixCButton_clicked() { // Defaults to home if empty field already QString filepath = filenameC == "" ? "/home" : filenameC; // Get path from file selection dialog QString newFilenameC = QFileDialog::getOpenFileName(this, filepath); // Keep the existing text in the LineEdit when a file is not selected // Else replace with the new path selected from the file dialog filenameC = newFilenameC == "" ? filenameC : newFilenameC; // Set field text to selected or existing path ui->MatrixCLineEdit->setText(filenameC); } void MainWindow::on_MatrixCLineEdit_editingFinished() { // Set path to field text if user typed in path filenameC = ui->MatrixCLineEdit->text(); } void MainWindow::on_ComputeButton_clicked() { // Reset progresses ui->pThreadProgressBar->setValue(0); ui->QRunnableProgressBaR->setValue(0); ui->pThreadValueLabel->setText(0); ui->QRunnableValueLabel->setText(0); // Check each file for existance and readability if (!(filenameCheck(filenameA) && filenameCheck(filenameB) && filenameCheck(filenameC))) { QMessageBox::critical(this, "File I/O Error", "Unopenable, unreadable, or unwritable files"); return; } // Send the paths emit sendPaths(filenameA, filenameB, filenameC); // Make controller compute m_controller.compute(); } void MainWindow::updatePThreadProgressBar(int value) { ui->pThreadProgressBar->setValue(value); } void MainWindow::updateQRunnableProgressBar(int value) { ui->QRunnableProgressBaR->setValue(value); } bool MainWindow::filenameCheck(const QString filename) const { QFileInfo checkFilename(filename); bool ok = false; // Check if file exist, is it a file and openable if (checkFilename.exists() && checkFilename.isFile()) { QFile file(filename); if (file.open(QIODevice::ReadOnly)) { ok = true; file.close(); } } return ok; } <file_sep>/controller.h #ifndef CONTROLLER_H #define CONTROLLER_H #include <QBitArray> #include <QElapsedTimer> #include <QFile> #include <QFileDialog> #include <QFileInfo> #include <QList> #include <QMessageBox> #include <QObject> #include <QRegExp> #include <QRegularExpression> #include <QRunnable> #include <QString> #include <QTextStream> #include <QThreadPool> #include <QVector> #include <pthread.h> typedef QVector<QList<QString>> StringMatrix; typedef QVector<QVector<int>> IntegerMatrix; typedef QVector<QVector<double>> DecimalMatrix; typedef QVector<int> IntegerRow; typedef QVector<double> DecimalRow; enum MATRIX_TYPE { NONE, INT, DOUBLE }; class Controller : public QObject { Q_OBJECT public: explicit Controller(QObject *parent = nullptr); ~Controller(); // Handle threads void compute(); void computeThread(); QString getMatrixAPath(); QString getMatrixBPath(); QString getMatrixCPath(); int getPThreadProgress(); // Help emit signals void emitRWError(QString errorMessage); void emitPthreadTime(int PThreadTime); void emitQRunnableTime(int QRunnableTime); void emitPThreadProgress(int PThreadProgress); void emitQRunnableProgress(int QRunnableProgress); signals: void notifyTotalThreads(); void notifyPThreadCompleted(); void notifyQRunnableCompleted(); // Most important void notifyComputeCompleted(int PThreadTime, int QRunnableTime); void notifyProgressCompleted(int PThreadProgress, int QRunnableProgress); void readWriteError(QString errorMessage); public slots: void getPaths(QString pathA, QString pathB, QString pathC); private: // Parsing + error handling static void *computeThreads(void *arg); static void *read(void *arg); static void *write(void *arg); static void *multiply(void *arg); // Variables QString filePathA, filePathB, filePathC; int TotalPThreadTime = 0; int TotalQRunnableTime = 0; int TotalQRunnableProgress = 0; int TotalPThreadProgress = 0; MATRIX_TYPE type = NONE; }; struct PathArgs { Controller *controller; // Deallocate ??? ~PathArgs() { controller = nullptr; delete controller; } }; struct ReadArgs { QString filepath; MATRIX_TYPE type = NONE; IntegerMatrix intMatrix; DecimalMatrix decMatrix; bool error = false; QString errorMessage = ""; }; struct WriteArgs { QString filepath; MATRIX_TYPE type = NONE; IntegerMatrix intMatrixA; DecimalMatrix decMatrixA; IntegerMatrix intMatrixB; DecimalMatrix decMatrixB; IntegerMatrix intMatrixC; DecimalMatrix decMatrixC; bool error = false; QString errorMessage = ""; QList<QBitArray> locks; }; struct MultArgs { WriteArgs *write; PathArgs *paths; int i; int j; int totalThreads; }; #endif // CONTROLLER_H
487a72e73d23e32f18dcf2c752f6f934e770c8fe
[ "C++" ]
5
C++
hughiednguyen/applied_hw7_multithread_matrix_calc
0ff4294be046e21786d8b2a9ba5fcda62a37b808
1a9a1d2ba9ba2de6c9aaca26a918e9fb5292b97d
refs/heads/master
<file_sep>import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from numpy.random import RandomState def split_dataset(df, validation_percentage, seed): state = RandomState(seed) validation_indexes = state.choice(df.index, int(len(df.index) * validation_percentage), replace=False) training_set = df.loc[~df.index.isin(validation_indexes)] validation_set = df.loc[df.index.isin(validation_indexes)] return training_set, validation_set def train(datafile): data = pd.read_parquet(datafile) training_set, validation_set = split_dataset(data, 0.25, 1) #train training_set["s1"] = training_set["s1"].fillna(training_set["s1"].mean()) training_set["default"] = training_set["default"].fillna(training_set["default"].mode()[0]) clf = LogisticRegression(C=0.1) clf.fit(training_set[["s1", "s2", "s3", "s4"]], training_set["default"]) # evaluation validation_set["s1"] = validation_set["s1"].fillna(training_set["s1"].mean()) validation_set["default"] = validation_set["default"].fillna(training_set["default"].mode()[0]) validation_predictions = clf.predict_proba(validation_set[["s1", "s2", "s3", "s4"]])[:, 1] auc = roc_auc_score(validation_set[["default"]], validation_predictions) return clf, auc <file_sep>Flask==0.12.2 healthcheck==1.3.2 jsonschema==2.6.0 numpy==1.14.0 pandas==0.22.0 pyarrow==0.8.0 requests==2.18.4 scikit-learn==0.19.0 scipy==1.0.0 <file_sep>from datetime import datetime import os import stat from sklearn.externals import joblib from creditor import update_versions from model import train BASE_DIR = os.path.dirname(os.path.abspath(__file__)) MAIN_MODEL = os.environ.get('CREDITOR_MAIN_MODEL') MAIN_MODEL_ID = MAIN_MODEL[:-4] MAIN_DATAFILE = os.environ.get('CREDITOR_MAIN_DATAFILE') MODELS_FOLDER = os.path.join(BASE_DIR, 'models') DATAFILES_FOLDER = os.path.join(BASE_DIR, 'datafiles') VERSIONS_FILE = os.path.join(MODELS_FOLDER, '.versions') def on_starting(server): """Generates main model and adds it to the version control, if there are no other models""" if not open(VERSIONS_FILE, 'r').read(): initial_model, auc = train(os.path.join(DATAFILES_FOLDER, MAIN_DATAFILE)) initial_model_filepath = os.path.join(MODELS_FOLDER, MAIN_MODEL) joblib.dump(initial_model, initial_model_filepath) model_creation_time = datetime.fromtimestamp(os.stat(initial_model_filepath)[stat.ST_CTIME]) current_version = {'id': MAIN_MODEL_ID, 'created_at': str(model_creation_time), 'auc': auc} update_versions(current_version) <file_sep>FROM ubuntu:latest ENV CREDITOR_MAIN_MODEL askr.pkl ENV CREDITOR_MAIN_DATAFILE training_set.parquet ENV PYTHONPATH $PYTHONPATH:/deploy/creditor RUN apt-get update && apt-get install -y python python-dev python-pip gunicorn supervisor nginx RUN mkdir -p /deploy/creditor COPY . /deploy/creditor WORKDIR /deploy/creditor RUN pip install -r /deploy/creditor/requirements.txt RUN rm /etc/nginx/sites-enabled/default COPY nginx.conf /etc/nginx/sites-available/ RUN ln -s /etc/nginx/sites-available/nginx.conf /etc/nginx/sites-enabled/nginx.conf RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN mkdir -p /var/log/supervisor COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf CMD ["/usr/bin/supervisord"] <file_sep>from datetime import datetime import os import stat import unittest from flask import json from sklearn.externals import joblib from creditor import app, update_versions from model import train BASE_DIR = os.path.dirname(os.path.abspath(__file__)) app.config['MAIN_MODEL'] = 'askr.pkl' app.config['MAIN_MODEL_ID'] = app.config['MAIN_MODEL'][:-4] app.config['MODELS_FOLDER'] = os.path.join(BASE_DIR, 'tests', 'models') app.config['DATAFILES_FOLDER'] = os.path.join(BASE_DIR, 'tests', 'datafiles') app.config['VERSION_CONTROL'] = os.path.join(app.config['MODELS_FOLDER'], '.versions') # Status codes BAD_REQUEST = 400 NOT_FOUND = 404 OK = 200 INPUT_SAMPLE = '''{ "id": "488ef383211f472f957337d38a909c43", "s1": 480.0, "s2": 105.2, "s3": 0.8514, "s4": 94.2 }''' class CreditorTestCase(unittest.TestCase): """Independent tests for creditor module endpoints""" def setUp(self): app.testing = True self.app = app.test_client() test_model, auc = train(os.path.join(app.config['DATAFILES_FOLDER'], 'test_training_set.parquet')) test_model_filepath = os.path.join(app.config['MODELS_FOLDER'], app.config['MAIN_MODEL']) joblib.dump(test_model, test_model_filepath) model_creation_time = datetime.fromtimestamp(os.stat(test_model_filepath)[stat.ST_CTIME]) current_version = {'id': app.config['MAIN_MODEL_ID'], 'created_at': str(model_creation_time), 'auc': auc} update_versions(current_version) def testHealthcheck(self): """Tests if healthcheck endpoint is working and returning OK""" r = self.app.get('/healthcheck') r_dict = json.loads(r.data) self.assertEqual(r_dict['status'], 'success', 'Unhealthy server') self.assertTrue(r_dict['results'][0]['passed'], 'Not passed') def test_slashed_endpoints(self): """Tests if URLs containing slashes returns error 404 NOT FOUND""" f = open(os.path.join(app.config['DATAFILES_FOLDER'], 'test_training_set.parquet'), 'rb') files = {'file': f} try: update_req = self.app.post('/update/../foo', data=files) finally: f.close() self.assertEqual(update_req.status_code, NOT_FOUND, 'Not 404 for a slashed model at /update') predict_req = self.app.post('/predict/../foo', data=INPUT_SAMPLE) self.assertEqual(predict_req.status_code, NOT_FOUND, 'Not 404 for a slashed model at /predict') def test_schema_validation(self): """Tests if schema validation errors are thrown as expected""" input_data_missing_fields = '{"s3": 0.8514, "s4": 94.2}' input_data_extra_fields = '''{ "id": "488ef383211f472f957337d38a909c43", "s1": 480.0, "s2": 105.2, "s3": 0.8514, "s4": 94.2, "s5": 22.3 }''' input_data_wrong_type = '''{ "id": "488ef383211f472f957337d38a909c43", "s1": 480.0, "s2": "foo", "s3": "bar", "s4": 94.2 }''' r_missing = self.app.post('/predict', data=input_data_missing_fields) self.assertEqual(r_missing.status_code, BAD_REQUEST, 'Not 400 for missing fields in JSON') r_extra = self.app.post('/predict', data=input_data_extra_fields) self.assertEqual(r_extra.status_code, BAD_REQUEST, 'Not 400 for extra fields in JSON') r_wrong = self.app.post('/predict', data=input_data_wrong_type) self.assertEqual(r_wrong.status_code, BAD_REQUEST, 'Not 400 for type error in JSON') r = self.app.post('/predict', data=INPUT_SAMPLE) self.assertEqual(r.status_code, OK, 'Not 200 for a valid JSON') def test_predict_nonexistent_model(self): """Tests if endpoint /predict returns 404 NOT FOUND for a nonexistent model""" r = self.app.post('/predict/foo', data=INPUT_SAMPLE) self.assertEqual(r.status_code, NOT_FOUND, 'Not 404 for nonexistent model') def test_update_with_not_allowed_extension(self): """Tests if a POST request to /update with a file containing a not allowed extension returns 400 BAD REQUEST """ f = open(os.path.join(app.config['DATAFILES_FOLDER'], 'not_allowed.extension'), 'rb') files = {'file': f} try: r = self.app.post('/update/notallowed', data=files) finally: f.close() self.assertEqual(r.status_code, BAD_REQUEST, 'Not 400 for file missing or not allowed extension') def test_update_existent_model(self): """Tests if a POST request to /update with an existent model_id returns 400 BAD REQUEST""" model_id = app.config['MAIN_MODEL'][:-4] f = open(os.path.join(app.config['DATAFILES_FOLDER'], 'test_training_set.parquet'), 'rb') files = {'file': f} try: r = self.app.post('/update/{}'.format(model_id), data=files) finally: f.close() self.assertEqual(r.status_code, BAD_REQUEST, 'Not 400 for using an existent model_id') def tearDown(self): os.remove(os.path.join(app.config['MODELS_FOLDER'], app.config['MAIN_MODEL'])) with open(app.config['VERSION_CONTROL'], 'w') as f: f.truncate() class MonolithicCreditorTestCase(unittest.TestCase): """Monolithic test for creditor module endpoints. The output of one step is considered for the execution of the next step. Its purpose is to test the entire pipeline at once """ def setUp(self): self.app = app.test_client() test_model, auc = train(os.path.join(app.config['DATAFILES_FOLDER'], 'test_training_set.parquet')) test_model_filepath = os.path.join(app.config['MODELS_FOLDER'], app.config['MAIN_MODEL']) joblib.dump(test_model, test_model_filepath) model_creation_time = datetime.fromtimestamp(os.stat(test_model_filepath)[stat.ST_CTIME]) model_id = app.config['MAIN_MODEL'][:-4] current_version = {'id': model_id, 'created_at': str(model_creation_time), 'auc': auc} update_versions(current_version) # Predicts using the main model def step1(self): r = self.app.post('/predict', data=INPUT_SAMPLE) r_dict = json.loads(r.data) self.assertEqual(len(r_dict), 2) self.assertEqual(r_dict['id'], '488ef383211f472f957337d38a909c43') self.assertAlmostEqual(r_dict['probability'], 0.15156206771062417) # Creates a new model called embla def step2(self): f = open(os.path.join(app.config['DATAFILES_FOLDER'], 'test_random_training_set.parquet'), 'rb') files = {'file': f} try: r = self.app.post('/update/embla', data=files) finally: f.close() r_dict = json.loads(r.data) self.assertEqual(r.status_code, OK) self.assertIn('up and running', r_dict['message']) self.assertIn('embla.pkl', os.listdir(app.config['MODELS_FOLDER'])) self.assertIn('embla.parquet', os.listdir(app.config['DATAFILES_FOLDER'])) # Checks if embla is added to the list of model versions def step3(self): r = self.app.get('/versions') r_dict = json.loads(r.data) model_ids = [model['id'] for model in r_dict] self.assertEqual(len(model_ids), 2) self.assertIn(u'askr', model_ids) self.assertIn(u'embla', model_ids) # Predicts using embla def step4(self): r = self.app.post('/predict/embla', data=INPUT_SAMPLE) r_dict = json.loads(r.data) self.assertEqual(len(r_dict), 2) self.assertEqual(r_dict['id'], '488ef383211f472f957337d38a909c43') self.assertAlmostEqual(r_dict['probability'], 0.47938034279039) def _steps(self): for name in sorted(dir(self)): if name.startswith("step"): yield name, getattr(self, name) def test_steps(self): for name, step in self._steps(): try: step() except Exception as e: self.fail("{} failed ({}: {})".format(step, type(e), e)) def tearDown(self): os.remove(os.path.join(app.config['DATAFILES_FOLDER'], 'embla.parquet')) os.remove(os.path.join(app.config['MODELS_FOLDER'], 'askr.pkl')) os.remove(os.path.join(app.config['MODELS_FOLDER'], 'embla.pkl')) with open(app.config['VERSION_CONTROL'], 'w') as f: f.truncate() if __name__ == '__main__': unittest.main() <file_sep>from datetime import datetime import os import stat from flask import Flask, json, jsonify, request, make_response from healthcheck import HealthCheck from jsonschema import validate, ValidationError import pandas as pd from sklearn.externals import joblib from model import train from schemas.payload_schema import payload_schema app = Flask(__name__) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) app.config['MAIN_MODEL'] = os.environ.get('CREDITOR_MAIN_MODEL') app.config['MAIN_MODEL_ID'] = app.config['MAIN_MODEL'][:-4] app.config['MODELS_FOLDER'] = os.path.join(BASE_DIR, 'models') app.config['DATAFILES_FOLDER'] = os.path.join(BASE_DIR, 'datafiles') app.config['ALLOWED_EXTENSIONS'] = {'parquet'} app.config['VERSION_CONTROL'] = os.path.join(app.config['MODELS_FOLDER'], '.versions') # Example request: curl -X GET http://localhost/healthcheck health = HealthCheck(app, "/healthcheck") # Healthcheck section def models_available(): """Checks the availability of the main model and if it is predicting""" model_filepath = os.path.join(app.config['MODELS_FOLDER'], app.config['MAIN_MODEL']) model = joblib.load(model_filepath) sample_data = { 'score_3': 420.0, 'score_4': 99.384867, 'score_5': 0.661019, 'score_6': 106.788234 } sample_input = pd.DataFrame.from_dict([sample_data], orient='columns') _ = model.predict_proba( sample_input[[ 'score_3', 'score_4', 'score_5', 'score_6' ]])[:, 1][0] return True, "Model loading and prediction are ok" health.add_check(models_available) # Error handling section # Class InvalidUsage taken from Flask documentation class InvalidUsage(Exception): # Defaults to Bad Request status_code = 400 def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.errorhandler(404) def not_found(error): return make_response(jsonify({'message': 'Resource not found'}), 404) # Helper functions section def allowed_file(filename): """Checks if the file has an allowed file extension""" return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] def exists(model_id): """Checks if model <model_id> is available in the disk""" return '{}.pkl'.format(model_id) in os.listdir(app.config['MODELS_FOLDER']) def validate_json_payload(payload): """Validates input data against a predefined JSON schema""" try: validate(payload, payload_schema) except ValidationError: raise InvalidUsage('JSON schema mismatch: please review your input data') def update_versions(current_version): """ Adds current version to the version control file """ versions_file = os.path.join(app.config['MODELS_FOLDER'], '.versions') with open(versions_file, 'r') as f: try: models_versions = json.load(f) except ValueError: models_versions = [] models_versions.append(current_version) with open(versions_file, 'w') as f: json.dump(models_versions, f) # Views section @app.route("/predict", methods=['POST']) @app.route("/predict/<string:model_id>", methods=['POST']) def predict(model_id=app.config['MAIN_MODEL_ID']): """Predicts default risk for a potential client POST: Predicts default risk for a potential client using the Main Logistic Regression Model (endpoint /predict) or using the Logistic Regression model defined by <model_id> (endpoint /predict/<model_id>); body is a JSON content payload with input data. Returns HTTP 200 on success; Returns HTTP 400 in case of JSON schema mismatch or if the model defined by <model_id> does not exist Example requests: curl -H "Content-Type: application/json" -X POST -d <json_input> http://localhost/predict curl -H "Content-Type: application/json" -X POST -d <json_input> http://localhost/predict/<model_id> """ if not exists(model_id): raise InvalidUsage( 'Model {} does not exist. Check the running versions at /versions'.format(model_id), status_code=404 ) else: data = json.loads(request.data) validate_json_payload(data) input_data = pd.DataFrame.from_dict([data], orient='columns') model_filepath = os.path.join(app.config['MODELS_FOLDER'], '{}.pkl'.format(model_id)) model = joblib.load(model_filepath) output_data = { 'id': data['id'], 'probability': model.predict_proba(input_data[['s1', 's2', 's3', 's4']])[:, 1][0] } return jsonify(output_data) @app.route("/update/<string:model_id>", methods=['POST']) def update(model_id): """Updates Logistic Regression model when more data are available POST: Updates Logistic Regression model when more data are available; body is a binary .parquet file hosting the data. Returns HTTP 200 on success; Returns HTTP 400 if the model defined by <model_id> already exists or HTTP 413 if the file size is greater than 250 MB (can be redefined by the web server configuration) Example request: curl -H "Content-Type: multipart/form-data" -F "file=@/path/to/file.parquet" http://localhost/update/<model_id> """ if exists(model_id): raise InvalidUsage('Model {} already exists. Please choose another name'.format(model_id)) else: datafile = request.files['file'] if datafile and allowed_file(datafile.filename): data_filepath = os.path.join(app.config['DATAFILES_FOLDER'], '{}.parquet'.format(model_id)) datafile.save(data_filepath) model, auc = train(data_filepath) model_filepath = os.path.join(app.config['MODELS_FOLDER'], '{}.pkl'.format(model_id)) joblib.dump(model, model_filepath) model_creation_time = datetime.fromtimestamp(os.stat(model_filepath)[stat.ST_CTIME]) current_version = {'id': model_id, 'created_at': str(model_creation_time), 'auc': auc} update_versions(current_version) return jsonify({'message': 'Your new model {} is up and running'.format(model_id)}) else: raise InvalidUsage('File not found or file extension not allowed') @app.route("/versions", methods=['GET']) def versions(): """Shows the list of running models GET: Shows the list of running models with <model_id> and creation data for reference. Returns HTTP 200 on success Example request: curl -X GET http://localhost/versions """ versions_file = os.path.join(app.config['MODELS_FOLDER'], '.versions') return jsonify(json.loads(open(versions_file, 'r').read())) if __name__ == "__main__": app.run(host='0.0.0.0') <file_sep># Creditor A HTTP server that makes real-time default risk predictions based on multiple versions of a (dummy) Logistic Regression model. ## Overview Creditor uses a widely-spread approach to serve data via HTTP with good latency results: A _Flask_ app, _Gunicorn_ as the application server and _Nginx_ as the reverse-proxy server. [Flask](http://flask.pocoo.org/) is a well-known minimalistic and lightweight microframework. Together with [Gunicorn](http://gunicorn.org/), models can be served in a fast and reliable way. On top of that, [Nginx](https://www.nginx.com/) is a battle-tested way to receive the requests and distribute them among the Gunicorn workers efficiently. The logic employed is stateless. As an initial setup, the model is trained and serialized to the disk. When a request is received at `/predict`, the server loads it into memory so it can predict default risk for the input data. After predicted data is sent back to the client, the model's in-memory representation is left to the garbage collector. For the next request, it will get loaded from the disk again. The serialization-into-disk strategy works well with logistic regression models, considering that they are small (~ 800 bytes for the given LR model), no matter the size of the training data (it's just the coefficients of an equation, after all). For models that store the training set data (such as kNN) or huge neural network models, maybe a caching strategy should be employed (using Redis for caching is a common approach). For reloading these tiny, frequently accessed files, the operational system caching does its job. When more data are available, it is possible to update the model by making a request to `/update/<model_id>`, where `<model_id>` states for any valid string (the ones that does not contains slashes or whitespaces). A `.parquet` file for the updated dataset must be sent as form data, with the proper headers. The server is configured to receive files sized up to 250 MB, but it is possible to change this behavior editing `nginx.conf`. This HTTP file transfer approach was meant to be simple. In an insecure environment, one should consider using data encryption or some other way to upload files to the server. Requiring a token authentication could also be added as an extra layer of security. The new created model will, then, receive requests at `predict/<model_id>`. The endpoint `/predict` (without a `<model_id>`) will always serve the model given by `CREDITOR_MAIN_MODEL` environment variable, that can be set to point to any existing version of the model you want. A simple payload content validation was also implemented. If the input data schema differs the schema previously defined, an error code will be thrown. This validation accounts for lacking fields, extra fields and wrong types. Changes to the given model code (`model.py`) were intentionally kept to the minimum, only the necessary to fit it to the approach. This way, Pandas warnings on views and copies of dataframes were ignored. A list of versions with model id, creation timestamp and area under the ROC curve can be obtained by making a GET request at `/versions`. The service running status can be monitored by a proper tool making a GET request to `/healthcheck`. ## Main files - `creditor.py`: Main flask module, containing the views. This module also contains healthcheck, error handling and auxiliary functions that are used only for creditor. - `creditor_tests.py`: Testing. All endpoints were tested at least once, for positive and negative responses. Healthcheck, error handling, auxiliary functions and validation schema were also tested. - `model.py`: The given logistic regression model (with minor changes). - `models/.version`: Version control file. Holds information for existent models, such as id, creation timestamp and ROC AUC score. - `nginx.conf`: A simple configuration file for Nginx. - `setup.py`: A configuration script that runs on first server startup. It creates the main model and adds it to the version control file if there are no other versions. - `supervisord.conf`: Configuration file for _Supervisor_. It keeps Gunicorn and Nginx servers online, restarting them if needed. - `wsgi.py`: Gunicorn application object. Imports creditor app to be served by the gunicorn workers. ## Environment variables ``` CREDITOR_MAIN_MODEL= CREDITOR_MAIN_DATAFILE= ``` For examples, please read the [Dockerfile](./Dockerfile). ## Running Firstly, make sure you have Docker installed and running properly (for reference, I tested it with Docker for Mac `17.12.0-ce-mac46` and Docker for Linux `17.12.0-ce`). Then, check if there is no service listening on port 80 or if the port it not firewalled. After that, you can build and run a ready-for-use container executing the line below (do not forget do `cd` to the project folder, where the `Dockerfile` lies): ```sh docker build -t creditor . && docker run -d -p 80:80 creditor ``` Now Creditor should accept requests at port 80. Ubuntu needs `sudo` privileges to execute `docker` command by default. ## Testing ``` pip install -r requirements.txt python creditor_tests.py ``` Gitlab CI is configured to run the tests and get line coverage for `creditor.py` and `/schemas/payload_schema.py`. ## Performance The server was deployed to a MacBook Pro (i7 2.2 GHz Quad-core, 16 GB RAM), listening at the local network. Performance tests, using the `wrk` tool, show good latency results for 100 opened connections (30 seconds workload) requesting at `/predict` (using the given example input as payload): ``` Running 30s test @ http://192.168.1.11 4 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 88.34ms 5.29ms 108.78ms 94.22% Req/Sec 281.52 24.18 353.00 72.82% Latency Distribution 50% 88.49ms 75% 90.07ms 90% 91.90ms 99% 96.46ms 16454 requests in 30.06s, 3.81MB read Requests/sec: 547.30 Transfer/sec: 129.86KB ``` Gunicorn showed best results when deployed with 9 workers (CPUs * 2 + 1), the `-w` parameter at: ``` gunicorn --bind 0.0.0.0:5000 wsgi:app -w 9 -t 90 -c /deploy/creditor/setup.py ``` This approach can be vertically and horizontally scaled up. The hardware could be improved (MacBooks are not the best server material) and more machines could be added, with load balancing. Gunicorn and Nginx configurations could also be tweaked for best performance in the available hardware. <file_sep>payload_schema = { 'type': 'object', 'properties': { 'id': {'type': 'string'}, 's1': {'type': 'number'}, 's2': {'type': 'number'}, 's3': {'type': 'number'}, 's4': {'type': 'number'} }, 'additionalProperties': False, 'required': ['id', 's1', 's2', 's3', 's4'] }
7a335207484294cf3a28b28c6ba933d6feab5212
[ "Markdown", "Python", "Text", "Dockerfile" ]
8
Python
holypriest/creditor
830ccd51e6bdee993debc16fbb4019b3152f5e18
ebbd1212ed5ce17d016fab3941cc880ddabadcb2
refs/heads/master
<file_sep>import React from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; import { Container } from 'reactstrap'; import Header from './Header'; import Sidebar from './Sidebar'; import Breadcrumb from './Breadcrumb'; import Aside from './Aside'; import Footer from './Footer'; import EmployeesListContainer from '../../containers/EmployeesListContainer'; import EmployeesAddEditContainer from '../../containers/EmployeesAddEditContainer'; const Layout = ({ props }) => ( <div className="app"> <Header /> <div className="app-body"> <Sidebar {...props} /> <main className="main"> <Breadcrumb /> <Container fluid> <Switch> <Route path="/employees/:page" name="Employees" component={EmployeesListContainer} /> <Route path="/employees" name="Employees" component={EmployeesListContainer} /> <Route path="/add-edit-employee/:id" name="Add/Edit Employee" component={EmployeesAddEditContainer} /> <Route path="/add-edit-employee" name="Add/Edit Employee" component={EmployeesAddEditContainer} /> <Redirect from="/" to="/employees" /> </Switch> </Container> </main> <Aside /> </div> <Footer /> </div> ); export default Layout;<file_sep>import React from 'react'; import Calendar from '../common/Calendar'; const EmployeesAddEdit = ({ employee, onChange, onSubmit, onGoBack }) => <div className="row"> <div className="col-lg-6"> <div className="card"> <form className="form-horizontal"> <div className="card-header"> <button type="button" className="btn btn-sm" onClick={onGoBack}> <i className="fa fa-arrow-left"></i> </button> <strong>{employee.id ? "Edit" : "Add"} Employee</strong> </div> <div className="card-body card-block"> <div className="row form-group"> <div className="col col-md-3"> <label htmlFor="firstName" className="form-control-label">First Name</label> </div> <div className="col-12 col-md-9"> <input type="text" id="firstName" name="firstName" value={employee.firstName} onChange={onChange} placeholder="Enter First Name..." className="form-control" /> </div> </div> <div className="row form-group"> <div className="col col-md-3"> <label htmlFor="lastName" className="form-control-label">Last Name</label> </div> <div className="col-12 col-md-9"> <input type="text" id="lastName" name="lastName" value={employee.lastName} onChange={onChange} placeholder="Enter Last Name..." className="form-control" /> </div> </div> <div className="row form-group"> <div className="col col-md-3"> <label htmlFor="birthday" className="form-control-label">Birthday</label> </div> <div className="col-12 col-md-9"> <Calendar onChange={(field, value) => onChange({ target: { name: 'birthday', value: value } })} value={employee.birthday} /> </div> </div> <div className="row form-group"> <div className="col col-md-3"> <label htmlFor="gender" className="form-control-label">Gender</label> </div> <div className="col-12 col-md-9"> <div className="radio-inline"> <input className="radio-input" type="radio" name="gender" id="inlineRadio1" value="m" checked={employee.gender === "m"} onChange={onChange} /> <label className="radio-label" htmlFor="inlineRadio1">Male</label> </div> <div className="radio-inline"> <input className="radio-input" type="radio" name="gender" id="inlineRadio2" value="w" checked={employee.gender === "w"} onChange={onChange} /> <label className="radio-label" htmlFor="inlineRadio2">Female</label> </div> </div> </div> <div className="row form-group"> <div className="col col-md-3"> <label htmlFor="lastContact" className="form-control-label">Last Contact</label> </div> <div className="col-12 col-md-9"> <Calendar onChange={(field, value) => onChange({ target: { name: 'lastContact', value: value } })} value={employee.lastContact} /> </div> </div> <div className="row form-group"> <div className="col col-md-3"> <label htmlFor="employeeLifetimeValue" className="form-control-label">Lifetime</label> </div> <div className="col-12 col-md-9"> <input type="text" id="employeeLifetimeValue" name="employeeLifetimeValue" value={employee.employeeLifetimeValue} onChange={onChange} placeholder="Enter Employee Lifetime Value..." className="form-control" /> </div> </div> </div> <div className="card-footer buttons"> <button type="button" onClick={onSubmit} className="btn btn-primary btn-sm"> <i className="fa fa-floppy-o"></i> {employee.id ? "Save Changes" : "Create"} </button> </div> </form> </div> </div> </div> export default EmployeesAddEdit;<file_sep>import React from 'react'; import Paging from 'reactjs-paging'; import { pageSize } from '../../configuration'; import { Link } from 'react-router-dom'; const EmployeesList = ({ match, employees, pageIndex, totalCount, onPageClick, onDeleteClick }) => <div className="row"> <div className="col-lg-12"> <div className="card"> <div className="card-header"> <Link to={`/add-edit-employee`} className="btn btn-primary btn-sm"><i className="fa fa-plus"></i> Create New</Link> </div> <div className="card-block"> <table className="table table-bordered table-striped"> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Actions</th> </tr> </thead> <tbody> {employees.map(employee => <tr key={employee.id}> <td>{employee.id}</td> <td>{employee.firstName}</td> <td>{employee.lastName}</td> <td className="buttons"> <Link className="btn btn-default btn-sm" to={`/add-edit-employee/${employee.id}`}><i className="fa fa-pencil-square-o"></i> Edit</Link> <button className="btn btn-danger btn-sm" onClick={() => onDeleteClick(employee.id)}><i className="fa fa-trash-o"></i> Delete</button> </td> </tr> )} </tbody> </table> <div className="row"> <div className="col-md-12 col-sm-12"> <nav> {(totalCount > pageSize) && <Paging pageIndex={pageIndex} groupSize={5} navSize={2} totalCount={totalCount} pageSize={pageSize} onClick={onPageClick} /> } </nav> </div> </div> </div> </div> </div> </div> export default EmployeesList;<file_sep>const routes = { '/': 'Home', '/employees': 'Employees' }; export default routes; <file_sep>const express = require('express'); const database = require('../database'); const router = express.Router(); router.get('/', async (req, res, next) => { try { const pageIndex = req.query.pageIndex || 1; const pageSize = req.query.pageSize || 10; const employees = await database.all('SELECT * FROM EMPLOYEE ORDER BY id DESC LIMIT ?,?', ((pageIndex - 1) * pageSize), pageSize); const totalCount = await database.get('SELECT COUNT(*) as "Count" FROM EMPLOYEE'); res.send({ data: employees, totalCount: totalCount.Count }); } catch (err) { next(err); } }); router.get('/:id', async (req, res, next) => { try { const employee = await database.get('SELECT * FROM EMPLOYEE WHERE id = ?', req.params.id); res.send(employee); } catch (err) { next(err); } }); router.post('/', async (req, res, next) => { try { const employeeRequest = req.body; const result = await database.run('INSERT INTO EMPLOYEE(firstName, lastName, birthday, gender, lastContact, employeeLifetimeValue) VALUES(?,?,?,?,?,?)', employeeRequest.firstName, employeeRequest.lastName, employeeRequest.birthday, employeeRequest.gender, employeeRequest.lastContact, employeeRequest.employeeLifetimeValue); res.send({ lastId: result.stmt.lastID }); } catch (err) { next(err); } }); router.put('/:id', async (req, res, next) => { try { const employeeRequest = req.body; const result = await database.run('UPDATE EMPLOYEE SET firstName = ?, lastName = ?, birthday = ?, gender = ?, lastContact = ?,employeeLifetimeValue = ? where id = ?', employeeRequest.firstName, employeeRequest.lastName, employeeRequest.birthday, employeeRequest.gender, employeeRequest.lastContact, employeeRequest.employeeLifetimeValue, req.params.id); res.send({ changes: result.stmt.changes }); } catch (err) { next(err); } }); router.delete('/:id', async (req, res, next) => { try { const result = await database.run('DELETE FROM EMPLOYEE WHERE id = ?', req.params.id); res.send({ lastID: result.stmt.lastID, changes: result.stmt.changes }); } catch (err) { next(err); } }); module.exports = router;<file_sep>import React, { Component } from "react"; import PropTypes from 'prop-types'; import { getEmployees, deleteEmployee } from '../actions/employee'; import { connect } from 'react-redux'; import EmployeesList from '../components/employee/EmployeesList'; import { toastr } from 'react-redux-toastr'; class EmployeesListContainer extends Component { constructor(props, context) { super(props, context); this.state = { pageIndex: this.props.match.params.page || 1 } } static contextTypes = { router: PropTypes.object } static propTypes = { history: PropTypes.object } componentDidMount = () => { this.props.getEmployees(this.state.pageIndex); } onPageClick = (pageIndex) => { this.props.getEmployees(pageIndex); this.setState({ pageIndex: pageIndex }); this.context.router.history.push(`/employees/${pageIndex}`); } onDeleteClick = async (id) => { const result = await this.props.deleteEmployee(id); if (result.response.changes > 0) { toastr.success('Success', 'Employee deleted'); this.props.getEmployees(this.state.pageIndex); } } render = () => { return ( <EmployeesList employees={this.props.employees} pageIndex={this.state.pageIndex} totalCount={this.props.totalCount} onPageClick={this.onPageClick} onDeleteClick={this.onDeleteClick} /> ) } } const mapStateToProps = state => { return { employees: state.employee.data.result, totalCount: state.employee.data.totalCount } } const mapDispatchToProps = { getEmployees, deleteEmployee } export default connect(mapStateToProps, mapDispatchToProps)(EmployeesListContainer);<file_sep># Dedi-CRUD A SPA that CRUD employee data. Client-side project uses [CoreUI](https://github.com/mrholek/CoreUI-Free-Bootstrap-Admin-Template) admin template. ## Getting Started - `git clone https://github.com/wangdedi1990/dedi-crud.git` - `npm run postinsall` - `npm run install` - `npm run start-dev` Migration script inserts demo data in database for test usage. In order to reset the database to initial state, just delete `database.sqlite` file. ## To run tests in client project - `cd client` - `cd npm run test` ## Overview of libraries - `sqlite` - sqlite was chosen as data source because it is fast, easy - `express` - rest api implemented using Express Nodejs framework - `redux` + `redux-thunk` - state management library - `jest` - client test framework
c3324ce0338967e4f2be2850b02a545e2a878420
[ "JavaScript", "Markdown" ]
7
JavaScript
wangdedi1990/dedi-crud
f8e190f54745a0d428e880160cf3ed4058a15b8e
90c5701b704d65acf427cbb864557401c479da17
refs/heads/master
<repo_name>nemanjaMiljkovic/JS-Board-Game<file_sep>/js/app.js import * as PIXI from 'pixi.js'; PIXI.utils.sayHello(); let app = new PIXI.Application({ width: 512, // default: 800 height: 512, // default: 600 antialias: true, // default: false transparent: false, // default: false resolution: 1, // default: 1 autoResize: true, }); // let renderer = PIXI.autoDetectRenderer(512, 512, { // transparent: true, // backgroundColor: 'transparent', // }); document.getElementById('display').appendChild(app.view); <file_sep>/README.md # JS-Board-Game
8a059d08afeaa584133d87b8dde7a790bfac240c
[ "JavaScript", "Markdown" ]
2
JavaScript
nemanjaMiljkovic/JS-Board-Game
d5c66575c997a0333586e0d24479a65bea729b95
1461b7d6d52cc29c8c40255912451829d0db9676
refs/heads/master
<repo_name>coleged/modbusX310<file_sep>/x310.c /*********************************************** x310.c Control program for ControlByWeb WebRelay X-310 Quick hack to check out modbus A bit messy, but works OK. V 1.0 - messy hack V 1.0.1 - tidy up, no feature changes <NAME> <EMAIL> 22/5/2017 Usage overview - serves as a requirements specification. USAGE: x310 [options] option: -s status. Returns the status of relays inputs and sensors -1|2|3|4 addresses the relays 1-4 -e enables (switches on) the relay(s) addressed -d disables (switches off) the relay(s) addressed -v verbose -V prints version number requires libmodbus under Ubuntu in package libmodbus-dev to compile gcc x310.c -o x310 `pkg-config --cflags --libs libmodbus` Which expands to gcc x310.c -o x310 -I/usr/local/include/modbus -L/usr/local/lib -lmodbus *************************************************/ #define VERSION "x310: v1.0.1 22/5/17 <NAME> <EMAIL>\n" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <modbus.h> #define X310_IP "192.168.1.232" // libmodbus doesn't do host resolution #define RET_ERR -1 modbus_t *ctx; uint8_t relays[]={0,0,0,0}; // the state of the relays uint8_t inputs[]={0,0,0,0}; // the state of the digital inputs float sen[4]; // temperature sensors sen[0] = Sensor1 float vin; // Supply voltage - Vin int senAdd[]={272,274,276,278}; // modbus addresses for sensors int vinAdd = 16; // modbus address for Vin void print_status(int verbose); void usageError(char *prog); void turnON(int relay, int verbose); void turnOFF(int relay, int verbose); int main(int argc, char *argv[]){ int opt; int flag_s, flag_1, flag_2, flag_3, flag_4, flag_e, flag_d, flag_v = FALSE; while ((opt = getopt(argc, argv, "s1234edvV")) != -1){ switch (opt) { case 'V': printf(VERSION); exit(0); case 's': flag_s = TRUE; break; case '1': flag_1 = TRUE; break; case '2': flag_2 = TRUE; break; case '3': flag_3 = TRUE; break; case '4': flag_4 = TRUE; break; case 'e': flag_e = TRUE; break; case 'd': flag_d = TRUE; break; case 'v': flag_v = TRUE; break; default: usageError(argv[0]); }//switch }// while ctx = modbus_new_tcp(X310_IP, MODBUS_TCP_DEFAULT_PORT ); if (ctx == NULL) { fprintf(stderr, "Unable to allocate libmodbus context\n"); return RET_ERR; }//if if (modbus_connect(ctx) == -1) { fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno)); modbus_free(ctx); return RET_ERR; }//if modbus_read_bits(ctx,0,4, relays); modbus_read_input_bits(ctx,0,4,inputs); // x310 holds sensor as 32bit float, but modbus_read_registers // reads 16bit unsigned int, so cast the float address to // a pointer to uint16_t and read 2 registers modbus_read_registers(ctx,vinAdd,2,(uint16_t *) &vin); // Read 8 registers = 4 X 32bit floats modbus_read_registers(ctx,senAdd[0],8,(uint16_t *) &sen[0]); if (flag_s==TRUE){ printf("Initial state\n"); printf("=============\n"); print_status(flag_v); }//if if (flag_1==TRUE){ if (flag_e==TRUE) turnON(1,flag_v); if (flag_d==TRUE) turnOFF(1,flag_v); } if (flag_2==TRUE){ if (flag_e==TRUE) turnON(2,flag_v); if (flag_d==TRUE) turnOFF(2,flag_v); } if (flag_3==TRUE){ if (flag_e==TRUE) turnON(3,flag_v); if (flag_d==TRUE) turnOFF(3,flag_v); } if (flag_4==TRUE){ if (flag_e==TRUE) turnON(4,flag_v); if (flag_d==TRUE) turnOFF(4,flag_v); } if (flag_s==TRUE){ // print new status printf("\nFinal state\n"); printf("===========\n"); print_status(flag_v); } modbus_write_bits(ctx,0,4,relays); return(0); }//main void print_status(int verbose){ int i; printf("Inputs = %x %x %x %x\n", inputs[0],inputs[1],inputs[2],inputs[3]); printf("Relays = %x %x %x %x\n", relays[0],relays[1],relays[2],relays[3]); if (verbose==TRUE){ for (i=0;i<4;i++){ if (relays[i]==TRUE){ printf("Relay %x ON\n",i+1); }else{ printf("Relay %x OFF\n",i+1); }//if }//for }//if printf("Sensors = %.2f %.2f %.2f %.2f\n", sen[0],sen[1],sen[2],sen[3]); printf("Voltage = %.2f\n", vin); }//print_status //************ usageError void usageError(char *prog) { fprintf(stderr,"\nUsage:\n %s [options]\n",prog); fprintf(stderr,"\nOptions:\n"); fprintf(stderr," -s status\t\tprint status of inputs, relays and sensors\n"); fprintf(stderr," -v verbose\t\t\n"); fprintf(stderr," -[1234] relay\t\taddresses one or more relays\n"); fprintf(stderr," -e enable\t\tenbles (switches on) addressed relay(s)\n"); fprintf(stderr," -d disable\t\tdisables (switches off) addressed relay(s)\n"); fprintf(stderr," -V version\t\tprints program version number\n"); exit(1); } void turnON(int relay, int v){ relays[relay-1] = 1; if ( v == 1 ){ printf("Turning Relay %x ON\n",relay); } } void turnOFF(int relay, int v){ relays[relay-1] = 0; if ( v == 1 ){ printf("Turning Relay %x OFF\n",relay); } } <file_sep>/README.md # modbusX310 x310 Quick hack to test out modbus control of ControlByWeb X-310 WebRelay. It was developed on Ubuntu 14 Dependancies libmodbus To compile Copy Makefile and x310.c onto an Ubuntu machine and type make <EMAIL> may 2017
cb6b5e5e04cddb5ed29c7b5effde2f02e9192390
[ "Markdown", "C" ]
2
C
coleged/modbusX310
c4b1b5b525e4cc616b1492b360030024858b7bb5
81bc12cf54cb44f617ed4fc4870a9b6d3db7af04
refs/heads/master
<repo_name>yoheimuta/protolint<file_sep>/linter/visitor/hasExtendedVisitor.go package visitor import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/report" ) // HasExtendedVisitor is a required interface given to RunVisitor. type HasExtendedVisitor interface { parser.Visitor // OnStart is called when visiting is started. OnStart(*parser.Proto) error // Finally is called when visiting is done. Finally() error // Failures returns the accumulated failures. Failures() []report.Failure } // RunVisitor dispatches the call to the visitor. func RunVisitor( visitor HasExtendedVisitor, proto *parser.Proto, ruleID string, ) ([]report.Failure, error) { return RunVisitorAutoDisable(visitor, proto, ruleID, autodisable.Noop) } // RunVisitorAutoDisable dispatches the call to the visitor. func RunVisitorAutoDisable( visitor HasExtendedVisitor, proto *parser.Proto, ruleID string, autodisableType autodisable.PlacementType, ) ([]report.Failure, error) { // This check is just for existing test cases. protoFilename := "" if proto.Meta != nil { protoFilename = proto.Meta.Filename } autoDisabled, err := newExtendedAutoDisableVisitor(visitor, ruleID, protoFilename, autodisableType) if err != nil { return nil, err } disabled := newExtendedDisableRuleVisitor( autoDisabled, ruleID, ) if err := disabled.OnStart(proto); err != nil { return nil, err } proto.Accept(disabled) if err := disabled.Finally(); err != nil { return nil, err } return disabled.Failures(), nil } <file_sep>/linter/rule/rule.go package rule import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" ) // Severity represents the severity of the rule. // All failues will have this severity on export. type Severity string const ( // SeverityNote represents a note only rule severity SeverityNote Severity = "note" // SeverityWarning represents a rule severity at a warning level SeverityWarning Severity = "warning" // SeverityError represents a rule severity at a warning level SeverityError Severity = "error" ) // HasApply represents a rule which can be applied. type HasApply interface { // Apply applies the rule to the proto. Apply(proto *parser.Proto) ([]report.Failure, error) } // HasID represents a rule with ID. type HasID interface { // ID returns the ID of this rule. This should be all UPPER_SNAKE_CASE. ID() string } // HasPurpose represents a rule with Purpose. type HasPurpose interface { // Purpose returns the purpose of this rule. This should be a human-readable string. Purpose() string } // HasIsOfficial represents a rule with IsOfficial. type HasIsOfficial interface { // IsOfficial decides whether or not this rule belongs to the official guide. IsOfficial() bool } // HasSeverity represents a rule with a configurable severity type HasSeverity interface { // Severity returns the selected severity of a rule Severity() Severity } // Rule represents a rule which a linter can apply. type Rule interface { HasApply HasID HasPurpose HasIsOfficial HasSeverity } <file_sep>/internal/linter/config/servicesHaveCommentOption.go package config // ServicesHaveCommentOption represents the option for the SERVICES_HAVE_COMMENT rule. type ServicesHaveCommentOption struct { CustomizableSeverityOption ShouldFollowGolangStyle bool `yaml:"should_follow_golang_style"` } <file_sep>/linter/strs/pluralize.go package strs import ( "github.com/gertd/go-pluralize" ) // PluralizeClient represents a client to support a pluralization. type PluralizeClient struct { client *pluralize.Client } // NewPluralizeClient creates a new client. func NewPluralizeClient() *PluralizeClient { c := &PluralizeClient{ client: pluralize.NewClient(), } c.AddPluralRule("(?i)uri$", "uris") c.AddSingularRule("(?i)uris$", "uri") return c } // ToPlural converts the given string to its plural name. func (c *PluralizeClient) ToPlural(s string) string { return c.client.Plural(c.client.Singular(s)) } // AddPluralRule adds a pluralization rule to the collection. func (c *PluralizeClient) AddPluralRule(rule string, replacement string) { c.client.AddPluralRule(rule, replacement) } // AddSingularRule adds a singularization rule to the collection. func (c *PluralizeClient) AddSingularRule(rule string, replacement string) { c.client.AddSingularRule(rule, replacement) } // AddUncountableRule adds an uncountable word rule. func (c *PluralizeClient) AddUncountableRule(word string) { c.client.AddUncountableRule(word) } // AddIrregularRule adds an irregular word definition. func (c *PluralizeClient) AddIrregularRule(single string, plural string) { c.client.AddIrregularRule(single, plural) } <file_sep>/internal/linter/config/quoteConsistentOption.go package config import ( "fmt" "strings" ) // QuoteType is a type of quote for string. type QuoteType int // QuoteType constants. const ( DoubleQuote QuoteType = iota SingleQuote ) // QuoteConsistentOption represents the option for the QUOTE_CONSISTENT rule. type QuoteConsistentOption struct { CustomizableSeverityOption Quote QuoteType } // UnmarshalYAML implements yaml.v2 Unmarshaler interface. func (r *QuoteConsistentOption) UnmarshalYAML(unmarshal func(interface{}) error) error { var option struct { Quote string `yaml:"quote"` } if err := unmarshal(&option); err != nil { return err } if 0 < len(option.Quote) { supportQuotes := map[string]QuoteType{ "double": DoubleQuote, "single": SingleQuote, } quote, ok := supportQuotes[option.Quote] if !ok { var list []string for k := range supportQuotes { list = append(list, k) } return fmt.Errorf("%s is an invalid quote. valid options are [%s]", option.Quote, strings.Join(list, ",")) } r.Quote = quote } return nil } <file_sep>/internal/addon/rules/rpcsHaveCommentRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // RPCsHaveCommentRule verifies that all rpcs have a comment. type RPCsHaveCommentRule struct { RuleWithSeverity // Golang style comments should begin with the name of the thing being described. // See https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences shouldFollowGolangStyle bool } // NewRPCsHaveCommentRule creates a new RPCsHaveCommentRule. func NewRPCsHaveCommentRule( severity rule.Severity, shouldFollowGolangStyle bool, ) RPCsHaveCommentRule { return RPCsHaveCommentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, shouldFollowGolangStyle: shouldFollowGolangStyle, } } // ID returns the ID of this rule. func (r RPCsHaveCommentRule) ID() string { return "RPCS_HAVE_COMMENT" } // Purpose returns the purpose of this rule. func (r RPCsHaveCommentRule) Purpose() string { return "Verifies that all rpcs have a comment." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r RPCsHaveCommentRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r RPCsHaveCommentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &rpcsHaveCommentVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), shouldFollowGolangStyle: r.shouldFollowGolangStyle, } return visitor.RunVisitor(v, proto, r.ID()) } type rpcsHaveCommentVisitor struct { *visitor.BaseAddVisitor shouldFollowGolangStyle bool } // VisitRPC checks the rpc. func (v *rpcsHaveCommentVisitor) VisitRPC(rpc *parser.RPC) bool { n := rpc.RPCName if v.shouldFollowGolangStyle && !hasGolangStyleComment(rpc.Comments, n) { v.AddFailuref(rpc.Meta.Pos, `RPC %q should have a comment of the form "// %s ..."`, n, n) } else if !hasComments(rpc.Comments, rpc.InlineComment, rpc.InlineCommentBehindLeftCurly) { v.AddFailuref(rpc.Meta.Pos, `RPC %q should have a comment`, n) } return false } <file_sep>/internal/linter/config/directories.go package config import ( "strings" "github.com/yoheimuta/protolint/internal/filepathutil" ) // Directories represents the target directories. type Directories struct { Exclude []string `yaml:"exclude"` } func (d Directories) shouldSkipRule( displayPath string, ) bool { for _, exclude := range d.Exclude { if !strings.HasSuffix(exclude, string(filepathutil.OSPathSeparator)) { exclude += string(filepathutil.OSPathSeparator) } if filepathutil.HasUnixPathPrefix(displayPath, exclude) { return true } } return false } <file_sep>/internal/linter/rule/rules.go package rule import "github.com/yoheimuta/protolint/linter/rule" // Rules is a list of Rules. type Rules []rule.Rule // Default returns a default set of rules. func (rs Rules) Default() Rules { var d Rules for _, r := range rs { if r.IsOfficial() { d = append(d, r) } } return d } // IDs returns a set of rule ids. func (rs Rules) IDs() []string { return ruleIDs(rs) } func ruleIDs(rules []rule.Rule) []string { var ids []string for _, rule := range rules { ids = append(ids, rule.ID()) } return ids } <file_sep>/linter/visitor/hasExtendedVisitor_test.go package visitor_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/internal/util_test" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/visitor" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/go-protoparser/v4/parser" ) type testVisitor struct { *visitor.BaseAddVisitor next bool } func (v *testVisitor) VisitMessage(message *parser.Message) bool { v.AddFailuref(message.Meta.Pos, "Test Message") return v.next } type testVisitorInvalidEnumField struct { *visitor.BaseAddVisitor next bool } func (v *testVisitorInvalidEnumField) VisitEnumField(field *parser.EnumField) bool { v.AddFailuref(field.Meta.Pos, "Failed field") return v.next } func TestRunVisitor(t *testing.T) { tests := []struct { name string inputVisitor *testVisitor inputProto *parser.Proto inputRuleID string wantExistErr bool wantFailures []report.Failure }{ { name: "visit no messages", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, }, }, { name: "visit a message", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, ProtoBody: []parser.Visitee{ &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), }, }, { name: "visit messages", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, ProtoBody: []parser.Visitee{ &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, }, }, &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), }, }, { name: "visit messages recursively", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), next: true, }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, }, }, }, Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), }, }, { name: "visit a message. one is disabled.", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, ProtoBody: []parser.Visitee{ &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, }, Comments: []*parser.Comment{ { Raw: `// protolint:disable:next MESSAGE_NAMES_UPPER_CAMEL_CASE`, }, }, }, &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, }, }, }, }, inputRuleID: `MESSAGE_NAMES_UPPER_CAMEL_CASE`, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), }, }, { name: "visit a message. one is disabled by an inline comment.", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, ProtoBody: []parser.Visitee{ &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, }, InlineComment: &parser.Comment{ Raw: `// protolint:disable:this MESSAGE_NAMES_UPPER_CAMEL_CASE`, }, }, &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, }, }, }, }, inputRuleID: `MESSAGE_NAMES_UPPER_CAMEL_CASE`, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), }, }, { name: "visit messages. others are disabled.", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, ProtoBody: []parser.Visitee{ &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, }, Comments: []*parser.Comment{ { Raw: `// protolint:disable MESSAGE_NAMES_UPPER_CAMEL_CASE`, }, }, }, &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, }, }, &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 30, Column: 15, }, }, Comments: []*parser.Comment{ { Raw: `// protolint:enable MESSAGE_NAMES_UPPER_CAMEL_CASE`, }, }, }, }, }, inputRuleID: `MESSAGE_NAMES_UPPER_CAMEL_CASE`, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 30, Column: 15, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), }, }, { name: "visit messages. others are disabled by a last line comment.", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("MESSAGE_NAMES_UPPER_CAMEL_CASE", "error"), }, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{Filename: ""}, ProtoBody: []parser.Visitee{ &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 10, Column: 5, }, }, Comments: []*parser.Comment{ { Raw: `// protolint:disable MESSAGE_NAMES_UPPER_CAMEL_CASE`, }, }, }, &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 20, Column: 10, }, }, }, &parser.Comment{ Raw: `// protolint:enable MESSAGE_NAMES_UPPER_CAMEL_CASE`, }, &parser.Message{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 30, Column: 15, }, }, }, }, }, inputRuleID: `MESSAGE_NAMES_UPPER_CAMEL_CASE`, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 30, Column: 15, }, "MESSAGE_NAMES_UPPER_CAMEL_CASE", "Test Message", ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got, err := visitor.RunVisitor( test.inputVisitor, test.inputProto, test.inputRuleID, ) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestRunVisitorAutoDisable(t *testing.T) { tests := []struct { name string inputVisitor visitor.HasExtendedVisitor inputFilename string inputRuleID string inputPlacementType autodisable.PlacementType wantExistErr bool wantFailureCount int wantFilename string }{ { name: "Do nothing in case of no failures", inputVisitor: &testVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor("ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", "error"), }, inputFilename: "invalid.proto", inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputPlacementType: autodisable.Next, wantFilename: "invalid.proto", }, { name: "Insert a disable:next comment", inputVisitor: &testVisitorInvalidEnumField{ BaseAddVisitor: visitor.NewBaseAddVisitor("ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", "error"), }, inputFilename: "invalid.proto", inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputPlacementType: autodisable.Next, wantFailureCount: 1, wantFilename: "disable_next.proto", }, { name: "Insert a disable:this comment", inputVisitor: &testVisitorInvalidEnumField{ BaseAddVisitor: visitor.NewBaseAddVisitor("ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", "error"), }, inputFilename: "invalid.proto", inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputPlacementType: autodisable.ThisThenNext, wantFailureCount: 1, wantFilename: "disable_this.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { input, err := util_test.NewTestData(setting_test.TestDataPath("visitor", test.inputFilename)) if err != nil { t.Errorf("got err %v", err) return } want, err := util_test.NewTestData(setting_test.TestDataPath("visitor", test.wantFilename)) if err != nil { t.Errorf("got err %v", err) return } proto, err := file.NewProtoFile(input.FilePath, input.FilePath).Parse(false) if err != nil { t.Errorf(err.Error()) return } got, err := visitor.RunVisitorAutoDisable( test.inputVisitor, proto, test.inputRuleID, test.inputPlacementType, ) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } else if err != nil { t.Errorf("got err %v, but want nil", err) return } if len(got) != test.wantFailureCount { t.Errorf("len(got) %v, but want %v", len(got), test.wantFailureCount) } got2, _ := input.Data() if !reflect.DeepEqual(got2, want.OriginData) { t.Errorf( "got %s(%v), but want %s(%v)", string(got2), got, string(want.OriginData), want.OriginData, ) } err = input.Restore() if err != nil { t.Errorf("got err %v", err) } }) } } <file_sep>/internal/linter/config/ignore.go package config import "github.com/yoheimuta/protolint/internal/stringsutil" // Ignore represents files ignoring the specific rule. type Ignore struct { ID string `yaml:"id"` Files []string `yaml:"files"` } func (i Ignore) shouldSkipRule( ruleID string, displayPath string, ) bool { if i.ID != ruleID { return false } return stringsutil.ContainsCrossPlatformPathInSlice(displayPath, i.Files) } <file_sep>/internal/osutil/exitCode.go package osutil // ExitCode is a code for os.Exit() type ExitCode int // ExitCode constants. const ( ExitSuccess ExitCode = iota ExitLintFailure // Lint errors, exclusively. ExitInternalFailure // All other errors: parsing, internal, runtime errors. ) <file_sep>/internal/linter/config/rulesOption.go package config // RulesOption represents the option for some rules. type RulesOption struct { FileNamesLowerSnakeCase FileNamesLowerSnakeCaseOption `yaml:"file_names_lower_snake_case"` QuoteConsistentOption QuoteConsistentOption `yaml:"quote_consistent"` ImportsSorted ImportsSortedOption `yaml:"imports_sorted"` MaxLineLength MaxLineLengthOption `yaml:"max_line_length"` Indent IndentOption `yaml:"indent"` EnumFieldNamesZeroValueEndWith EnumFieldNamesZeroValueEndWithOption `yaml:"enum_field_names_zero_value_end_with"` ServiceNamesEndWith ServiceNamesEndWithOption `yaml:"service_names_end_with"` FieldNamesExcludePrepositions FieldNamesExcludePrepositionsOption `yaml:"field_names_exclude_prepositions"` MessageNamesExcludePrepositions MessageNamesExcludePrepositionsOption `yaml:"message_names_exclude_prepositions"` RPCNamesCaseOption RPCNamesCaseOption `yaml:"rpc_names_case"` MessagesHaveComment MessagesHaveCommentOption `yaml:"messages_have_comment"` ServicesHaveComment ServicesHaveCommentOption `yaml:"services_have_comment"` RPCsHaveComment RPCsHaveCommentOption `yaml:"rpcs_have_comment"` FieldsHaveComment FieldsHaveCommentOption `yaml:"fields_have_comment"` EnumsHaveComment EnumsHaveCommentOption `yaml:"enums_have_comment"` EnumFieldsHaveComment EnumFieldsHaveCommentOption `yaml:"enum_fields_have_comment"` SyntaxConsistent SyntaxConsistentOption `yaml:"syntax_consistent"` RepeatedFieldNamesPluralized RepeatedFieldNamesPluralizedOption `yaml:"repeated_field_names_pluralized"` EnumFieldNamesPrefix CustomizableSeverityOption `yaml:"enum_field_names_prefix"` EnumFieldNamesUpperSnakeCase CustomizableSeverityOption `yaml:"enum_field_names_upper_snake_case"` EnumNamesUpperCamelCase CustomizableSeverityOption `yaml:"enum_names_upper_camel_case"` FieldNamesLowerSnakeCase CustomizableSeverityOption `yaml:"field_names_lower_snake_case"` FileHasComment CustomizableSeverityOption `yaml:"file_has_comment"` MessageNamesUpperCamelCase CustomizableSeverityOption `yaml:"message_names_upper_camel_case"` Order CustomizableSeverityOption `yaml:"order"` PackageNameLowerCase CustomizableSeverityOption `yaml:"package_name_lower_case"` Proto3FieldsAvoidRequired CustomizableSeverityOption `yaml:"proto3_fields_avoid_required"` Proto3GroupsAvoid CustomizableSeverityOption `yaml:"proto3_groups_avoid"` RPCNamesUpperCamelCase CustomizableSeverityOption `yaml:"rpc_names_upper_camel_case"` ServiceNamesUpperCamelCase CustomizableSeverityOption `yaml:"service_names_upper_caml_case"` } <file_sep>/linter/strs/strs_test.go package strs_test import ( "reflect" "testing" "github.com/yoheimuta/protolint/linter/strs" ) func TestIsUpperCamelCase(t *testing.T) { tests := []struct { name string input string want bool }{ { name: "the first letter is not an uppercase character", input: "hello", }, { name: "_ is included", input: "Hello_world", }, { name: ". is included", input: "Hello.world", }, { name: "the first letter is an uppercase character", input: "Hello", want: true, }, { name: "the first letter is an uppercase character and rest is a camel case", input: "HelloWorld", want: true, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.IsUpperCamelCase(test.input) if got != test.want { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestIsLowerCamelCase(t *testing.T) { tests := []struct { name string input string want bool }{ { name: "the first letter is an uppercase character", input: "Hello", }, { name: "_ is included", input: "hello_world", }, { name: ". is included", input: "hello.world", }, { name: "the first letter is a lowercase character", input: "hello", want: true, }, { name: "the first letter is a lowercase character and rest is a camel case", input: "helloWorld", want: true, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.IsLowerCamelCase(test.input) if got != test.want { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestIsUpperSnakeCase(t *testing.T) { tests := []struct { name string input string want bool }{ { name: "empty is not uppercase", }, { name: "includes lowercase characters", input: "hello", }, { name: "includes a lowercase character", input: "hELLO", }, { name: "all uppercase", input: "HELLO", want: true, }, { name: "all uppercase with underscore", input: "FIRST_VALUE", want: true, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.IsUpperSnakeCase(test.input) if got != test.want { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestIsLowerSnakeCase(t *testing.T) { tests := []struct { name string input string want bool }{ { name: "empty is not lowercase", }, { name: "includes uppercase characters", input: "HELLO", }, { name: "includes a uppercase character", input: "Hello", }, { name: "all lowercase", input: "hello", want: true, }, { name: "all lowercase with underscore", input: "song_name", want: true, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.IsLowerSnakeCase(test.input) if got != test.want { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestSplitCamelCaseWord(t *testing.T) { tests := []struct { name string input string want []string }{ { name: "if s is empty, returns nil", }, { name: "if s is not camel_case, returns nil", input: "not_camel", }, { name: "input consists of one word", input: "Account", want: []string{ "Account", }, }, { name: "input consists of words with an initial capital", input: "AccountStatus", want: []string{ "Account", "Status", }, }, { name: "input consists of words without an initial capital", input: "accountStatus", want: []string{ "account", "Status", }, }, { name: "input consists of words with continuous upper letters", input: "ACCOUNTStatusException", want: []string{ "ACCOUNTStatus", "Exception", }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.SplitCamelCaseWord(test.input) if !reflect.DeepEqual(got, test.want) { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestToUpperSnakeCase(t *testing.T) { tests := []struct { name string input string want string }{ { name: "s is not camel_case", input: "not_camel", want: "NOT_CAMEL", }, { name: "input consists of one word", input: "Account", want: "ACCOUNT", }, { name: "input consists of words with an initial capital", input: "AccountStatus", want: "ACCOUNT_STATUS", }, { name: "input consists of words without an initial capital", input: "accountStatus", want: "ACCOUNT_STATUS", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.ToUpperSnakeCase(test.input) if !reflect.DeepEqual(got, test.want) { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestToLowerSnakeCase(t *testing.T) { tests := []struct { name string input string want string }{ { name: "input consists of one word", input: "Account", want: "account", }, { name: "input consists of words with an initial capital", input: "AccountStatus", want: "account_status", }, { name: "input consists of words without an initial capital", input: "accountStatus", want: "account_status", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.ToLowerSnakeCase(test.input) if !reflect.DeepEqual(got, test.want) { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestToUpperCamelCase(t *testing.T) { tests := []struct { name string input string want string }{ { name: "input consists of one word", input: "account", want: "Account", }, { name: "input consists of words with an initial capital", input: "AccountStatus", want: "AccountStatus", }, { name: "input consists of words without an initial capital", input: "accountStatus", want: "AccountStatus", }, { name: "input consists of words without capital letters", input: "accountstatus", want: "Accountstatus", }, { name: "input lower_snake_case", input: "account_status", want: "AccountStatus", }, { name: "input UPPER_SNAKE_CASE", input: "ACCOUNT_STATUS", want: "AccountStatus", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.ToUpperCamelCase(test.input) if !reflect.DeepEqual(got, test.want) { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestToLowerCamelCase(t *testing.T) { tests := []struct { name string input string want string }{ { name: "input consists of one word", input: "account", want: "account", }, { name: "input consists of words with an initial capital", input: "AccountStatus", want: "accountStatus", }, { name: "input consists of words without an initial capital", input: "accountStatus", want: "accountStatus", }, { name: "input consists of words without capital letters", input: "accountstatus", want: "accountstatus", }, { name: "input lower_snake_case", input: "account_status", want: "accountStatus", }, { name: "input UPPER_SNAKE_CASE", input: "ACCOUNT_STATUS", want: "accountStatus", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.ToLowerCamelCase(test.input) if !reflect.DeepEqual(got, test.want) { t.Errorf("got %v, but want %v", got, test.want) } }) } } func TestSplitSnakeCaseWord(t *testing.T) { tests := []struct { name string input string want []string }{ { name: "if s is empty, returns nil", }, { name: "if s is not snake_case, returns nil", input: "_not_snake", }, { name: "input consists of one word", input: "HELLO", want: []string{ "HELLO", }, }, { name: "input consists of multiple upper case words", input: "REASON_FOR_ERROR", want: []string{ "REASON", "FOR", "ERROR", }, }, { name: "input consists of multiple lower case words", input: "reason_for_error", want: []string{ "reason", "for", "error", }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got := strs.SplitSnakeCaseWord(test.input) if !reflect.DeepEqual(got, test.want) { t.Errorf("got %v, but want %v", got, test.want) } }) } } <file_sep>/lib/lint.go package lib import ( "errors" "io" "github.com/yoheimuta/protolint/internal/cmd" "github.com/yoheimuta/protolint/internal/osutil" ) var ( // ErrLintFailure error is returned when there is a linting error ErrLintFailure = errors.New("lint error") // ErrInternalFailure error is returned when there is a parsing, internal, or runtime error. ErrInternalFailure = errors.New("parsing, internal or runtime errors") ) // Lint is used to lint Protocol Buffer files with the protolint tool. // It takes an array of strings (args) representing command line arguments, // as well as two io.Writer instances (stdout and stderr) to which the output of the command should be written. // It returns an error in the case of a linting error (ErrLintFailure) // or a parsing, internal, or runtime error (ErrInternalFailure). // Otherwise, it returns nil on success. func Lint(args []string, stdout, stderr io.Writer) error { switch cmd.Do(args, stdout, stderr) { case osutil.ExitSuccess: return nil case osutil.ExitLintFailure: return ErrLintFailure default: return ErrInternalFailure } } <file_sep>/internal/linter/report/reporters/plainReporter.go package reporters import ( "fmt" "io" "github.com/yoheimuta/protolint/linter/report" ) // PlainReporter prints failures as it is. type PlainReporter struct{} // Report writes failures to w. func (r PlainReporter) Report(w io.Writer, fs []report.Failure) error { for _, failure := range fs { _, err := fmt.Fprintln(w, failure) if err != nil { return err } } return nil } <file_sep>/linter/disablerule/interpreter_test.go package disablerule_test import ( "reflect" "testing" "github.com/yoheimuta/protolint/linter/disablerule" "github.com/yoheimuta/go-protoparser/v4/parser" ) func TestInterpreter_Interpret(t *testing.T) { type inOut struct { name string inputComments []*parser.Comment inputInlineComments []*parser.Comment wantIsDisabled bool } tests := []struct { name string inputRuleID string inOuts []inOut }{ { name: "disable:next comments skip ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inOuts: []inOut{ { name: "rule is enabled when there are no comments", }, { name: "rule is enabled when there are no correct disable:next comments", inputComments: []*parser.Comment{ { Raw: `// disable:next ENUM_FIELD_NAMES_UPPER_SNAKE_CASE`, }, }, }, { name: "rule is enabled when the ruleID does not match it", inputComments: []*parser.Comment{ { Raw: `// protolint:disable:next ENUM_NAMES_UPPER_CAMEL_CASE`, }, }, }, { name: "rule is disabled when there is a disable:next comment with a ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:disable:next ENUM_FIELD_NAMES_UPPER_SNAKE_CASE`, }, }, wantIsDisabled: true, }, { name: "rule is disabled when there is a disable:next c-style comment with a ruleID", inputComments: []*parser.Comment{ { Raw: `/* protolint:disable:next ENUM_FIELD_NAMES_UPPER_SNAKE_CASE */`, }, }, wantIsDisabled: true, }, { name: "rule is disabled when there are disable:next comments with ruleIDs", inputComments: []*parser.Comment{ { Raw: `// protolint:disable:next ENUM_FIELD_NAMES_UPPER_SNAKE_CASE`, }, { Raw: `// protolint:disable:next ENUM_NAMES_UPPER_CAMEL_CASE`, }, }, wantIsDisabled: true, }, }, }, { name: "disable:next comments skip SERVICE_NAMES_UPPER_CAMEL_CASE", inputRuleID: "SERVICE_NAMES_UPPER_CAMEL_CASE", inOuts: []inOut{ { name: "rule is enabled when the ruleID does not match it", inputComments: []*parser.Comment{ { Raw: `// protolint:disable:next ENUM_NAMES_UPPER_CAMEL_CASE`, }, }, }, { name: "rule is disabled when there is a disable:next comment with a ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:disable:next SERVICE_NAMES_UPPER_CAMEL_CASE`, }, }, wantIsDisabled: true, }, }, }, { name: "disable:this comment skips SERVICE_NAMES_UPPER_CAMEL_CASE", inputRuleID: "SERVICE_NAMES_UPPER_CAMEL_CASE", inOuts: []inOut{ { name: "rule is enabled when the ruleID does not match it", inputInlineComments: []*parser.Comment{ { Raw: `// protolint:disable:this ENUM_NAMES_UPPER_CAMEL_CASE`, }, }, }, { name: "rule is disabled when there is a disable:this comment with a ruleID", inputInlineComments: []*parser.Comment{ { Raw: `// protolint:disable:this SERVICE_NAMES_UPPER_CAMEL_CASE`, }, }, wantIsDisabled: true, }, }, }, { name: "disable SERVICE_NAMES_UPPER_CAMEL_CASE", inputRuleID: "SERVICE_NAMES_UPPER_CAMEL_CASE", inOuts: []inOut{ { name: "rule is not disabled when there is a disable comment with another ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:disable ENUM_FIELD_NAMES_UPPER_SNAKE_CASE`, }, }, }, { name: "rule is disabled when there is a disable comment with a ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:disable SERVICE_NAMES_UPPER_CAMEL_CASE`, }, }, wantIsDisabled: true, }, { name: "rule is always disabled after a disable comment", wantIsDisabled: true, }, { name: "rule is disabled when there is a disable:next comment with a ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:disable:next SERVICE_NAMES_UPPER_CAMEL_CASE`, }, }, wantIsDisabled: true, }, { name: "rule is always disabled after a disable comment", wantIsDisabled: true, }, }, }, { name: "enable SERVICE_NAMES_UPPER_CAMEL_CASE", inputRuleID: "SERVICE_NAMES_UPPER_CAMEL_CASE", inOuts: []inOut{ { name: "rule is disabled when there is a disable comment with a ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:disable SERVICE_NAMES_UPPER_CAMEL_CASE`, }, }, wantIsDisabled: true, }, { name: "rule is not enabled when there is an enable comment with another ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:enable ENUM_FIELD_NAMES_UPPER_SNAKE_CASE`, }, }, wantIsDisabled: true, }, { name: "rule is enabled when there is an enable comment with a same ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:enable SERVICE_NAMES_UPPER_CAMEL_CASE`, }, }, }, { name: "rule is always enabled after an enable comment", }, { name: "rule is disabled when there is a disable:next comment with a ruleID", inputComments: []*parser.Comment{ { Raw: `// protolint:disable:next SERVICE_NAMES_UPPER_CAMEL_CASE`, }, }, wantIsDisabled: true, }, { name: "rule is always enabled after an enable comment and a disable:next comment", }, }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { interpreter := disablerule.NewInterpreter(test.inputRuleID) for _, expect := range test.inOuts { got := interpreter.Interpret(expect.inputComments, expect.inputInlineComments...) if got != expect.wantIsDisabled { t.Errorf("[%s] got %v, but want %v", expect.name, got, expect.wantIsDisabled) } } }) } } func TestInterpreter_CallEachIfValid(t *testing.T) { type outputType struct { index int line string } tests := []struct { name string inputRuleID string inputLines []string wantOutputLines []outputType }{ { name: "All lines are valid, so the function is called for each line.", inputRuleID: "MAX_LINE_LENGTH", inputLines: []string{ `enum enumAllowingAlias {`, `// disable:next MAX_LINE_LENGTH`, `option allow_alias = true;`, `}`, }, wantOutputLines: []outputType{ { index: 0, line: `enum enumAllowingAlias {`, }, { index: 1, line: `// disable:next MAX_LINE_LENGTH`, }, { index: 2, line: `option allow_alias = true;`, }, { index: 3, line: `}`, }, }, }, { name: "protolint:disable:next works.", inputRuleID: "MAX_LINE_LENGTH", inputLines: []string{ `enum enumAllowingAlias {`, `// protolint:disable:next MAX_LINE_LENGTH`, `option allow_alias = true;`, `}`, }, wantOutputLines: []outputType{ { index: 0, line: `enum enumAllowingAlias {`, }, { index: 1, line: `// protolint:disable:next MAX_LINE_LENGTH`, }, { index: 3, line: `}`, }, }, }, { name: "protolint:disable:this works.", inputRuleID: "MAX_LINE_LENGTH", inputLines: []string{ `enum enumAllowingAlias { // protolint:disable:this MAX_LINE_LENGTH`, `option allow_alias = true;`, `}`, }, wantOutputLines: []outputType{ { index: 1, line: `option allow_alias = true;`, }, { index: 2, line: `}`, }, }, }, { name: "protolint:disable and protolint:enable works", inputRuleID: "MAX_LINE_LENGTH", inputLines: []string{ `enum enumAllowingAlias {`, `// protolint:disable MAX_LINE_LENGTH`, `option allow_alias = true;`, `UNKNOWN = 0;`, `// protolint:enable MAX_LINE_LENGTH`, `STARTED = 1;`, `}`, }, wantOutputLines: []outputType{ { index: 0, line: `enum enumAllowingAlias {`, }, { index: 4, line: `// protolint:enable MAX_LINE_LENGTH`, }, { index: 5, line: `STARTED = 1;`, }, { index: 6, line: `}`, }, }, }, { name: "the mix of protolint:disable commands works", inputRuleID: "MAX_LINE_LENGTH", inputLines: []string{ `// protolint:disable:next MAX_LINE_LENGTH`, `enum enumAllowingAlias {`, `// protolint:disable MAX_LINE_LENGTH`, `option allow_alias = true; // protolint:disable:this MAX_LINE_LENGTH`, `UNKNOWN = 0;`, `// protolint:enable MAX_LINE_LENGTH`, `STARTED = 1;`, `RUNNING = 2; // protolint:disable:this MAX_LINE_LENGTH`, `// protolint:disable:next MAX_LINE_LENGTH`, `STOPPED = 3;`, `}`, }, wantOutputLines: []outputType{ { index: 0, line: `// protolint:disable:next MAX_LINE_LENGTH`, }, { index: 5, line: `// protolint:enable MAX_LINE_LENGTH`, }, { index: 6, line: `STARTED = 1;`, }, { index: 8, line: `// protolint:disable:next MAX_LINE_LENGTH`, }, { index: 10, line: `}`, }, }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { interpreter := disablerule.NewInterpreter(test.inputRuleID) var got []outputType interpreter.CallEachIfValid(test.inputLines, func(index int, line string) { got = append(got, outputType{ index: index, line: line, }) }) if !reflect.DeepEqual(got, test.wantOutputLines) { t.Errorf("got %v, but want %v", got, test.wantOutputLines) } }) } } <file_sep>/internal/cmd/subcmds/lint/cmdLint.go package lint import ( "fmt" "io" "log" "path/filepath" "github.com/hashicorp/go-plugin" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/linter/config" "github.com/yoheimuta/protolint/internal/linter" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/osutil" "github.com/yoheimuta/protolint/linter/report" ) // CmdLint is a lint command. type CmdLint struct { l *linter.Linter stdout io.Writer stderr io.Writer protoFiles []file.ProtoFile config CmdLintConfig output io.Writer } // NewCmdLint creates a new CmdLint. func NewCmdLint( flags Flags, stdout io.Writer, stderr io.Writer, ) (*CmdLint, error) { protoSet, err := file.NewProtoSet(flags.FilePaths) if err != nil { return nil, err } externalConfig, err := config.GetExternalConfig(flags.ConfigPath, flags.ConfigDirPath) if err != nil { return nil, err } if flags.Verbose { if externalConfig != nil { log.Printf("[INFO] protolint loads a config file at %s\n", externalConfig.SourcePath) } else { log.Println("[INFO] protolint doesn't load a config file") } } if externalConfig == nil { externalConfig = &(config.ExternalConfig{}) } lintConfig := NewCmdLintConfig( *externalConfig, flags, ) output := stderr return &CmdLint{ l: linter.NewLinter(), stdout: stdout, stderr: stderr, protoFiles: protoSet.ProtoFiles(), config: lintConfig, output: output, }, nil } // Run lints to proto files. func (c *CmdLint) Run() osutil.ExitCode { defer plugin.CleanupClients() failures, err := c.run() if err != nil { _, _ = fmt.Fprintln(c.stderr, err) return osutil.ExitInternalFailure } err = c.config.reporters.ReportWithFallback(c.output, failures) if err != nil { _, _ = fmt.Fprintln(c.stderr, err) return osutil.ExitInternalFailure } if 0 < len(failures) { return osutil.ExitLintFailure } return osutil.ExitSuccess } func (c *CmdLint) run() ([]report.Failure, error) { var allFailures []report.Failure for _, f := range c.protoFiles { failures, err := c.runOneFile(f) if err != nil { return nil, err } allFailures = append(allFailures, failures...) } return allFailures, nil } // ParseError represents the error returned through a parsing exception. type ParseError struct { Message string } func (p ParseError) Error() string { return p.Message } func (c *CmdLint) runOneFile( f file.ProtoFile, ) ([]report.Failure, error) { // Gen rules first // If there is no rule, we can skip parse proto file rs, err := c.config.GenRules(f) if err != nil { return nil, err } if len(rs) == 0 { return []report.Failure{}, nil } return c.l.Run(func(p *parser.Proto) (*parser.Proto, error) { // Recreate a protoFile if the previous rule changed the filename. if p != nil && p.Meta.Filename != f.DisplayPath() { newFilename := p.Meta.Filename newBase := filepath.Base(newFilename) f = file.NewProtoFile(filepath.Join(filepath.Dir(f.Path()), newBase), newFilename) } proto, err := f.Parse(c.config.verbose) if err != nil { if c.config.verbose { return nil, ParseError{Message: err.Error()} } return nil, ParseError{Message: fmt.Sprintf("%s. Use -v for more details", err)} } return proto, nil }, rs) } <file_sep>/internal/addon/rules/enumFieldNamesPrefixRule.go package rules import ( "strings" "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/visitor" ) // EnumFieldNamesPrefixRule verifies that enum field names are prefixed with its ENUM_NAME_UPPER_SNAKE_CASE. // See https://developers.google.com/protocol-buffers/docs/style#enums. type EnumFieldNamesPrefixRule struct { RuleWithSeverity fixMode bool autoDisableType autodisable.PlacementType } // NewEnumFieldNamesPrefixRule creates a new EnumFieldNamesPrefixRule. func NewEnumFieldNamesPrefixRule( severity rule.Severity, fixMode bool, autoDisableType autodisable.PlacementType, ) EnumFieldNamesPrefixRule { if autoDisableType != autodisable.Noop { fixMode = false } return EnumFieldNamesPrefixRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r EnumFieldNamesPrefixRule) ID() string { return "ENUM_FIELD_NAMES_PREFIX" } // Purpose returns the purpose of this rule. func (r EnumFieldNamesPrefixRule) Purpose() string { return `Verifies that enum field names are prefixed with its ENUM_NAME_UPPER_SNAKE_CASE.` } // IsOfficial decides whether or not this rule belongs to the official guide. func (r EnumFieldNamesPrefixRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r EnumFieldNamesPrefixRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &enumFieldNamesPrefixVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type enumFieldNamesPrefixVisitor struct { *visitor.BaseFixableVisitor enumName string } // VisitEnum checks the enum. func (v *enumFieldNamesPrefixVisitor) VisitEnum(enum *parser.Enum) bool { v.enumName = enum.EnumName return true } // VisitEnumField checks the enum field. func (v *enumFieldNamesPrefixVisitor) VisitEnumField(field *parser.EnumField) bool { expectedPrefix := strs.ToUpperSnakeCase(v.enumName) if !strings.HasPrefix(field.Ident, expectedPrefix) { v.AddFailuref(field.Meta.Pos, "EnumField name %q should have the prefix %q", field.Ident, expectedPrefix) expected := expectedPrefix + "_" + field.Ident err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } <file_sep>/internal/addon/rules/enumNamesUpperCamelCaseRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // EnumNamesUpperCamelCaseRule verifies that all enum names are CamelCase (with an initial capital). // See https://developers.google.com/protocol-buffers/docs/style#enums. type EnumNamesUpperCamelCaseRule struct { RuleWithSeverity fixMode bool autoDisableType autodisable.PlacementType } // NewEnumNamesUpperCamelCaseRule creates a new EnumNamesUpperCamelCaseRule. func NewEnumNamesUpperCamelCaseRule( severity rule.Severity, fixMode bool, autoDisableType autodisable.PlacementType, ) EnumNamesUpperCamelCaseRule { if autoDisableType != autodisable.Noop { fixMode = false } return EnumNamesUpperCamelCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r EnumNamesUpperCamelCaseRule) ID() string { return "ENUM_NAMES_UPPER_CAMEL_CASE" } // Purpose returns the purpose of this rule. func (r EnumNamesUpperCamelCaseRule) Purpose() string { return "Verifies that all enum names are CamelCase (with an initial capital)." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r EnumNamesUpperCamelCaseRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r EnumNamesUpperCamelCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &enumNamesUpperCamelCaseVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type enumNamesUpperCamelCaseVisitor struct { *visitor.BaseFixableVisitor } // VisitEnum checks the enum. func (v *enumNamesUpperCamelCaseVisitor) VisitEnum(enum *parser.Enum) bool { name := enum.EnumName if !strs.IsUpperCamelCase(name) { expected := strs.ToUpperCamelCase(name) v.AddFailuref(enum.Meta.Pos, "Enum name %q must be UpperCamelCase like %q", name, expected) err := v.Fixer.SearchAndReplace(enum.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } <file_sep>/internal/addon/rules/messageNamesExcludePrepositionsRule.go package rules import ( "strings" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/stringsutil" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // MessageNamesExcludePrepositionsRule verifies that all message names don't include prepositions (e.g. "With", "For"). // It is assumed that the message names are CamelCase (with an initial capital). // See https://cloud.google.com/apis/design/naming_convention#message_names. type MessageNamesExcludePrepositionsRule struct { RuleWithSeverity prepositions []string excludes []string } // NewMessageNamesExcludePrepositionsRule creates a new MessageNamesExcludePrepositionsRule. func NewMessageNamesExcludePrepositionsRule( severity rule.Severity, prepositions []string, excludes []string, ) MessageNamesExcludePrepositionsRule { if len(prepositions) == 0 { for _, p := range defaultPrepositions { prepositions = append(prepositions, strings.Title(p)) } } return MessageNamesExcludePrepositionsRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, prepositions: prepositions, excludes: excludes, } } // ID returns the ID of this rule. func (r MessageNamesExcludePrepositionsRule) ID() string { return "MESSAGE_NAMES_EXCLUDE_PREPOSITIONS" } // IsOfficial decides whether or not this rule belongs to the official guide. func (r MessageNamesExcludePrepositionsRule) IsOfficial() bool { return false } // Purpose returns the purpose of this rule. func (r MessageNamesExcludePrepositionsRule) Purpose() string { return `Verifies that all message names don't include prepositions (e.g. "With", "For").` } // Apply applies the rule to the proto. func (r MessageNamesExcludePrepositionsRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &messageNamesExcludePrepositionsVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), prepositions: r.prepositions, excludes: r.excludes, } return visitor.RunVisitor(v, proto, r.ID()) } type messageNamesExcludePrepositionsVisitor struct { *visitor.BaseAddVisitor prepositions []string excludes []string } // VisitMessage checks the message. func (v *messageNamesExcludePrepositionsVisitor) VisitMessage(message *parser.Message) bool { name := message.MessageName for _, e := range v.excludes { name = strings.Replace(name, e, "", -1) } parts := strs.SplitCamelCaseWord(name) for _, p := range parts { if stringsutil.ContainsStringInSlice(p, v.prepositions) { v.AddFailuref(message.Meta.Pos, "Message name %q should not include a preposition %q", message.MessageName, p) } } return true } <file_sep>/internal/linter/report/reporters/sarifReporter.go package reporters import ( "io" "github.com/chavacava/garif" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) // SarifReporter creates reports formatted as a JSON // Document. // The document format is used according to the SARIF // Standard. // Refer to http://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html // for details to the format. type SarifReporter struct{} var allSeverities map[string]rule.Severity = map[string]rule.Severity{ string(rule.SeverityError): rule.SeverityError, string(rule.SeverityWarning): rule.SeverityWarning, string(rule.SeverityNote): rule.SeverityNote, } func contains(s []string, e string) bool { for _, a := range s { if a == e { return true } } return false } // Report writes failures to w formatted as a SARIF document. func (r SarifReporter) Report(w io.Writer, fs []report.Failure) error { rulesByID := make(map[string]*garif.ReportingDescriptor) allRules := []*garif.ReportingDescriptor{} artifactLocations := []string{} tool := garif.NewDriver("protolint"). WithInformationUri("https://github.com/yoheimuta/protolint") run := garif.NewRun(garif.NewTool(tool)) for _, failure := range fs { _, ruleFound := rulesByID[failure.RuleID()] if !ruleFound { rule := garif.NewRule( failure.RuleID(), ). WithHelpUri("https://github.com/yoheimuta/protolint") rulesByID[failure.RuleID()] = rule allRules = append(allRules, rule) } if !(contains(artifactLocations, failure.Pos().Filename)) { artifactLocations = append(artifactLocations, failure.Pos().Filename) } run.WithResult( failure.RuleID(), failure.Message(), failure.Pos().Filename, failure.Pos().Line, failure.Pos().Column, ) if len(run.Results) > 0 { recentResult := run.Results[len(run.Results)-1] recentResult.Kind = garif.ResultKind_Fail if lvl, ok := allSeverities[failure.Severity()]; ok { recentResult.Level = getResultLevel(lvl) } } } tool.WithRules(allRules...) run.WithArtifactsURIs(artifactLocations...) logFile := garif.NewLogFile([]*garif.Run{run}, garif.Version210) return logFile.PrettyWrite(w) } func getResultLevel(severity rule.Severity) garif.ResultLevel { switch severity { case rule.SeverityError: return garif.ResultLevel_Error case rule.SeverityWarning: return garif.ResultLevel_Warning case rule.SeverityNote: return garif.ResultLevel_None } return garif.ResultLevel_None } <file_sep>/cmd/protoc-gen-protolint/README.md # protoc-gen-protolint ## Installation Download `protoc-gen-protolint` and make sure it's available in your PATH. Once it's in your PATH, `protoc` will be able to make use of the plug-in. ### Via Homebrew protoc-gen-protolint can be installed for Mac or Linux using Homebrew via the [yoheimuta/protolint](https://github.com/yoheimuta/homebrew-protolint) tap. ``` brew tap yoheimuta/protolint brew install protolint ``` ### Via GitHub Releases You can also download a pre-built binary from this release page: - https://github.com/yoheimuta/protolint/releases In the downloads section of each release, you can find pre-built binaries in .tar.gz packages. ### Via Maven Central This plugin is also available on Maven Central. For details about how to use it, check out the [gradle example](../../_example/gradle). ### From Source The binary can be installed from source if Go is available. However, I recommend using one of the pre-built binaries instead because it doesn't include the version info. ``` go get -u -v github.com/yoheimuta/protolint/cmd/protoc-gen-protolint ``` ## Usage ``` protoc --protolint_out=. *.proto ``` A version subcommand is supported. ``` protoc-gen-protolint version ``` All flags, which is supported by protolint are passed as an option to the plugin as a comma separated text. It should look like below. ``` protoc \ --protolint_out=. \ --protolint_opt=v,fix,config_dir_path=_example/config,reporter=junit,plugin=./plugin_example \ *.proto ``` ### With [Grpc.Tools package (.NET Build)](https://chromium.googlesource.com/external/github.com/grpc/grpc/+/HEAD/src/csharp/BUILD-INTEGRATION.md) When you specify `ProtoRoot`, make sure to add `--proto_root` option like the below. ``` <ItemGroup> <Protobuf Include="protos\**\*.proto" AdditionalProtocArguments="--protolint_out=.;--protolint_opt=proto_root=protos" ProtoRoot="protos" /> </ItemGroup> ``` ## Option ### proto_root If you add [protoc's --proto_path](https://developers.google.com/protocol-buffers/docs/proto3#generating) to read your proto files in the specified directory, protolint could fail to locate the proto files. You should tell protolint the root directory like the below. ``` ❯ ls protos helloworld.proto ❯ protoc \ --proto_path=protos --protolint_out=. \ --protolint_opt=proto_root=protos \ helloworld.proto ``` <file_sep>/lib/lint_test.go package lib_test import ( "bytes" "errors" "regexp" "testing" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/lib" ) func TestLint(t *testing.T) { tests := []struct { name string inputArgs []string wantStdoutRegex *regexp.Regexp wantStderrRegex *regexp.Regexp wantError error }{ { name: "no args", wantStderrRegex: regexp.MustCompile(`[\S\s]*Usage:[\S\s]*protolint <command> \[arguments\][\S\s]*`), wantError: lib.ErrInternalFailure, }, { name: "invalid args", inputArgs: []string{ "-config_path", setting_test.TestDataPath("lib", "not_exist.yaml"), setting_test.TestDataPath("lib", "valid.proto"), }, wantStderrRegex: regexp.MustCompile(`[\S\s]*not_exist.yaml: no such file or directory`), wantError: lib.ErrInternalFailure, }, { name: "lint failures", inputArgs: []string{ setting_test.TestDataPath("lib", "invalid.proto"), }, wantStderrRegex: regexp.MustCompile(`[\S\s]*Found an incorrect indentation style[\S\s]*`), wantError: lib.ErrLintFailure, }, { name: "lint success", inputArgs: []string{ setting_test.TestDataPath("lib", "valid.proto"), }, }, { name: "lint success by specifying a config file", inputArgs: []string{ "-config_path", setting_test.TestDataPath("lib", ".protolint.yaml"), setting_test.TestDataPath("lib", "invalid.proto"), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { var stdout bytes.Buffer var stderr bytes.Buffer err := lib.Lint(test.inputArgs, &stdout, &stderr) if !errors.Is(err, test.wantError) { t.Errorf("got err %v, but want err %v", err, test.wantError) } if test.wantStdoutRegex != nil { if !test.wantStdoutRegex.MatchString(stdout.String()) { t.Errorf("got stdout %s, but want to match %v", stdout.String(), test.wantStdoutRegex) } } else if stdout.Len() > 0 { t.Errorf("got stdout %s, but want empty stdout", stdout.String()) } if test.wantStderrRegex != nil { if !test.wantStderrRegex.MatchString(stderr.String()) { t.Errorf("got stderr %s, but want to match %v", stderr.String(), test.wantStderrRegex) } } else if stderr.Len() > 0 { t.Errorf("got stderr %s, but want empty stderr", stderr.String()) } }) } } <file_sep>/internal/linter/file/protoSet_test.go package file_test import ( "path/filepath" "testing" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/setting_test" ) func TestNewProtoSet(t *testing.T) { tests := []struct { name string inputTargetPaths []string wantProtoFiles []file.ProtoFile wantExistErr bool }{ { name: "innerdir3 includes no files", inputTargetPaths: []string{ setting_test.TestDataPath("testdir", "innerdir3"), }, wantExistErr: true, }, { name: "innerdir2 includes no proto files", inputTargetPaths: []string{ setting_test.TestDataPath("testdir", "innerdir2"), }, wantExistErr: true, }, { name: "innerdir includes a proto file", inputTargetPaths: []string{ setting_test.TestDataPath("testdir", "innerdir"), }, wantProtoFiles: []file.ProtoFile{ file.NewProtoFile( filepath.Join(setting_test.TestDataPath("testdir", "innerdir"), "/testinner.proto"), "../../../_testdata/testdir/innerdir/testinner.proto", ), }, }, { name: "testdir includes proto files and inner dirs", inputTargetPaths: []string{ setting_test.TestDataPath("testdir"), }, wantProtoFiles: []file.ProtoFile{ file.NewProtoFile( filepath.Join(setting_test.TestDataPath("testdir", "innerdir"), "/testinner.proto"), "../../../_testdata/testdir/innerdir/testinner.proto", ), file.NewProtoFile( filepath.Join(setting_test.TestDataPath("testdir"), "/test.proto"), "../../../_testdata/testdir/test.proto", ), file.NewProtoFile( filepath.Join(setting_test.TestDataPath("testdir"), "/test2.proto"), "../../../_testdata/testdir/test2.proto", ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got, err := file.NewProtoSet(test.inputTargetPaths) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } for i, gotf := range got.ProtoFiles() { wantf := test.wantProtoFiles[i] if gotf.Path() != wantf.Path() { t.Errorf("got %v, but want %v", gotf.Path(), wantf.Path()) } if gotf.DisplayPath() != wantf.DisplayPath() { t.Errorf("got %v, but want %v", gotf.DisplayPath(), wantf.DisplayPath()) } } }) } } <file_sep>/internal/addon/plugin/shared/gRPCClient.go package shared import ( "context" "github.com/yoheimuta/protolint/internal/addon/plugin/proto" ) // GRPCClient is the implementation of RuleSet. type GRPCClient struct { client proto.RuleSetServiceClient } // ListRules returns all supported rules metadata. func (c *GRPCClient) ListRules(req *proto.ListRulesRequest) (*proto.ListRulesResponse, error) { return c.client.ListRules(context.Background(), req) } // Apply applies the rule to the proto. func (c *GRPCClient) Apply(req *proto.ApplyRequest) (*proto.ApplyResponse, error) { return c.client.Apply(context.Background(), req) } <file_sep>/internal/linter/report/reporters/ciReporter.go package reporters import ( "bytes" "io" "log" "os" "strconv" "strings" "text/template" "github.com/yoheimuta/protolint/linter/report" ) type CiPipelineLogTemplate string const ( // problemMatcher provides a generic issue line that can be parsed in a problem matcher or jenkins pipeline problemMatcher CiPipelineLogTemplate = "Protolint {{ .Rule }} ({{ .Severity }}): {{ .File }}[{{ .Line }},{{ .Column }}]: {{ .Message }}" // azureDevOps provides a log message according to https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=bash#task-commands azureDevOps CiPipelineLogTemplate = "{{ if ne \"info\" .Severity }}##vso[task.logissue type={{ .Severity }};sourcepath={{ .File }};linenumber={{ .Line }};columnnumber={{ .Column }};code={{ .Rule }};]{{ .Message }}{{end}}" // gitlabCiCd provides an issue template where the severity is written in upper case. This is matched by the pipeline gitlabCiCd CiPipelineLogTemplate = "{{ .Severity | ToUpper }}: {{ .Rule }} {{ .File }}({{ .Line }},{{ .Column }}) : {{ .Message }}" // githubActions provides an issue template according to https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-a-notice-message githubActions CiPipelineLogTemplate = "::{{ if ne \"info\" .Severity }}{{ .Severity }}{{ else }}notice{{ end }} file={{ .File }},line={{ .Line }},col={{ .Column }},title={{ .Rule }}::{{ .Message }}" // empty provides default value for invalid returns empty CiPipelineLogTemplate = "" // env provides a marker for processing CI Templates from environment env CiPipelineLogTemplate = "[ENV]" ) type CiReporter struct { pattern CiPipelineLogTemplate } func NewCiReporterForAzureDevOps() CiReporter { return CiReporter{pattern: azureDevOps} } func NewCiReporterForGitlab() CiReporter { return CiReporter{pattern: gitlabCiCd} } func NewCiReporterForGithubActions() CiReporter { return CiReporter{pattern: githubActions} } func NewCiReporterWithGenericFormat() CiReporter { return CiReporter{pattern: problemMatcher} } func NewCiReporterFromEnv() CiReporter { return CiReporter{pattern: env} } type ciReportedFailure struct { Severity string File string Line int Column int Rule string Message string } func (c CiReporter) Report(w io.Writer, fs []report.Failure) error { template, err := c.getTemplate() if err != nil { return err } for _, failure := range fs { reportedFailure := ciReportedFailure{ Severity: getSeverity(failure.Severity()), File: failure.Pos().Filename, Line: failure.Pos().Line, Column: failure.Pos().Column, Rule: failure.RuleID(), Message: strings.Trim(strconv.Quote(failure.Message()), `"`), // Ensure message is on a single line without quotes } var buffer bytes.Buffer err = template.Execute(&buffer, reportedFailure) if err != nil { return err } written, err := w.Write(buffer.Bytes()) if err != nil { return err } if written > 0 { _, err = w.Write([]byte("\n")) if err != nil { return err } } } return nil } func getSeverity(s string) string { if s == "note" { return "info" } return s } func (c CiReporter) getTemplateString() CiPipelineLogTemplate { if c.pattern == env { template, err := getPatternFromEnv() if err != nil { log.Printf("[ERROR] Failed to process template from Environment: %s\n", err.Error()) return problemMatcher } if template == empty { return problemMatcher } return template } if c.pattern != empty { return c.pattern } return problemMatcher } func (c CiReporter) getTemplate() (*template.Template, error) { toParse := c.getTemplateString() toUpper := template.FuncMap{"ToUpper": strings.ToUpper} template := template.New("Failure").Funcs(toUpper) evaluate, err := template.Parse(string(toParse)) if err != nil { return nil, err } return evaluate, nil } func getPatternFromEnv() (CiPipelineLogTemplate, error) { templateString := os.Getenv("PROTOLINT_CIREPORTER_TEMPLATE_STRING") if templateString != "" { return CiPipelineLogTemplate(templateString), nil } templateFile := os.Getenv("PROTOLINT_CIREPORTER_TEMPLATE_FILE") if templateFile != "" { content, err := os.ReadFile(templateFile) if err != nil { if os.IsNotExist(err) { log.Printf("[ERROR] Failed to open file %s from 'PROTOLINT_CIREPORTER_TEMPLATE_FILE'. File does not exist.\n", templateFile) log.Println("[WARN] Starting output with default processor.") return empty, nil } if os.IsPermission(err) { log.Printf("[ERROR] Failed to open file %s from 'PROTOLINT_CIREPORTER_TEMPLATE_FILE'. Insufficient permissions.\n", templateFile) log.Println("[WARN] Starting output with default processor.") return empty, nil } return empty, err } content_string := string(content) return CiPipelineLogTemplate(content_string), nil } return empty, nil } <file_sep>/internal/addon/rules/fileNamesLowerSnakeCaseRule_test.go package rules_test import ( "os" "reflect" "strings" "testing" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/internal/util_test" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" ) func TestFileNamesLowerSnakeCaseRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto inputExcluded []string wantFailures []report.Failure }{ { name: "no failures for proto with a valid file name", inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: "../proto/simple.proto", }, }, }, { name: "no failures for proto with a valid lower snake case file name", inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: "../proto/lower_snake_case.proto", }, }, }, { name: "no failures for excluded proto", inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: "proto/lowerSnakeCase.proto", }, }, inputExcluded: []string{ "proto/lowerSnakeCase.proto", }, }, { name: "a failure for proto with a camel case file name", inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: "proto/lowerSnakeCase.proto", }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "proto/lowerSnakeCase.proto", Offset: 0, Line: 1, Column: 1, }, "FILE_NAMES_LOWER_SNAKE_CASE", `File name "lowerSnakeCase.proto" should be lower_snake_case.proto like "lower_snake_case.proto".`, ), }, }, { name: "a failure for proto with an invalid file extension", inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: "proto/lowerSnakeCase.txt", }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "proto/lowerSnakeCase.txt", Offset: 0, Line: 1, Column: 1, }, "FILE_NAMES_LOWER_SNAKE_CASE", `File name "lowerSnakeCase.txt" should be lower_snake_case.proto like "lower_snake_case.proto".`, ), }, }, { name: "a failure for proto with an invalid separater", inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: "proto/dot.separated.proto", }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "proto/dot.separated.proto", Offset: 0, Line: 1, Column: 1, }, "FILE_NAMES_LOWER_SNAKE_CASE", `File name "dot.separated.proto" should be lower_snake_case.proto like "dot_separated.proto".`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewFileNamesLowerSnakeCaseRule(rule.SeverityError, test.inputExcluded, false) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestFileNamesLowerSnakeCaseRule_Apply_fix(t *testing.T) { tests := []struct { name string inputExcluded []string inputFilename string wantFilename string wantAbort bool }{ { name: "no fix for a correct proto", inputFilename: "lower_snake_case.proto", wantFilename: "lower_snake_case.proto", }, { name: "abort to fix the proto because of alreadyExists", inputFilename: "lowerSnakeCase.proto", wantAbort: true, }, { name: "fix for an incorrect proto", inputFilename: "UpperCamelCase.proto", wantFilename: "upper_camel_case.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewFileNamesLowerSnakeCaseRule(rule.SeverityError, test.inputExcluded, true) dataDir := strs.ToLowerCamelCase(r.ID()) input, err := util_test.NewTestData(setting_test.TestDataPath("rules", dataDir, test.inputFilename)) if err != nil { t.Errorf("got err %v", err) return } proto, err := file.NewProtoFile(input.FilePath, input.FilePath).Parse(false) if err != nil { t.Errorf(err.Error()) return } fs, err := r.Apply(proto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if test.wantAbort { if _, err := os.Stat(input.FilePath); os.IsNotExist(err) { t.Errorf("not found %q, but want to locate it", input.FilePath) return } for _, f := range fs { if strings.Contains(f.Message(), "Failed to rename") { return } } t.Error("not found failure message, but want to include it") return } wantPath := setting_test.TestDataPath("rules", dataDir, test.wantFilename) if _, err := os.Stat(wantPath); os.IsNotExist(err) { t.Errorf("not found %q, but want to locate it", wantPath) return } err = os.Rename(wantPath, input.FilePath) if err != nil { t.Errorf("got err %v", err) } }) } } <file_sep>/internal/linter/config/indentOption_test.go package config_test import ( "reflect" "strings" "testing" yaml "gopkg.in/yaml.v2" "github.com/yoheimuta/protolint/internal/linter/config" ) func TestIndentOption_UnmarshalYAML(t *testing.T) { for _, test := range []struct { name string inputConfig []byte wantIndentOption config.IndentOption wantExistErr bool }{ { name: "not found supported style", inputConfig: []byte(` style: 4-space `), wantExistErr: true, }, { name: "style: tab", inputConfig: []byte(` style: tab `), wantIndentOption: config.IndentOption{ Style: "\t", }, }, { name: "style: 4", inputConfig: []byte(` style: 4 `), wantIndentOption: config.IndentOption{ Style: strings.Repeat(" ", 4), }, }, { name: "style: 2", inputConfig: []byte(` style: 2 `), wantIndentOption: config.IndentOption{ Style: strings.Repeat(" ", 2), }, }, { name: "not found supported newline", inputConfig: []byte(` style: tab newline: linefeed `), wantExistErr: true, }, { name: "newline: \n", inputConfig: []byte(` newline: "\n" `), wantIndentOption: config.IndentOption{ Newline: "\n", }, }, { name: "newline: \r", inputConfig: []byte(` newline: "\r" `), wantIndentOption: config.IndentOption{ Newline: "\r", }, }, { name: "newline: \r\n", inputConfig: []byte(` newline: "\r\n" `), wantIndentOption: config.IndentOption{ Newline: "\r\n", }, }, { name: "support not_insert_newline", inputConfig: []byte(` not_insert_newline: true `), wantIndentOption: config.IndentOption{ NotInsertNewline: true, }, }, } { test := test t.Run(test.name, func(t *testing.T) { var got config.IndentOption err := yaml.UnmarshalStrict(test.inputConfig, &got) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantIndentOption) { t.Errorf("got %v, but want %v", got, test.wantIndentOption) } }) } } <file_sep>/linter/autodisable/placementStrategy.go package autodisable import "github.com/yoheimuta/go-protoparser/v4/parser" // PlacementType is a selection of the placement strategies. type PlacementType int const ( // Noop does nothing Noop PlacementType = iota // ThisThenNext puts inline comments. ThisThenNext // Next puts newline comments. Next ) // NewPlacementStrategy creates a strategy object. func NewPlacementStrategy(ptype PlacementType, filename, ruleID string) (PlacementStrategy, error) { if ptype == Noop { return &noopPlacementStrategy{}, nil } c, err := newCommentator(filename, ruleID) if err != nil { return nil, err } switch ptype { case ThisThenNext: return newThisThenNextPlacementStrategy(c), err case Next: return newNextPlacementStrategy(c), err default: return nil, nil } } // PlacementStrategy is an abstraction to put a comment. type PlacementStrategy interface { Disable(offset int, comments []*parser.Comment, inline *parser.Comment) Finalize() error } type noopPlacementStrategy struct{} func (p *noopPlacementStrategy) Disable( offset int, comments []*parser.Comment, _ *parser.Comment) { } func (p *noopPlacementStrategy) Finalize() error { return nil } <file_sep>/internal/linter/config/rpcNamesCaseOption.go package config import ( "fmt" "strings" ) // ConventionType is a type of name case convention. type ConventionType int // ConventionType constants. const ( ConventionLowerCamel ConventionType = iota + 1 ConventionUpperSnake ConventionLowerSnake ) // RPCNamesCaseOption represents the option for the RPC_NAMES_CASE rule. type RPCNamesCaseOption struct { CustomizableSeverityOption Convention ConventionType } // UnmarshalYAML implements yaml.v2 Unmarshaler interface. func (r *RPCNamesCaseOption) UnmarshalYAML(unmarshal func(interface{}) error) error { var option struct { Convention string `yaml:"convention"` } if err := unmarshal(&option); err != nil { return err } if 0 < len(option.Convention) { supportConventions := map[string]ConventionType{ "lower_camel_case": ConventionLowerCamel, "upper_snake_case": ConventionUpperSnake, "lower_snake_case": ConventionLowerSnake, } convention, ok := supportConventions[option.Convention] if !ok { var list []string for k := range supportConventions { list = append(list, k) } return fmt.Errorf("%s is an invalid name convention. valid options are [%s]", option.Convention, strings.Join(list, ",")) } r.Convention = convention } return nil } <file_sep>/internal/addon/rules/packageNameLowerCaseRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestPackageNameLowerCaseRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto wantFailures []report.Failure }{ { name: "no failures for proto without service", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{}, }, }, }, { name: "no failures for proto with the valid package name", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Package{ Name: "package", }, }, }, }, { name: "no failures for proto with the valid package name with periods", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Package{ Name: "my.v1.package", }, }, }, }, { name: "failures for proto with the invalid package name", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Package{ Name: "myV1Package", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "PACKAGE_NAME_LOWER_CASE", `Package name "myV1Package" must not contain any uppercase letter. Consider to change like "myv1package".`, ), }, }, { name: "no failures for proto with the package name including _", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Package{ Name: "my.some_service", }, }, }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewPackageNameLowerCaseRule(rule.SeverityError, false) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestPackageNameLowerCaseRule_Apply_fix(t *testing.T) { tests := []struct { name string inputFilename string wantFilename string }{ { name: "no fix for a correct proto", inputFilename: "lowerCase.proto", wantFilename: "lowerCase.proto", }, { name: "fix for an incorrect proto", inputFilename: "invalid.proto", wantFilename: "lowerCase.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewPackageNameLowerCaseRule(rule.SeverityError, true) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } <file_sep>/linter/visitor/baseFixableVisitor.go package visitor import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/fixer" ) // BaseFixableVisitor represents a base visitor which can fix failures. type BaseFixableVisitor struct { *BaseAddVisitor Fixer fixer.Fixer finallyFn func() error } // NewBaseFixableVisitor creates a BaseFixableVisitor. func NewBaseFixableVisitor( ruleID string, fixMode bool, proto *parser.Proto, severity string, ) (*BaseFixableVisitor, error) { f, err := fixer.NewFixing(fixMode, proto) if err != nil { return nil, err } return &BaseFixableVisitor{ BaseAddVisitor: NewBaseAddVisitor(ruleID, severity), Fixer: f, finallyFn: f.Finally, }, nil } // Finally fixes the proto file by overwriting it. func (v *BaseFixableVisitor) Finally() error { err := v.finallyFn() if err != nil { return err } return v.BaseAddVisitor.Finally() } <file_sep>/linter/autodisable/placementStrategy_test.go package autodisable_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/internal/util_test" "github.com/yoheimuta/protolint/linter/autodisable" ) type inputDisable struct { inputOffset int inputComments []*parser.Comment inputInline *parser.Comment } func TestPlacementStrategy_Disable(t *testing.T) { tests := []struct { name string inputPlacementType autodisable.PlacementType inputFilename string inputRoleID string inputDisable []inputDisable wantFilename string }{ { name: "no auto disable", inputPlacementType: autodisable.Noop, inputRoleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisable: []inputDisable{ { inputOffset: 34, }, }, inputFilename: "invalid_enum_field_names.proto", wantFilename: "invalid_enum_field_names.proto", }, { name: "add a new line comment", inputPlacementType: autodisable.Next, inputRoleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisable: []inputDisable{ { inputOffset: 34, }, }, inputFilename: "invalid_enum_field_names.proto", wantFilename: "disabled_enum_field_names.proto", }, { name: "add new three line comments", inputPlacementType: autodisable.Next, inputRoleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisable: []inputDisable{ { inputOffset: 63, }, { inputOffset: 115, }, { inputOffset: 145, }, }, inputFilename: "invalid_many_enum_field_names.proto", wantFilename: "disabled_many_enum_field_names.proto", }, { name: "not merge the comment", inputPlacementType: autodisable.Next, inputRoleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisable: []inputDisable{ { inputOffset: 99, }, { inputOffset: 119, }, }, inputFilename: "invalid_enum_field_names_comment.proto", wantFilename: "disabled_nomerge_enum_field_names.proto", }, { name: "add an inline comment", inputPlacementType: autodisable.ThisThenNext, inputRoleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisable: []inputDisable{ { inputOffset: 34, }, }, inputFilename: "invalid_enum_field_names.proto", wantFilename: "disabled_inline_enum_field_names.proto", }, { name: "merge an inline comment", inputPlacementType: autodisable.ThisThenNext, inputRoleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisable: []inputDisable{ { inputOffset: 99, }, { inputOffset: 119, inputInline: &parser.Comment{ Raw: `// protolint:disable:this ENUM_FIELD_NAMES_PREFIX`, Meta: meta.Meta{Pos: meta.Position{Offset: 142}}, }, }, }, inputFilename: "invalid_inline_disable_enum_field_names.proto", wantFilename: "disabled_merge_inline_enum_field_names.proto", }, { name: "add an inline comment and a line comment", inputPlacementType: autodisable.ThisThenNext, inputRoleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisable: []inputDisable{ { inputOffset: 99, }, { inputOffset: 119, inputInline: &parser.Comment{ Raw: `// See the reference page.`, }, }, }, inputFilename: "invalid_inline_enum_field_names.proto", wantFilename: "disabled_inline_line_enum_field_names.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { inputFilePath := setting_test.TestDataPath("autodisable", test.inputFilename) wantFilePath := setting_test.TestDataPath("autodisable", test.wantFilename) strategy, err := autodisable.NewPlacementStrategy( test.inputPlacementType, inputFilePath, test.inputRoleID, ) if err != nil { t.Errorf("got err %v, but want nil", err) return } testDisable(t, strategy, test.inputDisable, inputFilePath, wantFilePath) }) } } func testDisable( t *testing.T, strategy autodisable.PlacementStrategy, inputDisable []inputDisable, inputFilePath string, wantFilePath string, ) { input, err := util_test.NewTestData(inputFilePath) if err != nil { t.Errorf("got err %v", err) return } want, err := util_test.NewTestData(wantFilePath) if err != nil { t.Errorf("got err %v", err) return } for _, p := range inputDisable { strategy.Disable(p.inputOffset, p.inputComments, p.inputInline) } err = strategy.Finalize() if err != nil { t.Errorf("got err %v", err) return } got, _ := input.Data() if !reflect.DeepEqual(got, want.OriginData) { t.Errorf( "got %s(%v), but want %s(%v)", string(got), got, string(want.OriginData), want.OriginData, ) } err = input.Restore() if err != nil { t.Errorf("got err %v", err) } } <file_sep>/internal/linter/config/messageNamesExcludePrepositionsOption.go package config // MessageNamesExcludePrepositionsOption represents the option for the MESSAGE_NAMES_EXCLUDE_PREPOSITIONS rule. type MessageNamesExcludePrepositionsOption struct { CustomizableSeverityOption Prepositions []string `yaml:"prepositions"` Excludes []string `yaml:"excludes"` } <file_sep>/internal/addon/rules/messageNamesUpperCamelCaseRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // MessageNamesUpperCamelCaseRule verifies that all message names are CamelCase (with an initial capital). // See https://developers.google.com/protocol-buffers/docs/style#message-and-field-names. type MessageNamesUpperCamelCaseRule struct { RuleWithSeverity fixMode bool autoDisableType autodisable.PlacementType } // NewMessageNamesUpperCamelCaseRule creates a new MessageNamesUpperCamelCaseRule. func NewMessageNamesUpperCamelCaseRule( severity rule.Severity, fixMode bool, autoDisableType autodisable.PlacementType, ) MessageNamesUpperCamelCaseRule { if autoDisableType != autodisable.Noop { fixMode = false } return MessageNamesUpperCamelCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r MessageNamesUpperCamelCaseRule) ID() string { return "MESSAGE_NAMES_UPPER_CAMEL_CASE" } // Purpose returns the purpose of this rule. func (r MessageNamesUpperCamelCaseRule) Purpose() string { return "Verifies that all message names are CamelCase (with an initial capital)." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r MessageNamesUpperCamelCaseRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r MessageNamesUpperCamelCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &messageNamesUpperCamelCaseVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type messageNamesUpperCamelCaseVisitor struct { *visitor.BaseFixableVisitor } // VisitMessage checks the message. func (v *messageNamesUpperCamelCaseVisitor) VisitMessage(message *parser.Message) bool { name := message.MessageName if !strs.IsUpperCamelCase(name) { expected := strs.ToUpperCamelCase(name) v.AddFailuref(message.Meta.Pos, "Message name %q must be UpperCamelCase like %q", name, expected) err := v.Fixer.SearchAndReplace(message.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return true } <file_sep>/internal/addon/rules/proto3GroupsAvoidRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // Proto3GroupsAvoidRule verifies that all groups should be avoided for proto3. // See https://developers.google.com/protocol-buffers/docs/style#things-to-avoid type Proto3GroupsAvoidRule struct { RuleWithSeverity autoDisableType autodisable.PlacementType } // NewProto3GroupsAvoidRule creates a new Proto3GroupsAvoidRule. func NewProto3GroupsAvoidRule( severity rule.Severity, autoDisableType autodisable.PlacementType, ) Proto3GroupsAvoidRule { return Proto3GroupsAvoidRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r Proto3GroupsAvoidRule) ID() string { return "PROTO3_GROUPS_AVOID" } // Purpose returns the purpose of this rule. func (r Proto3GroupsAvoidRule) Purpose() string { return "Verifies that all groups should be avoided for proto3." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r Proto3GroupsAvoidRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r Proto3GroupsAvoidRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &proto3GroupsAvoidVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type proto3GroupsAvoidVisitor struct { *visitor.BaseAddVisitor isProto3 bool } // VisitSyntax checks the syntax. func (v *proto3GroupsAvoidVisitor) VisitSyntax(s *parser.Syntax) bool { v.isProto3 = s.ProtobufVersion == "proto3" return false } // VisitGroupField checks the group field. func (v *proto3GroupsAvoidVisitor) VisitGroupField(field *parser.GroupField) bool { if v.isProto3 { v.AddFailuref(field.Meta.Pos, `Group %q should be avoided for proto3`, field.GroupName) } return false } <file_sep>/internal/linter/config/serviceNamesEndWithOption.go package config // ServiceNamesEndWithOption represents the option for the SERVICE_NAMES_END_WITH rule. type ServiceNamesEndWithOption struct { CustomizableSeverityOption Text string `yaml:"text"` } <file_sep>/README.md # protolint ![Action](https://github.com/yoheimuta/protolint/workflows/Go/badge.svg) [![Release](https://img.shields.io/github/v/release/yoheimuta/protolint?include_prereleases)](https://github.com/yoheimuta/protolint/releases)[ ![Go Report Card](https://goreportcard.com/badge/github.com/yoheimuta/protolint)](https://goreportcard.com/report/github.com/yoheimuta/protolint) [![License](http://img.shields.io/:license-mit-blue.svg)](https://github.com/yoheimuta/protolint/blob/master/LICENSE) [![Docker](https://img.shields.io/docker/pulls/yoheimuta/protolint)](https://hub.docker.com/r/yoheimuta/protolint) protolint is the pluggable linting/fixing utility for Protocol Buffer files (proto2+proto3): - Runs fast because this works without compiler. - Easy to follow the official style guide. The rules and the style guide correspond to each other exactly. - Fixer automatically fixes all the possible official style guide violations. - Allows to disable rules with a comment in a Protocol Buffer file. - It is useful for projects which must keep API compatibility while enforce the style guide as much as possible. - Some rules can be automatically disabled by inserting comments to the spotted violations. - Loads plugins to contain your custom lint rules. - Undergone testing for all rules. - Many integration supports. - protoc plugin - Editor integration - GitHub Action - CI Integration ## Demo For example, vim-protolint works like the following. <img src="_doc/demo-v2.gif" alt="demo" width="600"/> ## Installation ### Via Homebrew protolint can be installed for Mac or Linux using Homebrew via the [yoheimuta/protolint](https://github.com/yoheimuta/homebrew-protolint) tap. ```sh brew tap yoheimuta/protolint brew install protolint ``` Since [homebrew-core](https://github.com/Homebrew/homebrew-core/pkgs/container/core%2Fprotolint) includes `protolint,` you can also install it by just `brew install protolint.` This is the default tap that is installed by default. It's easier, but not maintained by the same author. To keep it updated, I recommend you run `brew tap yoheimuta/protolint` first. ### Via GitHub Releases You can also download a pre-built binary from this release page: - https://github.com/yoheimuta/protolint/releases In the downloads section of each release, you can find pre-built binaries in .tar.gz packages. ### Use the maintained Docker image protolint ships a Docker image [yoheimuta/protolint](https://hub.docker.com/r/yoheimuta/protolint) that allows you to use protolint as part of your Docker workflow. ``` ❯❯❯ docker run --volume "$(pwd):/workspace" --workdir /workspace yoheimuta/protolint lint _example/proto [_example/proto/invalidFileName.proto:1:1] File name should be lower_snake_case.proto. [_example/proto/issue_88/oneof_options.proto:11:5] Found an incorrect indentation style " ". " " is correct. [_example/proto/issue_88/oneof_options.proto:12:5] Found an incorrect indentation style " ". " " is correct. ``` ### From Source The binary can be installed from source if Go is available. However, I recommend using one of the pre-built binaries instead because it doesn't include the version info. ```sh go install github.com/yoheimuta/protolint/cmd/protolint@latest ``` ## Usage ```sh protolint lint example.proto example2.proto # file mode, specify multiple specific files protolint lint . # directory mode, search for all .proto files recursively protolint . # same as "protolint lint ." protolint lint -config_path=path/to/your_protolint.yaml . # use path/to/your_protolint.yaml protolint lint -config_dir_path=path/to . # search path/to for .protolint.yaml protolint lint -fix . # automatically fix some of the problems reported by some rules protolint lint -fix -auto_disable=next . # this is preferable when you want to fix problems while maintaining the compatibility. Automatically fix some problems and insert disable comments to the other problems. The available values are next and this. protolint lint -auto_disable=next . # automatically insert disable comments to the other problems. protolint lint -v . # with verbose output to investigate the parsing error protolint lint -no-error-on-unmatched-pattern . # exits with success code even if no file is found (file & directory mode) protolint lint -reporter junit . # output results in JUnit XML format protolint lint -output_file=path/to/out.txt # output results to path/to/out.txt protolint lint -plugin ./my_custom_rule1 -plugin ./my_custom_rule2 . # run custom lint rules. protolint list # list all current lint rules being used protolint version # print protolint version ``` protolint does not require configuration by default, for the majority of projects it should work out of the box. ## Version Control Integration protolint is available as a [pre-commit](https://pre-commit.com) hook. Add this to your `.pre-commit-config.yaml` in your repository to run protolint with Go: ```yaml repos: - repo: https://github.com/yoheimuta/protolint rev: <version> # Select a release here like v0.44.0 hooks: - id: protolint ``` or alternatively use this to run protolint with Docker: ```yaml repos: - repo: https://github.com/yoheimuta/protolint rev: <version> # Select a release here like v0.44.0 hooks: - id: protolint-docker ``` ## Editor Integration Visual Studio Code - [vscode-protolint](https://github.com/plexsystems/vscode-protolint) JetBrains IntelliJ IDEA, GoLand, WebStorm, PHPStorm, PyCharm... - [intellij-protolint](https://github.com/yoheimuta/intellij-protolint) Vim([ALE engine](https://github.com/dense-analysis/ale)) - [ale](https://github.com/dense-analysis/ale)'s [built-in support](https://github.com/dense-analysis/ale/blob/master/supported-tools.md) Vim([Syntastic](https://github.com/vim-syntastic/syntastic)) - [vim-protolint](https://github.com/yoheimuta/vim-protolint) ## GitHub Action A [GitHub Action](https://github.com/features/actions) to run protolint in your workflows - [github/super-linter](https://github.com/github/super-linter) - [plexsystems/protolint-action](https://github.com/plexsystems/protolint-action) - [yoheimuta/action-protolint](https://github.com/yoheimuta/action-protolint) - Integrated with [reviewdog](https://github.com/reviewdog/reviewdog) ## CI Integration Jenkins Plugins - [warnings-ng](https://github.com/jenkinsci/warnings-ng-plugin) and any that use [violatons-lib](https://github.com/tomasbjerre/violations-lib) ### Environment specific output It is possible to format your linting according to the formatting of the CI/CD environment. The environment must be set using the output format. Currently, the following output is realized: | Environment | Command Line Value | Description | Example | |-------------|--------------------|-------------|---------| | Github Actions | ci-gh | [Github Help](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-a-notice-message) | `::warning file=example.proto,line=10,col=20,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES` | | Azure DevOps | ci-az | [Azure DevOps Help](https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=bash#task-commands) | `##vso[task.logissue type=warning;sourcepath=example.proto;linenumber=10;columnnumber=20;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES` | | Gitlab CI/CD | ci-glab | Reverse Engineered from Examples | `WARNING: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(10,20) : EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES` | You can also use the generic `ci` formatter, which will create a generic problem matcher. With the `ci-env` value, you can specify the template from the following environment variables: | Environment Variable | Priority | Meaning | |----------------------|----------|---------| | PROTOLINT_CIREPORTER_TEMPLATE_STRING | 1 | String containing a Go-template | | PROTOLINT_CIREPORTER_TEMPLATE_FILE | 2 | Path to a file containing a Go-template | The resulting line-feed must not be added, as it will be added automatically. The following fields are available: `Severity` : The severity as string (either note, warning or error) `File` : Path to the file containing the error `Line` : Line within the `file` containing the error (starting position) `Column` : Column within the `file` containing the error (starting position) `Rule` : The name of the rule that is faulting `Message` : The error message that descibes the error ### Producing an output file and an CI/CD Error stream You can create a specific output matching your CI/CD environment and also create an output file, e.g. for your static code analysis tools like github CodeQL or SonarQube. This can be done by adding the `--add-reporter` flag. Please note, that the value must be formatted `<reporter-name>:<output-file-path>` (omitting `<` and `>`). ```shell $ protolint --reporter ci-gh --add-reporter sarif:/path/to/my/output.sarif.json proto/*.proto ``` ## Use as a protoc plugin protolint also maintains a binary [protoc-gen-protolint](cmd/protoc-gen-protolint) that performs the lint functionality as a protoc plugin. See [cmd/protoc-gen-protolint/README.md](https://github.com/yoheimuta/protolint/blob/master/cmd/protoc-gen-protolint/README.md) in detail. This is useful in situations where you already have a protoc plugin workflow. ## Call from Go code You can also use protolint from Go code. See [Go Documentation](https://pkg.go.dev/github.com/yoheimuta/protolint/lib) and [lib/lint_test.go](https://github.com/yoheimuta/protolint/blob/master/lib/lint_test.go) in detail. ```go args := []string{"-config_path", "path/to/your_protolint.yaml", "."} var stdout bytes.Buffer var stderr bytes.Buffer err := lib.Lint(test.inputArgs, &stdout, &stderr) ``` ## Rules See `internal/addon/rules` in detail. The rule set follows: - [Official Style Guide](https://protobuf.dev/programming-guides/style/). This is enabled by default. Basically, these rules can fix the violations by appending `-fix` option. - Unofficial Style Guide. This is disabled by default. You can enable each rule with `.protolint.yaml`. The `-fix` option on the command line can automatically fix all the problems reported by fixable rules. See Fixable columns below. The `-auto_disable` option on the command line can automatically disable all the problems reported by auto-disable rules. This feature is helpful when fixing the existing violations breaks the compatibility. See AutoDisable columns below. - *1: These rules are not supposed to support AutoDisable because the fixes don't break their compatibilities. You should run the protolint with `-fix`. | Official | Fixable | AutoDisable | ID | Purpose | |----------|---------|---------|-----------------------------------|--------------------------------------------------------------------------| | Yes | ✅ | ✅ | ENUM_FIELD_NAMES_PREFIX | Verifies that enum field names are prefixed with its ENUM_NAME_UPPER_SNAKE_CASE. | | Yes | ✅ | ✅ | ENUM_FIELD_NAMES_UPPER_SNAKE_CASE | Verifies that all enum field names are CAPITALS_WITH_UNDERSCORES. | | Yes | ✅ | ✅ | ENUM_FIELD_NAMES_ZERO_VALUE_END_WITH | Verifies that the zero value enum should have the suffix (e.g. "UNSPECIFIED", "INVALID"). The default is "UNSPECIFIED". You can configure the specific suffix with `.protolint.yaml`. | | Yes | ✅ | ✅ | ENUM_NAMES_UPPER_CAMEL_CASE | Verifies that all enum names are CamelCase (with an initial capital). | | Yes | ✅ | *1 | FILE_NAMES_LOWER_SNAKE_CASE | Verifies that all file names are lower_snake_case.proto. You can configure the excluded files with `.protolint.yaml`. | | Yes | ✅ | ✅ | FIELD_NAMES_LOWER_SNAKE_CASE | Verifies that all field names are underscore_separated_names. | | Yes | ✅ | *1 | IMPORTS_SORTED | Verifies that all imports are sorted. | | Yes | ✅ | ✅ | MESSAGE_NAMES_UPPER_CAMEL_CASE | Verifies that all message names are CamelCase (with an initial capital). | | Yes | ✅ | *1 | ORDER | Verifies that all files should be ordered in the specific manner. | | Yes | ✅ | *1 | PACKAGE_NAME_LOWER_CASE | Verifies that the package name should only contain lowercase letters. | | Yes | ✅ | ✅ | RPC_NAMES_UPPER_CAMEL_CASE | Verifies that all rpc names are CamelCase (with an initial capital). | | Yes | ✅ | ✅ | SERVICE_NAMES_UPPER_CAMEL_CASE | Verifies that all service names are CamelCase (with an initial capital). | | Yes | ✅ | ✅ | REPEATED_FIELD_NAMES_PLURALIZED | Verifies that repeated field names are pluralized names. | | Yes | ✅ | *1 | QUOTE_CONSISTENT | Verifies that the use of quote for strings is consistent. The default is double quoted. You can configure the specific quote with `.protolint.yaml`. | | Yes | ✅ | *1 | INDENT | Enforces a consistent indentation style. The default style is 2 spaces. Inserting appropriate new lines is also forced by default. You can configure the detail with `.protolint.yaml`. | | Yes | ✅ | *1 | PROTO3_FIELDS_AVOID_REQUIRED | Verifies that all fields should avoid required for proto3. | | Yes | _ | ✅ | PROTO3_GROUPS_AVOID | Verifies that all groups should be avoided for proto3. | | Yes | _ | *1 | MAX_LINE_LENGTH | Enforces a maximum line length. The length of a line is defined as the number of Unicode characters in the line. The default is 80 characters. You can configure the detail with `.protolint.yaml`. | | No | _ | - | SERVICE_NAMES_END_WITH | Enforces a consistent suffix for service names. You can configure the specific suffix with `.protolint.yaml`. | | No | _ | - | FIELD_NAMES_EXCLUDE_PREPOSITIONS | Verifies that all field names don't include prepositions (e.g. "for", "during", "at"). You can configure the specific prepositions and excluded keywords with `.protolint.yaml`. | | No | _ | - | MESSAGE_NAMES_EXCLUDE_PREPOSITIONS | Verifies that all message names don't include prepositions (e.g. "With", "For"). You can configure the specific prepositions and excluded keywords with `.protolint.yaml`. | | No | _ | - | RPC_NAMES_CASE | Verifies that all rpc names conform to the specified convention. You need to configure the specific convention with `.protolint.yaml`. | | No | _ | - | MESSAGES_HAVE_COMMENT | Verifies that all messages have a comment. You can configure to enforce Golang Style comments with `.protolint.yaml`. | | No | _ | - | SERVICES_HAVE_COMMENT | Verifies that all services have a comment. You can configure to enforce Golang Style comments with `.protolint.yaml`. | | No | _ | - | RPCS_HAVE_COMMENT | Verifies that all rps have a comment. You can configure to enforce Golang Style comments with `.protolint.yaml`. | | No | _ | - | FIELDS_HAVE_COMMENT | Verifies that all fields have a comment. You can configure to enforce Golang Style comments with `.protolint.yaml`. | | No | _ | - | ENUMS_HAVE_COMMENT | Verifies that all enums have a comment. You can configure to enforce Golang Style comments with `.protolint.yaml`. | | No | _ | - | ENUM_FIELDS_HAVE_COMMENT | Verifies that all enum fields have a comment. You can configure to enforce Golang Style comments with `.protolint.yaml`. | | No | _ | - | FILE_HAS_COMMENT | Verifies that a file starts with a doc comment. | | No | _ | - | SYNTAX_CONSISTENT | Verifies that syntax is a specified version. The default is proto3. You can configure the version with `.protolint.yaml`. | I recommend that you add `all_default: true` in `.protolint.yaml`, because all linters above are automatically enabled so that you can always enjoy maximum benefits whenever protolint is updated. Here are some examples that show good style enabled by default. `-` is a bad style, `+` is a good style: __ENUM_FIELD_NAMES_PREFIX__ ```diff enum FooBar { - UNSPECIFIED = 0; + FOO_BAR_UNSPECIFIED = 0; } ``` __ENUM_FIELD_NAMES_UPPER_SNAKE_CASE__ ```diff enum Foo { - firstValue = 0; + FIRST_VALUE = 0; - second_value = 1; + SECOND_VALUE = 1; } ``` __ENUM_FIELD_NAMES_ZERO_VALUE_END_WITH__ ```diff enum Foo { - FOO_FIRST = 0; + FOO_UNSPECIFIED = 0; } ``` __ENUM_NAMES_UPPER_CAMEL_CASE__ ```diff - enum foobar { + enum FooBar { FIRST_VALUE = 0; SECOND_VALUE = 1; } ``` __FIELD_NAMES_LOWER_SNAKE_CASE__ ```diff message SongServerRequest { - required string SongName = 1; + required string song_name = 1; } ``` __IMPORTS_SORTED__ ```diff - import public "new.proto"; + import "myproject/other_protos.proto"; - import "myproject/other_protos.proto"; + import public "new.proto"; import "google/protobuf/empty.proto"; import "google/protobuf/timestamp.proto"; ``` __MESSAGE_NAMES_UPPER_CAMEL_CASE__ ```diff - message song_server_request { + message SongServerRequest { required string SongName = 1; required string song_name = 1; } ``` __ORDER__ ```diff - option java_package = "com.example.foo"; - syntax = "proto3"; - package examplePb; - message song_server_request { } - import "other.proto"; + syntax = "proto3"; + package examplePb; + import "other.proto"; + option java_package = "com.example.foo"; + message song_server_request { } ``` __PACKAGE_NAME_LOWER_CASE__ ```diff - package myPackage + package my.package ``` __RPC_NAMES_UPPER_CAMEL_CASE__ ```diff service FooService { - rpc get_something(FooRequest) returns (FooResponse); + rpc GetSomething(FooRequest) returns (FooResponse); } ``` __RPC_NAMES_UPPER_CAMEL_CASE__ ```diff - service foo_service { + service FooService { rpc get_something(FooRequest) returns (FooResponse); rpc GetSomething(FooRequest) returns (FooResponse); } ``` __REPEATED_FIELD_NAMES_PLURALIZED__ ```diff - repeated string song_name = 1; + repeated string song_names = 1; ``` __INDENT__ ```diff enum enumAllowingAlias { UNKNOWN = 0; - option allow_alias = true; + option allow_alias = true; STARTED = 1; - RUNNING = 2 [(custom_option) = "hello world"]; + RUNNING = 2 [(custom_option) = "hello world"]; - } +} ``` ```diff - message TestMessage { string test_field = 1; } + message TestMessage { + string test_field = 1; +} ``` __QUOTE_CONSISTENT__ ```diff option java_package = "com.example.foo"; - option go_package = 'example'; + option go_package = "example"; ``` ## Creating your custom rules protolint is the pluggable linter so that you can freely create custom lint rules. A complete sample project (aka plugin) is included in this repo under the [_example/plugin](_example/plugin) directory. ## Reporters protolint comes with several built-in reporters(aka. formatters) to control the appearance of the linting results. You can specify a reporter using the -reporter flag on the command line. For example, `-reporter junit` uses the junit reporter. The built-in reporter options are: - plain (default) - junit - json - sarif - sonar (SonarQube generic issue format) - unix ## Configuring __Disable rules in a Protocol Buffer file__ Rules can be disabled with a comment inside a Protocol Buffer file with the following format. The rules will be disabled until the end of the file or until the linter sees a matching enable comment: ``` // protolint:disable <ruleID1> [<ruleID2> <ruleID3>...] ... // protolint:enable <ruleID1> [<ruleID2> <ruleID3>...] ``` It's also possible to modify a disable command by appending :next or :this for only applying the command to this(current) or the next line respectively. For example: ```proto enum Foo { // protolint:disable:next ENUM_FIELD_NAMES_UPPER_SNAKE_CASE firstValue = 0; // no error second_value = 1; // protolint:disable:this ENUM_FIELD_NAMES_UPPER_SNAKE_CASE THIRD_VALUE = 2; // spits out an error } ``` Setting the command-line option `-auto_disable` to `next` or `this` inserts disable commands whenever spotting problems. You can specify `-fix` option together. The rules supporting auto_disable suppress the violations instead of fixing them that cause a schema incompatibility. __Config file__ protolint can operate using a config file named `.protolint.yaml`. Refer to [_example/config/.protolint.yaml](_example/config/.protolint.yaml) for the config file specification. protolint will automatically search a current working directory for the config file by default and successive parent directories all the way up to the root directory of the filesystem. And it can search the specified directory with `-config_dir_path` flag. It can also search the specified file with `--config_path` flag. ## Exit codes When linting files, protolint will exit with one of the following exit codes: - `0`: Linting was successful and there are no linting errors. - `1`: Linting was successful and there is at least one linting error. - `2`: Linting was unsuccessful due to all other errors, such as parsing, internal, and runtime errors. ## Motivation There exists the similar protobuf linters as of 2018/12/20. One is a plug-in for Google's Protocol Buffers compiler. - When you just want to lint the files, it may be tedious to create the compilation environment. - And it generally takes a lot of time to compile the files than to parse the files. Other is a command line tool which also lints Protocol Buffer files. - While it has a lot of features other than lint, it seems cumbersome for users who just want the linter. - The lint rule slants towards to be opinionated. - Further more, the rule set and the official style guide don't correspond to each other exactly. It requires to understand both rules and the guide in detail, and then to combine the rules accurately. ### Other tools I wrote an article comparing various Protocol Buffer Linters, including protolint, on 2019/12/17. - https://qiita.com/yoheimuta/items/da7678fcd046b93a2637 - NOTE: This one is written in Japanese. ## Dependencies - [go-protoparser](https://github.com/yoheimuta/go-protoparser) ## License The MIT License (MIT) ## Acknowledgement Thank you to the prototool package: https://github.com/uber/prototool I referred to the package for the good proven design, interface and some source code. <file_sep>/internal/addon/rules/base.go package rules import "github.com/yoheimuta/protolint/linter/rule" // RuleWithSeverity represents a rule with a configurable severity. type RuleWithSeverity struct { severity rule.Severity } // NewRuleWithSeverity takes a severity and adds it to a new instance // of RuleWithSeverity func NewRuleWithSeverity( severity rule.Severity, ) RuleWithSeverity { return RuleWithSeverity{severity: severity} } // Severity returns the configured severity. func (r RuleWithSeverity) Severity() rule.Severity { return r.severity } <file_sep>/internal/cmd/subcmds/lint/autoDisableFlag.go package lint import ( "fmt" "github.com/yoheimuta/protolint/linter/autodisable" ) type autoDisableFlag struct { raw string autoDisableType autodisable.PlacementType } func (f *autoDisableFlag) String() string { return fmt.Sprint(f.raw) } func (f *autoDisableFlag) Set(value string) error { if f.autoDisableType != 0 { return fmt.Errorf("auto_disable is already set") } r, err := GetAutoDisableType(value) if err != nil { return err } f.raw = value f.autoDisableType = r return nil } // GetAutoDisableType returns a type from the specified key. func GetAutoDisableType(value string) (autodisable.PlacementType, error) { rs := map[string]autodisable.PlacementType{ "next": autodisable.Next, "this": autodisable.ThisThenNext, } if r, ok := rs[value]; ok { return r, nil } return autodisable.Noop, fmt.Errorf(`available auto_disable are "next" and "this"`) } <file_sep>/internal/linter/report/reporter.go package report import ( "io" "os" "github.com/yoheimuta/protolint/linter/report" ) const ( WriteToConsole string = "-" ) // Reporter is responsible to output results in the specific format. type Reporter interface { Report(io.Writer, []report.Failure) error } type ReporterWithOutput struct { reporter Reporter targetFile string } type ReportersWithOutput []ReporterWithOutput func (ro ReporterWithOutput) ReportWithFallback(w io.Writer, failures []report.Failure) error { if ro.targetFile != WriteToConsole { var err error w, err = os.OpenFile(ro.targetFile, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { return err } } return ro.reporter.Report(w, failures) } func (ros ReportersWithOutput) ReportWithFallback(w io.Writer, failures []report.Failure) error { for _, ro := range ros { err := ro.ReportWithFallback(w, failures) if err != nil { return err } } return nil } func NewReporterWithOutput(r Reporter, targetFile string) *ReporterWithOutput { return &ReporterWithOutput{r, targetFile} } <file_sep>/linter/disablerule/command.go package disablerule import ( "fmt" "regexp" "strings" ) type commandType int const ( commandDisable commandType = iota commandEnable commandDisableNext commandDisableThis ) // comment prefix const ( PrefixDisable = `protolint:disable` PrefixEnable = `protolint:enable` PrefixDisableNext = `protolint:disable:next` PrefixDisableThis = `protolint:disable:this` ) // comment prefix regexp var ( ReDisable = regexp.MustCompile(PrefixDisable + ` (.*)`) ReEnable = regexp.MustCompile(PrefixEnable + ` (.*)`) ReDisableNext = regexp.MustCompile(PrefixDisableNext + ` (.*)`) ReDisableThis = regexp.MustCompile(PrefixDisableThis + ` (.*)`) ) type command struct { ruleIDs []string t commandType } func newCommand( comment string, ) (command, error) { subs := ReDisable.FindStringSubmatch(comment) if len(subs) == 2 { ruleIDs := strings.Fields(strings.TrimSpace(subs[1])) return command{ ruleIDs: ruleIDs, t: commandDisable, }, nil } subs = ReEnable.FindStringSubmatch(comment) if len(subs) == 2 { ruleIDs := strings.Fields(strings.TrimSpace(subs[1])) return command{ ruleIDs: ruleIDs, t: commandEnable, }, nil } subs = ReDisableNext.FindStringSubmatch(comment) if len(subs) == 2 { ruleIDs := strings.Fields(strings.TrimSpace(subs[1])) return command{ ruleIDs: ruleIDs, t: commandDisableNext, }, nil } subs = ReDisableThis.FindStringSubmatch(comment) if len(subs) == 2 { ruleIDs := strings.Fields(strings.TrimSpace(subs[1])) return command{ ruleIDs: ruleIDs, t: commandDisableThis, }, nil } return command{}, fmt.Errorf("invalid disabled comments") } func (c command) enabled( ruleID string, ) bool { return c.t == commandEnable && c.matchRuleID(ruleID) } func (c command) disabled( ruleID string, ) bool { return c.t == commandDisable && c.matchRuleID(ruleID) } func (c command) disabledNext( ruleID string, ) bool { return c.t == commandDisableNext && c.matchRuleID(ruleID) } func (c command) disabledThis( ruleID string, ) bool { return c.t == commandDisableThis && c.matchRuleID(ruleID) } func (c command) matchRuleID( ruleID string, ) bool { for _, id := range c.ruleIDs { if id == ruleID { return true } } return false } <file_sep>/internal/addon/rules/fieldNamesExcludePrepositionsRule.go package rules import ( "strings" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/stringsutil" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // Default values are a conservative list picked out from all preposition candidates. // See https://www.talkenglish.com/vocabulary/top-50-prepositions.aspx var defaultPrepositions = []string{ "of", "with", "at", "from", "into", "during", "including", "until", "against", "among", "throughout", "despite", "towards", "upon", "concerning", "to", "in", "for", "on", "by", "about", } // FieldNamesExcludePrepositionsRule verifies that all field names don't include prepositions (e.g. "for", "during", "at"). // It is assumed that the field names are underscore_separated_names. // See https://cloud.google.com/apis/design/naming_convention#field_names. type FieldNamesExcludePrepositionsRule struct { RuleWithSeverity prepositions []string excludes []string } // NewFieldNamesExcludePrepositionsRule creates a new FieldNamesExcludePrepositionsRule. func NewFieldNamesExcludePrepositionsRule( severity rule.Severity, prepositions []string, excludes []string, ) FieldNamesExcludePrepositionsRule { if len(prepositions) == 0 { prepositions = defaultPrepositions } return FieldNamesExcludePrepositionsRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, prepositions: prepositions, excludes: excludes, } } // ID returns the ID of this rule. func (r FieldNamesExcludePrepositionsRule) ID() string { return "FIELD_NAMES_EXCLUDE_PREPOSITIONS" } // Purpose returns the purpose of this rule. func (r FieldNamesExcludePrepositionsRule) Purpose() string { return `Verifies that all field names don't include prepositions (e.g. "for", "during", "at").` } // IsOfficial decides whether or not this rule belongs to the official guide. func (r FieldNamesExcludePrepositionsRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r FieldNamesExcludePrepositionsRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &fieldNamesExcludePrepositionsVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), prepositions: r.prepositions, excludes: r.excludes, } return visitor.RunVisitor(v, proto, r.ID()) } type fieldNamesExcludePrepositionsVisitor struct { *visitor.BaseAddVisitor prepositions []string excludes []string } // VisitField checks the field. func (v *fieldNamesExcludePrepositionsVisitor) VisitField(field *parser.Field) bool { name := field.FieldName for _, e := range v.excludes { name = strings.Replace(name, e, "", -1) } parts := strs.SplitSnakeCaseWord(name) for _, p := range parts { if stringsutil.ContainsStringInSlice(p, v.prepositions) { v.AddFailuref(field.Meta.Pos, "Field name %q should not include a preposition %q", field.FieldName, p) } } return false } // VisitMapField checks the map field. func (v *fieldNamesExcludePrepositionsVisitor) VisitMapField(field *parser.MapField) bool { name := field.MapName for _, e := range v.excludes { name = strings.Replace(name, e, "", -1) } parts := strs.SplitSnakeCaseWord(name) for _, p := range parts { if stringsutil.ContainsStringInSlice(p, v.prepositions) { v.AddFailuref(field.Meta.Pos, "Field name %q should not include a preposition %q", field.MapName, p) } } return false } // VisitOneofField checks the oneof field. func (v *fieldNamesExcludePrepositionsVisitor) VisitOneofField(field *parser.OneofField) bool { name := field.FieldName for _, e := range v.excludes { name = strings.Replace(name, e, "", -1) } parts := strs.SplitSnakeCaseWord(name) for _, p := range parts { if stringsutil.ContainsStringInSlice(p, v.prepositions) { v.AddFailuref(field.Meta.Pos, "Field name %q should not include a preposition %q", field.FieldName, p) } } return false } <file_sep>/plugin/ruleGen.go package plugin import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) // RuleGen is a generator for a rule. It's adapted to rule.Rule interface. type RuleGen func( verbose bool, fixMode bool, ) rule.Rule // ID implements rule.Rule. func (RuleGen) ID() string { return "" } // Purpose implements rule.Rule. func (RuleGen) Purpose() string { return "" } // IsOfficial implements rule.Rule. func (RuleGen) IsOfficial() bool { return true } // Severity implements rule.Rule. func (RuleGen) Severity() rule.Severity { return rule.SeverityError } // Apply implements rule.Rule. func (RuleGen) Apply(proto *parser.Proto) ([]report.Failure, error) { return nil, nil } <file_sep>/_example/gradle/settings.gradle rootProject.name = 'gradle-demo' <file_sep>/internal/addon/rules/orderRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestOrderRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto wantFailures []report.Failure }{ { name: "no failures for proto including all elements in order", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{}, &parser.Package{}, &parser.Import{}, &parser.Import{}, &parser.Option{}, &parser.Option{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the syntax", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Package{}, &parser.Import{}, &parser.Import{}, &parser.Option{}, &parser.Option{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the package", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{}, &parser.Import{}, &parser.Import{}, &parser.Option{}, &parser.Option{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the imports", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{}, &parser.Package{}, &parser.Option{}, &parser.Option{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the options", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{}, &parser.Package{}, &parser.Import{}, &parser.Import{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the everything else", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{}, &parser.Package{}, &parser.Import{}, &parser.Import{}, &parser.Option{}, &parser.Option{}, }, }, }, { name: "no failures for proto including only the everything else", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the syntax and the package", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Import{}, &parser.Import{}, &parser.Option{}, &parser.Option{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the syntax, the package and the imports", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Option{}, &parser.Option{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "no failures for proto omitting the syntax, the package and the options", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Import{}, &parser.Import{}, &parser.Message{}, &parser.Enum{}, &parser.Service{}, &parser.Extend{}, }, }, }, { name: "failures for proto in which the order of the syntax is invalid", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Package{}, &parser.Syntax{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ORDER", `Syntax should be located at the top. Check if the file is ordered in the correct manner.`, ), }, }, { name: "failures for proto in which the order of the package is invalid", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{}, &parser.Import{}, &parser.Package{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ORDER", `The order of Package is invalid. Check if the file is ordered in the correct manner.`, ), }, }, { name: "failures for proto in which the order of the imports is invalid", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{}, &parser.Package{}, &parser.Message{}, &parser.Import{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.Import{}, &parser.Option{}, &parser.Import{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ORDER", `The order of Import is invalid. Check if the file is ordered in the correct manner.`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ORDER", `The order of Import is invalid. Check if the file is ordered in the correct manner.`, ), }, }, { name: "failures for proto in which the order of the options is invalid", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Option{}, &parser.Extend{}, &parser.Option{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.Option{}, &parser.Service{}, &parser.Option{ Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ORDER", `The order of Option is invalid. Check if the file is ordered in the correct manner.`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ORDER", `The order of Option is invalid. Check if the file is ordered in the correct manner.`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewOrderRule(rule.SeverityError, false) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestOrderRule_Apply_fix(t *testing.T) { tests := []struct { name string inputFilename string wantFilename string }{ { name: "no fix for a correct proto", inputFilename: "order.proto", wantFilename: "order.proto", }, { name: "fix for an incorrect proto", inputFilename: "invalid.proto", wantFilename: "order.proto", }, { name: "fix for an incorrect proto while keeping contiguous misc elements", inputFilename: "invalidContiguousMisc.proto", wantFilename: "orderContiguousMisc.proto", }, { name: "fix for an incorrect proto filled with many elements", inputFilename: "invalidMany.proto", wantFilename: "orderMany.proto", }, { name: "fix for an incorrect proto filled with many comments", inputFilename: "invalidWithComments.proto", wantFilename: "orderWithComments.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewOrderRule(rule.SeverityError, true) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } <file_sep>/internal/cmd/subcmds/rules.go package subcmds import ( "github.com/yoheimuta/protolint/internal/addon/plugin" "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/internal/linter/config" internalrule "github.com/yoheimuta/protolint/internal/linter/rule" "github.com/yoheimuta/protolint/linter/autodisable" ) // NewAllRules creates new all rules. func NewAllRules( option config.RulesOption, fixMode bool, autoDisableType autodisable.PlacementType, verbose bool, plugins []shared.RuleSet, ) (internalrule.Rules, error) { rs := newAllInternalRules(option, fixMode, autoDisableType) es, err := plugin.GetExternalRules(plugins, fixMode, verbose) if err != nil { return nil, err } rs = append(rs, es...) return rs, nil } func newAllInternalRules( option config.RulesOption, fixMode bool, autoDisableType autodisable.PlacementType, ) internalrule.Rules { syntaxConsistent := option.SyntaxConsistent fileNamesLowerSnakeCase := option.FileNamesLowerSnakeCase indent := option.Indent maxLineLength := option.MaxLineLength enumFieldNamesZeroValueEndWith := option.EnumFieldNamesZeroValueEndWith serviceNamesEndWith := option.ServiceNamesEndWith fieldNamesExcludePrepositions := option.FieldNamesExcludePrepositions messageNamesExcludePrepositions := option.MessageNamesExcludePrepositions messagesHaveComment := option.MessagesHaveComment servicesHaveComment := option.ServicesHaveComment rpcsHaveComment := option.RPCsHaveComment fieldsHaveComment := option.FieldsHaveComment enumsHaveComment := option.EnumsHaveComment enumFieldsHaveComment := option.EnumFieldsHaveComment repeatedFieldNamesPluralized := option.RepeatedFieldNamesPluralized return internalrule.Rules{ rules.NewFileHasCommentRule( option.FileHasComment.Severity(), ), rules.NewSyntaxConsistentRule( syntaxConsistent.Severity(), syntaxConsistent.Version, ), rules.NewFileNamesLowerSnakeCaseRule( fileNamesLowerSnakeCase.Severity(), fileNamesLowerSnakeCase.Excludes, fixMode, ), rules.NewQuoteConsistentRule( option.QuoteConsistentOption.Severity(), option.QuoteConsistentOption.Quote, fixMode, ), rules.NewOrderRule( option.Order.Severity(), fixMode, ), rules.NewIndentRule( indent.Severity(), indent.Style, indent.NotInsertNewline, fixMode, ), rules.NewMaxLineLengthRule( maxLineLength.Severity(), maxLineLength.MaxChars, maxLineLength.TabChars, ), rules.NewPackageNameLowerCaseRule( option.PackageNameLowerCase.Severity(), fixMode, ), rules.NewImportsSortedRule( option.ImportsSorted.Severity(), fixMode, ), rules.NewEnumFieldNamesPrefixRule( option.EnumFieldNamesPrefix.Severity(), fixMode, autoDisableType, ), rules.NewEnumFieldNamesUpperSnakeCaseRule( option.EnumFieldNamesUpperSnakeCase.Severity(), fixMode, autoDisableType, ), rules.NewEnumFieldNamesZeroValueEndWithRule( enumFieldNamesZeroValueEndWith.Severity(), enumFieldNamesZeroValueEndWith.Suffix, fixMode, autoDisableType, ), rules.NewEnumFieldsHaveCommentRule( enumFieldsHaveComment.Severity(), enumFieldsHaveComment.ShouldFollowGolangStyle, ), rules.NewEnumNamesUpperCamelCaseRule( option.EnumFieldNamesUpperSnakeCase.Severity(), fixMode, autoDisableType, ), rules.NewEnumsHaveCommentRule( enumsHaveComment.Severity(), enumsHaveComment.ShouldFollowGolangStyle, ), rules.NewFieldNamesLowerSnakeCaseRule( option.FieldNamesLowerSnakeCase.Severity(), fixMode, autoDisableType, ), rules.NewFieldNamesExcludePrepositionsRule( fieldNamesExcludePrepositions.Severity(), fieldNamesExcludePrepositions.Prepositions, fieldNamesExcludePrepositions.Excludes, ), rules.NewFieldsHaveCommentRule( fieldsHaveComment.Severity(), fieldsHaveComment.ShouldFollowGolangStyle, ), rules.NewProto3FieldsAvoidRequiredRule( option.Proto3FieldsAvoidRequired.Severity(), fixMode, ), rules.NewProto3GroupsAvoidRule( option.Proto3GroupsAvoid.Severity(), autoDisableType, ), rules.NewRepeatedFieldNamesPluralizedRule( repeatedFieldNamesPluralized.Severity(), repeatedFieldNamesPluralized.PluralRules, repeatedFieldNamesPluralized.SingularRules, repeatedFieldNamesPluralized.UncountableRules, repeatedFieldNamesPluralized.IrregularRules, fixMode, autoDisableType, ), rules.NewMessageNamesUpperCamelCaseRule( option.MessageNamesUpperCamelCase.Severity(), fixMode, autoDisableType, ), rules.NewMessageNamesExcludePrepositionsRule( messageNamesExcludePrepositions.Severity(), messageNamesExcludePrepositions.Prepositions, messageNamesExcludePrepositions.Excludes, ), rules.NewMessagesHaveCommentRule( messagesHaveComment.Severity(), messagesHaveComment.ShouldFollowGolangStyle, ), rules.NewRPCNamesUpperCamelCaseRule( option.RPCNamesUpperCamelCase.Severity(), fixMode, autoDisableType, ), rules.NewRPCNamesCaseRule( option.RPCNamesCaseOption.Severity(), option.RPCNamesCaseOption.Convention, ), rules.NewRPCsHaveCommentRule( rpcsHaveComment.Severity(), rpcsHaveComment.ShouldFollowGolangStyle, ), rules.NewServiceNamesUpperCamelCaseRule( option.ServiceNamesUpperCamelCase.Severity(), fixMode, autoDisableType, ), rules.NewServiceNamesEndWithRule( option.ServiceNamesEndWith.Severity(), serviceNamesEndWith.Text, ), rules.NewServicesHaveCommentRule( option.ServicesHaveComment.Severity(), servicesHaveComment.ShouldFollowGolangStyle, ), } } <file_sep>/internal/addon/plugin/shared/gRPCServer.go package shared import ( "context" "github.com/yoheimuta/protolint/internal/addon/plugin/proto" ) // GRPCServer is the implementation of RuleSet. type GRPCServer struct { proto.UnimplementedRuleSetServiceServer server RuleSet } // ListRules returns all supported rules metadata. func (s *GRPCServer) ListRules(_ context.Context, req *proto.ListRulesRequest) (*proto.ListRulesResponse, error) { return s.server.ListRules(req) } // Apply applies the rule to the proto. func (s *GRPCServer) Apply(_ context.Context, req *proto.ApplyRequest) (*proto.ApplyResponse, error) { return s.server.Apply(req) } <file_sep>/internal/util_test/pretty.go package util_test import ( "encoding/json" "fmt" ) // PrettyFormat formats any objects for test debug use. func PrettyFormat(v interface{}) string { b, err := json.MarshalIndent(v, "", " ") if err != nil { return fmt.Sprintf("orig=%v, err=%v", v, err) } return string(b) } <file_sep>/linter/visitor/baseAddVisitor.go package visitor import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/linter/report" ) // BaseAddVisitor represents a base visitor which can accumulate failures. type BaseAddVisitor struct { BaseVisitor ruleID string severity string failures []report.Failure } // NewBaseAddVisitor creates a BaseAddVisitor. func NewBaseAddVisitor(ruleID string, severity string) *BaseAddVisitor { return &BaseAddVisitor{ ruleID: ruleID, severity: severity, } } // Failures returns the accumulated failures. func (v *BaseAddVisitor) Failures() []report.Failure { return v.failures } // AddFailuref adds to the internal buffer and the formatting works like fmt.Sprintf. func (v *BaseAddVisitor) AddFailuref( pos meta.Position, format string, a ...interface{}, ) { v.failures = append(v.failures, report.FailureWithSeverityf(pos, v.ruleID, v.severity, format, a...)) } // AddFailurefWithProtoMeta adds to the internal buffer and the formatting works like fmt.Sprintf. func (v *BaseAddVisitor) AddFailurefWithProtoMeta( p *parser.ProtoMeta, format string, a ...interface{}, ) { v.AddFailuref( meta.Position{ Filename: p.Filename, Offset: 0, Line: 1, Column: 1, }, format, a..., ) } <file_sep>/internal/util_test/testFile.go package util_test import ( "io/ioutil" "strings" "github.com/yoheimuta/protolint/internal/osutil" ) // TestData is a wrapped test file. type TestData struct { FilePath string OriginData []byte } // NewTestData create a new TestData. func NewTestData( filePath string, ) (TestData, error) { data, err := ioutil.ReadFile(filePath) if err != nil { return TestData{}, nil } return TestData{ FilePath: filePath, OriginData: data, }, nil } // Data returns a content. func (d TestData) Data() ([]byte, error) { return ioutil.ReadFile(d.FilePath) } // Restore writes the original content back to the file. func (d TestData) Restore() error { newlineChar := "\n" lines := strings.Split(string(d.OriginData), newlineChar) return osutil.WriteLinesToExistingFile(d.FilePath, lines, newlineChar) } <file_sep>/linter/visitor/extendedDisableRuleVisitor.go package visitor import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/disablerule" "github.com/yoheimuta/protolint/linter/report" ) // TODO: To work `enable comments` more precisely, this implementation has to be modified. type extendedDisableRuleVisitor struct { inner HasExtendedVisitor interpreter *disablerule.Interpreter } func newExtendedDisableRuleVisitor( inner HasExtendedVisitor, ruleID string, ) extendedDisableRuleVisitor { interpreter := disablerule.NewInterpreter(ruleID) return extendedDisableRuleVisitor{ inner: inner, interpreter: interpreter, } } func (v extendedDisableRuleVisitor) OnStart(p *parser.Proto) error { return v.inner.OnStart(p) } func (v extendedDisableRuleVisitor) Finally() error { return v.inner.Finally() } func (v extendedDisableRuleVisitor) Failures() []report.Failure { return v.inner.Failures() } func (v extendedDisableRuleVisitor) VisitEmptyStatement(e *parser.EmptyStatement) (next bool) { return v.inner.VisitEmptyStatement(e) } func (v extendedDisableRuleVisitor) VisitComment(c *parser.Comment) { if v.interpreter.Interpret([]*parser.Comment{c}) { return } v.inner.VisitComment(c) } func (v extendedDisableRuleVisitor) VisitEnum(e *parser.Enum) (next bool) { if v.interpreter.Interpret(e.Comments, e.InlineComment, e.InlineCommentBehindLeftCurly) { return true } return v.inner.VisitEnum(e) } func (v extendedDisableRuleVisitor) VisitEnumField(e *parser.EnumField) (next bool) { if v.interpreter.Interpret(e.Comments, e.InlineComment) { return true } return v.inner.VisitEnumField(e) } func (v extendedDisableRuleVisitor) VisitExtend(m *parser.Extend) (next bool) { if v.interpreter.Interpret(m.Comments, m.InlineComment, m.InlineCommentBehindLeftCurly) { return true } return v.inner.VisitExtend(m) } func (v extendedDisableRuleVisitor) VisitExtensions(m *parser.Extensions) (next bool) { if v.interpreter.Interpret(m.Comments, m.InlineComment) { return true } return v.inner.VisitExtensions(m) } func (v extendedDisableRuleVisitor) VisitField(f *parser.Field) (next bool) { if v.interpreter.Interpret(f.Comments, f.InlineComment) { return true } return v.inner.VisitField(f) } func (v extendedDisableRuleVisitor) VisitGroupField(m *parser.GroupField) (next bool) { if v.interpreter.Interpret(m.Comments, m.InlineComment, m.InlineCommentBehindLeftCurly) { return true } return v.inner.VisitGroupField(m) } func (v extendedDisableRuleVisitor) VisitImport(i *parser.Import) (next bool) { if v.interpreter.Interpret(i.Comments, i.InlineComment) { return true } return v.inner.VisitImport(i) } func (v extendedDisableRuleVisitor) VisitMapField(m *parser.MapField) (next bool) { if v.interpreter.Interpret(m.Comments, m.InlineComment) { return true } return v.inner.VisitMapField(m) } func (v extendedDisableRuleVisitor) VisitMessage(m *parser.Message) (next bool) { if v.interpreter.Interpret(m.Comments, m.InlineComment, m.InlineCommentBehindLeftCurly) { return true } return v.inner.VisitMessage(m) } func (v extendedDisableRuleVisitor) VisitOneof(o *parser.Oneof) (next bool) { if v.interpreter.Interpret(o.Comments, o.InlineComment, o.InlineCommentBehindLeftCurly) { return true } return v.inner.VisitOneof(o) } func (v extendedDisableRuleVisitor) VisitOneofField(o *parser.OneofField) (next bool) { if v.interpreter.Interpret(o.Comments, o.InlineComment) { return true } return v.inner.VisitOneofField(o) } func (v extendedDisableRuleVisitor) VisitOption(o *parser.Option) (next bool) { if v.interpreter.Interpret(o.Comments, o.InlineComment) { return true } return v.inner.VisitOption(o) } func (v extendedDisableRuleVisitor) VisitPackage(p *parser.Package) (next bool) { if v.interpreter.Interpret(p.Comments, p.InlineComment) { return true } return v.inner.VisitPackage(p) } func (v extendedDisableRuleVisitor) VisitReserved(r *parser.Reserved) (next bool) { if v.interpreter.Interpret(r.Comments, r.InlineComment) { return true } return v.inner.VisitReserved(r) } func (v extendedDisableRuleVisitor) VisitRPC(r *parser.RPC) (next bool) { if v.interpreter.Interpret(r.Comments, r.InlineComment) { return true } return v.inner.VisitRPC(r) } func (v extendedDisableRuleVisitor) VisitService(s *parser.Service) (next bool) { if v.interpreter.Interpret(s.Comments, s.InlineComment, s.InlineCommentBehindLeftCurly) { return true } return v.inner.VisitService(s) } func (v extendedDisableRuleVisitor) VisitSyntax(s *parser.Syntax) (next bool) { if v.interpreter.Interpret(s.Comments, s.InlineComment) { return true } return v.inner.VisitSyntax(s) } <file_sep>/internal/addon/rules/fieldsHaveCommentRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestFieldsHaveCommentRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto inputShouldFollowGolangStyle bool wantFailures []report.Failure }{ { name: "no failures for proto without field", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{}, }, }, { name: "no failures for proto including valid fields with comments", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "FieldName", Comments: []*parser.Comment{ { Raw: "// a field name.", }, }, }, &parser.MapField{ MapName: "MapFieldName", Comments: []*parser.Comment{ { Raw: "// a map field name.", }, }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "OneofFieldName", Comments: []*parser.Comment{ { Raw: "// a oneof field name.", }, }, }, }, }, &parser.Field{ FieldName: "FieldName", InlineComment: &parser.Comment{ Raw: "// a field name.", }, }, &parser.MapField{ MapName: "MapFieldName", InlineComment: &parser.Comment{ Raw: "// a map field name.", }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "OneofFieldName", InlineComment: &parser.Comment{ Raw: "// a oneof field name.", }, }, }, }, }, }, }, }, }, { name: "no failures for proto including valid fields with Golang style comments", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "FieldName", Comments: []*parser.Comment{ { Raw: "// FieldName is a field name.", }, }, }, &parser.MapField{ MapName: "MapFieldName", Comments: []*parser.Comment{ { Raw: "// MapFieldName is a map field name.", }, }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "OneofFieldName", Comments: []*parser.Comment{ { Raw: "// OneofFieldName is a oneof field name.", }, }, }, }, }, }, }, }, }, inputShouldFollowGolangStyle: true, }, { name: "failures for proto with invalid fields", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "FieldName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 150, Line: 7, Column: 15, }, }, }, &parser.MapField{ MapName: "MapFieldName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 14, Column: 30, }, }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "OneofFieldName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, }, }, }, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 150, Line: 7, Column: 15, }, "FIELDS_HAVE_COMMENT", `Field "FieldName" should have a comment`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 14, Column: 30, }, "FIELDS_HAVE_COMMENT", `Field "MapFieldName" should have a comment`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, "FIELDS_HAVE_COMMENT", `Field "OneofFieldName" should have a comment`, ), }, }, { name: "failures for proto with invalid fields without Golang style comments", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "FieldName", Comments: []*parser.Comment{ { Raw: "// a field name.", }, }, Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 150, Line: 7, Column: 15, }, }, }, &parser.MapField{ MapName: "MapFieldName", Comments: []*parser.Comment{ { Raw: "// a map field name.", }, }, Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 14, Column: 30, }, }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "OneofFieldName", Comments: []*parser.Comment{ { Raw: "// a oneof field name.", }, }, Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, }, }, }, }, }, }, }, }, inputShouldFollowGolangStyle: true, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 150, Line: 7, Column: 15, }, "FIELDS_HAVE_COMMENT", `Field "FieldName" should have a comment of the form "// FieldName ..."`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 14, Column: 30, }, "FIELDS_HAVE_COMMENT", `Field "MapFieldName" should have a comment of the form "// MapFieldName ..."`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, "FIELDS_HAVE_COMMENT", `Field "OneofFieldName" should have a comment of the form "// OneofFieldName ..."`, ), }, }, { name: "failures for proto with fields without Golang style comments due to the inline comment", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "FieldName2", InlineComment: &parser.Comment{ Raw: "// FieldName2 is a field name.", }, }, &parser.MapField{ MapName: "MapFieldName2", InlineComment: &parser.Comment{ Raw: "// MapFieldName2 is a map field name.", }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "OneofFieldName2", InlineComment: &parser.Comment{ Raw: "// OneofFieldName2 is a oneof field name.", }, }, }, }, }, }, }, }, inputShouldFollowGolangStyle: true, wantFailures: []report.Failure{ report.Failuref( meta.Position{}, "FIELDS_HAVE_COMMENT", `Field "FieldName2" should have a comment of the form "// FieldName2 ..."`, ), report.Failuref( meta.Position{}, "FIELDS_HAVE_COMMENT", `Field "MapFieldName2" should have a comment of the form "// MapFieldName2 ..."`, ), report.Failuref( meta.Position{}, "FIELDS_HAVE_COMMENT", `Field "OneofFieldName2" should have a comment of the form "// OneofFieldName2 ..."`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewFieldsHaveCommentRule(rule.SeverityError, test.inputShouldFollowGolangStyle) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } <file_sep>/internal/linter/config/enumFieldsHaveCommentOption.go package config // EnumFieldsHaveCommentOption represents the option for the ENUM_FIELDS_HAVE_COMMENT rule. type EnumFieldsHaveCommentOption struct { CustomizableSeverityOption ShouldFollowGolangStyle bool `yaml:"should_follow_golang_style"` } <file_sep>/_example/plugin/customrules/enumNamesLowerSnakeCaseRule.go package customrules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // EnumNamesLowerSnakeCaseRule verifies that all enum names are LowerSnakeCase. type EnumNamesLowerSnakeCaseRule struct { } // NewEnumNamesLowerSnakeCaseRule creates a new EnumNamesLowerSnakeCaseRule. func NewEnumNamesLowerSnakeCaseRule() EnumNamesLowerSnakeCaseRule { return EnumNamesLowerSnakeCaseRule{} } // ID returns the ID of this rule. func (r EnumNamesLowerSnakeCaseRule) ID() string { return "ENUM_NAMES_LOWER_SNAKE_CASE" } // Purpose returns the purpose of this rule. func (r EnumNamesLowerSnakeCaseRule) Purpose() string { return "Verifies that all enum names are LowerSnakeCase." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r EnumNamesLowerSnakeCaseRule) IsOfficial() bool { return true } // Severity gets the severity of the rule func (r EnumNamesLowerSnakeCaseRule) Severity() rule.Severity { return rule.SeverityWarning } // Apply applies the rule to the proto. func (r EnumNamesLowerSnakeCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &enumNamesLowerSnakeCaseVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), } return visitor.RunVisitor(v, proto, r.ID()) } type enumNamesLowerSnakeCaseVisitor struct { *visitor.BaseAddVisitor } // VisitEnum checks the enum field. func (v *enumNamesLowerSnakeCaseVisitor) VisitEnum(e *parser.Enum) bool { if !strs.IsLowerSnakeCase(e.EnumName) { v.AddFailuref(e.Meta.Pos, "Enum name %q must be underscore_separated_names", e.EnumName) } return false } <file_sep>/internal/stringsutil/slice.go package stringsutil import "github.com/yoheimuta/protolint/internal/filepathutil" // ContainsStringInSlice searches the haystack for the needle. func ContainsStringInSlice( needle string, haystack []string, ) bool { for _, h := range haystack { if h == needle { return true } } return false } // ContainsCrossPlatformPathInSlice searches the unix path haystack for the cross-platform needle. func ContainsCrossPlatformPathInSlice( needle string, unixPathHaystack []string, ) bool { for _, h := range unixPathHaystack { if filepathutil.IsSameUnixPath(h, needle) { return true } } return false } <file_sep>/internal/linter/report/reporters/sonarReporter.go package reporters import ( "encoding/json" "io" "github.com/yoheimuta/protolint/linter/report" ) const ( protolintSonarEngineId string = "protolint" protolintSonarIssueType string = "CODE_SMELL" severityError string = "MAJOR" severityWarn string = "MINOR" severityNote string = "INFO" ) type SonarReporter struct { } // for details refer to https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/importing-external-issues/generic-issue-import-format/ type sonarTextRange struct { StartLine int `json:"startLine"` StartColumn int `json:"startColumn"` } type sonarLocation struct { Message string `json:"message"` FilePath string `json:"filePath"` TextRange sonarTextRange `json:"textRange"` } type sonarIssue struct { EngineId string `json:"engineId"` RuleId string `json:"ruleId"` PrimaryLocation sonarLocation `json:"primaryLocation"` Severity string `json:"severity"` IssueType string `json:"issueType"` } func (s SonarReporter) Report(w io.Writer, fs []report.Failure) error { var issues []sonarIssue for _, f := range fs { issue := sonarIssue{ EngineId: protolintSonarEngineId, RuleId: f.RuleID(), IssueType: protolintSonarIssueType, Severity: getSonarSeverity(f.Severity()), PrimaryLocation: sonarLocation{ Message: f.Message(), FilePath: f.Pos().Filename, TextRange: sonarTextRange{ StartLine: f.Pos().Line, StartColumn: f.Pos().Column, }, }, } issues = append(issues, issue) } bs, err := json.MarshalIndent(issues, "", " ") if err != nil { return err } _, err = w.Write(bs) if err != nil { return err } return nil } func getSonarSeverity(severity string) string { if severity == "warn" { return severityWarn } if severity == "note" { return severityNote } return severityError } <file_sep>/internal/linter/config/rules.go package config import "github.com/yoheimuta/protolint/internal/stringsutil" // Rules represents the enabled rule set. type Rules struct { NoDefault bool `yaml:"no_default"` AllDefault bool `yaml:"all_default"` Add []string `yaml:"add"` Remove []string `yaml:"remove"` } func (r Rules) shouldSkipRule( ruleID string, defaultRuleIDs []string, ) bool { var ruleIDs []string if !r.NoDefault { ruleIDs = append(ruleIDs, defaultRuleIDs...) } for _, add := range r.Add { ruleIDs = append(ruleIDs, add) } var newRuleIDs []string for _, id := range ruleIDs { if !stringsutil.ContainsStringInSlice(id, r.Remove) { newRuleIDs = append(newRuleIDs, id) } } return !stringsutil.ContainsStringInSlice(ruleID, newRuleIDs) } <file_sep>/internal/cmd/subcmds/list/cmdList.go package list import ( "fmt" "io" "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/yoheimuta/protolint/internal/linter/config" "github.com/yoheimuta/protolint/internal/cmd/subcmds" "github.com/yoheimuta/protolint/internal/osutil" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/rule" ) // CmdList is a rule list command. type CmdList struct { stdout io.Writer stderr io.Writer flags Flags } // NewCmdList creates a new CmdList. func NewCmdList( flags Flags, stdout io.Writer, stderr io.Writer, ) *CmdList { return &CmdList{ flags: flags, stdout: stdout, stderr: stderr, } } // Run lists each rule description. func (c *CmdList) Run() osutil.ExitCode { err := c.run() if err != nil { return osutil.ExitInternalFailure } return osutil.ExitSuccess } func (c *CmdList) run() error { rules, err := hasIDAndPurposes(c.flags.Plugins) if err != nil { return err } for _, r := range rules { _, err := fmt.Fprintf( c.stdout, "%s: %s\n", r.ID(), r.Purpose(), ) if err != nil { return err } } return nil } type hasIDAndPurpose interface { rule.HasID rule.HasPurpose } func hasIDAndPurposes(plugins []shared.RuleSet) ([]hasIDAndPurpose, error) { rs, err := subcmds.NewAllRules(config.RulesOption{}, false, autodisable.Noop, false, plugins) if err != nil { return nil, err } var rules []hasIDAndPurpose for _, r := range rs { rules = append(rules, r) } return rules, nil } <file_sep>/linter/report/failure.go package report import ( "fmt" "path/filepath" "strings" "github.com/yoheimuta/go-protoparser/v4/parser/meta" ) const errorLevel = "error" // Failure represents a lint error information. type Failure struct { pos meta.Position message string ruleID string severity string } // Failuref creates a new Failure and the formatting works like fmt.Sprintf. func Failuref( pos meta.Position, ruleID string, format string, a ...interface{}, ) Failure { return FailureWithSeverityf( pos, ruleID, errorLevel, format, a..., ) } // FailureWithSeverityf creates a new Failure accepting a severity level description and the formatting works like fmt.Sprintf. func FailureWithSeverityf( pos meta.Position, ruleID string, severity string, format string, a ...interface{}, ) Failure { return Failure{ pos: pos, message: fmt.Sprintf(format, a...), ruleID: ruleID, severity: severity, } } // String stringifies Failure. func (f Failure) String() string { return fmt.Sprintf("[%s] %s", f.pos, f.message) } // Message returns a raw message. func (f Failure) Message() string { return f.message } // Pos returns a raw position. func (f Failure) Pos() meta.Position { return f.pos } // RuleID returns a rule ID. func (f Failure) RuleID() string { return f.ruleID } // Severity represents the severity of a severity func (f Failure) Severity() string { return f.severity } // FilenameWithoutExt returns a filename without the extension. func (f Failure) FilenameWithoutExt() string { name := f.pos.Filename return strings.TrimSuffix(name, filepath.Ext(name)) } <file_sep>/plugin/grpcServer.go package plugin import ( "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/yoheimuta/protolint/linter/rule" "github.com/hashicorp/go-plugin" ) // RegisterCustomRules registers custom rules. func RegisterCustomRules( rules ...rule.Rule, ) { plugin.Serve( &plugin.ServeConfig{ HandshakeConfig: shared.Handshake, Plugins: map[string]plugin.Plugin{ "ruleSet": &shared.RuleSetGRPCPlugin{Impl: newRuleSet(rules)}, }, GRPCServer: plugin.DefaultGRPCServer, }, ) } <file_sep>/internal/linter/config/files.go package config import "github.com/yoheimuta/protolint/internal/stringsutil" // Files represents the target files. type Files struct { Exclude []string `yaml:"exclude"` } func (d Files) shouldSkipRule( displayPath string, ) bool { return stringsutil.ContainsCrossPlatformPathInSlice(displayPath, d.Exclude) } <file_sep>/internal/addon/plugin/externalRuleProvider.go package plugin import ( "github.com/yoheimuta/protolint/internal/addon/plugin/proto" "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/yoheimuta/protolint/linter/rule" ) // GetExternalRules provides the external rules. func GetExternalRules( clients []shared.RuleSet, fixMode bool, verbose bool, ) ([]rule.Rule, error) { var rs []rule.Rule for _, client := range clients { resp, err := client.ListRules(&proto.ListRulesRequest{ Verbose: verbose, FixMode: fixMode, }) if err != nil { return nil, err } for _, r := range resp.Rules { severity := getSeverity(r.Severity) rs = append(rs, newExternalRule(r.Id, r.Purpose, client, severity)) } } return rs, nil } func getSeverity(ruleSeverity proto.RuleSeverity) rule.Severity { switch ruleSeverity { case proto.RuleSeverity_RULE_SEVERITY_ERROR: return rule.SeverityError case proto.RuleSeverity_RULE_SEVERITY_WARNING: return rule.SeverityWarning case proto.RuleSeverity_RULE_SEVERITY_NOTE: return rule.SeverityNote } return rule.SeverityError } <file_sep>/internal/cmd/subcmds/lint/cmdLintConfig.go package lint import ( "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/yoheimuta/protolint/internal/cmd/subcmds" "github.com/yoheimuta/protolint/internal/linter/config" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/linter/report" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/rule" ) // CmdLintConfig is a config for lint command. type CmdLintConfig struct { external config.ExternalConfig fixMode bool autoDisableType autodisable.PlacementType verbose bool reporters report.ReportersWithOutput plugins []shared.RuleSet } // NewCmdLintConfig creates a new CmdLintConfig. func NewCmdLintConfig( externalConfig config.ExternalConfig, flags Flags, ) CmdLintConfig { output := report.WriteToConsole if 0 < len(flags.OutputFilePath) { output = flags.OutputFilePath } var reporters report.ReportersWithOutput reporters = append(reporters, *report.NewReporterWithOutput(flags.Reporter, output)) for _, additionalReporter := range flags.AdditionalReporters { r := *report.NewReporterWithOutput(additionalReporter.reporter, additionalReporter.targetFile) reporters = append(reporters, r) } return CmdLintConfig{ external: externalConfig, fixMode: flags.FixMode, autoDisableType: flags.AutoDisableType, verbose: flags.Verbose, reporters: reporters, plugins: flags.Plugins, } } // GenRules generates rules which are applied to the filename path. func (c CmdLintConfig) GenRules( f file.ProtoFile, ) ([]rule.HasApply, error) { allRules, err := subcmds.NewAllRules(c.external.Lint.RulesOption, c.fixMode, c.autoDisableType, c.verbose, c.plugins) if err != nil { return nil, err } var defaultRuleIDs []string if c.external.Lint.Rules.AllDefault { defaultRuleIDs = allRules.IDs() } else { defaultRuleIDs = allRules.Default().IDs() } var hasApplies []rule.HasApply for _, r := range allRules { if c.external.ShouldSkipRule(r.ID(), f.DisplayPath(), defaultRuleIDs) { continue } hasApplies = append(hasApplies, r) } return hasApplies, nil } <file_sep>/linter/strs/strs.go // Package strs contains common string manipulation functionality. package strs import ( "strings" "unicode" "unicode/utf8" ) // IsUpperCamelCase returns true if s is not empty and is camel case with an initial capital. func IsUpperCamelCase(s string) bool { if !isCapitalized(s) { return false } return isCamelCase(s) } // IsLowerCamelCase returns true if s is not empty and is camel case without an initial capital. func IsLowerCamelCase(s string) bool { if isCapitalized(s) { return false } return isCamelCase(s) } // IsUpperSnakeCase returns true if s only contains uppercase letters, // digits, and/or underscores. s MUST NOT begin or end with an underscore. func IsUpperSnakeCase(s string) bool { if s == "" || s[0] == '_' || s[len(s)-1] == '_' { return false } for _, r := range s { if !(isUpper(r) || isDigit(r) || r == '_') { return false } } return true } // IsLowerSnakeCase returns true if s only contains lowercase letters, // digits, and/or underscores. s MUST NOT begin or end with an underscore. func IsLowerSnakeCase(s string) bool { if s == "" || s[0] == '_' || s[len(s)-1] == '_' { return false } for _, r := range s { if !(isLower(r) || isDigit(r) || r == '_') { return false } } return true } // isCapitalized returns true if is not empty and the first letter is // an uppercase character. func isCapitalized(s string) bool { if s == "" { return false } r, _ := utf8.DecodeRuneInString(s) return isUpper(r) } // isCamelCase returns false if s is empty or contains any character that is // not between 'A' and 'Z', 'a' and 'z', '0' and '9', or in extraRunes. // It does not care about lowercase or uppercase. func isCamelCase(s string) bool { if s == "" { return false } for _, c := range s { if !(isLetter(c) || isDigit(c)) { return false } } return true } // isSnake returns true if s only contains letters, digits, and/or underscores. // s MUST NOT begin or end with an underscore. func isSnake(s string) bool { if s == "" || s[0] == '_' || s[len(s)-1] == '_' { return false } for _, r := range s { if !(isLetter(r) || isDigit(r) || r == '_') { return false } } return true } // HasAnyUpperCase returns true if s contains any of characters in the range A-Z. func HasAnyUpperCase(s string) bool { for _, r := range s { if isUpper(r) { return true } } return false } // ToUpperSnakeCase converts s to UPPER_SNAKE_CASE. func ToUpperSnakeCase(s string) string { ws := SplitCamelCaseWord(s) if ws == nil { ws = []string{s} } return strings.ToUpper( strings.Join(ws, "_"), ) } // ToLowerSnakeCase converts s to lower_snake_case. func ToLowerSnakeCase(s string) string { ws := SplitCamelCaseWord(s) if ws == nil { ws = []string{s} } return strings.ToLower( strings.Join(ws, "_"), ) } // ToUpperCamelCase converts s to UpperCamelCase. func ToUpperCamelCase(s string) string { if IsUpperSnakeCase(s) { s = strings.ToLower(s) } var output string for _, w := range SplitSnakeCaseWord(s) { output += strings.Title(w) } return output } // ToLowerCamelCase converts s to lowerCamelCase. func ToLowerCamelCase(s string) string { var output string for i, r := range ToUpperCamelCase(s) { if i == 0 { output += string(unicode.ToLower(r)) } else { output += string(r) } } return output } // toSnake converts s to snake_case. func toSnake(s string) string { output := "" s = strings.TrimSpace(s) priorLower := false for _, c := range s { if priorLower && isUpper(c) { output += "_" } output += string(c) priorLower = isLower(c) } return output } // SplitCamelCaseWord splits a CamelCase word into its parts. // // If s is empty, returns nil. // If s is not CamelCase, returns nil. func SplitCamelCaseWord(s string) []string { if s == "" { return nil } s = strings.TrimSpace(s) if !isCamelCase(s) { return nil } return SplitSnakeCaseWord(toSnake(s)) } // SplitSnakeCaseWord splits a snake_case word into its parts. // // If s is empty, returns nil. // If s is not snake_case, returns nil. func SplitSnakeCaseWord(s string) []string { if s == "" { return nil } s = strings.TrimSpace(s) if !isSnake(s) { return nil } return strings.Split(s, "_") } func isLetter(r rune) bool { return isUpper(r) || isLower(r) } func isLower(r rune) bool { return 'a' <= r && r <= 'z' } func isUpper(r rune) bool { return 'A' <= r && r <= 'Z' } func isDigit(r rune) bool { return '0' <= r && r <= '9' } <file_sep>/cmd/protolint/main.go package main import ( "os" "github.com/yoheimuta/protolint/internal/cmd" ) func main() { os.Exit(int( cmd.Do( os.Args[1:], os.Stdout, os.Stderr, ), )) } <file_sep>/internal/cmd/subcmds/lint/reporterFlag.go package lint import ( "fmt" "strings" "github.com/yoheimuta/protolint/internal/linter/report" "github.com/yoheimuta/protolint/internal/linter/report/reporters" ) type reporterFlag struct { raw string reporter report.Reporter } type reporterStreamFlag struct { reporterFlag targetFile string } type reporterStreamFlags []reporterStreamFlag func (f *reporterStreamFlag) String() string { return fmt.Sprint(f.raw) } func (f *reporterStreamFlag) Set(value string) error { if f.reporter != nil { return fmt.Errorf("reporter is already set") } valueSplit := strings.SplitN(value, ":", 2) if len(valueSplit) != 2 { return fmt.Errorf("cannot find output file in %s", value) } reporterName := valueSplit[0] outputFile := valueSplit[1] r, err := GetReporter(reporterName) if err != nil { return err } f.raw = value f.reporter = r f.targetFile = outputFile return nil } func (fs *reporterStreamFlags) String() string { var items []string for _, flag := range *fs { items = append(items, flag.String()) } return strings.Join(items, " ") } func (fs *reporterStreamFlags) Set(value string) error { var r reporterStreamFlag err := r.Set(value) if err != nil { return err } *fs = append(*fs, r) return nil } func (f *reporterFlag) String() string { return fmt.Sprint(f.raw) } func (f *reporterFlag) Set(value string) error { if f.reporter != nil { return fmt.Errorf("reporter is already set") } r, err := GetReporter(value) if err != nil { return err } f.raw = value f.reporter = r return nil } // GetReporter returns a reporter from the specified key. func GetReporter(value string) (report.Reporter, error) { rs := map[string]report.Reporter{ "plain": reporters.PlainReporter{}, "junit": reporters.JUnitReporter{}, "unix": reporters.UnixReporter{}, "json": reporters.JSONReporter{}, "sarif": reporters.SarifReporter{}, "sonar": reporters.SonarReporter{}, "ci": reporters.NewCiReporterWithGenericFormat(), "ci-az": reporters.NewCiReporterForAzureDevOps(), "ci-gh": reporters.NewCiReporterForGithubActions(), "ci-glab": reporters.NewCiReporterForGitlab(), "ci-env": reporters.NewCiReporterFromEnv(), } if r, ok := rs[value]; ok { return r, nil } return nil, fmt.Errorf(`available reporters are "plain", "junit", "json", "sarif", and "unix, available reporters for CI/CD are ci, ci-az, ci-gh, ci-glab"`) } <file_sep>/linter/disablerule/commands.go package disablerule import ( "github.com/yoheimuta/go-protoparser/v4/parser" ) type commands []command func newCommands( comments []*parser.Comment, ) commands { var cmds []command for _, comment := range comments { if comment == nil { continue } cmd, err := newCommand(comment.Raw) if err == nil { cmds = append(cmds, cmd) } } return cmds } func (cs commands) enabled( ruleID string, ) bool { for _, cmd := range cs { if cmd.enabled(ruleID) { return true } } return false } func (cs commands) disabled( ruleID string, ) bool { for _, cmd := range cs { if cmd.disabled(ruleID) { return true } } return false } func (cs commands) disabledNext( ruleID string, ) bool { for _, cmd := range cs { if cmd.disabledNext(ruleID) { return true } } return false } func (cs commands) disabledThis( ruleID string, ) bool { for _, cmd := range cs { if cmd.disabledThis(ruleID) { return true } } return false } <file_sep>/linter/autodisable/thisThenNextPlacementStrategy.go package autodisable import "github.com/yoheimuta/go-protoparser/v4/parser" type thisThenNextPlacementStrategy struct { c *commentator } func newThisThenNextPlacementStrategy(c *commentator) *thisThenNextPlacementStrategy { return &thisThenNextPlacementStrategy{ c: c, } } func (p *thisThenNextPlacementStrategy) Disable( offset int, comments []*parser.Comment, inline *parser.Comment) { if inline == nil { p.c.insertInline(offset) return } if p.c.tryMergeInline(inline) { return } p.c.insertNewline(offset) } func (p *thisThenNextPlacementStrategy) Finalize() error { return p.c.finalize() } <file_sep>/linter/strs/pluralize_test.go package strs_test import ( "testing" "github.com/yoheimuta/protolint/linter/strs" ) func TestPluralizeClient_ToPlural(t *testing.T) { tests := []struct { name string word string pluralizedWord string }{ {"PluralizeNormalSingularWord", "car", "cars"}, {"PluralizeSingularWord", "person", "people"}, {"PluralizePluralWord", "people", "people"}, {"PluralizeNonstandardPluralWord", "persons", "people"}, {"PluralizeNoPluralFormWord", "moose", "moose"}, {"PluralizePluralLatinWord", "cacti", "cacti"}, {"PluralizeNonstandardPluralLatinWord", "cactuses", "cacti"}, {"PluralizePluralCamelCaseWord", "office_chairs", "office_chairs"}, {"PluralizeSingularCamelCaseWord", "office_chair", "office_chairs"}, {"special case #312: appends s to uri", "uri", "uris"}, {"special case #312: appends s to module_uri", "module_uri", "module_uris"}, {"special case #312: not change uris", "uris", "uris"}, {"special case #312: not change module_uris", "module_uris", "module_uris"}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { c := strs.NewPluralizeClient() if got := c.ToPlural(test.word); got != test.pluralizedWord { t.Errorf("Plural(%s) got %s, but want %s", test.word, got, test.pluralizedWord) } }) } } func TestPluralizeClient_AddPluralRule(t *testing.T) { tests := []struct { name string word string pluralizedWord string rule string replacement string }{ { name: "normal conversion", word: "regex", pluralizedWord: "regexes", }, { name: "special conversion after adding manually", word: "regex", pluralizedWord: "regexii", rule: "(?i)gex$", replacement: "gexii", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { c := strs.NewPluralizeClient() if 0 < len(test.rule) { c.AddPluralRule(test.rule, test.replacement) } if got := c.ToPlural(test.word); got != test.pluralizedWord { t.Errorf("Plural(%s) got %s, but want %s", test.word, got, test.pluralizedWord) } }) } } func TestPluralizeClient_AddSingularRule(t *testing.T) { tests := []struct { name string word string pluralizedWord string rule string replacement string }{ { name: "normal conversion", word: "singles", pluralizedWord: "singles", }, { name: "special conversion after adding manually", word: "singles", pluralizedWord: "singulars", rule: "(?i)singles$", replacement: "singular", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { c := strs.NewPluralizeClient() if 0 < len(test.rule) { c.AddSingularRule(test.rule, test.replacement) } if got := c.ToPlural(test.word); got != test.pluralizedWord { t.Errorf("Singular(%s) got %s, but want %s", test.word, got, test.pluralizedWord) } }) } } <file_sep>/internal/addon/rules/fieldNamesExcludePrepositionsRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestFieldNamesExcludePrepositionsRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto inputPrepositions []string inputExcludes []string wantFailures []report.Failure }{ { name: "no failures for proto without fields", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Enum{}, }, }, }, { name: "no failures for proto with valid field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "error_reason", }, &parser.Field{ FieldName: "failure_time_cpu_usage", }, &parser.MapField{ MapName: "song_name2", }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "song_name3", }, }, }, }, }, }, }, }, { name: "failures for proto with invalid field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "reason_for_error", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.Field{ FieldName: "cpu_usage_at_time_of_failure", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, &parser.MapField{ MapName: "name_of_song", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 210, Line: 14, Column: 30, }, }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "name_of_song2", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, }, }, }, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "FIELD_NAMES_EXCLUDE_PREPOSITIONS", `Field name "reason_for_error" should not include a preposition "for"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "FIELD_NAMES_EXCLUDE_PREPOSITIONS", `Field name "cpu_usage_at_time_of_failure" should not include a preposition "at"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "FIELD_NAMES_EXCLUDE_PREPOSITIONS", `Field name "cpu_usage_at_time_of_failure" should not include a preposition "of"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 210, Line: 14, Column: 30, }, "FIELD_NAMES_EXCLUDE_PREPOSITIONS", `Field name "name_of_song" should not include a preposition "of"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, "FIELD_NAMES_EXCLUDE_PREPOSITIONS", `Field name "name_of_song2" should not include a preposition "of"`, ), }, }, { name: "failures for proto with invalid field names, but field name including the excluded keyword is no problem", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "end_of_support_version", }, &parser.MapField{ MapName: "end_of_support_version", }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "end_of_support_version", }, }, }, &parser.Field{ FieldName: "version_of_support_end", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, }, }, }, }, inputExcludes: []string{ "end_of_support", }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "FIELD_NAMES_EXCLUDE_PREPOSITIONS", `Field name "version_of_support_end" should not include a preposition "of"`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewFieldNamesExcludePrepositionsRule(rule.SeverityError, test.inputPrepositions, test.inputExcludes) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } <file_sep>/internal/addon/rules/rpcNamesCaseRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/protolint/internal/linter/config" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestRPCNamesCaseRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto inputConvention config.ConventionType wantFailures []report.Failure }{ { name: "no failures for proto without rpc", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, }, }, inputConvention: config.ConventionLowerCamel, }, { name: "no failures for proto with valid rpc", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceBody: []parser.Visitee{ &parser.RPC{ RPCName: "rpcName", }, }, }, }, }, inputConvention: config.ConventionLowerCamel, }, { name: "no failures for proto with valid rpc", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceBody: []parser.Visitee{ &parser.RPC{ RPCName: "RPC_NAME", }, }, }, }, }, inputConvention: config.ConventionUpperSnake, }, { name: "no failures for proto with valid rpc", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceBody: []parser.Visitee{ &parser.RPC{ RPCName: "rpc_name", }, }, }, }, }, inputConvention: config.ConventionLowerSnake, }, { name: "failures for proto with the option of LowerCamelCase", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceBody: []parser.Visitee{ &parser.RPC{ RPCName: "RPCName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.RPC{ RPCName: "RPC_NAME", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, &parser.RPC{ RPCName: "rpc_name", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 30, }, }, }, }, }, }, }, inputConvention: config.ConventionLowerCamel, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "RPC_NAMES_CASE", `RPC name "RPCName" must be LowerCamelCase`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "RPC_NAMES_CASE", `RPC name "RPC_NAME" must be LowerCamelCase`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 30, }, "RPC_NAMES_CASE", `RPC name "rpc_name" must be LowerCamelCase`, ), }, }, { name: "failures for proto with the option of UpperSnakeCase", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceBody: []parser.Visitee{ &parser.RPC{ RPCName: "RPCName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.RPC{ RPCName: "rpcName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, &parser.RPC{ RPCName: "rpc_name", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 30, }, }, }, }, }, }, }, inputConvention: config.ConventionUpperSnake, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "RPC_NAMES_CASE", `RPC name "RPCName" must be UpperSnakeCase`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "RPC_NAMES_CASE", `RPC name "rpcName" must be UpperSnakeCase`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 30, }, "RPC_NAMES_CASE", `RPC name "rpc_name" must be UpperSnakeCase`, ), }, }, { name: "failures for proto with the option of LowerSnakeCase", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceBody: []parser.Visitee{ &parser.RPC{ RPCName: "RPCName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.RPC{ RPCName: "rpcName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, &parser.RPC{ RPCName: "RPC_NAME", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 30, }, }, }, }, }, }, }, inputConvention: config.ConventionLowerSnake, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "RPC_NAMES_CASE", `RPC name "RPCName" must be LowerSnakeCase`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "RPC_NAMES_CASE", `RPC name "rpcName" must be LowerSnakeCase`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 30, }, "RPC_NAMES_CASE", `RPC name "RPC_NAME" must be LowerSnakeCase`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewRPCNamesCaseRule(rule.SeverityError, test.inputConvention) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } <file_sep>/internal/addon/rules/base_test.go package rules_test import ( "testing" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/rule" ) func TestRulesWithSeverityHasSeverity(t *testing.T) { tests := []rule.Severity{ rule.SeverityNote, rule.SeverityWarning, rule.SeverityError, } for _, test := range tests { test := test t.Run(string(test), func(t *testing.T) { var rule_to_test rule.HasSeverity rule_to_test = rules.NewRuleWithSeverity(test) if rule_to_test.Severity() != test { t.Errorf("Rule should have %v severity, but got %v", test, rule_to_test.Severity()) } }) } } <file_sep>/_example/gradle/build.gradle plugins { id 'java' id 'com.google.protobuf' version '0.8.18' } protobuf { protoc { artifact = "com.google.protobuf:protoc:3.19.4" } plugins { protolint { artifact = "io.github.yoheimuta:protoc-gen-protolint:0.43.2" } } generateProtoTasks { all().each { task -> task.plugins { protolint { option 'proto_root=src/main/proto' option 'output_file=build/generated/source/proto/main/protolint/results.txt' } } } } } repositories { mavenCentral() } <file_sep>/_example/plugin/README.md # Plugin Example ### Build ```bash go build -o plugin_example main.go ``` NOTE: protolint plugin is backed by [hashicorp/go-plugin](https://github.com/hashicorp/go-plugin), not the [plugin](https://golang.org/pkg/plugin/) standard library. Therefore, you can build the plugin just as a normal Go main package. ### Run ```bash protolint -plugin ./plugin_example /path/to/files # Or you can pass some flags to your plugin: protolint -plugin "./plugin_example -go_style=false" /path/to/files # You can see that your plugin is loaded correctly. protolint list -plugin ./plugin_example ``` NOTE: `sh` must be in your PATH. NOTE2: Even when you specify the plugin, the configuration defined in `.protolint.yaml` can stop your plugin from working. Check the yaml when your plugin doesn't appear to be working. See https://github.com/yoheimuta/protolint/issues/260 in detail. <file_sep>/internal/linter/config/importsSortedOption.go package config import ( "fmt" ) // ImportsSortedOption represents the option for the IMPORTS_SORTED rule. type ImportsSortedOption struct { CustomizableSeverityOption // Deprecated: not used Newline string } // UnmarshalYAML implements yaml.v2 Unmarshaler interface. func (i *ImportsSortedOption) UnmarshalYAML(unmarshal func(interface{}) error) error { var option struct { Newline string `yaml:"newline"` } if err := unmarshal(&option); err != nil { return err } switch option.Newline { case "\n", "\r", "\r\n", "": i.Newline = option.Newline default: return fmt.Errorf(`%s is an invalid newline option. valid option is \n, \r or \r\n`, option.Newline) } return nil } <file_sep>/internal/linter/config/customizableSeverityOption.go package config import "github.com/yoheimuta/protolint/linter/rule" // CustomizableSeverityOption represents an option where the // severity of a rule can be configured via yaml. type CustomizableSeverityOption struct { severity *rule.Severity `yaml:"severity"` } // Severity returns the configured severity. If no severity // is set, the default severity will be ERROR func (c CustomizableSeverityOption) Severity() rule.Severity { if c.severity == nil { return rule.SeverityError } return *c.severity } <file_sep>/internal/addon/rules/maxLineLengthRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestMaxLineLengthRule_Apply(t *testing.T) { tests := []struct { name string inputMaxChars int inputTabChars int inputProto *parser.Proto wantFailures []report.Failure wantExistErr bool }{ { name: "not found proto file", inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: "", }, }, wantExistErr: true, }, { name: "not found long lines", inputMaxChars: 120, inputTabChars: 4, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: setting_test.TestDataPath("rules", "max_line_length_rule.proto"), }, }, }, { name: "found long lines", inputTabChars: 4, inputProto: &parser.Proto{ Meta: &parser.ProtoMeta{ Filename: setting_test.TestDataPath("rules", "max_line_length_rule.proto"), }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "max_line_length_rule.proto"), Line: 3, Column: 1, }, "MAX_LINE_LENGTH", `The line length is 91, but it must be shorter than 80`, ), report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "max_line_length_rule.proto"), Line: 15, Column: 1, }, "MAX_LINE_LENGTH", `The line length is 88, but it must be shorter than 80`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewMaxLineLengthRule( rule.SeverityError, test.inputMaxChars, test.inputTabChars, ) got, err := rule.Apply(test.inputProto) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } <file_sep>/internal/addon/rules/messagesHaveCommentRule.go package rules import ( "fmt" "strings" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // MessagesHaveCommentRule verifies that all messages have a comment. type MessagesHaveCommentRule struct { RuleWithSeverity // Golang style comments should begin with the name of the thing being described. // See https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences shouldFollowGolangStyle bool } // NewMessagesHaveCommentRule creates a new MessagesHaveCommentRule. func NewMessagesHaveCommentRule( severity rule.Severity, shouldFollowGolangStyle bool, ) MessagesHaveCommentRule { return MessagesHaveCommentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, shouldFollowGolangStyle: shouldFollowGolangStyle, } } // ID returns the ID of this rule. func (r MessagesHaveCommentRule) ID() string { return "MESSAGES_HAVE_COMMENT" } // Purpose returns the purpose of this rule. func (r MessagesHaveCommentRule) Purpose() string { return "Verifies that all messages have a comment." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r MessagesHaveCommentRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r MessagesHaveCommentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &messagesHaveCommentVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), shouldFollowGolangStyle: r.shouldFollowGolangStyle, } return visitor.RunVisitor(v, proto, r.ID()) } type messagesHaveCommentVisitor struct { *visitor.BaseAddVisitor shouldFollowGolangStyle bool } // VisitMessage checks the message. func (v *messagesHaveCommentVisitor) VisitMessage(message *parser.Message) bool { n := message.MessageName if v.shouldFollowGolangStyle && !hasGolangStyleComment(message.Comments, n) { v.AddFailuref(message.Meta.Pos, `Message %q should have a comment of the form "// %s ..."`, n, n) } else if !hasComments(message.Comments, message.InlineComment, message.InlineCommentBehindLeftCurly) { v.AddFailuref(message.Meta.Pos, `Message %q should have a comment`, n) } return true } func hasGolangStyleComment( comments []*parser.Comment, describedName string, ) bool { return hasComment(comments) && strings.HasPrefix(comments[0].Lines()[0], fmt.Sprintf(" %s", describedName)) } func hasComment(comments []*parser.Comment) bool { return 0 < len(comments) } func hasComments(comments []*parser.Comment, inlines ...*parser.Comment) bool { if 0 < len(comments) { return true } for _, inline := range inlines { if inline != nil { return true } } return false } <file_sep>/internal/linter/report/reporters/jsonReporter_test.go package reporters_test import ( "bytes" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/linter/report/reporters" "github.com/yoheimuta/protolint/linter/report" ) func TestJSONReporter_Report(t *testing.T) { tests := []struct { name string inputFailures []report.Failure wantOutput string }{ { name: "Prints failures in JSON format", inputFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ENUM_NAMES_UPPER_CAMEL_CASE", `EnumField name "fIRST_VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ENUM_NAMES_UPPER_CAMEL_CASE", `EnumField name "SECOND.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), }, wantOutput: `{ "lints": [ { "filename": "example.proto", "line": 5, "column": 10, "message": "EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES", "rule": "ENUM_NAMES_UPPER_CAMEL_CASE" }, { "filename": "example.proto", "line": 10, "column": 20, "message": "EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES", "rule": "ENUM_NAMES_UPPER_CAMEL_CASE" } ] } `, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { buf := &bytes.Buffer{} err := reporters.JSONReporter{}.Report(buf, test.inputFailures) if err != nil { t.Errorf("got err %v, but want nil", err) return } if buf.String() != test.wantOutput { t.Errorf("got %s, but want %s", buf.String(), test.wantOutput) } }) } } <file_sep>/linter/visitor/extendedAutoDisableVisitor.go package visitor import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/report" ) type extendedAutoDisableVisitor struct { inner HasExtendedVisitor automator autodisable.PlacementStrategy } func newExtendedAutoDisableVisitor( inner HasExtendedVisitor, ruleID string, protoFilename string, placementType autodisable.PlacementType, ) (*extendedAutoDisableVisitor, error) { automator, err := autodisable.NewPlacementStrategy(placementType, protoFilename, ruleID) if err != nil { return nil, err } return &extendedAutoDisableVisitor{ inner: inner, automator: automator, }, nil } func (v *extendedAutoDisableVisitor) OnStart(p *parser.Proto) error { return v.inner.OnStart(p) } func (v *extendedAutoDisableVisitor) Finally() error { err := v.automator.Finalize() if err != nil { return err } return v.inner.Finally() } func (v *extendedAutoDisableVisitor) Failures() []report.Failure { return v.inner.Failures() } func (v *extendedAutoDisableVisitor) VisitEmptyStatement(e *parser.EmptyStatement) (next bool) { return v.inner.VisitEmptyStatement(e) } func (v *extendedAutoDisableVisitor) VisitComment(c *parser.Comment) { v.inner.VisitComment(c) } func (v *extendedAutoDisableVisitor) VisitEnum(e *parser.Enum) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitEnum(e) }, func(offset int) { v.automator.Disable(offset, e.Comments, e.InlineCommentBehindLeftCurly) }) } func (v *extendedAutoDisableVisitor) VisitEnumField(e *parser.EnumField) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitEnumField(e) }, func(offset int) { v.automator.Disable(offset, e.Comments, e.InlineComment) }) } func (v *extendedAutoDisableVisitor) VisitExtend(m *parser.Extend) (next bool) { return v.inner.VisitExtend(m) } func (v *extendedAutoDisableVisitor) VisitExtensions(m *parser.Extensions) (next bool) { return v.inner.VisitExtensions(m) } func (v *extendedAutoDisableVisitor) VisitField(f *parser.Field) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitField(f) }, func(offset int) { v.automator.Disable(offset, f.Comments, f.InlineComment) }) } func (v *extendedAutoDisableVisitor) VisitGroupField(m *parser.GroupField) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitGroupField(m) }, func(offset int) { v.automator.Disable(offset, m.Comments, m.InlineComment) }) } func (v *extendedAutoDisableVisitor) VisitImport(i *parser.Import) (next bool) { return v.inner.VisitImport(i) } func (v *extendedAutoDisableVisitor) VisitMapField(m *parser.MapField) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitMapField(m) }, func(offset int) { v.automator.Disable(offset, m.Comments, m.InlineComment) }) } func (v *extendedAutoDisableVisitor) VisitMessage(m *parser.Message) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitMessage(m) }, func(offset int) { v.automator.Disable(offset, m.Comments, m.InlineCommentBehindLeftCurly) }) } func (v *extendedAutoDisableVisitor) VisitOneof(o *parser.Oneof) (next bool) { return v.inner.VisitOneof(o) } func (v *extendedAutoDisableVisitor) VisitOneofField(o *parser.OneofField) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitOneofField(o) }, func(offset int) { v.automator.Disable(offset, o.Comments, o.InlineComment) }) } func (v *extendedAutoDisableVisitor) VisitOption(o *parser.Option) (next bool) { return v.inner.VisitOption(o) } func (v *extendedAutoDisableVisitor) VisitPackage(p *parser.Package) (next bool) { return v.inner.VisitPackage(p) } func (v *extendedAutoDisableVisitor) VisitReserved(r *parser.Reserved) (next bool) { return v.inner.VisitReserved(r) } func (v *extendedAutoDisableVisitor) VisitRPC(r *parser.RPC) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitRPC(r) }, func(offset int) { v.automator.Disable(offset, r.Comments, r.InlineComment) }) } func (v *extendedAutoDisableVisitor) VisitService(s *parser.Service) (next bool) { return v.doIfFailure(func() bool { return v.inner.VisitService(s) }, func(offset int) { v.automator.Disable(offset, s.Comments, s.InlineCommentBehindLeftCurly) }) } func (v *extendedAutoDisableVisitor) VisitSyntax(s *parser.Syntax) (next bool) { return v.inner.VisitSyntax(s) } func (v *extendedAutoDisableVisitor) doIfFailure( visit func() bool, disable func(int), ) bool { prev := v.inner.Failures() next := visit() curr := v.inner.Failures() if len(prev) == len(curr) { return next } disable(curr[len(curr)-1].Pos().Offset) return next } <file_sep>/internal/addon/plugin/externalRule.go package plugin import ( "path/filepath" "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/addon/plugin/proto" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) // externalRule represents a customized rule that works as a plugin. type externalRule struct { id string purpose string client shared.RuleSet severity rule.Severity } func newExternalRule( id string, purpose string, client shared.RuleSet, severity rule.Severity, ) externalRule { return externalRule{ id: id, purpose: purpose, client: client, severity: severity, } } // ID returns the ID of this rule. func (r externalRule) ID() string { return r.id } // Purpose returns the purpose of this rule. func (r externalRule) Purpose() string { return r.purpose } // IsOfficial decides whether or not this rule belongs to the official guide. func (r externalRule) IsOfficial() bool { return true } // Severity returns the severity of a rule (note, warning, error) func (r externalRule) Severity() rule.Severity { return r.severity } // Apply applies the rule to the proto. func (r externalRule) Apply(p *parser.Proto) ([]report.Failure, error) { relPath := p.Meta.Filename absPath, err := filepath.Abs(relPath) if err != nil { return nil, err } resp, err := r.client.Apply(&proto.ApplyRequest{ Id: r.id, Path: absPath, }) if err != nil { return nil, err } var fs []report.Failure for _, f := range resp.Failures { fs = append(fs, report.FailureWithSeverityf(meta.Position{ Filename: relPath, Offset: int(f.Pos.Offset), Line: int(f.Pos.Line), Column: int(f.Pos.Column), }, r.id, string(r.severity), f.Message)) } return fs, nil } <file_sep>/internal/addon/plugin/shared/ruleSet.go package shared import "github.com/yoheimuta/protolint/internal/addon/plugin/proto" // RuleSet is the interface that we're exposing as a plugin. type RuleSet interface { ListRules(*proto.ListRulesRequest) (*proto.ListRulesResponse, error) Apply(*proto.ApplyRequest) (*proto.ApplyResponse, error) } <file_sep>/linter/disablerule/interpreter.go package disablerule import "github.com/yoheimuta/go-protoparser/v4/parser" // Interpreter represents an interpreter for disable rule comments. type Interpreter struct { ruleID string isDisabled bool } // NewInterpreter creates an Interpreter. func NewInterpreter( ruleID string, ) *Interpreter { return &Interpreter{ ruleID: ruleID, } } // Interpret interprets comments and returns a bool whether not apply the rule to a next or this element. func (i *Interpreter) Interpret( comments []*parser.Comment, inlines ...*parser.Comment, ) (isDisabled bool) { cmds := newCommands(comments) inlineCmds := newCommands(inlines) allCmds := append(append([]command{}, cmds...), inlineCmds...) return i.interpret(allCmds) || i.interpretNext(cmds) || i.interpretThis(inlineCmds) || i.isDisabled } // CallEachIfValid calls a given function each time the line is not disabled. func (i *Interpreter) CallEachIfValid( lines []string, f func(index int, line string), ) { shouldSkip := false for index, line := range lines { cmd, err := newCommand(line) if err != nil { if !i.isDisabled && !shouldSkip { f(index, line) } if shouldSkip { shouldSkip = false } continue } if cmd.enabled(i.ruleID) { i.isDisabled = false f(index, line) continue } if cmd.disabled(i.ruleID) { i.isDisabled = true continue } if cmd.disabledThis(i.ruleID) { continue } if cmd.disabledNext(i.ruleID) { shouldSkip = true f(index, line) continue } if shouldSkip { shouldSkip = false continue } f(index, line) } } func (i *Interpreter) interpret( cmds commands, ) bool { id := i.ruleID if cmds.enabled(id) { i.isDisabled = false return false } if cmds.disabled(id) { i.isDisabled = true return true } return false } func (i *Interpreter) interpretNext( cmds commands, ) bool { id := i.ruleID if cmds.disabledNext(id) { return true } return false } func (i *Interpreter) interpretThis( cmds commands, ) bool { id := i.ruleID if cmds.disabledThis(id) { return true } return false } <file_sep>/go.mod module github.com/yoheimuta/protolint require ( github.com/gertd/go-pluralize v0.2.0 github.com/golang/protobuf v1.5.2 github.com/hashicorp/go-hclog v1.2.0 github.com/hashicorp/go-plugin v1.4.3 github.com/yoheimuta/go-protoparser/v4 v4.7.0 google.golang.org/grpc v1.46.0 google.golang.org/protobuf v1.27.1 gopkg.in/yaml.v2 v2.4.0 ) require ( github.com/chavacava/garif v0.0.0-20230608123814-4bd63c2919ab // indirect github.com/fatih/color v1.7.0 // indirect github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb // indirect github.com/mattn/go-colorable v0.1.4 // indirect github.com/mattn/go-isatty v0.0.10 // indirect github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 // indirect github.com/oklog/run v1.0.0 // indirect golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 // indirect golang.org/x/text v0.3.3 // indirect google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect ) go 1.21 <file_sep>/internal/addon/rules/serviceNamesUpperCamelCaseRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // ServiceNamesUpperCamelCaseRule verifies that all service names are CamelCase (with an initial capital). // See https://developers.google.com/protocol-buffers/docs/style#services. type ServiceNamesUpperCamelCaseRule struct { RuleWithSeverity fixMode bool autoDisableType autodisable.PlacementType } // NewServiceNamesUpperCamelCaseRule creates a new ServiceNamesUpperCamelCaseRule. func NewServiceNamesUpperCamelCaseRule( severity rule.Severity, fixMode bool, autoDisableType autodisable.PlacementType, ) ServiceNamesUpperCamelCaseRule { if autoDisableType != autodisable.Noop { fixMode = false } return ServiceNamesUpperCamelCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r ServiceNamesUpperCamelCaseRule) ID() string { return "SERVICE_NAMES_UPPER_CAMEL_CASE" } // Purpose returns the purpose of this rule. func (r ServiceNamesUpperCamelCaseRule) Purpose() string { return "Verifies that all service names are CamelCase (with an initial capital)." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r ServiceNamesUpperCamelCaseRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r ServiceNamesUpperCamelCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &serviceNamesUpperCamelCaseVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type serviceNamesUpperCamelCaseVisitor struct { *visitor.BaseFixableVisitor } // VisitService checks the service. func (v *serviceNamesUpperCamelCaseVisitor) VisitService(service *parser.Service) bool { name := service.ServiceName if !strs.IsUpperCamelCase(name) { expected := strs.ToUpperCamelCase(name) v.AddFailuref(service.Meta.Pos, "Service name %q must be UpperCamelCase like %q", name, expected) err := v.Fixer.SearchAndReplace(service.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } <file_sep>/internal/addon/rules/maxLineLengthRule.go package rules import ( "bufio" "os" "strings" "unicode/utf8" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/linter/disablerule" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) const ( // Keep the line length to 80 characters. // See https://developers.google.com/protocol-buffers/docs/style#standard-file-formatting defaultMaxChars = 80 defaultTabChars = 4 ) // MaxLineLengthRule enforces a maximum line length to increase code readability and maintainability. // The length of a line is defined as the number of Unicode characters in the line. type MaxLineLengthRule struct { RuleWithSeverity maxChars int tabChars int } // NewMaxLineLengthRule creates a new MaxLineLengthRule. func NewMaxLineLengthRule( severity rule.Severity, maxChars int, tabChars int, ) MaxLineLengthRule { if maxChars == 0 { maxChars = defaultMaxChars } if tabChars == 0 { tabChars = defaultTabChars } return MaxLineLengthRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, maxChars: maxChars, tabChars: tabChars, } } // ID returns the ID of this rule. func (r MaxLineLengthRule) ID() string { return "MAX_LINE_LENGTH" } // Purpose returns the purpose of this rule. func (r MaxLineLengthRule) Purpose() string { return "Enforces a maximum line length." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r MaxLineLengthRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r MaxLineLengthRule) Apply(proto *parser.Proto) ( failures []report.Failure, err error, ) { fileName := proto.Meta.Filename reader, err := os.Open(fileName) if err != nil { return nil, err } defer func() { closeErr := reader.Close() if err != nil { return } if closeErr != nil { err = closeErr } }() var lines []string scanner := bufio.NewScanner(reader) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err := scanner.Err(); err != nil { return nil, err } disablerule.NewInterpreter(r.ID()).CallEachIfValid( lines, func(index int, line string) { line = strings.Replace(line, "\t", strings.Repeat(" ", r.tabChars), -1) lineCount := utf8.RuneCountInString(line) if r.maxChars < lineCount { failures = append(failures, report.Failuref( meta.Position{ Filename: fileName, Line: index + 1, Column: 1, }, r.ID(), "The line length is %d, but it must be shorter than %d", lineCount, r.maxChars, )) } }, ) return failures, nil } <file_sep>/internal/linter/report/reporters/jsonReporter.go package reporters import ( "encoding/json" "fmt" "io" "github.com/yoheimuta/protolint/linter/report" ) // JSONReporter prints failures as a single JSON struct, allowing // for simple machine-readable output. // // The format is: // // { // "lints": // [ // {"filename": FILENAME, "line": LINE, "column": COL, "message": MESSAGE, "rule": RULE} // ], // } type JSONReporter struct{} type lintJSON struct { Filename string `json:"filename"` Line int `json:"line"` Column int `json:"column"` Message string `json:"message"` Rule string `json:"rule"` } type outJSON struct { Lints []lintJSON `json:"lints"` } // Report writes failures to w. func (r JSONReporter) Report(w io.Writer, fs []report.Failure) error { out := outJSON{} for _, failure := range fs { out.Lints = append(out.Lints, lintJSON{ Filename: failure.Pos().Filename, Line: failure.Pos().Line, Column: failure.Pos().Column, Message: failure.Message(), Rule: failure.RuleID(), }) } bs, err := json.MarshalIndent(out, "", " ") if err != nil { return err } _, err = fmt.Fprintln(w, string(bs)) if err != nil { return err } return nil } <file_sep>/internal/addon/rules/quoteConsistentRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/linter/config" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestQuoteConsistentRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto inputQuote config.QuoteType wantFailures []report.Failure }{ { name: "no failures for proto with consistent double-quoted strings", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{ ProtobufVersionQuote: `"proto3"`, }, &parser.Import{ Location: `"google/protobuf/empty.proto"`, }, &parser.Option{ Constant: `"com.example.foo"`, }, &parser.Enum{ EnumBody: []parser.Visitee{ &parser.EnumField{ EnumValueOptions: []*parser.EnumValueOption{ { Constant: `"custom option"`, }, }, }, }, }, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldOptions: []*parser.FieldOption{ { Constant: `"field option"`, }, }, }, }, }, }, }, inputQuote: config.DoubleQuote, }, { name: "no failures for proto with consistent single-quoted strings", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{ ProtobufVersionQuote: `'proto3'`, }, &parser.Import{ Location: `'google/protobuf/empty.proto'`, }, &parser.Option{ Constant: `'com.example.foo'`, }, &parser.Enum{ EnumBody: []parser.Visitee{ &parser.EnumField{ EnumValueOptions: []*parser.EnumValueOption{ { Constant: `'custom option'`, }, }, }, }, }, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldOptions: []*parser.FieldOption{ { Constant: `'field option'`, }, }, }, }, }, }, }, inputQuote: config.SingleQuote, }, { name: "failures for proto with an inconsistent double-quoted strings", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{ ProtobufVersionQuote: `"proto3"`, }, &parser.Import{ Location: `"google/protobuf/empty.proto"`, }, &parser.Option{ Constant: `"com.example.foo"`, }, &parser.Enum{ EnumBody: []parser.Visitee{ &parser.EnumField{ EnumValueOptions: []*parser.EnumValueOption{ { Constant: `"custom option"`, }, }, }, }, }, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldOptions: []*parser.FieldOption{ { Constant: `"field option"`, }, }, }, }, }, }, }, inputQuote: config.SingleQuote, wantFailures: []report.Failure{ report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be 'proto3' but was "proto3".`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be 'google/protobuf/empty.proto' but was "google/protobuf/empty.proto".`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be 'com.example.foo' but was "com.example.foo".`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be 'custom option' but was "custom option".`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be 'field option' but was "field option".`, ), }, }, { name: "failures for proto with an inconsistent single-quoted strings", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Syntax{ ProtobufVersionQuote: `'proto3'`, }, &parser.Import{ Location: `'google/protobuf/empty.proto'`, }, &parser.Option{ Constant: `'com.example.foo'`, }, &parser.Enum{ EnumBody: []parser.Visitee{ &parser.EnumField{ EnumValueOptions: []*parser.EnumValueOption{ { Constant: `'custom option'`, }, }, }, }, }, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldOptions: []*parser.FieldOption{ { Constant: `'field option'`, }, }, }, }, }, }, }, inputQuote: config.DoubleQuote, wantFailures: []report.Failure{ report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be "proto3" but was 'proto3'.`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be "google/protobuf/empty.proto" but was 'google/protobuf/empty.proto'.`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be "com.example.foo" but was 'com.example.foo'.`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be "custom option" but was 'custom option'.`, ), report.Failuref( meta.Position{}, "QUOTE_CONSISTENT", `Quoted string should be "field option" but was 'field option'.`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewQuoteConsistentRule(rule.SeverityError, test.inputQuote, false) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestQuoteConsistentRule_Apply_fix(t *testing.T) { tests := []struct { name string inputQuote config.QuoteType inputFilename string wantFilename string }{ { name: "no fix for a double-quoted proto", inputQuote: config.DoubleQuote, inputFilename: "double-quoted.proto", wantFilename: "double-quoted.proto", }, { name: "fix for an inconsistent proto with double-quoted consistency", inputQuote: config.DoubleQuote, inputFilename: "inconsistent.proto", wantFilename: "double-quoted.proto", }, { name: "fix for an inconsistent proto with single-quoted consistency", inputQuote: config.SingleQuote, inputFilename: "inconsistent.proto", wantFilename: "single-quoted.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewQuoteConsistentRule( rule.SeverityError, test.inputQuote, true, ) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } <file_sep>/internal/addon/rules/repeatedFieldNamesPluralizedRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestRepeatedFieldNamesPluralizedRule_Apply(t *testing.T) { tests := []struct { name string pluralRules map[string]string singularRules map[string]string uncountableRules []string irregularRules map[string]string inputProto *parser.Proto wantFailures []report.Failure }{ { name: "no failures for proto without fields", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Enum{}, }, }, }, { name: "no failures for proto with valid field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "singer", }, &parser.Field{ IsRepeated: true, FieldName: "singers", }, &parser.GroupField{ IsRepeated: true, GroupName: "people", MessageBody: []parser.Visitee{ &parser.Field{ IsRepeated: true, FieldName: "some_singers", }, }, }, }, }, }, }, }, { name: "no failures for proto with valid field names considering the rule is case insensitive", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ IsRepeated: true, FieldName: "RunningOnDeviceIDS", }, &parser.GroupField{ IsRepeated: true, GroupName: "RunningOnDeviceIDs", }, }, }, }, }, }, { name: "no failures for proto with field names including 'uri' by applying some customization internally", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ IsRepeated: true, FieldName: "uris", }, &parser.Field{ IsRepeated: true, FieldName: "module_uris", }, }, }, }, }, }, { name: "no failures for proto with field names by applying some customization", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ IsRepeated: true, FieldName: "regexii", }, &parser.Field{ IsRepeated: true, FieldName: "paper", }, &parser.Field{ IsRepeated: true, FieldName: "paper", }, &parser.Field{ IsRepeated: true, FieldName: "regular", }, }, }, }, }, pluralRules: map[string]string{ "(?i)gex$": "gexii", }, singularRules: map[string]string{ "(?i)gexii": "gex", }, uncountableRules: []string{ "paper", }, irregularRules: map[string]string{ "irregular": "regular", }, }, { name: "failures for proto with non-pluralized repeated field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ IsRepeated: true, FieldName: "singer", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.Field{ IsRepeated: true, FieldName: "persons", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, }, }, &parser.GroupField{ IsRepeated: true, GroupName: "some_singer", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 210, Line: 14, Column: 30, }, }, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "REPEATED_FIELD_NAMES_PLURALIZED", `Repeated field name "singer" must be pluralized name "singers"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "REPEATED_FIELD_NAMES_PLURALIZED", `Repeated field name "persons" must be pluralized name "people"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 210, Line: 14, Column: 30, }, "REPEATED_FIELD_NAMES_PLURALIZED", `Repeated group name "some_singer" must be pluralized name "some_singers"`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewRepeatedFieldNamesPluralizedRule( rule.SeverityError, test.pluralRules, test.singularRules, test.uncountableRules, test.irregularRules, false, autodisable.Noop, ) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestRepeatedFieldNamesPluralizedRule_Apply_fix(t *testing.T) { tests := []struct { name string pluralRules map[string]string singularRules map[string]string uncountableRules []string irregularRules map[string]string inputFilename string wantFilename string }{ { name: "no fix for a correct proto", inputFilename: "pluralized.proto", wantFilename: "pluralized.proto", }, { name: "fix for an incorrect proto", inputFilename: "invalid.proto", wantFilename: "pluralized.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewRepeatedFieldNamesPluralizedRule( rule.SeverityError, test.pluralRules, test.singularRules, test.uncountableRules, test.irregularRules, true, autodisable.Noop, ) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } func TestRepeatedFieldNamesPluralizedRule_Apply_disable(t *testing.T) { tests := []struct { name string pluralRules map[string]string singularRules map[string]string uncountableRules []string irregularRules map[string]string inputFilename string inputPlacementType autodisable.PlacementType wantFilename string }{ { name: "do nothing in case of no violations", inputFilename: "pluralized.proto", wantFilename: "pluralized.proto", }, { name: "insert disable:next comments", inputFilename: "invalid.proto", inputPlacementType: autodisable.Next, wantFilename: "disable_next.proto", }, { name: "insert disable:this comments", inputFilename: "invalid.proto", inputPlacementType: autodisable.ThisThenNext, wantFilename: "disable_this.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewRepeatedFieldNamesPluralizedRule( rule.SeverityError, test.pluralRules, test.singularRules, test.uncountableRules, test.irregularRules, true, test.inputPlacementType, ) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } <file_sep>/internal/filepathutil/platform.go package filepathutil import ( "os" "strings" ) const unixPathSeparator = '/' // OSPathSeparator is just a variable that is equal to os.PathSeparator. // It's set by outside for mainly test usage. var OSPathSeparator = os.PathSeparator // IsSameUnixPath compares an unix path to a cross platform path. // // The interpretation of the unix path depends on the platform it runs. func IsSameUnixPath(unixPath, crossPlatformPath string) bool { if OSPathSeparator == unixPathSeparator { return unixPath == crossPlatformPath } return convertToOSPath(unixPath) == crossPlatformPath } // HasUnixPathPrefix checks whether a cross platform path has an unix path as its prefix. // // The interpretation of the unix path depends on the platform it runs. func HasUnixPathPrefix(crossPlatformPath, unixPath string) bool { if OSPathSeparator == unixPathSeparator { return strings.HasPrefix(crossPlatformPath, unixPath) } return strings.HasPrefix( crossPlatformPath, convertToOSPath(unixPath), ) } func convertToOSPath(unixPath string) string { return strings.Replace( unixPath, string(unixPathSeparator), osPathSeparator(), -1, ) } func osPathSeparator() string { return string(OSPathSeparator) } <file_sep>/cmd/protoc-gen-protolint/main.go package main import ( "os" protoc "github.com/yoheimuta/protolint/internal/cmd/protocgenprotolint" ) func main() { os.Exit(int( protoc.Do( os.Args[1:], os.Stdin, os.Stdout, os.Stderr, ), )) } <file_sep>/Dockerfile FROM alpine:3.15.4 RUN apk -U --no-cache upgrade; /bin/rm -rf /var/cache/apk/* ENTRYPOINT ["/usr/local/bin/protolint"] COPY protolint /usr/local/bin/protolint <file_sep>/internal/addon/rules/util_test.go package rules_test import ( "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/internal/util_test" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "reflect" "testing" ) func testApplyFix( t *testing.T, r rule.Rule, inputFilename string, wantFilename string, ) { dataDir := strs.ToLowerCamelCase(r.ID()) input, err := util_test.NewTestData(setting_test.TestDataPath("rules", dataDir, inputFilename)) if err != nil { t.Errorf("got err %v", err) return } want, err := util_test.NewTestData(setting_test.TestDataPath("rules", dataDir, wantFilename)) if err != nil { t.Errorf("got err %v", err) return } proto, err := file.NewProtoFile(input.FilePath, input.FilePath).Parse(false) if err != nil { t.Errorf(err.Error()) return } _, err = r.Apply(proto) if err != nil { t.Errorf("got err %v, but want nil", err) return } got, err := input.Data() if !reflect.DeepEqual(got, want.OriginData) { t.Errorf( "got %s(%v), but want %s(%v)", string(got), got, string(want.OriginData), want.OriginData, ) } err = input.Restore() if err != nil { t.Errorf("got err %v", err) } } <file_sep>/internal/linter/report/reporters/unixReporter.go package reporters import ( "fmt" "io" "github.com/yoheimuta/protolint/linter/report" ) // UnixReporter prints failures as it respects Unix output conventions // those are frequently employed by preprocessors and compilers. // // The format is "FILENAME:LINE:COL: MESSAGE". type UnixReporter struct{} // Report writes failures to w. func (r UnixReporter) Report(w io.Writer, fs []report.Failure) error { for _, failure := range fs { unix := fmt.Sprintf( "%s: %s", failure.Pos(), failure.Message(), ) _, err := fmt.Fprintln(w, unix) if err != nil { return err } } return nil } <file_sep>/internal/linter/report/reporters/jUnitReporter_test.go package reporters_test import ( "bytes" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/linter/report/reporters" "github.com/yoheimuta/protolint/linter/report" ) func TestJUnitReporter_Report(t *testing.T) { tests := []struct { name string inputFailures []report.Failure wantOutput string }{ { name: "Prints no failures in the JUnit XML format", wantOutput: `<?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite tests="1" failures="0" time="0"> <package>net.protolint</package> <testcase classname="net.protolint.ALL_RULES" name="All Rules" time="0"></testcase> </testsuite> </testsuites> `, }, { name: "Prints failures in the JUnit XML format", inputFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ENUM_NAMES_UPPER_CAMEL_CASE", `EnumField name "fIRST_VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ENUM_NAMES_UPPER_CAMEL_CASE", `EnumField name "SECOND.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), }, wantOutput: `<?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite tests="2" failures="2" time="0"> <package>net.protolint</package> <testcase classname="example" name="net.protolint.ENUM_NAMES_UPPER_CAMEL_CASE" time="0"> <failure message="EnumField name &#34;fIRST_VALUE&#34; must be CAPITALS_WITH_UNDERSCORES" type="error"><![CDATA[line 5, col 10]]></failure> </testcase> <testcase classname="example" name="net.protolint.ENUM_NAMES_UPPER_CAMEL_CASE" time="0"> <failure message="EnumField name &#34;SECOND.VALUE&#34; must be CAPITALS_WITH_UNDERSCORES" type="error"><![CDATA[line 10, col 20]]></failure> </testcase> </testsuite> </testsuites> `, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { buf := &bytes.Buffer{} err := reporters.JUnitReporter{}.Report(buf, test.inputFailures) if err != nil { t.Errorf("got err %v, but want nil", err) return } if buf.String() != test.wantOutput { t.Errorf("got %s, but want %s", buf.String(), test.wantOutput) } }) } } <file_sep>/internal/addon/rules/enumFieldNamesPrefixRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestEnumFieldNamesPrefixRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto wantFailures []report.Failure }{ { name: "no failures for proto without enum fields", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Enum{ EnumName: "FooBar", }, }, }, }, { name: "no failures for proto with valid enum field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Enum{ EnumName: "FooBar", EnumBody: []parser.Visitee{ &parser.EnumField{ Ident: "FOO_BAR_UNSPECIFIED", Number: "0", }, &parser.EnumField{ Ident: "FOO_BAR_FIRST_VALUE", Number: "1", }, &parser.EnumField{ Ident: "FOO_BAR_SECOND_VALUE", Number: "2", }, }, }, }, }, }, { name: "no failures for proto with valid enum field names even when its enum name is snake case", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Enum{ EnumName: "foo_bar", EnumBody: []parser.Visitee{ &parser.EnumField{ Ident: "FOO_BAR_UNSPECIFIED", Number: "0", }, }, }, }, }, }, { name: "failures for proto with invalid enum field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Enum{ EnumName: "FooBar", EnumBody: []parser.Visitee{ &parser.EnumField{ Ident: "BAR_UNSPECIFIED", Number: "0", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ENUM_FIELD_NAMES_PREFIX", `EnumField name "BAR_UNSPECIFIED" should have the prefix "FOO_BAR"`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewEnumFieldNamesPrefixRule(rule.SeverityError, false, autodisable.Noop) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestEnumFieldNamesPrefixRule_Apply_fix(t *testing.T) { tests := []struct { name string inputFilename string wantFilename string }{ { name: "no fix for a correct proto", inputFilename: "prefix.proto", wantFilename: "prefix.proto", }, { name: "fix for an incorrect proto", inputFilename: "invalid.proto", wantFilename: "prefix.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewEnumFieldNamesPrefixRule(rule.SeverityError, true, autodisable.Noop) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } func TestEnumFieldNamesPrefixRule_Apply_disable(t *testing.T) { tests := []struct { name string inputFilename string inputPlacementType autodisable.PlacementType wantFilename string }{ { name: "do nothing in case of no violations", inputFilename: "prefix.proto", wantFilename: "prefix.proto", }, { name: "insert disable:next comments", inputFilename: "invalid.proto", inputPlacementType: autodisable.Next, wantFilename: "disable_next.proto", }, { name: "insert disable:this comments", inputFilename: "invalid.proto", inputPlacementType: autodisable.ThisThenNext, wantFilename: "disable_this.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewEnumFieldNamesPrefixRule(rule.SeverityError, true, test.inputPlacementType) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } <file_sep>/internal/cmd/subcmds/pluginFlag.go package subcmds import ( "fmt" "os/exec" "strings" "github.com/hashicorp/go-hclog" "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/hashicorp/go-plugin" ) // PluginFlag manages a flag for plugins. type PluginFlag struct { raws []string } // String implements flag.Value. func (f *PluginFlag) String() string { return fmt.Sprint(strings.Join(f.raws, ",")) } // Set implements flag.Value. func (f *PluginFlag) Set(value string) error { f.raws = append(f.raws, value) return nil } // BuildPlugins builds all plugins. func (f *PluginFlag) BuildPlugins(verbose bool) ([]shared.RuleSet, error) { var plugins []shared.RuleSet for _, value := range f.raws { level := hclog.Warn if verbose { level = hclog.Trace } client := plugin.NewClient(&plugin.ClientConfig{ HandshakeConfig: shared.Handshake, Plugins: shared.PluginMap, Cmd: exec.Command("sh", "-c", value), AllowedProtocols: []plugin.Protocol{ plugin.ProtocolGRPC, }, Logger: hclog.New(&hclog.LoggerOptions{ Output: hclog.DefaultOutput, Level: level, Name: "plugin", }), // To cleanup. See. https://github.com/yoheimuta/protolint/issues/237 Managed: true, }) rpcClient, err := client.Client() if err != nil { return nil, fmt.Errorf("failed client.Client(), err=%s", err) } ruleSet, err := rpcClient.Dispense("ruleSet") if err != nil { return nil, fmt.Errorf("failed Dispense, err=%s", err) } plugins = append(plugins, ruleSet.(shared.RuleSet)) } return plugins, nil } <file_sep>/CONTRIBUTING.md # Contributing - Fork it - Create your feature branch: git checkout -b your-new-feature - Commit changes: git commit -m 'Add your feature' - Pass all tests - Push to the branch: git push origin your-new-feature - Submit a pull request ## Publish the Maven artifacts Once a release is done, artifacts will need to be promoted in Maven Central to make them generally available. 1. Head over to https://s01.oss.sonatype.org/#stagingRepositories 1. Verify the contents of the staging repo and close it 1. After successful closing (test suite is run), release the repo <file_sep>/internal/linter/config/messagesHaveCommentOption.go package config // MessagesHaveCommentOption represents the option for the MESSAGES_HAVE_COMMENT rule. type MessagesHaveCommentOption struct { CustomizableSeverityOption ShouldFollowGolangStyle bool `yaml:"should_follow_golang_style"` } <file_sep>/internal/cmd/subcmds/lint/flags.go package lint import ( "flag" "github.com/yoheimuta/protolint/internal/cmd/subcmds" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/internal/addon/plugin/shared" "github.com/yoheimuta/protolint/internal/linter/report/reporters" "github.com/yoheimuta/protolint/internal/linter/report" ) // Flags represents a set of lint flag parameters. type Flags struct { *flag.FlagSet FilePaths []string ConfigPath string ConfigDirPath string FixMode bool Reporter report.Reporter AutoDisableType autodisable.PlacementType OutputFilePath string Verbose bool NoErrorOnUnmatchedPattern bool Plugins []shared.RuleSet AdditionalReporters reporterStreamFlags } // NewFlags creates a new Flags. func NewFlags( args []string, ) (Flags, error) { f := Flags{ FlagSet: flag.NewFlagSet("lint", flag.ExitOnError), Reporter: reporters.PlainReporter{}, AutoDisableType: autodisable.Noop, } var rf reporterFlag var af autoDisableFlag var pf subcmds.PluginFlag var rfs reporterStreamFlags f.StringVar( &f.ConfigPath, "config_path", "", "path/to/protolint.yaml. Note that if both are set, config_dir_path is ignored.", ) f.StringVar( &f.ConfigDirPath, "config_dir_path", "", "path/to/the_directory_including_protolint.yaml", ) f.BoolVar( &f.FixMode, "fix", false, "mode that the command line automatically fix some of the problems", ) f.Var( &rf, "reporter", `formatter to output results in the specific format. Available reporters are "plain"(default), "junit", "json", "sarif", and "unix".`, ) f.Var( &af, "auto_disable", `mode that the command line automatically disable some of the problems. Available auto_disable are "next" and "this".`, ) f.StringVar( &f.OutputFilePath, "output_file", "", "path/to/output.txt", ) f.Var( &pf, "plugin", `plugins to provide custom lint rule set. Note that it's necessary to specify it as path format'`, ) f.BoolVar( &f.Verbose, "v", false, "verbose output that includes parsing process details", ) f.BoolVar( &f.NoErrorOnUnmatchedPattern, "no-error-on-unmatched-pattern", false, "exits with 0 when no file is matched", ) f.Var( &rfs, "add-reporter", "Adds a reporter to the list of reporters to use. The format should be 'name of reporter':'Path-To_output_file'", ) _ = f.Parse(args) if rf.reporter != nil { f.Reporter = rf.reporter } if len(rfs) > 0 { f.AdditionalReporters = rfs } if af.autoDisableType != 0 { f.AutoDisableType = af.autoDisableType } plugins, err := pf.BuildPlugins(f.Verbose) if err != nil { return Flags{}, err } f.Plugins = plugins f.FilePaths = f.Args() return f, nil } <file_sep>/internal/osutil/file_test.go package osutil_test import ( "testing" "github.com/yoheimuta/protolint/internal/osutil" ) func TestDetectLineEnding(t *testing.T) { tests := []struct { name string input string want string wantExistErr bool }{ { name: "An empty string has no line ending", input: ``, }, { name: "a line string has no line ending", input: `first line`, }, { name: "two lines have \n", input: `first line second line`, want: "\n", }, { name: "two lines have \r", input: `first line` + "\r" + `second line`, want: "\r", }, { name: "two lines have \r\n", input: `first line` + "\r\n" + `second line`, want: "\r\n", }, { name: "two lines have a mix of \n and \r, and \n is more", input: `first line second line third line` + "\r" + `forth line`, want: "\n", }, { name: "two lines have a mix of \n and \r, and \r is more", input: `first line second line` + "\r" + `third line` + "\r" + `forth line`, want: "\r", }, { name: "two lines have a mix of \r\n and \r, and \r\n is more", input: `first line` + "\r\n" + `second line` + "\r\n" + `third line` + "\r" + `forth line`, want: "\r\n", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { got, err := osutil.DetectLineEnding(test.input) if test.wantExistErr && err == nil { t.Errorf("got err nil, but want err") return } else if err != nil { t.Errorf("got err, but want nil") return } if got != test.want { t.Errorf("got %v, but want %v", got, test.want) } }) } } <file_sep>/_example/plugin/main.go package main import ( "flag" "github.com/yoheimuta/protolint/_example/plugin/customrules" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/plugin" ) var ( goStyle = flag.Bool("go_style", true, "the comments should follow a golang style") ) func main() { flag.Parse() plugin.RegisterCustomRules( // The purpose of this line just illustrates that you can implement the same as internal linter rules. rules.NewEnumsHaveCommentRule(rule.SeverityWarning, *goStyle), // A common custom rule example. It's simple. customrules.NewEnumNamesLowerSnakeCaseRule(), // Wrapping with RuleGen allows referring to command-line flags. plugin.RuleGen(func( verbose bool, fixMode bool, ) rule.Rule { return customrules.NewSimpleRule(verbose, fixMode, rule.SeverityError) }), ) } <file_sep>/internal/linter/report/reporters/sarifReporter_test.go package reporters_test import ( "bytes" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/linter/report/reporters" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestSarifReporter_Report(t *testing.T) { tests := []struct { name string inputFailures []report.Failure wantOutput string }{ { name: "Prints failures in JSON format", inputFailures: []report.Failure{ report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityError), `EnumField name "fIRST_VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityWarning), `EnumField name "SECOND.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), }, wantOutput: `{ "runs": [ { "artifacts": [ { "location": { "uri": "example.proto" } } ], "results": [ { "kind": "fail", "level": "error", "locations": [ { "physicalLocation": { "artifactLocation": { "uri": "example.proto" }, "region": { "startColumn": 10, "startLine": 5 } } } ], "message": { "text": "EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES" }, "ruleId": "ENUM_NAMES_UPPER_CAMEL_CASE" }, { "kind": "fail", "level": "warning", "locations": [ { "physicalLocation": { "artifactLocation": { "uri": "example.proto" }, "region": { "startColumn": 20, "startLine": 10 } } } ], "message": { "text": "EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES" }, "ruleId": "ENUM_NAMES_UPPER_CAMEL_CASE" } ], "tool": { "driver": { "informationUri": "https://github.com/yoheimuta/protolint", "name": "protolint", "rules": [ { "helpUri": "https://github.com/yoheimuta/protolint", "id": "ENUM_NAMES_UPPER_CAMEL_CASE" } ] } } } ], "version": "2.1.0" }`, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { buf := &bytes.Buffer{} err := reporters.SarifReporter{}.Report(buf, test.inputFailures) if err != nil { t.Errorf("got err %v, but want nil", err) return } if buf.String() != test.wantOutput { t.Errorf("got %s, but want %s", buf.String(), test.wantOutput) } }) } } <file_sep>/internal/linter/config/fileNamesLowerSnakeCaseOption.go package config // FileNamesLowerSnakeCaseOption represents the option for the FILE_NAMES_LOWER_SNAKE_CASE rule. type FileNamesLowerSnakeCaseOption struct { CustomizableSeverityOption Excludes []string `yaml:"excludes"` } <file_sep>/internal/addon/rules/fileHasCommentRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // FileHasCommentRule verifies that a file starts with a doc comment. type FileHasCommentRule struct { RuleWithSeverity } // NewFileHasCommentRule creates a new FileHasCommentRule. func NewFileHasCommentRule(severity rule.Severity) FileHasCommentRule { return FileHasCommentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, } } // ID returns the ID of this rule. func (r FileHasCommentRule) ID() string { return "FILE_HAS_COMMENT" } // Purpose returns the purpose of this rule. func (r FileHasCommentRule) Purpose() string { return "Verifies that a file starts with a doc comment." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r FileHasCommentRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r FileHasCommentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &fileHasCommentVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), } return visitor.RunVisitor(v, proto, r.ID()) } type fileHasCommentVisitor struct { *visitor.BaseAddVisitor } // VisitSyntax checks the syntax. func (v *fileHasCommentVisitor) VisitSyntax(s *parser.Syntax) bool { if !hasComment(s.Comments) { v.AddFailuref(s.Meta.Pos, `File should start with a doc comment`) } return false } <file_sep>/internal/linter/config/externalConfigProvider_test.go package config_test import ( "os" "reflect" "testing" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/internal/linter/config" ) func TestGetExternalConfig(t *testing.T) { for _, test := range []struct { name string inputFilePath string inputDirPath string cwdPath string wantExternalConfig *config.ExternalConfig wantExistErr bool }{ { name: "invalid config file", inputDirPath: setting_test.TestDataPath("invalidconfig"), wantExistErr: true, }, { name: "not found a config file", }, { name: "valid config file", inputDirPath: setting_test.TestDataPath("validconfig"), wantExternalConfig: &config.ExternalConfig{ SourcePath: setting_test.TestDataPath("validconfig", "protolint.yaml"), Lint: config.Lint{ Ignores: []config.Ignore{ { ID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", Files: []string{ "path/to/foo.proto", "path/to/bar.proto", }, }, { ID: "ENUM_NAMES_UPPER_CAMEL_CASE", Files: []string{ "path/to/foo.proto", }, }, }, Rules: struct { NoDefault bool `yaml:"no_default"` AllDefault bool `yaml:"all_default"` Add []string `yaml:"add"` Remove []string `yaml:"remove"` }{ NoDefault: true, Add: []string{ "FIELD_NAMES_LOWER_SNAKE_CASE", "MESSAGE_NAMES_UPPER_CAMEL_CASE", }, Remove: []string{ "RPC_NAMES_UPPER_CAMEL_CASE", }, }, RulesOption: config.RulesOption{ MaxLineLength: config.MaxLineLengthOption{ MaxChars: 80, TabChars: 2, }, Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "load .protolint.yaml", inputDirPath: setting_test.TestDataPath("validconfig", "hidden"), wantExternalConfig: &config.ExternalConfig{ SourcePath: setting_test.TestDataPath("validconfig", "hidden", ".protolint.yaml"), Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "load my_protolint.yaml", inputFilePath: setting_test.TestDataPath("validconfig", "particular_name", "my_protolint.yaml"), wantExternalConfig: &config.ExternalConfig{ SourcePath: setting_test.TestDataPath("validconfig", "particular_name", "my_protolint.yaml"), Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "load protolint.yml", inputDirPath: setting_test.TestDataPath("validconfig", "yml"), wantExternalConfig: &config.ExternalConfig{ SourcePath: setting_test.TestDataPath("validconfig", "yml", "protolint.yml"), Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "load .protolint.yml", inputDirPath: setting_test.TestDataPath("validconfig", "yml_hidden"), wantExternalConfig: &config.ExternalConfig{ SourcePath: setting_test.TestDataPath("validconfig", "yml_hidden", ".protolint.yml"), Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "load .protolint.yml at cwd automatically", cwdPath: setting_test.TestDataPath("validconfig", "default"), wantExternalConfig: &config.ExternalConfig{ SourcePath: ".protolint.yml", Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "prefer .protolint.yml at cwd to one at its parent dir", cwdPath: setting_test.TestDataPath("validconfig", "default", "child"), wantExternalConfig: &config.ExternalConfig{ SourcePath: ".protolint.yaml", Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "locate .protolint.yml at the parent when not found at cwd", cwdPath: setting_test.TestDataPath("validconfig", "default", "empty_child"), wantExternalConfig: &config.ExternalConfig{ SourcePath: setting_test.TestDataPath("validconfig", "default", ".protolint.yml"), Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "locate .protolint.yml at the grand parent when not found at cwd", cwdPath: setting_test.TestDataPath("validconfig", "default", "empty_child", "empty_grand_child"), wantExternalConfig: &config.ExternalConfig{ SourcePath: setting_test.TestDataPath("validconfig", "default", ".protolint.yml"), Lint: config.Lint{ RulesOption: config.RulesOption{ Indent: config.IndentOption{ Style: "\t", Newline: "\n", }, }, }, }, }, { name: "not found a config file even so inputDirPath is set", inputDirPath: setting_test.TestDataPath("validconfig", "particular_name"), wantExistErr: true, }, { name: "not found a config file even so inputFilePath is set", inputFilePath: setting_test.TestDataPath("validconfig", "particular_name", "not_found.yaml"), wantExistErr: true, }, } { test := test t.Run(test.name, func(t *testing.T) { if len(test.cwdPath) != 0 { err := os.Chdir(test.cwdPath) if err != nil { t.Errorf("got err %v", err) return } } got, err := config.GetExternalConfig(test.inputFilePath, test.inputDirPath) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantExternalConfig) { t.Errorf("got %v, but want %v", got, test.wantExternalConfig) } }) } } <file_sep>/build.gradle plugins { id 'maven-publish' id 'signing' } group = 'io.github.yoheimuta' publishing { publications { maven(MavenPublication) { groupId = 'io.github.yoheimuta' artifactId = rootProject.name version = System.getenv("GITHUB_REF_NAME") // Strip "v" from version number if (version.startsWith("v")) { version = version.substring(1) } pom { name = groupId + ':' + rootProject.name description = 'protolint is the pluggable linting/fixing utility for Protocol Buffer files (proto2+proto3)' url = 'https://github.com/yoheimuta/protolint' licenses { license { name = 'MIT License' url = 'https://github.com/yoheimuta/protolint/blob/master/LICENSE' } } developers { developer { id = 'yoheimuta' name = '<NAME>' email = '<EMAIL>' } } scm { connection = 'scm:git:<EMAIL>:yoheimuta/protolint.git' developerConnection = 'scm:git:<EMAIL>:yoheimuta/protolint.git' url = 'https://github.com/yoheimuta/protolint' } } //linux 64 arm artifact("$projectDir/dist/protoc-gen-protolint_linux_arm64/protoc-gen-protolint") { classifier 'linux-aarch_64' extension 'exe' } //linux 64 intel artifact("$projectDir/dist/protoc-gen-protolint_linux_amd64_v1/protoc-gen-protolint") { classifier 'linux-x86_64' extension 'exe' } //mac 64 arm artifact("$projectDir/dist/protoc-gen-protolint_darwin_arm64/protoc-gen-protolint") { classifier 'osx-aarch_64' extension 'exe' } //mac 64 intel artifact("$projectDir/dist/protoc-gen-protolint_darwin_amd64_v1/protoc-gen-protolint") { classifier 'osx-x86_64' extension 'exe' } //windows 64 arm artifact("$projectDir/dist/protoc-gen-protolint_windows_arm64/protoc-gen-protolint.exe") { classifier 'windows-aarch_64' extension 'exe' } //windows 64 intel artifact("$projectDir/dist/protoc-gen-protolint_windows_amd64_v1/protoc-gen-protolint.exe") { classifier 'windows-x86_64' extension 'exe' } } } repositories { maven { name = "OSSRH" def releasesRepoUrl = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/" def snapshotsRepoUrl = "https://s01.oss.sonatype.org/content/repositories/snapshots/" url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl credentials { username = System.getenv("MAVEN_USERNAME") password = System.<PASSWORD>("<PASSWORD>") } } } } signing { def signingKey = project.getProperty('signingKey') def signingPassword = project.getProperty('signingPassword') useInMemoryPgpKeys(signingKey, signingPassword) sign publishing.publications.maven } <file_sep>/internal/cmd/cmd.go package cmd import ( "fmt" "io" "strings" "github.com/yoheimuta/protolint/internal/cmd/subcmds/lint" "github.com/yoheimuta/protolint/internal/cmd/subcmds/list" "github.com/yoheimuta/protolint/internal/osutil" ) const ( help = ` Protocol Buffer Linter Command. Usage: protolint <command> [arguments] The commands are: lint lint protocol buffer files list list all current lint rules being used version print protolint version ` ) const ( subCmdLint = "lint" subCmdList = "list" subCmdVersion = "version" ) var ( version = "master" revision = "latest" ) // Do runs the command logic. func Do( args []string, stdout io.Writer, stderr io.Writer, ) osutil.ExitCode { switch { case len(args) == 0: _, _ = fmt.Fprint(stderr, help) return osutil.ExitInternalFailure default: return doSub( args, stdout, stderr, ) } } func doSub( args []string, stdout io.Writer, stderr io.Writer, ) osutil.ExitCode { switch args[0] { case subCmdLint: return doLint(args[1:], stdout, stderr) case subCmdList: return doList(args[1:], stdout, stderr) case subCmdVersion: return doVersion(stdout) default: return doLint(args, stdout, stderr) } } func doLint( args []string, stdout io.Writer, stderr io.Writer, ) osutil.ExitCode { if len(args) < 1 { _, _ = fmt.Fprintln(stderr, "protolint lint requires at least one argument. See Usage.") _, _ = fmt.Fprint(stderr, help) return osutil.ExitInternalFailure } flags, err := lint.NewFlags(args) if err != nil { _, _ = fmt.Fprint(stderr, err) return osutil.ExitInternalFailure } if len(flags.Args()) < 1 { _, _ = fmt.Fprintln(stderr, "protolint lint requires at least one argument. See Usage.") _, _ = fmt.Fprint(stderr, help) return osutil.ExitInternalFailure } subCmd, err := lint.NewCmdLint( flags, stdout, stderr, ) if err != nil { _, _ = fmt.Fprintln(stderr, err) if flags.NoErrorOnUnmatchedPattern && (strings.Contains(err.Error(), "not found protocol buffer files") || strings.Contains(err.Error(), "system cannot find the file")) { return osutil.ExitSuccess } return osutil.ExitInternalFailure } return subCmd.Run() } func doList( args []string, stdout io.Writer, stderr io.Writer, ) osutil.ExitCode { flags, err := list.NewFlags(args) if err != nil { _, _ = fmt.Fprint(stderr, err) return osutil.ExitInternalFailure } subCmd := list.NewCmdList( flags, stdout, stderr, ) return subCmd.Run() } func doVersion( stdout io.Writer, ) osutil.ExitCode { _, _ = fmt.Fprintln(stdout, "protolint version "+version+"("+revision+")") return osutil.ExitSuccess } <file_sep>/internal/linter/config/quoteConsistentOption_test.go package config_test import ( "reflect" "testing" "github.com/yoheimuta/protolint/internal/linter/config" "gopkg.in/yaml.v2" ) func TestQuoteConsistentOption_UnmarshalYAML(t *testing.T) { for _, test := range []struct { name string inputConfig []byte wantQuoteConsistentOption config.QuoteConsistentOption wantExistErr bool }{ { name: "not found supported quote", inputConfig: []byte(` quote: backtick `), wantExistErr: true, }, { name: "empty config", inputConfig: []byte(` `), }, { name: "quote: double", inputConfig: []byte(` quote: double `), wantQuoteConsistentOption: config.QuoteConsistentOption{ Quote: config.DoubleQuote, }, }, { name: "quote: single", inputConfig: []byte(` quote: single `), wantQuoteConsistentOption: config.QuoteConsistentOption{ Quote: config.SingleQuote, }, }, } { test := test t.Run(test.name, func(t *testing.T) { var got config.QuoteConsistentOption err := yaml.UnmarshalStrict(test.inputConfig, &got) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantQuoteConsistentOption) { t.Errorf("got %v, but want %v", got, test.wantQuoteConsistentOption) } }) } } <file_sep>/.github/install_dep.sh #!/bin/sh set -eux go install golang.org/x/tools/cmd/goimports@latest go install github.com/kisielk/errcheck@latest go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest go install github.com/gordonklaus/ineffassign@latest go install github.com/opennota/check/cmd/varcheck@latest go install github.com/opennota/check/cmd/aligncheck@latest go install github.com/mdempsky/unconvert@latest <file_sep>/Makefile ## test/all runs all related tests. test/all: test/lint test ## test runs `go test` test: go test -v -p 2 -count 1 -timeout 240s -race ./... ## test runs `go test -run $(RUN)` test/run: go test -v -p 2 -count 1 -timeout 240s -race ./... -run $(RUN) ## test/lint runs linter test/lint: # checks the coding style. (! gofmt -s -d `find . -name vendor -prune -type f -o -name '*.go'` | grep '^') # checks the import format. (! goimports -l `find . -name vendor -prune -type f -o -name '*.go'` | grep -v 'pb.go' | grep 'go') # checks the error the compiler can't find. go vet ./... # checks shadowed variables. go vet -vettool=$(which shadow) ./... # checks no used assigned value. ineffassign ./... # checks not to ignore the error. errcheck ./... # checks unused global variables and constants. varcheck ./... # checks dispensable type conversions. unconvert -v ./... ## dev/install/dep installs depenencies required for development. dev/install/dep: sh ./.github/install_dep.sh ## dev/build/proto builds proto files under the _proto directory. dev/build/proto: protoc -I _proto _proto/*.proto --go_out=plugins=grpc:internal/addon/plugin/proto ## ARG is command arguments. ARG=lint _example/proto ## run/cmd/protolint runs protolint with ARG run/cmd/protolint: go run cmd/protolint/main.go $(ARG) ## run/cmd/protolint/exampleconfig runs protolint with ARG under _example/config run/cmd/protolint/exampleconfig: cd _example/config && go run ../../cmd/protolint/main.go $(ARG) ## build/cmd/protolint builds protolint build/cmd/protolint: go build \ -ldflags "-X github.com/yoheimuta/protolint/internal/cmd.version=`git describe --tags --abbrev=0` -X github.com/yoheimuta/protolint/internal/cmd.revision=`git rev-parse --short HEAD`" \ -o protolint \ cmd/protolint/main.go ## build/example/plugin builds a plugin build/example/plugin: go build -o plugin_example _example/plugin/main.go ## build/cmd/protoc-gen-protolint builds protoc-gen-protolint build/cmd/protoc-gen-protolint: go build \ -ldflags "-X github.com/yoheimuta/protolint/internal/cmd/protocgenprotolint.version=`git describe --tags --abbrev=0` -X github.com/yoheimuta/protolint/internal/cmd/protocgenprotolint.revision=`git rev-parse --short HEAD`" \ -o protoc-gen-protolint \ cmd/protoc-gen-protolint/main.go <file_sep>/internal/addon/rules/fileNamesLowerSnakeCaseRule.go package rules import ( "os" "path/filepath" "strings" "github.com/yoheimuta/protolint/internal/stringsutil" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // FileNamesLowerSnakeCaseRule verifies that all file names are lower_snake_case.proto. // See https://developers.google.com/protocol-buffers/docs/style#file-structure. type FileNamesLowerSnakeCaseRule struct { RuleWithSeverity excluded []string fixMode bool } // NewFileNamesLowerSnakeCaseRule creates a new FileNamesLowerSnakeCaseRule. func NewFileNamesLowerSnakeCaseRule( severity rule.Severity, excluded []string, fixMode bool, ) FileNamesLowerSnakeCaseRule { return FileNamesLowerSnakeCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, excluded: excluded, fixMode: fixMode, } } // ID returns the ID of this rule. func (r FileNamesLowerSnakeCaseRule) ID() string { return "FILE_NAMES_LOWER_SNAKE_CASE" } // Purpose returns the purpose of this rule. func (r FileNamesLowerSnakeCaseRule) Purpose() string { return "Verifies that all file names are lower_snake_case.proto." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r FileNamesLowerSnakeCaseRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r FileNamesLowerSnakeCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &fileNamesLowerSnakeCaseVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), excluded: r.excluded, fixMode: r.fixMode, } return visitor.RunVisitor(v, proto, r.ID()) } type fileNamesLowerSnakeCaseVisitor struct { *visitor.BaseAddVisitor excluded []string fixMode bool } // OnStart checks the file. func (v *fileNamesLowerSnakeCaseVisitor) OnStart(proto *parser.Proto) error { path := proto.Meta.Filename if stringsutil.ContainsStringInSlice(path, v.excluded) { return nil } filename := filepath.Base(path) ext := filepath.Ext(filename) base := strings.TrimSuffix(filename, ext) if ext != ".proto" || !strs.IsLowerSnakeCase(base) { expected := strs.ToLowerSnakeCase(base) expected = strings.ReplaceAll(expected, ".", "_") expected += ".proto" v.AddFailurefWithProtoMeta(proto.Meta, "File name %q should be lower_snake_case.proto like %q.", filename, expected) if v.fixMode { dir := filepath.Dir(path) newPath := filepath.Join(dir, expected) if _, err := os.Stat(newPath); !os.IsNotExist(err) { v.AddFailurefWithProtoMeta(proto.Meta, "Failed to rename %q because %q already exists.", filename, expected) return nil } err := os.Rename(path, newPath) if err != nil { return err } // Notify the upstream this new filename by updating the proto. proto.Meta.Filename = newPath } } return nil } <file_sep>/plugin/ruleSet.go package plugin import ( "fmt" "github.com/yoheimuta/protolint/internal/addon/plugin/proto" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/linter/rule" ) type ruleSet struct { rawRules []rule.Rule rules map[string]rule.Rule verbose bool } func newRuleSet(rules []rule.Rule) *ruleSet { return &ruleSet{ rawRules: rules, } } func (c *ruleSet) initialize(req *proto.ListRulesRequest) { c.verbose = req.Verbose ruleMap := make(map[string]rule.Rule) for _, r := range c.rawRules { if f, ok := r.(RuleGen); ok { r = f( req.Verbose, req.FixMode, ) } ruleMap[r.ID()] = r } c.rules = ruleMap } func (c *ruleSet) ListRules(req *proto.ListRulesRequest) (*proto.ListRulesResponse, error) { c.initialize(req) var meta []*proto.ListRulesResponse_Rule for _, r := range c.rules { meta = append(meta, &proto.ListRulesResponse_Rule{ Id: r.ID(), Purpose: r.Purpose(), Severity: getSeverity(r.Severity()), }) } return &proto.ListRulesResponse{ Rules: meta, }, nil } func getSeverity(severity rule.Severity) proto.RuleSeverity { switch severity { case rule.SeverityError: return proto.RuleSeverity_RULE_SEVERITY_ERROR case rule.SeverityWarning: return proto.RuleSeverity_RULE_SEVERITY_WARNING case rule.SeverityNote: return proto.RuleSeverity_RULE_SEVERITY_NOTE } return proto.RuleSeverity_RULE_SEVERITY_UNSPECIFIED } func (c *ruleSet) Apply(req *proto.ApplyRequest) (*proto.ApplyResponse, error) { r, ok := c.rules[req.Id] if !ok { return nil, fmt.Errorf("not found rule=%s", req.Id) } absPath := req.Path protoFile := file.NewProtoFile(absPath, absPath) p, err := protoFile.Parse(c.verbose) if err != nil { return nil, err } fs, err := r.Apply(p) if err != nil { return nil, err } var fsp []*proto.ApplyResponse_Failure for _, f := range fs { fsp = append(fsp, &proto.ApplyResponse_Failure{ Message: f.Message(), Pos: &proto.ApplyResponse_Position{ Offset: int32(f.Pos().Offset), Line: int32(f.Pos().Line), Column: int32(f.Pos().Column), }, }) } return &proto.ApplyResponse{ Failures: fsp, }, nil } <file_sep>/internal/linter/config/syntaxConsistentOption.go package config // SyntaxConsistentOption represents the option for the SYNTAX_CONSISTENT rule. type SyntaxConsistentOption struct { CustomizableSeverityOption Version string `yaml:"version"` } <file_sep>/internal/linter/file/protoFile.go package file import ( "os" protoparser "github.com/yoheimuta/go-protoparser/v4" "github.com/yoheimuta/go-protoparser/v4/parser" ) // ProtoFile is a Protocol Buffer file. type ProtoFile struct { // The path to the .proto file. // Must be absolute. // Must be cleaned. path string // The path to display in output. // This will be relative to the working directory, or the absolute path // if the file was outside the working directory. displayPath string } // NewProtoFile creates a new proto file. func NewProtoFile( path string, displayPath string, ) ProtoFile { return ProtoFile{ path: path, displayPath: displayPath, } } // Parse parses a Protocol Buffer file. func (f ProtoFile) Parse( debug bool, ) (_ *parser.Proto, err error) { reader, err := os.Open(f.path) if err != nil { return nil, err } defer func() { closeErr := reader.Close() if err != nil { return } if closeErr != nil { err = closeErr } }() proto, err := protoparser.Parse( reader, protoparser.WithFilename(f.displayPath), protoparser.WithBodyIncludingComments(true), protoparser.WithDebug(debug), ) if err != nil { return nil, err } return proto, nil } // Path returns the path to the .proto file. func (f ProtoFile) Path() string { return f.path } // DisplayPath returns the path to display in output. func (f ProtoFile) DisplayPath() string { return f.displayPath } <file_sep>/internal/addon/rules/rpcNamesCaseRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/linter/config" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // RPCNamesCaseRule verifies that all rpc names conform to the specified convention. type RPCNamesCaseRule struct { RuleWithSeverity convention config.ConventionType } // NewRPCNamesCaseRule creates a new RPCNamesCaseRule. func NewRPCNamesCaseRule( severity rule.Severity, convention config.ConventionType, ) RPCNamesCaseRule { return RPCNamesCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, convention: convention, } } // ID returns the ID of this rule. func (r RPCNamesCaseRule) ID() string { return "RPC_NAMES_CASE" } // Purpose returns the purpose of this rule. func (r RPCNamesCaseRule) Purpose() string { return "Verifies that all rpc names conform to the specified convention." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r RPCNamesCaseRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r RPCNamesCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &rpcNamesCaseVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), convention: r.convention, } return visitor.RunVisitor(v, proto, r.ID()) } type rpcNamesCaseVisitor struct { *visitor.BaseAddVisitor convention config.ConventionType } // VisitRPC checks the rpc. func (v *rpcNamesCaseVisitor) VisitRPC(rpc *parser.RPC) bool { if v.convention == config.ConventionLowerCamel && !strs.IsLowerCamelCase(rpc.RPCName) { v.AddFailuref(rpc.Meta.Pos, "RPC name %q must be LowerCamelCase", rpc.RPCName) } else if v.convention == config.ConventionUpperSnake && !strs.IsUpperSnakeCase(rpc.RPCName) { v.AddFailuref(rpc.Meta.Pos, "RPC name %q must be UpperSnakeCase", rpc.RPCName) } else if v.convention == config.ConventionLowerSnake && !strs.IsLowerSnakeCase(rpc.RPCName) { v.AddFailuref(rpc.Meta.Pos, "RPC name %q must be LowerSnakeCase", rpc.RPCName) } return false } <file_sep>/internal/linter/config/externalConfig_test.go package config_test import ( "testing" "github.com/yoheimuta/protolint/internal/filepathutil" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/internal/cmd/subcmds" "github.com/yoheimuta/protolint/internal/linter/config" ) func TestExternalConfig_ShouldSkipRule(t *testing.T) { noDefaultExternalConfig := config.ExternalConfig{ Lint: config.Lint{ Ignores: []config.Ignore{ { ID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", Files: []string{ "path/to/foo.proto", "/path/to/bar.proto", `\path\to\bar_windows.proto`, }, }, { ID: "ENUM_NAMES_UPPER_CAMEL_CASE", Files: []string{ "path/to/foo.proto", }, }, }, Directories: config.Directories{ Exclude: []string{ "path/to/dir", "/path/to/dir2", `\path\to\dir_windows`, }, }, Files: config.Files{ Exclude: []string{ "path/to/file.proto", "/path/to/file2.proto", `path\to\file_windows.proto`, }, }, Rules: struct { NoDefault bool `yaml:"no_default"` AllDefault bool `yaml:"all_default"` Add []string `yaml:"add"` Remove []string `yaml:"remove"` }{ NoDefault: true, Add: []string{ "FIELD_NAMES_LOWER_SNAKE_CASE", "MESSAGE_NAMES_UPPER_CAMEL_CASE", "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", "ENUM_NAMES_UPPER_CAMEL_CASE", }, Remove: []string{ "RPC_NAMES_UPPER_CAMEL_CASE", }, }, }, } defaultExternalConfig := config.ExternalConfig{ Lint: config.Lint{ Ignores: []config.Ignore{ { ID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", Files: []string{ "path/to/foo.proto", "path/to/bar.proto", }, }, { ID: "ENUM_NAMES_UPPER_CAMEL_CASE", Files: []string{ "path/to/foo.proto", }, }, }, Rules: struct { NoDefault bool `yaml:"no_default"` AllDefault bool `yaml:"all_default"` Add []string `yaml:"add"` Remove []string `yaml:"remove"` }{ NoDefault: false, Add: []string{ "FIELD_NAMES_LOWER_SNAKE_CASE", "MESSAGE_NAMES_UPPER_CAMEL_CASE", }, Remove: []string{ "RPC_NAMES_UPPER_CAMEL_CASE", }, }, }, } allRules, err := subcmds.NewAllRules(config.RulesOption{}, false, autodisable.Noop, false, nil) if err != nil { t.Error(err) return } for _, test := range []struct { name string externalConfig config.ExternalConfig inputRuleID string inputDisplayPath string inputDefaultRuleIDs []string inputIsWindowsPathSeparator bool wantSkipRule bool }{ { name: "ignore ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisplayPath: "path/to/foo.proto", wantSkipRule: true, }, { name: "ignore ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisplayPath: "/path/to/bar.proto", wantSkipRule: true, }, { name: "ignore ENUM_NAMES_UPPER_CAMEL_CASE", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_NAMES_UPPER_CAMEL_CASE", inputDisplayPath: "path/to/foo.proto", wantSkipRule: true, }, { name: "ignore a windows path by referring to a windows path", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisplayPath: `\path\to\bar_windows.proto`, inputIsWindowsPathSeparator: true, wantSkipRule: true, }, { name: "ignore a windows path by referring to an unix path", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisplayPath: `path\to\foo.proto`, inputIsWindowsPathSeparator: true, wantSkipRule: true, }, { name: "not ignore FIELD_NAMES_LOWER_SNAKE_CASE", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "/path/to/bar.proto", }, { name: "not ignore ENUM_FIELD_NAMES_UPPER_SNAKE_CASE because of a file mismatch", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisplayPath: "path/to/baz.proto", }, { name: "not ignore ENUM_NAMES_UPPER_CAMEL_CASE because of a file mismatch", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_NAMES_UPPER_CAMEL_CASE", inputDisplayPath: "path/to/bar.proto", }, { name: "not ignore an unix path by referring to a windows path", externalConfig: noDefaultExternalConfig, inputRuleID: "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE", inputDisplayPath: `/path/to/bar_windows.proto`, }, { name: "not skip Add rules", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", }, { name: "skip noAdd rules", externalConfig: noDefaultExternalConfig, inputRuleID: "RPC_NAMES_UPPER_CAMEL_CASE", wantSkipRule: true, }, { name: "skip Remove rule", externalConfig: defaultExternalConfig, inputRuleID: "RPC_NAMES_UPPER_CAMEL_CASE", wantSkipRule: true, }, { name: "not skip noRemove rule", externalConfig: defaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", }, { name: "not skip default rules", externalConfig: defaultExternalConfig, inputRuleID: "HOGE_RULE", inputDefaultRuleIDs: []string{ "HOGE_RULE", }, }, { name: "not skip default one", externalConfig: config.ExternalConfig{}, inputRuleID: allRules.Default().IDs()[0], inputDefaultRuleIDs: allRules.Default().IDs(), }, { name: "exclude the directory", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "path/to/dir/bar.proto", wantSkipRule: true, }, { name: "exclude the another directory", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "/path/to/dir2/bar.proto", wantSkipRule: true, }, { name: "exclude the child directory", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "/path/to/dir2/child/bar.proto", wantSkipRule: true, }, { name: "exclude the matched windows directory", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: `\path\to\dir_windows\foo.proto`, inputIsWindowsPathSeparator: true, wantSkipRule: true, }, { name: "exclude the matched windows directory by referring to an unix filepath", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: `\path\to\dir2\child\bar.proto`, inputIsWindowsPathSeparator: true, wantSkipRule: true, }, { name: "not exclude the another directory", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "path/to/dir3/bar.proto", }, { name: "not exclude the unix directory by referring to a windows directory", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: `/path/to/dir_windows/bar.proto`, }, { name: "exclude the matched file", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "path/to/file.proto", wantSkipRule: true, }, { name: "exclude the matched file", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "/path/to/file2.proto", wantSkipRule: true, }, { name: "exclude the matched windows file", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: `path\to\file_windows.proto`, inputIsWindowsPathSeparator: true, wantSkipRule: true, }, { name: "exclude the matched windows file by referring to an unix file", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: `\path\to\file2.proto`, inputIsWindowsPathSeparator: true, wantSkipRule: true, }, { name: "not exclude the unmatched file", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "/path/to/file3.proto", }, { name: "not exclude the unmatched file path", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: "path/to1/file.proto", }, { name: "not exclude the unix file by referring to a windows path", externalConfig: noDefaultExternalConfig, inputRuleID: "FIELD_NAMES_LOWER_SNAKE_CASE", inputDisplayPath: `path/to/file_windows.proto`, }, } { test := test t.Run(test.name, func(t *testing.T) { osPathSep := '/' if test.inputIsWindowsPathSeparator { osPathSep = '\\' } prevOSPathSep := filepathutil.OSPathSeparator filepathutil.OSPathSeparator = osPathSep defer func() { filepathutil.OSPathSeparator = prevOSPathSep }() got := test.externalConfig.ShouldSkipRule( test.inputRuleID, test.inputDisplayPath, test.inputDefaultRuleIDs, ) if got != test.wantSkipRule { t.Errorf("got %v, but want %v", got, test.wantSkipRule) } }) } } <file_sep>/internal/addon/rules/indentRule_test.go package rules_test import ( "reflect" "strings" "testing" "github.com/yoheimuta/protolint/internal/util_test" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestIndentRule_Apply(t *testing.T) { defaultSpace := strings.Repeat(" ", 2) tests := []struct { name string inputStyle string inputProtoPath string inputInsertNewline bool wantFailures []report.Failure wantExistErr bool }{ { name: "correct syntax", inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "syntax.proto"), }, { name: "incorrect syntax", inputStyle: defaultSpace, inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "incorrect_syntax.proto"), wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_syntax.proto"), Offset: 14, Line: 2, Column: 5, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", "", ), }, }, { name: "correct enum", inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "enum.proto"), }, { name: "incorrect enum", inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "incorrect_enum.proto"), wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_enum.proto"), Offset: 67, Line: 4, Column: 9, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", defaultSpace, ), report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_enum.proto"), Offset: 114, Line: 6, Column: 6, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", defaultSpace, ), report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_enum.proto"), Offset: 162, Line: 7, Column: 2, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", "", ), }, }, { name: "correct message", inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "message.proto"), }, { name: "incorrect message", inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "incorrect_message.proto"), wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_message.proto"), Offset: 100, Line: 6, Column: 3, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", strings.Repeat(defaultSpace, 2), ), report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_message.proto"), Offset: 156, Line: 9, Column: 1, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, "", defaultSpace, ), report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_message.proto"), Offset: 287, Line: 14, Column: 7, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", strings.Repeat(defaultSpace, 2), ), }, }, { name: "handle the proto containing extend. Fix https://github.com/yoheimuta/protolint/issues/63", inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "issue_63.proto"), }, { name: `handle the case that the last rpc method of a service is having a statement block. Fix https://github.com/yoheimuta/protolint/issues/74`, inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "issue_74.proto"), }, { name: `skip wrong indentations of inner elements on the same line. Fix https://github.com/yoheimuta/protolint/issues/139`, inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "issue_139.proto"), }, { name: `detect only a toplevel indentation mistake and skip other than that on the same line. Fix https://github.com/yoheimuta/protolint/issues/139`, inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "incorrect_issue_139.proto"), wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_issue_139.proto"), Offset: 222, Line: 11, Column: 3, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", "", ), }, }, { name: `do not skip wrong indentations of inner elements on the same line. Fix https://github.com/yoheimuta/protolint/issues/139`, inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "incorrect_issue_139_short.proto"), inputInsertNewline: true, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_issue_139_short.proto"), Offset: 82, Line: 7, Column: 3, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", "", ), report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_issue_139_short.proto"), Offset: 104, Line: 7, Column: 25, }, "INDENT", `Found a possible incorrect indentation style. Inserting a new line is recommended.`, ), report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "incorrect_issue_139_short.proto"), Offset: 127, Line: 7, Column: 48, }, "INDENT", `Found a possible incorrect indentation style. Inserting a new line is recommended.`, ), }, }, { name: `handle the case that the proto has a mixture of line ending formats like LF and CRLF. Fix https://github.com/yoheimuta/protolint/issues/280`, inputProtoPath: setting_test.TestDataPath("rules", "indentrule", "issue_280_mix_lineending.proto"), wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: setting_test.TestDataPath("rules", "indentrule", "issue_280_mix_lineending.proto"), Offset: 580, Line: 27, Column: 5, }, "INDENT", `Found an incorrect indentation style "%s". "%s" is correct.`, " ", " ", ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewIndentRule( rule.SeverityError, test.inputStyle, !test.inputInsertNewline, false, ) proto, err := file.NewProtoFile(test.inputProtoPath, test.inputProtoPath).Parse(false) if err != nil { t.Errorf(err.Error()) return } got, err := rule.Apply(proto) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) if len(got) != len(test.wantFailures) { t.Errorf("len(got) %v, but len(want) %v", len(got), len(test.wantFailures)) return } for k, v := range got { if !reflect.DeepEqual(v.Pos(), test.wantFailures[k].Pos()) { t.Errorf("got[%v].Pos() %v(offset=%v), but want[%v].Pos() %v", k, v.Pos(), v.Pos().Offset, k, test.wantFailures[k].Pos()) continue } if !reflect.DeepEqual(v.Message(), test.wantFailures[k].Message()) { t.Errorf("got[%v].Message() %v, but want[%v].Message() %v", k, v.Message(), k, test.wantFailures[k].Message()) continue } if !reflect.DeepEqual(v, test.wantFailures[k]) { t.Errorf("got[%v] %v, but want[%v] %v", k, v, k, test.wantFailures[k]) continue } } } }) } } func newTestIndentData( fileName string, ) (util_test.TestData, error) { return util_test.NewTestData(setting_test.TestDataPath("rules", "indentrule", fileName)) } func TestIndentRule_Apply_fix(t *testing.T) { space2 := strings.Repeat(" ", 2) correctSyntaxPath, err := newTestIndentData("syntax.proto") if err != nil { t.Errorf("got err %v", err) return } incorrectSyntaxPath, err := newTestIndentData("incorrect_syntax.proto") if err != nil { t.Errorf("got err %v", err) return } correctEnumPath, err := newTestIndentData("enum.proto") if err != nil { t.Errorf("got err %v", err) return } incorrectEnumPath, err := newTestIndentData("incorrect_enum.proto") if err != nil { t.Errorf("got err %v", err) return } correctMessagePath, err := newTestIndentData("message.proto") if err != nil { t.Errorf("got err %v", err) return } incorrectMessagePath, err := newTestIndentData("incorrect_message.proto") if err != nil { t.Errorf("got err %v", err) return } correctIssue99Path, err := newTestIndentData("issue_99.proto") if err != nil { t.Errorf("got err %v", err) return } incorrectIssue99Path, err := newTestIndentData("incorrect_issue_99.proto") if err != nil { t.Errorf("got err %v", err) return } incorrectIssue139Path, err := newTestIndentData("incorrect_issue_139.proto") if err != nil { t.Errorf("got err %v", err) return } correctIssue139Path, err := newTestIndentData("issue_139.proto") if err != nil { t.Errorf("got err %v", err) return } correctIssue139InsertPath, err := newTestIndentData("issue_139_insert_linebreaks.proto") if err != nil { t.Errorf("got err %v", err) return } tests := []struct { name string inputTestData util_test.TestData inputInsertNewline bool wantCorrectData util_test.TestData }{ { name: "correct syntax", inputTestData: correctSyntaxPath, wantCorrectData: correctSyntaxPath, }, { name: "incorrect syntax", inputTestData: incorrectSyntaxPath, wantCorrectData: correctSyntaxPath, }, { name: "correct enum", inputTestData: correctEnumPath, wantCorrectData: correctEnumPath, }, { name: "incorrect enum", inputTestData: incorrectEnumPath, wantCorrectData: correctEnumPath, }, { name: "correct message", inputTestData: correctMessagePath, wantCorrectData: correctMessagePath, }, { name: "incorrect message", inputTestData: incorrectMessagePath, wantCorrectData: correctMessagePath, }, { name: "correct issue_99", inputTestData: correctIssue99Path, wantCorrectData: correctIssue99Path, }, { name: "incorrect issue_99", inputTestData: incorrectIssue99Path, wantCorrectData: correctIssue99Path, }, { name: "do nothing against inner elements on the same line. Fix https://github.com/yoheimuta/protolint/issues/139", inputTestData: incorrectIssue139Path, wantCorrectData: correctIssue139Path, }, { name: "insert linebreaks against inner elements on the same line. Fix https://github.com/yoheimuta/protolint/issues/139", inputTestData: incorrectIssue139Path, inputInsertNewline: true, wantCorrectData: correctIssue139InsertPath, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule_to_test := rules.NewIndentRule( rule.SeverityError, space2, !test.inputInsertNewline, true, ) proto, err := file.NewProtoFile(test.inputTestData.FilePath, test.inputTestData.FilePath).Parse(false) if err != nil { t.Errorf(err.Error()) return } _, err = rule_to_test.Apply(proto) if err != nil { t.Errorf("got err %v, but want nil", err) return } got, err := test.inputTestData.Data() if !reflect.DeepEqual(got, test.wantCorrectData.OriginData) { t.Errorf( "got %s(%v), but want %s(%v)", string(got), got, string(test.wantCorrectData.OriginData), test.wantCorrectData.OriginData, ) } // restore the file defer func() { err = test.inputTestData.Restore() if err != nil { t.Errorf("got err %v", err) } }() // check whether the modified content can pass the lint in the end. ruleOnlyCheck := rules.NewIndentRule( rule.SeverityError, space2, !test.inputInsertNewline, false, ) proto, err = file.NewProtoFile(test.inputTestData.FilePath, test.inputTestData.FilePath).Parse(false) if err != nil { t.Errorf(err.Error()) return } gotCheck, err := ruleOnlyCheck.Apply(proto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if 0 < len(gotCheck) { t.Errorf("got failures %v, but want no failures", gotCheck) return } }) } } <file_sep>/internal/addon/rules/enumFieldsHaveCommentRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // EnumFieldsHaveCommentRule verifies that all enumFields have a comment. type EnumFieldsHaveCommentRule struct { RuleWithSeverity // Golang style comments should begin with the name of the thing being described. // See https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences shouldFollowGolangStyle bool } // NewEnumFieldsHaveCommentRule creates a new EnumFieldsHaveCommentRule. func NewEnumFieldsHaveCommentRule( severity rule.Severity, shouldFollowGolangStyle bool, ) EnumFieldsHaveCommentRule { return EnumFieldsHaveCommentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, shouldFollowGolangStyle: shouldFollowGolangStyle, } } // ID returns the ID of this rule. func (r EnumFieldsHaveCommentRule) ID() string { return "ENUM_FIELDS_HAVE_COMMENT" } // Purpose returns the purpose of this rule. func (r EnumFieldsHaveCommentRule) Purpose() string { return "Verifies that all enum fields have a comment." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r EnumFieldsHaveCommentRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r EnumFieldsHaveCommentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &enumFieldsHaveCommentVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), shouldFollowGolangStyle: r.shouldFollowGolangStyle, } return visitor.RunVisitor(v, proto, r.ID()) } type enumFieldsHaveCommentVisitor struct { *visitor.BaseAddVisitor shouldFollowGolangStyle bool } // VisitEnumField checks the enumField. func (v *enumFieldsHaveCommentVisitor) VisitEnumField(enumField *parser.EnumField) bool { n := enumField.Ident if v.shouldFollowGolangStyle && !hasGolangStyleComment(enumField.Comments, n) { v.AddFailuref(enumField.Meta.Pos, `EnumField %q should have a comment of the form "// %s ..."`, n, n) } else if !hasComments(enumField.Comments, enumField.InlineComment) { v.AddFailuref(enumField.Meta.Pos, `EnumField %q should have a comment`, n) } return false } <file_sep>/internal/addon/rules/repeatedFieldNamesPluralizedRule.go package rules import ( "strings" "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/lexer/scanner" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // RepeatedFieldNamesPluralizedRule verifies that repeated field names are pluralized names. // See https://developers.google.com/protocol-buffers/docs/style#repeated-fields. type RepeatedFieldNamesPluralizedRule struct { RuleWithSeverity pluralRules map[string]string singularRules map[string]string uncountableRules []string irregularRules map[string]string fixMode bool autoDisableType autodisable.PlacementType } // NewRepeatedFieldNamesPluralizedRule creates a new RepeatedFieldNamesPluralizedRule. func NewRepeatedFieldNamesPluralizedRule( severity rule.Severity, pluralRules map[string]string, singularRules map[string]string, uncountableRules []string, irregularRules map[string]string, fixMode bool, autoDisableType autodisable.PlacementType, ) RepeatedFieldNamesPluralizedRule { if autoDisableType != autodisable.Noop { fixMode = false } return RepeatedFieldNamesPluralizedRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, pluralRules: pluralRules, singularRules: singularRules, uncountableRules: uncountableRules, irregularRules: irregularRules, fixMode: fixMode, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r RepeatedFieldNamesPluralizedRule) ID() string { return "REPEATED_FIELD_NAMES_PLURALIZED" } // Purpose returns the purpose of this rule. func (r RepeatedFieldNamesPluralizedRule) Purpose() string { return "Verifies that repeated field names are pluralized names." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r RepeatedFieldNamesPluralizedRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r RepeatedFieldNamesPluralizedRule) Apply(proto *parser.Proto) ([]report.Failure, error) { c := strs.NewPluralizeClient() for k, v := range r.pluralRules { c.AddPluralRule(k, v) } for k, v := range r.singularRules { c.AddSingularRule(k, v) } for _, w := range r.uncountableRules { c.AddUncountableRule(w) } for k, v := range r.irregularRules { c.AddIrregularRule(k, v) } base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &repeatedFieldNamesPluralizedVisitor{ BaseFixableVisitor: base, pluralizeClient: c, } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type repeatedFieldNamesPluralizedVisitor struct { *visitor.BaseFixableVisitor pluralizeClient *strs.PluralizeClient } // VisitField checks the field. func (v *repeatedFieldNamesPluralizedVisitor) VisitField(field *parser.Field) bool { got := field.FieldName want := v.pluralizeClient.ToPlural(got) if field.IsRepeated && strings.ToLower(got) != strings.ToLower(want) { v.AddFailuref(field.Meta.Pos, "Repeated field name %q must be pluralized name %q", got, want) err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() switch lex.Token { case scanner.TREPEATED, scanner.TREQUIRED, scanner.TOPTIONAL: default: lex.UnNext() } parseType(lex) lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(want), } }) if err != nil { panic(err) } } return false } // VisitGroupField checks the group field. func (v *repeatedFieldNamesPluralizedVisitor) VisitGroupField(field *parser.GroupField) bool { got := field.GroupName want := v.pluralizeClient.ToPlural(got) if field.IsRepeated && strings.ToLower(got) != strings.ToLower(want) { v.AddFailuref(field.Meta.Pos, "Repeated group name %q must be pluralized name %q", got, want) err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() switch lex.Token { case scanner.TREPEATED, scanner.TREQUIRED, scanner.TOPTIONAL: default: lex.UnNext() } lex.NextKeyword() lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(want), } }) if err != nil { panic(err) } } return true } <file_sep>/internal/linter/linter.go package linter import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) // Linter represents the protocol buffer linter with some rules. type Linter struct{} // NewLinter creates a new Linter. func NewLinter() *Linter { return &Linter{} } // Run lints the protocol buffer. func (l *Linter) Run( genProto func(*parser.Proto) (*parser.Proto, error), hasApplies []rule.HasApply, ) ([]report.Failure, error) { var fs []report.Failure var p *parser.Proto var err error for _, hasApply := range hasApplies { p, err = genProto(p) if err != nil { return nil, err } f, err := hasApply.Apply(p) if err != nil { return nil, err } fs = append(fs, f...) } return fs, nil } <file_sep>/linter/autodisable/nextPlacementStrategy.go package autodisable import "github.com/yoheimuta/go-protoparser/v4/parser" type nextPlacementStrategy struct { c *commentator } func newNextPlacementStrategy(c *commentator) *nextPlacementStrategy { return &nextPlacementStrategy{ c: c, } } func (p *nextPlacementStrategy) Disable( offset int, _ []*parser.Comment, _ *parser.Comment) { p.c.insertNewline(offset) } func (p *nextPlacementStrategy) Finalize() error { return p.c.finalize() } <file_sep>/internal/addon/rules/fieldNamesLowerSnakeCaseRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/lexer/scanner" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // FieldNamesLowerSnakeCaseRule verifies that all field names are underscore_separated_names. // See https://developers.google.com/protocol-buffers/docs/style#message-and-field-names. type FieldNamesLowerSnakeCaseRule struct { RuleWithSeverity fixMode bool autoDisableType autodisable.PlacementType } // NewFieldNamesLowerSnakeCaseRule creates a new FieldNamesLowerSnakeCaseRule. func NewFieldNamesLowerSnakeCaseRule( severity rule.Severity, fixMode bool, autoDisableType autodisable.PlacementType, ) FieldNamesLowerSnakeCaseRule { if autoDisableType != autodisable.Noop { fixMode = false } return FieldNamesLowerSnakeCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r FieldNamesLowerSnakeCaseRule) ID() string { return "FIELD_NAMES_LOWER_SNAKE_CASE" } // Purpose returns the purpose of this rule. func (r FieldNamesLowerSnakeCaseRule) Purpose() string { return "Verifies that all field names are underscore_separated_names." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r FieldNamesLowerSnakeCaseRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r FieldNamesLowerSnakeCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &fieldNamesLowerSnakeCaseVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type fieldNamesLowerSnakeCaseVisitor struct { *visitor.BaseFixableVisitor } // VisitField checks the field. func (v *fieldNamesLowerSnakeCaseVisitor) VisitField(field *parser.Field) bool { name := field.FieldName if !strs.IsLowerSnakeCase(name) { expected := strs.ToLowerSnakeCase(name) v.AddFailuref(field.Meta.Pos, "Field name %q must be underscore_separated_names like %q", name, expected) err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() switch lex.Token { case scanner.TREPEATED, scanner.TREQUIRED, scanner.TOPTIONAL: default: lex.UnNext() } parseType(lex) lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } // VisitMapField checks the map field. func (v *fieldNamesLowerSnakeCaseVisitor) VisitMapField(field *parser.MapField) bool { name := field.MapName if !strs.IsLowerSnakeCase(name) { expected := strs.ToLowerSnakeCase(name) v.AddFailuref(field.Meta.Pos, "Field name %q must be underscore_separated_names like %q", name, expected) err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() lex.Next() lex.Next() lex.Next() parseType(lex) lex.Next() lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } // VisitOneofField checks the oneof field. func (v *fieldNamesLowerSnakeCaseVisitor) VisitOneofField(field *parser.OneofField) bool { name := field.FieldName if !strs.IsLowerSnakeCase(name) { expected := strs.ToLowerSnakeCase(name) v.AddFailuref(field.Meta.Pos, "Field name %q must be underscore_separated_names like %q", name, expected) err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { parseType(lex) lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } // Below codes are copied from go-protoparser. var typeConstants = map[string]struct{}{ "double": {}, "float": {}, "int32": {}, "int64": {}, "uint32": {}, "uint64": {}, "sint32": {}, "sint64": {}, "fixed32": {}, "fixed64": {}, "sfixed32": {}, "sfixed64": {}, "bool": {}, "string": {}, "bytes": {}, } func parseType(lex *lexer.Lexer) { lex.Next() if _, ok := typeConstants[lex.Text]; ok { return } lex.UnNext() _, _, err := lex.ReadMessageType() if err != nil { panic(err) } } <file_sep>/internal/addon/rules/serviceNamesEndWithRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestValidServiceNamesEndWithRule_Apply(t *testing.T) { validTestCase := struct { name string inputProto *parser.Proto wantFailures []report.Failure }{ name: "no failures for proto with valid service names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceName: "SomeServiceService", }, &parser.Service{ ServiceName: "AnotherService", }, }, }, } t.Run(validTestCase.name, func(t *testing.T) { rule := rules.NewServiceNamesEndWithRule(rule.SeverityError, "Service") _, err := rule.Apply(validTestCase.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } }) } func TestInvalidServiceNamesEndWithRule_Apply(t *testing.T) { invalidTestCase := struct { name string inputProto *parser.Proto wantFailures []report.Failure }{ name: "failures for proto with invalid service names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{ ServiceName: "SomeThing", }, &parser.Service{ ServiceName: "AnotherThing", }, }, }, wantFailures: []report.Failure{ report.Failuref(meta.Position{}, "SERVICE_NAMES_END_WITH", `Service name "SomeThing" must end with Service`), report.Failuref(meta.Position{}, "SERVICE_NAMES_END_WITH", `Service name "AnotherThing" must end with Service`), }, } t.Run(invalidTestCase.name, func(t *testing.T) { rule := rules.NewServiceNamesEndWithRule(rule.SeverityError, "Service") got, err := rule.Apply(invalidTestCase.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, invalidTestCase.wantFailures) { t.Errorf("got %v, but want %v", got, invalidTestCase.wantFailures) } }) } <file_sep>/linter/fixer/fixer.go package fixer import ( "bytes" "io/ioutil" "strings" "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/osutil" ) // TextEdit represents the replacement of the code between Pos and End with the new text. type TextEdit struct { Pos int End int // Inclusive. If the target is abc, pos and end are 1 and 3, respectively. NewText []byte } // Fixer provides the ways to operate the proto content. type Fixer interface { // NOTE: This method is insufficient to process unexpected multi-line contents. ReplaceText(line int, old, new string) ReplaceAll(proc func(lines []string) []string) SearchAndReplace(startPos meta.Position, lex func(lex *lexer.Lexer) TextEdit) error ReplaceContent(proc func(content []byte) []byte) Lines() []string } // Fixing adds the way to modify the proto file to Fixer. type Fixing interface { Fixer Finally() error } // NewFixing creates a fixing, depending on fixMode. func NewFixing(fixMode bool, proto *parser.Proto) (Fixing, error) { if fixMode { return NewBaseFixing(proto.Meta.Filename) } return NopFixing{}, nil } // BaseFixing implements Fixing. type BaseFixing struct { content []byte lineEnding string fileName string textEdits []TextEdit } // NewBaseFixing creates a BaseFixing. func NewBaseFixing(protoFileName string) (*BaseFixing, error) { content, err := ioutil.ReadFile(protoFileName) if err != nil { return nil, err } // Regardless of the actual dominant line ending, the fixer will go with LF // because the parser recognizes only LF as a line ending. // // It will work for most cases like used LF, CRLF, and a mix of LF and CRLF. // See also https://github.com/yoheimuta/protolint/issues/280. lineEnding := "\n" return &BaseFixing{ content: content, lineEnding: lineEnding, fileName: protoFileName, }, nil } // ReplaceText replaces the text at the line. func (f *BaseFixing) ReplaceText(line int, old, new string) { lines := strings.Split(string(f.content), f.lineEnding) lines[line-1] = strings.Replace(lines[line-1], old, new, 1) f.content = []byte(strings.Join(lines, f.lineEnding)) } // ReplaceAll replaces the lines. func (f *BaseFixing) ReplaceAll(proc func(lines []string) []string) { lines := strings.Split(string(f.content), f.lineEnding) lines = proc(lines) f.content = []byte(strings.Join(lines, f.lineEnding)) } // SearchAndReplace locates text edits and replaces with them. func (f *BaseFixing) SearchAndReplace(startPos meta.Position, lex func(lex *lexer.Lexer) TextEdit) error { r := bytes.NewReader(f.content) _, err := r.Seek(int64(startPos.Offset), 0) if err != nil { return err } l := lexer.NewLexer(r) t := lex(l) t.Pos += startPos.Offset t.End += startPos.Offset f.textEdits = append(f.textEdits, t) return nil } // ReplaceContent replaces entire content. func (f *BaseFixing) ReplaceContent(proc func(content []byte) []byte) { f.content = proc(f.content) } // Lines returns the line format of f.content. func (f *BaseFixing) Lines() []string { return strings.Split(string(f.content), f.lineEnding) } // Finally writes the fixed content to the file. func (f *BaseFixing) Finally() error { diff := 0 for _, t := range f.textEdits { t.Pos += diff t.End += diff f.content = append(f.content[:t.Pos], append(t.NewText, f.content[t.End+1:]...)...) diff += len(t.NewText) - (t.End - t.Pos + 1) } return osutil.WriteExistingFile(f.fileName, f.content) } // Replace records a textedit to replace the old with the next later. func (f *BaseFixing) Replace(t TextEdit) { f.textEdits = append(f.textEdits, t) } // Content returns f.content. func (f *BaseFixing) Content() []byte { return f.content } // LineEnding is a detected line ending. func (f *BaseFixing) LineEnding() string { return f.lineEnding } // NopFixing does nothing. type NopFixing struct{} // ReplaceText noop func (f NopFixing) ReplaceText(line int, old, new string) {} // ReplaceAll noop func (f NopFixing) ReplaceAll(proc func(lines []string) []string) {} // SearchAndReplace noop func (f NopFixing) SearchAndReplace(startPos meta.Position, lex func(lexer *lexer.Lexer) TextEdit) error { return nil } // ReplaceContent noop. func (f NopFixing) ReplaceContent(proc func(content []byte) []byte) {} // Lines noop. func (f NopFixing) Lines() []string { return []string{} } // Finally noop func (f NopFixing) Finally() error { return nil } <file_sep>/internal/linter/config/rpcsHaveCommentOption.go package config // RPCsHaveCommentOption represents the option for the RPCS_HAVE_COMMENT rule. type RPCsHaveCommentOption struct { CustomizableSeverityOption ShouldFollowGolangStyle bool `yaml:"should_follow_golang_style"` } <file_sep>/internal/linter/config/ignores.go package config // Ignores represents list about files ignoring the specific rule. type Ignores []Ignore func (is Ignores) shouldSkipRule( ruleID string, displayPath string, ) bool { for _, ignore := range is { if ignore.shouldSkipRule(ruleID, displayPath) { return true } } return false } <file_sep>/internal/linter/report/reporters/jUnitReporter.go package reporters import ( "encoding/xml" "fmt" "io" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/linter/report" ) const ( packageName = "net.protolint" ) // JUnitTestSuites is a collection of JUnit test suites. type JUnitTestSuites struct { XMLName xml.Name `xml:"testsuites"` Suites []JUnitTestSuite } // JUnitTestSuite is a single JUnit test suite which may contain many testcases. type JUnitTestSuite struct { XMLName xml.Name `xml:"testsuite"` Package string `xml:"package"` Tests int `xml:"tests,attr"` Failures int `xml:"failures,attr"` Time string `xml:"time,attr"` TestCases []JUnitTestCase } // JUnitTestCase is a single test case with its result. type JUnitTestCase struct { XMLName xml.Name `xml:"testcase"` ClassName string `xml:"classname,attr"` Name string `xml:"name,attr"` Time string `xml:"time,attr"` Failure *JUnitFailure `xml:"failure,omitempty"` } // JUnitFailure contains data related to a failed test. type JUnitFailure struct { Message string `xml:"message,attr"` Type string `xml:"type,attr"` Contents string `xml:",cdata"` } func constructTestCaseName(ruleID string) string { return packageName + "." + ruleID } func constructContents(pos meta.Position) string { return fmt.Sprintf("line %d, col %d", pos.Line, pos.Column) } // JUnitReporter prints failures in JUnit XML format. type JUnitReporter struct{} // Report writes failures to w. func (r JUnitReporter) Report(w io.Writer, fs []report.Failure) error { suites := &JUnitTestSuites{} if 0 < len(fs) { var testcases []JUnitTestCase for _, f := range fs { testcase := JUnitTestCase{ Name: constructTestCaseName(f.RuleID()), ClassName: f.FilenameWithoutExt(), Time: "0", Failure: &JUnitFailure{ Message: f.Message(), Type: "error", Contents: constructContents(f.Pos()), }, } testcases = append(testcases, testcase) } suite := JUnitTestSuite{ Package: packageName, Tests: len(fs), Failures: len(fs), Time: "0", TestCases: testcases, } suites.Suites = append(suites.Suites, suite) } else { suites.Suites = []JUnitTestSuite{ { Package: packageName, Tests: 1, Time: "0", TestCases: []JUnitTestCase{ { ClassName: constructTestCaseName("ALL_RULES"), Name: "All Rules", Time: "0", }, }, }, } } _, err := w.Write([]byte(xml.Header)) if err != nil { return err } enc := xml.NewEncoder(w) enc.Indent(" ", " ") err = enc.Encode(suites) if err != nil { return err } _, err = w.Write([]byte("\n")) if err != nil { return err } return nil } <file_sep>/internal/cmd/subcmds/list/flags.go package list import ( "flag" "github.com/yoheimuta/protolint/internal/cmd/subcmds" "github.com/yoheimuta/protolint/internal/addon/plugin/shared" ) // Flags represents a set of lint flag parameters. type Flags struct { *flag.FlagSet Plugins []shared.RuleSet } // NewFlags creates a new Flags. func NewFlags( args []string, ) (Flags, error) { f := Flags{ FlagSet: flag.NewFlagSet("list", flag.ExitOnError), } var pf subcmds.PluginFlag f.Var( &pf, "plugin", `plugins to provide custom lint rule set. Note that it's necessary to specify it as path format'`, ) _ = f.Parse(args) plugins, err := pf.BuildPlugins(false) if err != nil { return Flags{}, err } f.Plugins = plugins return f, nil } <file_sep>/internal/addon/rules/proto3FieldsAvoidRequiredRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // Proto3FieldsAvoidRequiredRule verifies that all fields should avoid required for proto3. // See https://developers.google.com/protocol-buffers/docs/style#things-to-avoid type Proto3FieldsAvoidRequiredRule struct { RuleWithSeverity fixMode bool } // NewProto3FieldsAvoidRequiredRule creates a new Proto3FieldsAvoidRequiredRule. func NewProto3FieldsAvoidRequiredRule( severity rule.Severity, fixMode bool, ) Proto3FieldsAvoidRequiredRule { return Proto3FieldsAvoidRequiredRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, } } // ID returns the ID of this rule. func (r Proto3FieldsAvoidRequiredRule) ID() string { return "PROTO3_FIELDS_AVOID_REQUIRED" } // Purpose returns the purpose of this rule. func (r Proto3FieldsAvoidRequiredRule) Purpose() string { return "Verifies that all fields should avoid required for proto3." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r Proto3FieldsAvoidRequiredRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r Proto3FieldsAvoidRequiredRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &proto3FieldsAvoidRequiredVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitor(v, proto, r.ID()) } type proto3FieldsAvoidRequiredVisitor struct { *visitor.BaseFixableVisitor isProto3 bool } // VisitSyntax checks the syntax. func (v *proto3FieldsAvoidRequiredVisitor) VisitSyntax(s *parser.Syntax) bool { v.isProto3 = s.ProtobufVersion == "proto3" return false } // VisitField checks the field. func (v *proto3FieldsAvoidRequiredVisitor) VisitField(field *parser.Field) bool { if v.isProto3 && field.IsRequired { v.AddFailuref(field.Meta.Pos, `Field %q should avoid required for proto3`, field.FieldName) err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text), NewText: []byte(""), } }) if err != nil { panic(err) } } return false } <file_sep>/_example/gradle/README.md # Gradle Example This is an example project that leverages protoc-gen-protolint. You can test it out by running `gradle generateProto`. After a successful run, you should see `results.txt` in the _build/generated/source/proto/main/protolint_ directory. <file_sep>/internal/linter/config/fieldNamesExcludePrepositionsOption.go package config // FieldNamesExcludePrepositionsOption represents the option for the FIELD_NAMES_EXCLUDE_PREPOSITIONS rule. type FieldNamesExcludePrepositionsOption struct { CustomizableSeverityOption Prepositions []string `yaml:"prepositions"` Excludes []string `yaml:"excludes"` } <file_sep>/internal/addon/rules/packageNameLowerCaseRule.go package rules import ( "strings" "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // PackageNameLowerCaseRule verifies that the package name doesn't contain any uppercase letters. // See https://developers.google.com/protocol-buffers/docs/style#packages. type PackageNameLowerCaseRule struct { RuleWithSeverity fixMode bool } // NewPackageNameLowerCaseRule creates a new PackageNameLowerCaseRule. func NewPackageNameLowerCaseRule( severity rule.Severity, fixMode bool, ) PackageNameLowerCaseRule { return PackageNameLowerCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, } } // ID returns the ID of this rule. func (r PackageNameLowerCaseRule) ID() string { return "PACKAGE_NAME_LOWER_CASE" } // Purpose returns the purpose of this rule. func (r PackageNameLowerCaseRule) Purpose() string { return "Verifies that the package name doesn't contain any uppercase letters." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r PackageNameLowerCaseRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r PackageNameLowerCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &packageNameLowerCaseVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitor(v, proto, r.ID()) } type packageNameLowerCaseVisitor struct { *visitor.BaseFixableVisitor } // VisitPackage checks the package. func (v *packageNameLowerCaseVisitor) VisitPackage(p *parser.Package) bool { name := p.Name if !isPackageLowerCase(name) { expected := strings.ToLower(name) v.AddFailuref(p.Meta.Pos, "Package name %q must not contain any uppercase letter. Consider to change like %q.", name, expected) err := v.Fixer.SearchAndReplace(p.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.NextKeyword() ident, startPos, _ := lex.ReadFullIdent() return fixer.TextEdit{ Pos: startPos.Offset, End: startPos.Offset + len(ident) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } func isPackageLowerCase(packageName string) bool { return !strs.HasAnyUpperCase(packageName) } <file_sep>/linter/visitor/baseVisitor.go package visitor import ( "github.com/yoheimuta/go-protoparser/v4/parser" ) // BaseVisitor represents a base visitor with noop logic. type BaseVisitor struct{} // OnStart works noop. func (BaseVisitor) OnStart(*parser.Proto) error { return nil } // Finally works noop. func (BaseVisitor) Finally() error { return nil } // VisitComment works noop. func (BaseVisitor) VisitComment(*parser.Comment) {} // VisitEmptyStatement works noop. func (BaseVisitor) VisitEmptyStatement(*parser.EmptyStatement) (next bool) { return true } // VisitEnum works noop. func (BaseVisitor) VisitEnum(*parser.Enum) (next bool) { return true } // VisitEnumField works noop. func (BaseVisitor) VisitEnumField(*parser.EnumField) (next bool) { return true } // VisitExtensions works noop. func (BaseVisitor) VisitExtensions(*parser.Extensions) bool { return true } // VisitExtend works noop. func (BaseVisitor) VisitExtend(*parser.Extend) (next bool) { return true } // VisitField works noop. func (BaseVisitor) VisitField(*parser.Field) (next bool) { return true } // VisitGroupField works noop. func (BaseVisitor) VisitGroupField(*parser.GroupField) bool { return true } // VisitImport works noop. func (BaseVisitor) VisitImport(*parser.Import) (next bool) { return true } // VisitMapField works noop. func (BaseVisitor) VisitMapField(*parser.MapField) (next bool) { return true } // VisitMessage works noop. func (BaseVisitor) VisitMessage(*parser.Message) (next bool) { return true } // VisitOneof works noop. func (BaseVisitor) VisitOneof(*parser.Oneof) (next bool) { return true } // VisitOneofField works noop. func (BaseVisitor) VisitOneofField(*parser.OneofField) (next bool) { return true } // VisitOption works noop. func (BaseVisitor) VisitOption(*parser.Option) (next bool) { return true } // VisitPackage works noop. func (BaseVisitor) VisitPackage(*parser.Package) (next bool) { return true } // VisitReserved works noop. func (BaseVisitor) VisitReserved(*parser.Reserved) (next bool) { return true } // VisitRPC works noop. func (BaseVisitor) VisitRPC(*parser.RPC) (next bool) { return true } // VisitService works noop. func (BaseVisitor) VisitService(*parser.Service) (next bool) { return true } // VisitSyntax works noop. func (BaseVisitor) VisitSyntax(*parser.Syntax) (next bool) { return true } <file_sep>/internal/linter/config/enumFieldNamesZeroValueEndWithOption.go package config // EnumFieldNamesZeroValueEndWithOption represents the option for the ENUM_FIELD_NAMES_ZERO_VALUE_END_WITH rule. type EnumFieldNamesZeroValueEndWithOption struct { CustomizableSeverityOption Suffix string `yaml:"suffix"` } <file_sep>/internal/addon/rules/servicesHaveCommentRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // ServicesHaveCommentRule verifies that all services have a comment. type ServicesHaveCommentRule struct { RuleWithSeverity // Golang style comments should begin with the name of the thing being described. // See https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences shouldFollowGolangStyle bool } // NewServicesHaveCommentRule creates a new ServicesHaveCommentRule. func NewServicesHaveCommentRule( severity rule.Severity, shouldFollowGolangStyle bool, ) ServicesHaveCommentRule { return ServicesHaveCommentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, shouldFollowGolangStyle: shouldFollowGolangStyle, } } // ID returns the ID of this rule. func (r ServicesHaveCommentRule) ID() string { return "SERVICES_HAVE_COMMENT" } // Purpose returns the purpose of this rule. func (r ServicesHaveCommentRule) Purpose() string { return "Verifies that all services have a comment." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r ServicesHaveCommentRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r ServicesHaveCommentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &servicesHaveCommentVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), shouldFollowGolangStyle: r.shouldFollowGolangStyle, } return visitor.RunVisitor(v, proto, r.ID()) } type servicesHaveCommentVisitor struct { *visitor.BaseAddVisitor shouldFollowGolangStyle bool } // VisitService checks the service. func (v *servicesHaveCommentVisitor) VisitService(service *parser.Service) bool { n := service.ServiceName if v.shouldFollowGolangStyle && !hasGolangStyleComment(service.Comments, n) { v.AddFailuref(service.Meta.Pos, `Service %q should have a comment of the form "// %s ..."`, n, n) } else if !hasComments(service.Comments, service.InlineComment, service.InlineCommentBehindLeftCurly) { v.AddFailuref(service.Meta.Pos, `Service %q should have a comment`, n) } return false } <file_sep>/internal/cmd/protocgenprotolint/cmd.go package protocgenprotolint import ( "bytes" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "google.golang.org/protobuf/types/pluginpb" "github.com/yoheimuta/protolint/internal/cmd/subcmds" "github.com/yoheimuta/protolint/internal/cmd/subcmds/lint" "github.com/golang/protobuf/proto" protogen "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/yoheimuta/protolint/internal/osutil" ) var ( version = "master" revision = "latest" ) const ( subCmdVersion = "version" ) // Do runs the command logic. func Do( args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer, ) osutil.ExitCode { if 0 < len(args) && args[0] == subCmdVersion { return doVersion(stdout) } err := signalSupportProto3Optional() if err != nil { _, _ = fmt.Fprintln(stderr, err) return osutil.ExitInternalFailure } subCmd, err := newSubCmd(stdin, stdout, stderr) if err != nil { _, _ = fmt.Fprintln(stderr, err) return osutil.ExitInternalFailure } return subCmd.Run() } func signalSupportProto3Optional() error { // supports proto3 field presence // See https://github.com/protocolbuffers/protobuf/blob/cdc11c2d2d314ce0382fe0eaa715e5e0e1270438/docs/implementing_proto3_presence.md#signaling-that-your-code-generator-supports-proto3-optional var supportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL) data, err := proto.Marshal(&protogen.CodeGeneratorResponse{ SupportedFeatures: &supportedFeatures, }) if err != nil { return err } _, err = io.Copy(os.Stdout, bytes.NewReader(data)) if err != nil { return err } return nil } func newSubCmd( stdin io.Reader, stdout io.Writer, stderr io.Writer, ) (*lint.CmdLint, error) { data, err := ioutil.ReadAll(stdin) if err != nil { return nil, err } var req protogen.CodeGeneratorRequest err = proto.Unmarshal(data, &req) if err != nil { return nil, err } flags, err := newFlags(&req) if err != nil { return nil, err } subCmd, err := lint.NewCmdLint( *flags, stdout, stderr, ) if err != nil { return nil, err } return subCmd, nil } func newFlags( req *protogen.CodeGeneratorRequest, ) (*lint.Flags, error) { flags, err := lint.NewFlags(req.FileToGenerate) if err != nil { return nil, err } var pf subcmds.PluginFlag for _, p := range strings.Split(req.GetParameter(), ",") { params := strings.SplitN(strings.TrimSpace(p), "=", 2) switch params[0] { case "": continue case "config_path": if len(params) != 2 { return nil, fmt.Errorf("config_path should be specified") } flags.ConfigDirPath = params[1] case "config_dir_path": if len(params) != 2 { return nil, fmt.Errorf("config_dir_path should be specified") } flags.ConfigDirPath = params[1] case "fix": flags.FixMode = true case "reporter": if len(params) != 2 { return nil, fmt.Errorf("reporter should be specified") } value := params[1] r, err := lint.GetReporter(value) if err != nil { return nil, err } flags.Reporter = r case "output_file": if len(params) != 2 { return nil, fmt.Errorf("output_file should be specified") } flags.OutputFilePath = params[1] case "plugin": if len(params) != 2 { return nil, fmt.Errorf("plugin should be specified") } err = pf.Set(params[1]) if err != nil { return nil, err } case "v": flags.Verbose = true case "proto_root": if len(params) != 2 { return nil, fmt.Errorf("proto_root should be specified") } for i, f := range flags.FilePaths { flags.FilePaths[i] = filepath.Join(params[1], f) } default: return nil, fmt.Errorf("unmatched parameter: %s", p) } } plugins, err := pf.BuildPlugins(flags.Verbose) if err != nil { return nil, err } flags.Plugins = plugins return &flags, nil } func doVersion( stdout io.Writer, ) osutil.ExitCode { _, _ = fmt.Fprintln(stdout, "protoc-gen-protolint version "+version+"("+revision+")") return osutil.ExitSuccess } <file_sep>/internal/linter/config/rpcNamesCaseOption_test.go package config_test import ( "reflect" "testing" "github.com/yoheimuta/protolint/internal/linter/config" "gopkg.in/yaml.v2" ) func TestRPCNamesCaseOption_UnmarshalYAML(t *testing.T) { for _, test := range []struct { name string inputConfig []byte wantRPCNamesCaseOption config.RPCNamesCaseOption wantExistErr bool }{ { name: "not found supported convention", inputConfig: []byte(` convention: upper_camel_case `), wantExistErr: true, }, { name: "empty config", inputConfig: []byte(` `), }, { name: "convention: lower_camel_case", inputConfig: []byte(` convention: lower_camel_case `), wantRPCNamesCaseOption: config.RPCNamesCaseOption{ Convention: config.ConventionLowerCamel, }, }, { name: "convention: upper_snake_case", inputConfig: []byte(` convention: upper_snake_case `), wantRPCNamesCaseOption: config.RPCNamesCaseOption{ Convention: config.ConventionUpperSnake, }, }, { name: "convention: lower_snake_case", inputConfig: []byte(` convention: lower_snake_case `), wantRPCNamesCaseOption: config.RPCNamesCaseOption{ Convention: config.ConventionLowerSnake, }, }, } { test := test t.Run(test.name, func(t *testing.T) { var got config.RPCNamesCaseOption err := yaml.UnmarshalStrict(test.inputConfig, &got) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantRPCNamesCaseOption) { t.Errorf("got %v, but want %v", got, test.wantRPCNamesCaseOption) } }) } } <file_sep>/internal/linter/config/indentOption.go package config import ( "fmt" "strings" ) // IndentOption represents the option for the INDENT rule. type IndentOption struct { CustomizableSeverityOption Style string // Deprecated: not used Newline string NotInsertNewline bool } // UnmarshalYAML implements yaml.v2 Unmarshaler interface. func (i *IndentOption) UnmarshalYAML(unmarshal func(interface{}) error) error { var option struct { Style string `yaml:"style"` Newline string `yaml:"newline"` NotInsertNewline bool `yaml:"not_insert_newline"` } if err := unmarshal(&option); err != nil { return err } var style string switch option.Style { case "tab": style = "\t" case "4": style = strings.Repeat(" ", 4) case "2": style = strings.Repeat(" ", 2) case "": break default: return fmt.Errorf("%s is an invalid style option. valid option is tab, 4 or 2", option.Style) } i.Style = style switch option.Newline { case "\n", "\r", "\r\n", "": i.Newline = option.Newline default: return fmt.Errorf(`%s is an invalid newline option. valid option is \n, \r or \r\n`, option.Newline) } i.NotInsertNewline = option.NotInsertNewline return nil } <file_sep>/internal/setting_test/setting.go package setting_test import ( "path/filepath" "runtime" ) func projectRootPath() string { _, this, _, ok := runtime.Caller(0) if !ok { return "" } return filepath.Dir(filepath.Dir(filepath.Dir(this))) } // TestDataPath is the directory path for the data used by tests. func TestDataPath(elem ...string) string { ps := []string{ projectRootPath(), "_testdata", } ps = append(ps, elem...) return filepath.Join(ps...) } <file_sep>/internal/addon/rules/importsSortedRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/setting_test" "github.com/yoheimuta/protolint/internal/util_test" "github.com/yoheimuta/protolint/internal/linter/file" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func testImportSortedProtoPath(name string) string { return setting_test.TestDataPath("rules", "importsSorted", name) } func TestImportsSortedRule_Apply(t *testing.T) { tests := []struct { name string inputFilename string wantFailures []report.Failure wantExistErr bool }{ { name: "no failures for proto with sorted imports", inputFilename: "sorted.proto", }, { name: "no failures for proto with sorted imports separated by a newline", inputFilename: "sortedWithNewline.proto", }, { name: "failures for proto with not sorted imports", inputFilename: "notSorted.proto", wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: testImportSortedProtoPath("notSorted.proto"), Offset: 20, Line: 3, Column: 1, }, "IMPORTS_SORTED", `Imports are not sorted.`, ), report.Failuref( meta.Position{ Filename: testImportSortedProtoPath("notSorted.proto"), Offset: 47, Line: 4, Column: 1, }, "IMPORTS_SORTED", `Imports are not sorted.`, ), }, }, { name: "failures for proto with not sorted imports separated by a newline", inputFilename: "notSortedWithNewline.proto", wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: testImportSortedProtoPath("notSortedWithNewline.proto"), Offset: 20, Line: 3, Column: 1, }, "IMPORTS_SORTED", `Imports are not sorted.`, ), report.Failuref( meta.Position{ Filename: testImportSortedProtoPath("notSortedWithNewline.proto"), Offset: 42, Line: 4, Column: 1, }, "IMPORTS_SORTED", `Imports are not sorted.`, ), report.Failuref( meta.Position{ Filename: testImportSortedProtoPath("notSortedWithNewline.proto"), Offset: 151, Line: 9, Column: 1, }, "IMPORTS_SORTED", `Imports are not sorted.`, ), report.Failuref( meta.Position{ Filename: testImportSortedProtoPath("notSortedWithNewline.proto"), Offset: 190, Line: 10, Column: 1, }, "IMPORTS_SORTED", `Imports are not sorted.`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewImportsSortedRule( rule.SeverityError, false, ) protoPath := testImportSortedProtoPath(test.inputFilename) proto, err := file.NewProtoFile(protoPath, protoPath).Parse(false) if err != nil { t.Errorf(err.Error()) return } got, err := rule.Apply(proto) if test.wantExistErr { if err == nil { t.Errorf("got err nil, but want err") } return } if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func newTestImportsSortedData( fileName string, ) (util_test.TestData, error) { return util_test.NewTestData(testImportSortedProtoPath(fileName)) } func TestImportsSortedRule_Apply_fix(t *testing.T) { tests := []struct { name string inputFilename string wantFilename string }{ { name: "no fix for proto with sorted imports", inputFilename: "sorted.proto", wantFilename: "sorted.proto", }, { name: "no fix for proto with sorted imports separated by a newline", inputFilename: "sortedWithNewline.proto", wantFilename: "sortedWithNewline.proto", }, { name: "fix for proto with not sorted imports", inputFilename: "notSorted.proto", wantFilename: "sorted.proto", }, { name: "fix for proto with sorted imports separated by a newline", inputFilename: "notSortedWithNewline.proto", wantFilename: "sortedWithNewline.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewImportsSortedRule( rule.SeverityError, true, ) input, err := newTestImportsSortedData(test.inputFilename) if err != nil { t.Errorf("got err %v", err) return } want, err := newTestImportsSortedData(test.wantFilename) if err != nil { t.Errorf("got err %v", err) return } proto, err := file.NewProtoFile(input.FilePath, input.FilePath).Parse(false) if err != nil { t.Errorf(err.Error()) return } _, err = rule.Apply(proto) if err != nil { t.Errorf("got err %v, but want nil", err) return } got, err := input.Data() if !reflect.DeepEqual(got, want.OriginData) { t.Errorf( "got %s(%v), but want %s(%v)", string(got), got, string(want.OriginData), want.OriginData, ) } err = input.Restore() if err != nil { t.Errorf("got err %v", err) } }) } } <file_sep>/internal/osutil/file.go package osutil import ( "fmt" "io" "io/ioutil" "os" "strings" ) // Constants used by LineEnding. const ( lf = "\n" cr = "\r" crlf = "\r\n" ) // ReadAllLines reads all lines from a file. func ReadAllLines( fileName string, newlineChar string, ) ([]string, error) { data, err := ioutil.ReadFile(fileName) if err != nil { return nil, err } return strings.Split(string(data), newlineChar), nil } // WriteLinesToExistingFile writes lines to an existing file. func WriteLinesToExistingFile( fileName string, lines []string, newlineChar string, ) error { data := strings.Join(lines, newlineChar) return WriteExistingFile( fileName, []byte(data), ) } // WriteExistingFile writes the byte array to an existing file. func WriteExistingFile( fileName string, data []byte, ) error { f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC, 0) if err != nil { return err } n, err := f.Write(data) if err == nil && n < len(data) { err = io.ErrShortWrite } if err1 := f.Close(); err == nil { err = err1 } return err } // DetectLineEnding detects a dominant line ending in the content. func DetectLineEnding(content string) (string, error) { prev := ' ' counts := make(map[string]int) for _, c := range content { if c == '\r' && prev != '\n' { counts[cr]++ } else if c == '\n' { if prev == '\r' { counts[crlf]++ counts[cr]-- } else { counts[lf]++ } } prev = c } if counts[crlf]+counts[cr]+counts[lf] == 0 { return "", nil } if counts[crlf] > counts[cr] && counts[crlf] > counts[lf] { return crlf, nil } else if counts[cr] > counts[lf] && counts[cr] > counts[crlf] { return cr, nil } else if counts[lf] > counts[cr] && counts[lf] > counts[crlf] { return lf, nil } return "", fmt.Errorf("not found dominant line ending, counts=%v", counts) } <file_sep>/internal/addon/rules/fieldNamesLowerSnakeCaseRule_test.go package rules_test import ( "reflect" "testing" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/addon/rules" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) func TestFieldNamesLowerSnakeCaseRule_Apply(t *testing.T) { tests := []struct { name string inputProto *parser.Proto wantFailures []report.Failure }{ { name: "no failures for proto without fields", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Enum{}, }, }, }, { name: "no failures for proto with valid field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Service{}, &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "song_name", }, &parser.Field{ FieldName: "singer", }, &parser.MapField{ MapName: "song_name2", }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "song_name3", }, }, }, }, }, }, }, }, { name: "failures for proto with invalid field names", inputProto: &parser.Proto{ ProtoBody: []parser.Visitee{ &parser.Message{ MessageBody: []parser.Visitee{ &parser.Field{ FieldName: "song_Name", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, }, }, &parser.MapField{ MapName: "MapFieldName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 210, Line: 14, Column: 30, }, }, }, &parser.Oneof{ OneofFields: []*parser.OneofField{ { FieldName: "OneofFieldName", Meta: meta.Meta{ Pos: meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, }, }, }, }, }, }, }, }, wantFailures: []report.Failure{ report.Failuref( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "FIELD_NAMES_LOWER_SNAKE_CASE", `Field name "song_Name" must be underscore_separated_names like "song_name"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 210, Line: 14, Column: 30, }, "FIELD_NAMES_LOWER_SNAKE_CASE", `Field name "MapFieldName" must be underscore_separated_names like "map_field_name"`, ), report.Failuref( meta.Position{ Filename: "example.proto", Offset: 300, Line: 21, Column: 45, }, "FIELD_NAMES_LOWER_SNAKE_CASE", `Field name "OneofFieldName" must be underscore_separated_names like "oneof_field_name"`, ), }, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { rule := rules.NewFieldNamesLowerSnakeCaseRule(rule.SeverityError, false, autodisable.Noop) got, err := rule.Apply(test.inputProto) if err != nil { t.Errorf("got err %v, but want nil", err) return } if !reflect.DeepEqual(got, test.wantFailures) { t.Errorf("got %v, but want %v", got, test.wantFailures) } }) } } func TestFieldNamesLowerSnakeCaseRule_Apply_fix(t *testing.T) { tests := []struct { name string inputFilename string wantFilename string }{ { name: "no fix for a correct proto", inputFilename: "lower_snake_case.proto", wantFilename: "lower_snake_case.proto", }, { name: "fix for an incorrect proto", inputFilename: "invalid.proto", wantFilename: "lower_snake_case.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewFieldNamesLowerSnakeCaseRule(rule.SeverityError, true, autodisable.Noop) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } func TestFieldNamesLowerSnakeCaseRule_Apply_disable(t *testing.T) { tests := []struct { name string inputFilename string inputPlacementType autodisable.PlacementType wantFilename string }{ { name: "do nothing in case of no violations", inputFilename: "lower_snake_case.proto", wantFilename: "lower_snake_case.proto", }, { name: "insert disable:next comments", inputFilename: "invalid.proto", inputPlacementType: autodisable.Next, wantFilename: "disable_next.proto", }, { name: "insert disable:this comments", inputFilename: "invalid.proto", inputPlacementType: autodisable.ThisThenNext, wantFilename: "disable_this.proto", }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { r := rules.NewFieldNamesLowerSnakeCaseRule(rule.SeverityError, true, test.inputPlacementType) testApplyFix(t, r, test.inputFilename, test.wantFilename) }) } } <file_sep>/internal/addon/rules/enumFieldNamesUpperSnakeCaseRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/lexer" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/autodisable" "github.com/yoheimuta/protolint/linter/fixer" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/strs" "github.com/yoheimuta/protolint/linter/visitor" ) // EnumFieldNamesUpperSnakeCaseRule verifies that all enum field names are CAPITALS_WITH_UNDERSCORES. // See https://developers.google.com/protocol-buffers/docs/style#enums. type EnumFieldNamesUpperSnakeCaseRule struct { RuleWithSeverity fixMode bool autoDisableType autodisable.PlacementType } // NewEnumFieldNamesUpperSnakeCaseRule creates a new EnumFieldNamesUpperSnakeCaseRule. func NewEnumFieldNamesUpperSnakeCaseRule( severity rule.Severity, fixMode bool, autoDisableType autodisable.PlacementType, ) EnumFieldNamesUpperSnakeCaseRule { if autoDisableType != autodisable.Noop { fixMode = false } return EnumFieldNamesUpperSnakeCaseRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, autoDisableType: autoDisableType, } } // ID returns the ID of this rule. func (r EnumFieldNamesUpperSnakeCaseRule) ID() string { return "ENUM_FIELD_NAMES_UPPER_SNAKE_CASE" } // Purpose returns the purpose of this rule. func (r EnumFieldNamesUpperSnakeCaseRule) Purpose() string { return "Verifies that all enum field names are CAPITALS_WITH_UNDERSCORES." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r EnumFieldNamesUpperSnakeCaseRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r EnumFieldNamesUpperSnakeCaseRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &enumFieldNamesUpperSnakeCaseVisitor{ BaseFixableVisitor: base, } return visitor.RunVisitorAutoDisable(v, proto, r.ID(), r.autoDisableType) } type enumFieldNamesUpperSnakeCaseVisitor struct { *visitor.BaseFixableVisitor } // VisitEnumField checks the enum field. func (v *enumFieldNamesUpperSnakeCaseVisitor) VisitEnumField(field *parser.EnumField) bool { name := field.Ident if !strs.IsUpperSnakeCase(name) { expected := strs.ToUpperSnakeCase(name) v.AddFailuref(field.Meta.Pos, "EnumField name %q must be CAPITALS_WITH_UNDERSCORES like %q", name, expected) err := v.Fixer.SearchAndReplace(field.Meta.Pos, func(lex *lexer.Lexer) fixer.TextEdit { lex.Next() return fixer.TextEdit{ Pos: lex.Pos.Offset, End: lex.Pos.Offset + len(lex.Text) - 1, NewText: []byte(expected), } }) if err != nil { panic(err) } } return false } <file_sep>/internal/linter/config/enumsHaveCommentOption.go package config // EnumsHaveCommentOption represents the option for the ENUMS_HAVE_COMMENT rule. type EnumsHaveCommentOption struct { CustomizableSeverityOption ShouldFollowGolangStyle bool `yaml:"should_follow_golang_style"` } <file_sep>/internal/linter/report/reporters/ciReporter_test.go package reporters_test import ( "bytes" "fmt" "os" "path/filepath" "testing" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/internal/linter/report/reporters" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) type testFiles struct { files []string } type testStruct struct { name string inputFailures []report.Failure wantOutput string expectedError error files testFiles } type testCases struct { oneWarningOneError testStruct onlyErrors testStruct oneOfEach testStruct } func makeTestData() testCases { return testCases{ oneWarningOneError: testStruct{ name: "oneWarningOneError", wantOutput: "", expectedError: nil, files: testFiles{}, inputFailures: []report.Failure{ report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityWarning), `EnumField name "fIRST_VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityError), `EnumField name "SECOND.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), }, }, onlyErrors: testStruct{ name: "onlyErrors", wantOutput: "", expectedError: nil, files: testFiles{}, inputFailures: []report.Failure{ report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityError), `EnumField name "fIRST_VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityError), `EnumField name "SECOND.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 40, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityError), `EnumField name "third.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), }, }, oneOfEach: testStruct{ name: "oneOfEach", wantOutput: "", expectedError: nil, files: testFiles{}, inputFailures: []report.Failure{ report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 100, Line: 5, Column: 10, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityNote), `EnumField name "fIRST_VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 200, Line: 10, Column: 20, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityWarning), `EnumField name "SECOND.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), report.FailureWithSeverityf( meta.Position{ Filename: "example.proto", Offset: 300, Line: 20, Column: 40, }, "ENUM_NAMES_UPPER_CAMEL_CASE", string(rule.SeverityError), `EnumField name "third.VALUE" must be CAPITALS_WITH_UNDERSCORES`, ), }, }, } } func TestProblemMatcherReporter_Report(t *testing.T) { initTestCases := makeTestData() initTestCases.oneOfEach.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (info): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (warning): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[20,40]: EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (warning): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[20,40]: EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterWithGenericFormat() run_tests(t, tests, reporter) } func TestAzureDevOpsMatcherReporter_Report(t *testing.T) { initTestCases := makeTestData() initTestCases.oneOfEach.want(`##vso[task.logissue type=warning;sourcepath=example.proto;linenumber=10;columnnumber=20;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES ##vso[task.logissue type=error;sourcepath=example.proto;linenumber=20;columnnumber=40;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.want(`##vso[task.logissue type=warning;sourcepath=example.proto;linenumber=5;columnnumber=10;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES ##vso[task.logissue type=error;sourcepath=example.proto;linenumber=10;columnnumber=20;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.want(`##vso[task.logissue type=error;sourcepath=example.proto;linenumber=5;columnnumber=10;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES ##vso[task.logissue type=error;sourcepath=example.proto;linenumber=10;columnnumber=20;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES ##vso[task.logissue type=error;sourcepath=example.proto;linenumber=20;columnnumber=40;code=ENUM_NAMES_UPPER_CAMEL_CASE;]EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterForAzureDevOps() run_tests(t, tests, reporter) } func TestGithubActionMatcherReporter_Report(t *testing.T) { initTestCases := makeTestData() initTestCases.oneOfEach.want(`::notice file=example.proto,line=5,col=10,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES ::warning file=example.proto,line=10,col=20,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES ::error file=example.proto,line=20,col=40,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.want(`::warning file=example.proto,line=5,col=10,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES ::error file=example.proto,line=10,col=20,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.want(`::error file=example.proto,line=5,col=10,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES ::error file=example.proto,line=10,col=20,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES ::error file=example.proto,line=20,col=40,title=ENUM_NAMES_UPPER_CAMEL_CASE::EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterForGithubActions() run_tests(t, tests, reporter) } func TestGitlabCiCdMatcherReporter_Report(t *testing.T) { initTestCases := makeTestData() initTestCases.oneOfEach.want(`INFO: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(5,10) : EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES WARNING: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(10,20) : EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES ERROR: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(20,40) : EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.want(`WARNING: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(5,10) : EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES ERROR: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(10,20) : EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.want(`ERROR: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(5,10) : EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES ERROR: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(10,20) : EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES ERROR: ENUM_NAMES_UPPER_CAMEL_CASE example.proto(20,40) : EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterForGitlab() run_tests(t, tests, reporter) } func TestEnvMatcherReporterFromTemplateString_Report(t *testing.T) { t.Setenv("PROTOLINT_CIREPORTER_TEMPLATE_STRING", "{{ .Severity }}@{{ .File }}[{{ .Line }},{{ .Column }}] triggered rule {{ .Rule }} with message {{ .Message }}") initTestCases := makeTestData() initTestCases.oneOfEach.want(`info@example.proto[5,10] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES warning@example.proto[10,20] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES error@example.proto[20,40] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.want(`warning@example.proto[5,10] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES error@example.proto[10,20] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.want(`<EMAIL>.proto[5,10] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES <EMAIL>.proto[10,20] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES <EMAIL>[20,40] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterFromEnv() run_tests(t, tests, reporter) } func TestEnvMatcherReporterFromTemplateFile_Report(t *testing.T) { initTestCases := makeTestData() initTestCases.oneOfEach.files.appendFile(t, "0oneOfEach.template", "[fromfile:0oneOfEach.template] {{ .Severity }}@{{ .File }}[{{ .Line }},{{ .Column }}] triggered rule {{ .Rule }} with message {{ .Message }}") initTestCases.oneOfEach.want(`[fromfile:0oneOfEach.template] info@example.proto[5,10] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES [fromfile:0oneOfEach.template] warning@example.proto[10,20] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES [fromfile:0oneOfEach.template] error@example.proto[20,40] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.files.appendFile(t, "0oneWarningOneError.template", "[fromfile:0oneWarningOneError.template] {{ .Severity }}@{{ .File }}[{{ .Line }},{{ .Column }}] triggered rule {{ .Rule }} with message {{ .Message }}") initTestCases.oneWarningOneError.want(`[fromfile:0oneWarningOneError.template] <EMAIL>.proto[5,10] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES [fromfile:0oneWarningOneError.template] <EMAIL>.proto[10,20] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.files.appendFile(t, "0onlyErrors.template", "[fromfile:0onlyErrors.template] {{ .Severity }}@{{ .File }}[{{ .Line }},{{ .Column }}] triggered rule {{ .Rule }} with message {{ .Message }}") initTestCases.onlyErrors.want(`[fromfile:0onlyErrors.template] error@example.proto[5,10] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES [fromfile:0onlyErrors.template] error@example.proto[10,20] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES [fromfile:0onlyErrors.template] error@example.proto[20,40] triggered rule ENUM_NAMES_UPPER_CAMEL_CASE with message EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterFromEnv() run_tests(t, tests, reporter) } func TestEnvMatcherReporterFromNonExistingTemplateFile_Report(t *testing.T) { t.Setenv("PROTOLINT_CIREPORTER_TEMPLATE_FILE", filepath.Join(t.TempDir(), "does.not.exist")) initTestCases := makeTestData() initTestCases.oneOfEach.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (info): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (warning): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[20,40]: EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (warning): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[20,40]: EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterFromEnv() run_tests(t, tests, reporter) } func TestEnvMatcherReporterFromUnallowedTemplateFile_Report(t *testing.T) { tplFile := filepath.Join(t.TempDir(), "does.exist") t.Setenv("PROTOLINT_CIREPORTER_TEMPLATE_FILE", tplFile) t.Cleanup(func() { if _, err := os.Stat(tplFile); os.IsNotExist(err) { t.Logf("File %s already deleted", tplFile) } err := os.Remove(tplFile) if err != nil { t.Errorf("ERROR while cleaning up file %s: %v", tplFile, err) } }) file, err := os.Create(tplFile) if err != nil { t.Errorf("Failed to create temp file: %v", err) } _, err = file.Write([]byte("[fromfile:does.exist] {{ .Severity }}@{{ .File }}[{{ .Line }},{{ .Column }}] triggered rule {{ .Rule }} with message {{ .Message }}")) if err != nil { t.Errorf("Failed to write temp file: %v", err) } err = file.Close() if err != nil { t.Errorf("Failed to create temp file (error while closing): %v", err) } err = os.Chmod(tplFile, 0200) if err != nil { t.Errorf("Failed to remove read permissions: %v", err) } initTestCases := makeTestData() initTestCases.oneOfEach.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (info): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (warning): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[20,40]: EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.oneWarningOneError.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (warning): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) initTestCases.onlyErrors.want(`Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[5,10]: EnumField name \"fIRST_VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[10,20]: EnumField name \"SECOND.VALUE\" must be CAPITALS_WITH_UNDERSCORES Protolint ENUM_NAMES_UPPER_CAMEL_CASE (error): example.proto[20,40]: EnumField name \"third.VALUE\" must be CAPITALS_WITH_UNDERSCORES `) tests := initTestCases.tests() reporter := reporters.NewCiReporterFromEnv() run_tests(t, tests, reporter) } func TestEnvMatcherReporterFromErroneousTemplateFile_ReportTestEnvMatcherReporterFromErroneousTemplateString_Report(t *testing.T) { initTestCases := makeTestData() initTestCases.oneOfEach.files.appendFile(t, "1oneOfEach.template", "[fromfile:1oneOfEach.template] {{ .Severit }}@{{ .Fil }}[{{ .Lne }},{{ .Colum }}] triggered rule {{ .ule }} with message {{ .Msg }}") initTestCases.oneOfEach.expectError(`template: Failure:1:34: executing "Failure" at <.Severit>: can't evaluate field Severit in type reporters.ciReportedFailure`) initTestCases.oneWarningOneError.files.appendFile(t, "1oneWarningOneError.template", "[fromfile:1oneWarningOneError.template] {{ .Severit }}@{{ .Fil }}[{{ .Lne }},{{ .Colum }}] triggered rule {{ .ule }} with message {{ .Msg }}") initTestCases.oneWarningOneError.expectError(`template: Failure:1:43: executing "Failure" at <.Severit>: can't evaluate field Severit in type reporters.ciReportedFailure`) initTestCases.onlyErrors.files.appendFile(t, "1onlyErrors.template", "[fromfile:1onlyErrors.template] {{ .Severit }}@{{ .Fil }}[{{ .Lne }},{{ .Colum }}] triggered rule {{ .ule }} with message {{ .Msg }}") initTestCases.onlyErrors.expectError(`template: Failure:1:35: executing "Failure" at <.Severit>: can't evaluate field Severit in type reporters.ciReportedFailure`) tests := initTestCases.tests() reporter := reporters.NewCiReporterFromEnv() run_tests(t, tests, reporter) } func TestEnvMatcherReporterFromErroneousTemplateString_Report(t *testing.T) { t.Setenv("PROTOLINT_CIREPORTER_TEMPLATE_STRING", "{{ .Severit }}@{{ .Fil }}[{{ .Lne }},{{ .Colum }}] triggered rule {{ .ule }} with message {{ .Msg }}") initTestCases := makeTestData() initTestCases.oneOfEach.expectError(`template: Failure:1:3: executing "Failure" at <.Severit>: can't evaluate field Severit in type reporters.ciReportedFailure`) initTestCases.oneWarningOneError.expectError(`template: Failure:1:3: executing "Failure" at <.Severit>: can't evaluate field Severit in type reporters.ciReportedFailure`) initTestCases.onlyErrors.expectError(`template: Failure:1:3: executing "Failure" at <.Severit>: can't evaluate field Severit in type reporters.ciReportedFailure`) tests := initTestCases.tests() reporter := reporters.NewCiReporterFromEnv() run_tests(t, tests, reporter) } func run_tests(t *testing.T, tests []testStruct, r reporters.CiReporter) { if len(tests) == 0 { t.SkipNow() } for _, test := range tests { test := test t.Cleanup(func() { test.cleanUp(t) }) t.Run(test.name, func(t *testing.T) { if len(test.files.files) > 0 { t.Setenv("PROTOLINT_CIREPORTER_TEMPLATE_FILE", test.files.files[0]) } buf := &bytes.Buffer{} err := r.Report(buf, test.inputFailures) test.cleanUp(t) if err != nil { isExpectedError := false if test.expectedError != nil { isExpectedError = err.Error() == test.expectedError.Error() } if !isExpectedError { t.Errorf("got err %v, but want %v", err, test.expectedError) return } else { t.Logf("Wanted %v, got %v", test.expectedError, err) } } if buf.String() != test.wantOutput { t.Errorf(` got %s , but want %s`, buf.String(), test.wantOutput) } }) } } func (ts testStruct) cleanUp(t *testing.T) { ts.files.cleanUp(t) } func (tf testFiles) cleanUp(t *testing.T) { for _, file := range tf.files { if _, err := os.Stat(file); os.IsNotExist(err) { t.Logf("File %s already deleted", file) continue } err := os.Remove(file) if err != nil { t.Errorf("ERROR while cleaning up file %s: %v", file, err) } } } func (tf *testFiles) appendFile(t *testing.T, fileName string, fileContent string) { filePath := filepath.Join(t.TempDir(), fileName) file, err := os.Create(filePath) if err != nil { t.Errorf("Failed to create file %s: %v", filePath, err) return } defer func(td *testing.T) { err = file.Close() if err != nil { td.Errorf("Failed to content to file %s: %v", filePath, err) return } }(t) _, err = file.WriteString(fileContent) if err != nil { t.Errorf("Failed to content to file %s: %v", filePath, err) return } tf.files = append(tf.files, filePath) } func (ts *testStruct) want(input string) { ts.wantOutput = input } func (ts *testStruct) expectError(err string) { ts.expectedError = fmt.Errorf(err) ts.want("") } func (td testCases) tests() []testStruct { var allCases []testStruct allCases = append(allCases, td.oneOfEach) allCases = append(allCases, td.oneWarningOneError) allCases = append(allCases, td.onlyErrors) return allCases } <file_sep>/internal/addon/rules/indentRule.go package rules import ( "strings" "unicode" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) const ( // Use an indent of 2 spaces. // See https://developers.google.com/protocol-buffers/docs/style#standard-file-formatting defaultStyle = " " ) // IndentRule enforces a consistent indentation style. type IndentRule struct { RuleWithSeverity style string notInsertNewline bool fixMode bool } // NewIndentRule creates a new IndentRule. func NewIndentRule( severity rule.Severity, style string, notInsertNewline bool, fixMode bool, ) IndentRule { if len(style) == 0 { style = defaultStyle } return IndentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, style: style, notInsertNewline: notInsertNewline, fixMode: fixMode, } } // ID returns the ID of this rule. func (r IndentRule) ID() string { return "INDENT" } // Purpose returns the purpose of this rule. func (r IndentRule) Purpose() string { return "Enforces a consistent indentation style." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r IndentRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r IndentRule) Apply( proto *parser.Proto, ) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), true, proto, string(r.Severity())) if err != nil { return nil, err } v := &indentVisitor{ BaseFixableVisitor: base, style: r.style, fixMode: r.fixMode, notInsertNewline: r.notInsertNewline, indentFixes: make(map[int][]indentFix), } return visitor.RunVisitor(v, proto, r.ID()) } type indentFix struct { currentChars int replacement string level int pos meta.Position isLast bool } type indentVisitor struct { *visitor.BaseFixableVisitor style string currentLevel int fixMode bool notInsertNewline bool indentFixes map[int][]indentFix } func (v indentVisitor) Finally() error { if v.fixMode { return v.fix() } return nil } func (v indentVisitor) VisitEnum(e *parser.Enum) (next bool) { v.validateIndentLeading(e.Meta.Pos) defer func() { v.validateIndentLast(e.Meta.LastPos) }() for _, comment := range e.Comments { v.validateIndentLeading(comment.Meta.Pos) } defer v.nest()() for _, body := range e.EnumBody { body.Accept(v) } return false } func (v indentVisitor) VisitEnumField(f *parser.EnumField) (next bool) { v.validateIndentLeading(f.Meta.Pos) for _, comment := range f.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitExtend(e *parser.Extend) (next bool) { v.validateIndentLeading(e.Meta.Pos) defer func() { v.validateIndentLast(e.Meta.LastPos) }() for _, comment := range e.Comments { v.validateIndentLeading(comment.Meta.Pos) } defer v.nest()() for _, body := range e.ExtendBody { body.Accept(v) } return false } func (v indentVisitor) VisitField(f *parser.Field) (next bool) { v.validateIndentLeading(f.Meta.Pos) for _, comment := range f.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitGroupField(f *parser.GroupField) (next bool) { v.validateIndentLeading(f.Meta.Pos) defer func() { v.validateIndentLast(f.Meta.LastPos) }() for _, comment := range f.Comments { v.validateIndentLeading(comment.Meta.Pos) } defer v.nest()() for _, body := range f.MessageBody { body.Accept(v) } return false } func (v indentVisitor) VisitImport(i *parser.Import) (next bool) { v.validateIndentLeading(i.Meta.Pos) for _, comment := range i.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitMapField(m *parser.MapField) (next bool) { v.validateIndentLeading(m.Meta.Pos) for _, comment := range m.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitMessage(m *parser.Message) (next bool) { v.validateIndentLeading(m.Meta.Pos) defer func() { v.validateIndentLast(m.Meta.LastPos) }() for _, comment := range m.Comments { v.validateIndentLeading(comment.Meta.Pos) } defer v.nest()() for _, body := range m.MessageBody { body.Accept(v) } return false } func (v indentVisitor) VisitOneof(o *parser.Oneof) (next bool) { v.validateIndentLeading(o.Meta.Pos) defer func() { v.validateIndentLast(o.Meta.LastPos) }() for _, comment := range o.Comments { v.validateIndentLeading(comment.Meta.Pos) } defer v.nest()() for _, field := range o.OneofFields { field.Accept(v) } return false } func (v indentVisitor) VisitOneofField(f *parser.OneofField) (next bool) { v.validateIndentLeading(f.Meta.Pos) for _, comment := range f.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitOption(o *parser.Option) (next bool) { v.validateIndentLeading(o.Meta.Pos) for _, comment := range o.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitPackage(p *parser.Package) (next bool) { v.validateIndentLeading(p.Meta.Pos) for _, comment := range p.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitReserved(r *parser.Reserved) (next bool) { v.validateIndentLeading(r.Meta.Pos) for _, comment := range r.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) VisitRPC(r *parser.RPC) (next bool) { v.validateIndentLeading(r.Meta.Pos) defer func() { line := v.Fixer.Lines()[r.Meta.LastPos.Line-1] runes := []rune(line) for i := r.Meta.LastPos.Column - 2; 0 < i; i-- { r := runes[i] if r == '{' || r == ')' { // skip validating the indentation when the line ends with {}, {};, or ); return } if r == '}' || unicode.IsSpace(r) { continue } break } v.validateIndentLast(r.Meta.LastPos) }() for _, comment := range r.Comments { v.validateIndentLeading(comment.Meta.Pos) } defer v.nest()() for _, body := range r.Options { body.Accept(v) } return false } func (v indentVisitor) VisitService(s *parser.Service) (next bool) { v.validateIndentLeading(s.Meta.Pos) defer func() { v.validateIndentLast(s.Meta.LastPos) }() for _, comment := range s.Comments { v.validateIndentLeading(comment.Meta.Pos) } defer v.nest()() for _, body := range s.ServiceBody { body.Accept(v) } return false } func (v indentVisitor) VisitSyntax(s *parser.Syntax) (next bool) { v.validateIndentLeading(s.Meta.Pos) for _, comment := range s.Comments { v.validateIndentLeading(comment.Meta.Pos) } return false } func (v indentVisitor) validateIndentLeading( pos meta.Position, ) { v.validateIndent(pos, false) } func (v indentVisitor) validateIndentLast( pos meta.Position, ) { v.validateIndent(pos, true) } func (v indentVisitor) validateIndent( pos meta.Position, isLast bool, ) { line := v.Fixer.Lines()[pos.Line-1] leading := "" for _, r := range string([]rune(line)[:pos.Column-1]) { if unicode.IsSpace(r) { leading += string(r) } } indentation := strings.Repeat(v.style, v.currentLevel) v.indentFixes[pos.Line-1] = append(v.indentFixes[pos.Line-1], indentFix{ currentChars: len(leading), replacement: indentation, level: v.currentLevel, pos: pos, isLast: isLast, }) if leading == indentation { return } if 1 < len(v.indentFixes[pos.Line-1]) && v.notInsertNewline { return } if len(v.indentFixes[pos.Line-1]) == 1 { v.AddFailuref( pos, `Found an incorrect indentation style "%s". "%s" is correct.`, leading, indentation, ) } else { v.AddFailuref( pos, `Found a possible incorrect indentation style. Inserting a new line is recommended.`, ) } } func (v *indentVisitor) nest() func() { v.currentLevel++ return func() { v.currentLevel-- } } func (v indentVisitor) fix() error { var shouldFixed bool v.Fixer.ReplaceAll(func(lines []string) []string { var fixedLines []string for i, line := range lines { lines := []string{line} if fixes, ok := v.indentFixes[i]; ok { lines[0] = fixes[0].replacement + line[fixes[0].currentChars:] shouldFixed = true if 1 < len(fixes) && !v.notInsertNewline { // compose multiple lines in reverse order from right to left on one line. var rlines []string for j := len(fixes) - 1; 0 <= j; j-- { indentation := strings.Repeat(v.style, fixes[j].level) if fixes[j].isLast { // deal with last position followed by ';'. See https://github.com/yoheimuta/protolint/issues/99 for line[fixes[j].pos.Column-1] == ';' { fixes[j].pos.Column-- } } endColumn := len(line) if j < len(fixes)-1 { endColumn = fixes[j+1].pos.Column - 1 } text := line[fixes[j].pos.Column-1 : endColumn] text = strings.TrimRightFunc(text, func(r rune) bool { // removing right spaces is a possible side effect that users do not expect, // but it's probably acceptable and usually recommended. return unicode.IsSpace(r) }) rlines = append(rlines, indentation+text) } // sort the multiple lines in order lines = []string{} for j := len(rlines) - 1; 0 <= j; j-- { lines = append(lines, rlines[j]) } } } fixedLines = append(fixedLines, lines...) } return fixedLines }) if !shouldFixed { return nil } return v.BaseFixableVisitor.Finally() } <file_sep>/internal/linter/config/fieldsHaveCommentOption.go package config // FieldsHaveCommentOption represents the option for the FIELDS_HAVE_COMMENT rule. type FieldsHaveCommentOption struct { CustomizableSeverityOption ShouldFollowGolangStyle bool `yaml:"should_follow_golang_style"` } <file_sep>/internal/linter/file/protoSet.go package file import ( "fmt" "os" "path/filepath" ) // ProtoSet represents a set of .proto files. type ProtoSet struct { protoFiles []ProtoFile } // NewProtoSet creates a new ProtoSet. func NewProtoSet( targetPaths []string, ) (ProtoSet, error) { fs, err := collectAllProtoFilesFromArgs(targetPaths) if err != nil { return ProtoSet{}, err } if len(fs) == 0 { return ProtoSet{}, fmt.Errorf("not found protocol buffer files in %v", targetPaths) } return ProtoSet{ protoFiles: fs, }, nil } // ProtoFiles returns proto files. func (s ProtoSet) ProtoFiles() []ProtoFile { return s.protoFiles } func collectAllProtoFilesFromArgs( targetPaths []string, ) ([]ProtoFile, error) { cwd, err := os.Getwd() if err != nil { return nil, err } absCwd, err := absClean(cwd) if err != nil { return nil, err } // Eval a possible symlink for the cwd to calculate the correct relative paths in the next step. if newPath, err := filepath.EvalSymlinks(absCwd); err == nil { absCwd = newPath } var fs []ProtoFile for _, path := range targetPaths { absTarget, err := absClean(path) if err != nil { return nil, err } f, err := collectAllProtoFiles(absCwd, absTarget) if err != nil { return nil, err } fs = append(fs, f...) } return fs, nil } func collectAllProtoFiles( absWorkDirPath string, absPath string, ) ([]ProtoFile, error) { var fs []ProtoFile err := filepath.Walk( absPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if filepath.Ext(path) != ".proto" { return nil } displayPath, err := filepath.Rel(absWorkDirPath, path) if err != nil { displayPath = path } displayPath = filepath.Clean(displayPath) fs = append(fs, NewProtoFile(path, displayPath)) return nil }, ) if err != nil { return nil, err } return fs, nil } // absClean returns the cleaned absolute path of the given path. func absClean(path string) (string, error) { if path == "" { return path, nil } if !filepath.IsAbs(path) { return filepath.Abs(path) } return filepath.Clean(path), nil } <file_sep>/internal/addon/rules/importsSortedRule.go package rules import ( "sort" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // ImportsSortedRule enforces sorted imports. type ImportsSortedRule struct { RuleWithSeverity fixMode bool } // NewImportsSortedRule creates a new ImportsSortedRule. func NewImportsSortedRule( severity rule.Severity, fixMode bool, ) ImportsSortedRule { return ImportsSortedRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, } } // ID returns the ID of this rule. func (r ImportsSortedRule) ID() string { return "IMPORTS_SORTED" } // Purpose returns the purpose of this rule. func (r ImportsSortedRule) Purpose() string { return "Enforces sorted imports." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r ImportsSortedRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r ImportsSortedRule) Apply( proto *parser.Proto, ) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), true, proto, string(r.Severity())) if err != nil { return nil, err } v := &importsSortedVisitor{ BaseFixableVisitor: base, fixMode: r.fixMode, sorter: new(importSorter), } return visitor.RunVisitor(v, proto, r.ID()) } type importsSortedVisitor struct { *visitor.BaseFixableVisitor fixMode bool sorter *importSorter } func (v importsSortedVisitor) VisitImport(i *parser.Import) (next bool) { v.sorter.add(i) return false } func (v importsSortedVisitor) Finally() error { notSorted := v.sorter.notSortedImports() v.Fixer.ReplaceAll(func(lines []string) []string { var fixedLines []string for i, line := range lines { if invalid, ok := notSorted[i+1]; ok { v.AddFailuref( invalid.Meta.Pos, `Imports are not sorted.`, ) line = lines[invalid.sortedLine-1] } fixedLines = append(fixedLines, line) } return fixedLines }) if !v.fixMode { return nil } return v.BaseFixableVisitor.Finally() } type notSortedImport struct { *parser.Import sortedLine int } type importGroup []*parser.Import func (g importGroup) isContiguous(i *parser.Import) bool { last := g[len(g)-1] return i.Meta.Pos.Line-last.Meta.Pos.Line == 1 } func (g importGroup) sorted() importGroup { var s importGroup s = append(s, g...) sort.Slice(s, func(i, j int) bool { return s[i].Location < s[j].Location }) return s } func (g importGroup) notSortedImports() map[int]*notSortedImport { is := make(map[int]*notSortedImport) s := g.sorted() for idx, i := range g { sorted := s[idx] if i.Location != sorted.Location { is[i.Meta.Pos.Line] = &notSortedImport{ Import: i, sortedLine: sorted.Meta.Pos.Line, } } } return is } type importSorter struct { groups []*importGroup } func (s *importSorter) add(i *parser.Import) { for _, g := range s.groups { if g.isContiguous(i) { *g = append(*g, i) return } } s.groups = append(s.groups, &importGroup{i}) } func (s *importSorter) notSortedImports() map[int]*notSortedImport { is := make(map[int]*notSortedImport) for _, g := range s.groups { ps := g.notSortedImports() for line, p := range ps { is[line] = p } } return is } <file_sep>/linter/autodisable/commentator.go package autodisable import ( "log" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/disablerule" "github.com/yoheimuta/protolint/linter/fixer" ) type commentator struct { fixing *fixer.BaseFixing ruleID string } func newCommentator(filename, ruleID string) (*commentator, error) { f, err := fixer.NewBaseFixing(filename) if err != nil { return nil, err } return &commentator{ fixing: f, ruleID: ruleID, }, nil } func (c *commentator) insertNewline(offset int) { comment := disablerule.PrefixDisableNext + " " + c.ruleID space := "" pos := offset loop: for i := offset; 0 < i; i-- { ch := c.fixing.Content()[i] switch ch { case ' ', '\t': space += " " case '\n', '\r': break loop default: pos = i space = "" } } c.insert("// "+comment+c.fixing.LineEnding()+space, pos) } func (c *commentator) tryMergeInline(inline *parser.Comment) bool { matches := disablerule.ReDisableThis.FindStringIndex(inline.Raw) log.Println(matches) if matches != nil { extracted := inline.Raw[matches[0]:matches[1]] log.Println(extracted) startPos := inline.Meta.Pos.Offset c.fixing.Replace(fixer.TextEdit{ Pos: startPos + matches[0], End: startPos + matches[1] - 1, NewText: []byte(extracted + " " + c.ruleID), }) return true } return false } func (c *commentator) insertInline(offset int) { comment := disablerule.PrefixDisableThis + " " + c.ruleID pos := offset content := c.fixing.Content() loop: for i := offset; i < len(content); i++ { ch := content[i] switch ch { case ' ', '\t': case '\n', '\r': break loop default: pos = i } } c.insert(" // "+comment, pos+1) } func (c *commentator) finalize() error { return c.fixing.Finally() } func (c *commentator) insert(text string, pos int) { c.fixing.Replace(fixer.TextEdit{ Pos: pos, End: pos - 1, NewText: []byte(text), }) } <file_sep>/internal/addon/rules/quoteConsistentRule.go package rules import ( "strings" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/internal/linter/config" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // QuoteConsistentRule verifies that the use of quote for strings is consistent. type QuoteConsistentRule struct { RuleWithSeverity quote config.QuoteType fixMode bool } // NewQuoteConsistentRule creates a new QuoteConsistentRule. func NewQuoteConsistentRule( severity rule.Severity, quote config.QuoteType, fixMode bool, ) QuoteConsistentRule { return QuoteConsistentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, quote: quote, fixMode: fixMode, } } // ID returns the ID of this rule. func (r QuoteConsistentRule) ID() string { return "QUOTE_CONSISTENT" } // Purpose returns the purpose of this rule. func (r QuoteConsistentRule) Purpose() string { return "Verifies that the use of quote for strings is consistent." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r QuoteConsistentRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r QuoteConsistentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &quoteConsistentVisitor{ BaseFixableVisitor: base, quote: r.quote, } return visitor.RunVisitor(v, proto, r.ID()) } type quoteConsistentVisitor struct { *visitor.BaseFixableVisitor quote config.QuoteType } func (v quoteConsistentVisitor) VisitSyntax(s *parser.Syntax) bool { str := s.ProtobufVersionQuote converted := convertConsistentQuote(str, v.quote) if str != converted { v.AddFailuref(s.Meta.Pos, "Quoted string should be %s but was %s.", converted, str) v.Fixer.ReplaceText(s.Meta.Pos.Line, str, converted) } return false } func (v quoteConsistentVisitor) VisitImport(i *parser.Import) (next bool) { str := i.Location converted := convertConsistentQuote(str, v.quote) if str != converted { v.AddFailuref(i.Meta.Pos, "Quoted string should be %s but was %s.", converted, str) v.Fixer.ReplaceText(i.Meta.Pos.Line, str, converted) } return false } func (v quoteConsistentVisitor) VisitOption(o *parser.Option) (next bool) { str := o.Constant converted := convertConsistentQuote(str, v.quote) if str != converted { v.AddFailuref(o.Meta.Pos, "Quoted string should be %s but was %s.", converted, str) v.Fixer.ReplaceText(o.Meta.Pos.Line, str, converted) } return false } func (v quoteConsistentVisitor) VisitEnumField(f *parser.EnumField) (next bool) { for _, option := range f.EnumValueOptions { str := option.Constant converted := convertConsistentQuote(str, v.quote) if str != converted { v.AddFailuref(f.Meta.Pos, "Quoted string should be %s but was %s.", converted, str) v.Fixer.ReplaceText(f.Meta.Pos.Line, str, converted) } } return false } func (v quoteConsistentVisitor) VisitField(f *parser.Field) (next bool) { for _, option := range f.FieldOptions { str := option.Constant converted := convertConsistentQuote(str, v.quote) if str != converted { v.AddFailuref(f.Meta.Pos, "Quoted string should be %s but was %s.", converted, str) v.Fixer.ReplaceText(f.Meta.Pos.Line, str, converted) } } return false } func convertConsistentQuote(s string, quote config.QuoteType) string { var valid, invalid string if quote == config.DoubleQuote { valid, invalid = "\"", "'" } else { valid, invalid = "'", "\"" } if strings.HasPrefix(s, invalid) && strings.HasSuffix(s, invalid) { return valid + s[1:len(s)-1] + valid } return s } <file_sep>/_example/plugin/customrules/simpleRule.go package customrules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" ) // SimpleRule verifies that all enum names are LowerSnakeCase. type SimpleRule struct { verbose bool fixMode bool severity rule.Severity } // NewSimpleRule creates a new SimpleRule. func NewSimpleRule( verbose bool, fixMode bool, severity rule.Severity, ) SimpleRule { return SimpleRule{ verbose: verbose, fixMode: fixMode, severity: severity, } } // ID returns the ID of this rule. func (r SimpleRule) ID() string { return "SIMPLE" } // Purpose returns the purpose of this rule. func (r SimpleRule) Purpose() string { return "Simple custom rule." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r SimpleRule) IsOfficial() bool { return true } // Severity gets the rule severity func (r SimpleRule) Severity() rule.Severity { return r.severity } // Apply applies the rule to the proto. func (r SimpleRule) Apply(proto *parser.Proto) ([]report.Failure, error) { return []report.Failure{ report.Failuref(meta.Position{}, r.ID(), "Custom Rule, verbose=%v, fixMode=%v", r.verbose, r.fixMode), }, nil } <file_sep>/internal/linter/config/externalConfig.go package config // Lint represents the lint configuration. type Lint struct { Ignores Ignores Files Files Directories Directories Rules Rules RulesOption RulesOption `yaml:"rules_option"` } // ExternalConfig represents the external configuration. type ExternalConfig struct { SourcePath string Lint Lint } // ShouldSkipRule checks whether to skip applying the rule to the file. func (c ExternalConfig) ShouldSkipRule( ruleID string, displayPath string, defaultRuleIDs []string, ) bool { lint := c.Lint return lint.Ignores.shouldSkipRule(ruleID, displayPath) || lint.Files.shouldSkipRule(displayPath) || lint.Directories.shouldSkipRule(displayPath) || lint.Rules.shouldSkipRule(ruleID, defaultRuleIDs) } <file_sep>/internal/addon/plugin/shared/config.go package shared import ( "context" "github.com/yoheimuta/protolint/internal/addon/plugin/proto" "github.com/hashicorp/go-plugin" "google.golang.org/grpc" ) // Handshake is a common handshake that is shared by plugin and host. var Handshake = plugin.HandshakeConfig{ ProtocolVersion: 1, MagicCookieKey: "BASIC_PLUGIN", MagicCookieValue: "hello", } // PluginMap is the map of plugins we can dispense. var PluginMap = map[string]plugin.Plugin{ "ruleSet": &RuleSetGRPCPlugin{}, } // RuleSetGRPCPlugin is the implementation of plugin.GRPCPlugin so we can serve/consume this. type RuleSetGRPCPlugin struct { plugin.Plugin Impl RuleSet } // GRPCServer registers this plugin. func (p *RuleSetGRPCPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { proto.RegisterRuleSetServiceServer(s, &GRPCServer{server: p.Impl}) return nil } // GRPCClient returns the interface implementation for the plugin. func (p *RuleSetGRPCPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { return &GRPCClient{client: proto.NewRuleSetServiceClient(c)}, nil } <file_sep>/internal/addon/rules/serviceNamesEndWithRule.go package rules import ( "strings" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // ServiceNamesEndWithRule verifies that all service names end with the specified value. type ServiceNamesEndWithRule struct { RuleWithSeverity text string } // NewServiceNamesEndWithRule creates a new ServiceNamesEndWithRule. func NewServiceNamesEndWithRule( severity rule.Severity, text string, ) ServiceNamesEndWithRule { return ServiceNamesEndWithRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, text: text, } } // ID returns the ID of this rule. func (r ServiceNamesEndWithRule) ID() string { return "SERVICE_NAMES_END_WITH" } // Purpose returns the purpose of this rule. func (r ServiceNamesEndWithRule) Purpose() string { return "Verifies that all service names end with the specified value." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r ServiceNamesEndWithRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r ServiceNamesEndWithRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &serviceNamesEndWithVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), text: r.text, } return visitor.RunVisitor(v, proto, r.ID()) } type serviceNamesEndWithVisitor struct { *visitor.BaseAddVisitor text string } // VisitService checks the service. func (v *serviceNamesEndWithVisitor) VisitService(service *parser.Service) bool { if !strings.HasSuffix(service.ServiceName, v.text) { v.AddFailuref(service.Meta.Pos, "Service name %q must end with %s", service.ServiceName, v.text) } return false } <file_sep>/internal/linter/config/maxLineLengthOption.go package config // MaxLineLengthOption represents the option for the MAX_LINE_LENGTH rule. type MaxLineLengthOption struct { CustomizableSeverityOption MaxChars int `yaml:"max_chars"` TabChars int `yaml:"tab_chars"` } <file_sep>/settings.gradle rootProject.name = 'protoc-gen-protolint' <file_sep>/cmd/pl/main.go package main import ( "os" "github.com/yoheimuta/protolint/internal/cmd" ) // DEPRECATED: Use cmd/protolint. See https://github.com/yoheimuta/protolint/issues/20. func main() { os.Exit(int( cmd.Do( os.Args[1:], os.Stdout, os.Stderr, ), )) } <file_sep>/internal/linter/config/externalConfigProvider.go package config import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "github.com/yoheimuta/protolint/internal/stringsutil" yaml "gopkg.in/yaml.v2" ) const ( externalConfigFileName = ".protolint" externalConfigFileName2 = "protolint" externalConfigFileExtension = ".yaml" externalConfigFileExtension2 = ".yml" ) // GetExternalConfig provides the externalConfig. func GetExternalConfig( filePath string, dirPath string, ) (*ExternalConfig, error) { newPath, err := getExternalConfigPath(filePath, dirPath) if err != nil { if len(filePath) == 0 && len(dirPath) == 0 { return nil, nil } return nil, err } data, err := ioutil.ReadFile(newPath) if err != nil { return nil, err } if len(data) == 0 { return nil, fmt.Errorf("read %s, but the content is empty", newPath) } var config ExternalConfig if err := yaml.UnmarshalStrict(data, &config); err != nil { return nil, err } config.SourcePath = newPath return &config, nil } func getExternalConfigPath( filePath string, dirPath string, ) (string, error) { if 0 < len(filePath) { return filePath, nil } dirPaths := []string{dirPath} if len(dirPath) == 0 { absPath, err := os.Getwd() if err != nil { return "", err } absPath = filepath.Dir(absPath) for !stringsutil.ContainsStringInSlice(absPath, dirPaths) { dirPaths = append(dirPaths, absPath) absPath = filepath.Dir(absPath) } } var checkedPaths []string for _, dir := range dirPaths { for _, name := range []string{ externalConfigFileName, externalConfigFileName2, } { for _, ext := range []string{ externalConfigFileExtension, externalConfigFileExtension2, } { filePath := filepath.Join(dir, name+ext) checkedPaths = append(checkedPaths, filePath) if _, err := os.Stat(filePath); err != nil { if os.IsNotExist(err) { continue } return "", err } return filePath, nil } } } return "", fmt.Errorf("not found config file by searching `%s`", strings.Join(checkedPaths, ",")) } <file_sep>/internal/addon/rules/orderRule.go package rules import ( "bytes" "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/go-protoparser/v4/parser/meta" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // OrderRule verifies that all files should be ordered in the following manner: // 1. Syntax // 2. Package // 3. Imports (sorted) // 4. File options // 5. Everything else // See https://developers.google.com/protocol-buffers/docs/style#file-structure. type OrderRule struct { RuleWithSeverity fixMode bool } // NewOrderRule creates a new OrderRule. func NewOrderRule( severity rule.Severity, fixMode bool, ) OrderRule { return OrderRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, fixMode: fixMode, } } // ID returns the ID of this rule. func (r OrderRule) ID() string { return "ORDER" } // Purpose returns the purpose of this rule. func (r OrderRule) Purpose() string { return "Verifies that all files should be ordered in the specific manner." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r OrderRule) IsOfficial() bool { return true } // Apply applies the rule to the proto. func (r OrderRule) Apply(proto *parser.Proto) ([]report.Failure, error) { base, err := visitor.NewBaseFixableVisitor(r.ID(), r.fixMode, proto, string(r.Severity())) if err != nil { return nil, err } v := &orderVisitor{ BaseFixableVisitor: base, state: initialOrderState, machine: newOrderStateTransition(), } return visitor.RunVisitor(v, proto, r.ID()) } type orderVisitor struct { *visitor.BaseFixableVisitor state orderState machine orderStateTransition formatter formatter } func (v *orderVisitor) Finally() error { if 0 < len(v.Failures()) { shouldFixed := true v.Fixer.ReplaceContent(func(content []byte) []byte { newContent := v.formatter.format(content) if bytes.Equal(content, newContent) { shouldFixed = false } return newContent }) // TODO: BaseFixableVisitor.Finally should run the base Finally first, and then the fixing later. if shouldFixed { return v.BaseFixableVisitor.Finally() } } return nil } func (v *orderVisitor) VisitSyntax(s *parser.Syntax) bool { next := v.machine.transit(v.state, syntaxVisitEvent) if next == invalidOrderState { v.AddFailuref(s.Meta.Pos, "Syntax should be located at the top. Check if the file is ordered in the correct manner.") } v.state = syntaxOrderState v.formatter.syntax = s return false } func (v *orderVisitor) VisitPackage(p *parser.Package) bool { next := v.machine.transit(v.state, packageVisitEvent) if next == invalidOrderState { v.AddFailuref(p.Meta.Pos, "The order of Package is invalid. Check if the file is ordered in the correct manner.") } v.state = packageOrderState v.formatter.pkg = p return false } func (v *orderVisitor) VisitImport(i *parser.Import) bool { next := v.machine.transit(v.state, importsVisitEvent) if next == invalidOrderState { v.AddFailuref(i.Meta.Pos, "The order of Import is invalid. Check if the file is ordered in the correct manner.") } v.state = importsOrderState v.formatter.addImports(i) return false } func (v *orderVisitor) VisitOption(o *parser.Option) bool { next := v.machine.transit(v.state, fileOptionsVisitEvent) if next == invalidOrderState { v.AddFailuref(o.Meta.Pos, "The order of Option is invalid. Check if the file is ordered in the correct manner.") } v.state = fileOptionsOrderState v.formatter.addOptions(o) return false } func (v *orderVisitor) VisitMessage(m *parser.Message) bool { v.state = everythingElseOrderState v.formatter.addMisc(m) return false } func (v *orderVisitor) VisitEnum(e *parser.Enum) bool { v.state = everythingElseOrderState v.formatter.addMisc(e) return false } func (v *orderVisitor) VisitService(s *parser.Service) bool { v.state = everythingElseOrderState v.formatter.addMisc(s) return false } func (v *orderVisitor) VisitExtend(e *parser.Extend) bool { v.state = everythingElseOrderState v.formatter.addMisc(e) return false } func (v *orderVisitor) VisitComment(c *parser.Comment) { v.formatter.addComment(c) } // State Checker type orderState int const ( invalidOrderState orderState = iota initialOrderState syntaxOrderState packageOrderState importsOrderState fileOptionsOrderState everythingElseOrderState ) type orderEvent int const ( syntaxVisitEvent orderEvent = iota packageVisitEvent importsVisitEvent fileOptionsVisitEvent ) type orderInput struct { state orderState event orderEvent } type orderStateTransition struct { f map[orderInput]orderState } func newOrderStateTransition() orderStateTransition { return orderStateTransition{ f: map[orderInput]orderState{ { state: initialOrderState, event: syntaxVisitEvent, }: syntaxOrderState, { state: initialOrderState, event: packageVisitEvent, }: packageOrderState, { state: syntaxOrderState, event: packageVisitEvent, }: packageOrderState, { state: initialOrderState, event: importsVisitEvent, }: importsOrderState, { state: syntaxOrderState, event: importsVisitEvent, }: importsOrderState, { state: packageOrderState, event: importsVisitEvent, }: importsOrderState, { state: importsOrderState, event: importsVisitEvent, }: importsOrderState, { state: initialOrderState, event: fileOptionsVisitEvent, }: fileOptionsOrderState, { state: syntaxOrderState, event: fileOptionsVisitEvent, }: fileOptionsOrderState, { state: packageOrderState, event: fileOptionsVisitEvent, }: fileOptionsOrderState, { state: importsOrderState, event: fileOptionsVisitEvent, }: fileOptionsOrderState, { state: fileOptionsOrderState, event: fileOptionsVisitEvent, }: fileOptionsOrderState, }, } } func (t orderStateTransition) transit( state orderState, event orderEvent, ) orderState { out, ok := t.f[orderInput{state: state, event: event}] if !ok { return invalidOrderState } return out } // Formatter type indexedVisitee struct { index int visitee parser.Visitee } // NOTE: This check is not used at the moment. // If no one requests to put the same element in a row as much as possible, // we should delete this wrap struct, indexedVisitee. func (i indexedVisitee) isContiguous(a indexedVisitee) bool { return i.index-a.index == 1 } type formatter struct { syntax *parser.Syntax pkg *parser.Package imports []indexedVisitee options []indexedVisitee misc []indexedVisitee comments []indexedVisitee } func (f formatter) index() int { idx := 0 if f.syntax != nil { idx = 1 } if f.pkg != nil { idx++ } return idx + len(f.imports) + len(f.options) + len(f.misc) } func (f *formatter) addImports(t *parser.Import) { f.imports = append(f.imports, indexedVisitee{f.index(), t}) } func (f *formatter) addOptions(t *parser.Option) { f.options = append(f.options, indexedVisitee{f.index(), t}) } func (f *formatter) addMisc(t parser.Visitee) { f.misc = append(f.misc, indexedVisitee{f.index(), t}) } func (f *formatter) addComment(t parser.Visitee) { f.comments = append(f.comments, indexedVisitee{f.index(), t}) } type line struct { startPos meta.Position endPos meta.Position } func newLine(meta meta.Meta, comments []*parser.Comment, inline *parser.Comment) line { var l line l.startPos = meta.Pos if 0 < len(comments) { l.startPos = comments[0].Meta.Pos } l.endPos = meta.LastPos if inline != nil { l.endPos = inline.Meta.LastPos } return l } func newVisiteeLine(elm parser.Visitee) line { switch e := elm.(type) { case *parser.Syntax: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Package: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Import: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Option: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Message: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Extend: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Enum: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Service: return newLine(e.Meta, e.Comments, e.InlineComment) case *parser.Comment: return newLine(e.Meta, []*parser.Comment{}, nil) } return line{} } func (l line) hasEmptyLine(prev line) bool { return 1 < l.startPos.Line-prev.endPos.Line } type writer struct { content []byte newContent []byte } func (w *writer) write(l line) { w.newContent = append(w.newContent, w.content[l.startPos.Offset:l.endPos.Offset+1]...) } func (w *writer) writeN(l line) { w.write(l) w.newContent = append(w.newContent, "\n"...) } func (w *writer) writeNN(l line) { w.write(l) w.newContent = append(w.newContent, "\n\n"...) } func (w *writer) writeOnlyN() { w.newContent = append(w.newContent, "\n"...) } func (w *writer) removeLastRedundantN() { if bytes.Equal(w.newContent[len(w.newContent)-2:len(w.newContent)], []byte("\n\n")) { w.newContent = w.newContent[0 : len(w.newContent)-1] } } func (f formatter) format(content []byte) []byte { w := writer{content: content} sl := newVisiteeLine(f.syntax) w.writeNN(sl) if f.pkg != nil { pl := newVisiteeLine(f.pkg) w.writeNN(pl) } visitees := [][]indexedVisitee{f.imports, f.options, f.misc, f.comments} for i, vs := range visitees { var ls []line for _, elm := range vs { ls = append(ls, newVisiteeLine(elm.visitee)) } for i, l := range ls { // There are any empty lines between both ls if 0 < i && l.hasEmptyLine(ls[i-1]) { w.writeOnlyN() } w.writeN(l) } if 0 < len(ls) && i < len(visitees)-1 { w.writeOnlyN() } } w.removeLastRedundantN() return w.newContent } <file_sep>/internal/addon/rules/syntaxConsistentRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // SyntaxConsistentRule verifies that syntax is a specified version. type SyntaxConsistentRule struct { RuleWithSeverity version string } // NewSyntaxConsistentRule creates a new SyntaxConsistentRule. func NewSyntaxConsistentRule( severity rule.Severity, version string, ) SyntaxConsistentRule { if len(version) == 0 { version = "proto3" } return SyntaxConsistentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, version: version, } } // ID returns the ID of this rule. func (r SyntaxConsistentRule) ID() string { return "SYNTAX_CONSISTENT" } // Purpose returns the purpose of this rule. func (r SyntaxConsistentRule) Purpose() string { return "Verifies that syntax is a specified version(default is proto3)." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r SyntaxConsistentRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r SyntaxConsistentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &syntaxConsistentVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), version: r.version, } return visitor.RunVisitor(v, proto, r.ID()) } type syntaxConsistentVisitor struct { *visitor.BaseAddVisitor version string } // VisitSyntax checks the syntax. func (v *syntaxConsistentVisitor) VisitSyntax(s *parser.Syntax) bool { if s.ProtobufVersion != v.version { v.AddFailuref(s.Meta.Pos, "Syntax should be %q but was %q.", v.version, s.ProtobufVersion) } return false } <file_sep>/internal/linter/config/repeatedFieldNamesPluralizedOption.go package config // RepeatedFieldNamesPluralizedOption represents the option for the REPEATED_FIELD_NAMES_PLURALIZED rule. type RepeatedFieldNamesPluralizedOption struct { CustomizableSeverityOption PluralRules map[string]string `yaml:"plural_rules"` SingularRules map[string]string `yaml:"singular_rules"` UncountableRules []string `yaml:"uncountable_rules"` IrregularRules map[string]string `yaml:"irregular_rules"` } <file_sep>/internal/addon/rules/fieldsHaveCommentRule.go package rules import ( "github.com/yoheimuta/go-protoparser/v4/parser" "github.com/yoheimuta/protolint/linter/report" "github.com/yoheimuta/protolint/linter/rule" "github.com/yoheimuta/protolint/linter/visitor" ) // FieldsHaveCommentRule verifies that all fields have a comment. type FieldsHaveCommentRule struct { RuleWithSeverity // Golang style comments should begin with the name of the thing being described. // See https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences shouldFollowGolangStyle bool } // NewFieldsHaveCommentRule creates a new FieldsHaveCommentRule. func NewFieldsHaveCommentRule( severity rule.Severity, shouldFollowGolangStyle bool, ) FieldsHaveCommentRule { return FieldsHaveCommentRule{ RuleWithSeverity: RuleWithSeverity{severity: severity}, shouldFollowGolangStyle: shouldFollowGolangStyle, } } // ID returns the ID of this rule. func (r FieldsHaveCommentRule) ID() string { return "FIELDS_HAVE_COMMENT" } // Purpose returns the purpose of this rule. func (r FieldsHaveCommentRule) Purpose() string { return "Verifies that all fields have a comment." } // IsOfficial decides whether or not this rule belongs to the official guide. func (r FieldsHaveCommentRule) IsOfficial() bool { return false } // Apply applies the rule to the proto. func (r FieldsHaveCommentRule) Apply(proto *parser.Proto) ([]report.Failure, error) { v := &fieldsHaveCommentVisitor{ BaseAddVisitor: visitor.NewBaseAddVisitor(r.ID(), string(r.Severity())), shouldFollowGolangStyle: r.shouldFollowGolangStyle, } return visitor.RunVisitor(v, proto, r.ID()) } type fieldsHaveCommentVisitor struct { *visitor.BaseAddVisitor shouldFollowGolangStyle bool } // VisitField checks the field. func (v *fieldsHaveCommentVisitor) VisitField(field *parser.Field) bool { n := field.FieldName if v.shouldFollowGolangStyle && !hasGolangStyleComment(field.Comments, n) { v.AddFailuref(field.Meta.Pos, `Field %q should have a comment of the form "// %s ..."`, n, n) } else if !hasComments(field.Comments, field.InlineComment) { v.AddFailuref(field.Meta.Pos, `Field %q should have a comment`, n) } return false } // VisitMapField checks the map field. func (v *fieldsHaveCommentVisitor) VisitMapField(field *parser.MapField) bool { n := field.MapName if v.shouldFollowGolangStyle && !hasGolangStyleComment(field.Comments, n) { v.AddFailuref(field.Meta.Pos, `Field %q should have a comment of the form "// %s ..."`, n, n) } else if !hasComments(field.Comments, field.InlineComment) { v.AddFailuref(field.Meta.Pos, `Field %q should have a comment`, n) } return false } // VisitOneofField checks the oneof field. func (v *fieldsHaveCommentVisitor) VisitOneofField(field *parser.OneofField) bool { n := field.FieldName if v.shouldFollowGolangStyle && !hasGolangStyleComment(field.Comments, n) { v.AddFailuref(field.Meta.Pos, `Field %q should have a comment of the form "// %s ..."`, n, n) } else if !hasComments(field.Comments, field.InlineComment) { v.AddFailuref(field.Meta.Pos, `Field %q should have a comment`, n) } return false }
9ad94e65a74ff5e16efe4c4d9745e1a4bd59388e
[ "Markdown", "Makefile", "Gradle", "Go", "Go Module", "Dockerfile", "Shell" ]
165
Go
yoheimuta/protolint
ad00a18de409c463d0ff00ad4f6709998f48c19f
f5abf8889d3624ce7286e1dc3d5c38228d41b2fa
refs/heads/master
<repo_name>rschenck/game_of_life<file_sep>/main.py import pygame, sys from pygame.locals import * # import numpy as np import math import random import time from functionality import random_color, user_select, start, stop, reset, reset_options, info_button, info, click_creator from presets import gun, create_glider, blank, tens, pulsar, gliders, maze, faces, binary_101, rando # Define global variables # width = 1200 # height = 600 cellsize = 10 fps = 30.0 black = (0, 0, 0) white = (255,255,255) darkgrey = (40, 40, 40) red = (220,20,60) b_red = (255,0,0) green = (0,200,0) b_green = (0,255,0) # use these to track current cells and updates gridDict = {} otherDict = {} class cell: def __init__(self, loc, stat): self.loc = loc self.stat = stat # draw an empty grid for our cells to live in def drawGrid(width, height): for x in range(0, width, cellsize): pygame.draw.line(display_surface, darkgrey, (x,0),(x,height)) for y in range(0, height, cellsize): pygame.draw.line(display_surface, darkgrey, (0,y),(width,y)) return None # fill gridDict will cells, randomly assign cell.stat values def blanks(gridDict, width, height): for y in range(-20, height+20, cellsize): for x in range (-20, width+20, cellsize): # stat = 1 if random.randint(0,12) > 10 else 0 stat = 0 gridDict[x,y] = cell((x,y), stat) # Default Starting option rando(gridDict) return gridDict def user_tick(gridDict): #Colors user boxes color(gridDict) def check_neighbors(item, gridDict): ''' alive - number of neighboring cells that are alive dead - 1: current cell is alive, 0: its dead newStat - value to assign to the new cell object ''' alive = 0 dead = 0 newStat = 0 # cycle through neigbors and increment alive and assign dead for x in [10, -10, 0]: for y in [10, -10, 0]: if (x,y) != (0,0): try: alive += gridDict[(item[0]+x,item[1]+y)].stat except KeyError: pass else: try: dead += gridDict[(item[0]+x,item[1]+y)].stat except KeyError: pass # implement rules for conway's game of life if dead == 1: if alive < 2 or alive > 3: newStat = 0 else: newStat = 1 elif dead == 0: if alive == 3: newStat = 1 else: pass if x < -10 or y < -10 or x > 510 or y > 510: newStat = 0 return cell(item, newStat) # update cells for next round def tick(gridDict, otherDict): for item in gridDict: otherDict[item] = check_neighbors(item, gridDict) copyDict = otherDict.copy() otherDict = {} gridDict = copyDict.copy() # redraw cells color(gridDict) return gridDict, otherDict # draw the cells def color(gridDict): to_col = gridDict for item in to_col: # draw live cells as a colored rect color = white if to_col[item].stat == 1 else black try: pygame.draw.rect(display_surface, color, (to_col[item].loc[0],to_col[item].loc[1],cellsize,cellsize)) except KeyError: pass # draw dead cells as black rect def banner(display_surface, x, y): pygame.draw.rect(display_surface, white, (0, y-30, x, 30)) def main(gridDict, otherDict): pygame.init() pygame.mixer.init() # get screen size display_info = pygame.display.Info() if display_info.current_w > 2000: width = int(display_info.current_w/2.) height = int(display_info.current_h/2.) else: width = int(display_info.current_w) height = int(display_info.current_h) # Catch if width and height are valid for board assert width % cellsize == 0 assert height % cellsize == 0 pygame.mixer.music.load('sound/emotion.wav') pygame.mixer.music.play(loops=-1, start=0.0) global display_surface fpsclock = pygame.time.Clock() display_surface = pygame.display.set_mode((width,height)) display_surface.fill(black) pygame.display.set_caption('Game of Life') blanks(gridDict, width, height) color(gridDict) drawGrid(width, height) x = width y = height click_option = 1 mouse = (0,0,0) reset_this = False show_i = False option = '' banner(display_surface, x, y) run = start(display_surface, width, height) pygame.display.update() # time.sleep(40) # pos = (0,0) while True: #main game loop for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: mouse = (1,0,0) if event.button == 1 else (0,0,0) # pos = event.pos # mouse = mouse if mouse else pygame.mouse.get_pressed() pos = pygame.mouse.get_pos() # User picks grids (not if option menu is on) if mouse[0]: if reset_this == False and show_i == False: # create_glider(gridDict,pos[0],pos[1]) user_select(gridDict,pos[0],pos[1],width, height, click_option) if run: gridDict, otherDict = tick(gridDict, otherDict) else: pass user_tick(gridDict) drawGrid(width, height) banner(display_surface, x, y) # Controls click_option = click_creator(display_surface, width, height, click_option, pos, mouse) if run: run = stop(display_surface, width, height, pos, mouse) run, reset_this = reset(display_surface, width, height, run, pos, mouse) # info panel run, show_i = info_button(display_surface, width, height, run, pos, mouse) else: # stops start from being displayed with the Reset choices if reset_this or show_i: pass else: run = start(display_surface, width, height, pos, mouse) # info panel run, show_i = info_button(display_surface, width, height, run, pos, mouse) # Brings up options menu if reset_this: option = reset_options(display_surface, width, height, pos, mouse) else: pass if option == 'Blank': blank(gridDict) reset_this = False elif option == 'Gun': blank(gridDict) gun(gridDict) reset_this = False elif option == 'Ten': blank(gridDict) tens(gridDict) reset_this = False elif option == 'Binary': blank(gridDict) binary_101(gridDict) reset_this = False elif option == 'Face': blank(gridDict) faces(gridDict) reset_this = False elif option == 'Maze': blank(gridDict) maze(gridDict) reset_this = False elif option == 'Pulsar': blank(gridDict) pulsar(gridDict) reset_this = False elif option == 'Gliders': blank(gridDict) gliders(gridDict) reset_this = False elif option == 'Random': blank(gridDict) rando(gridDict) reset_this = False else: pass if show_i: show_i = info(display_surface, width, height, pos, mouse) else: pass pygame.display.update() fpsclock.tick(fps) mouse = (0,0,0) option = '' if __name__ == '__main__': main(gridDict, otherDict) <file_sep>/examples/highscore_example.py from kivy.app import App from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.storage.jsonstore import JsonStore from kivy.properties import NumericProperty from functools import partial from os.path import join class TestApp(App): def build(self): # Main component for high score data_dir = getattr(self, 'user_data_dir') self.highscorejson = JsonStore(join(data_dir, 'highscore.json')) self.score = 0 # Default value for current score if self.highscorejson.exists('highscore'): # Checking if 'highscore' exists in your cache file self.score = int(self.highscorejson.get('highscore')['best']) # Auxillary f = FloatLayout() self.btn = Button(text=str(self.score), font_size=150) self.btn.bind(on_press=partial(some_function, self)) f.add_widget(self.btn) return f def some_function(q, *args): # print q.score q.score += 1 if q.score > 70: q.highscorejson.put('highscore', best=q.score) q.btn.text = str(q.score) if __name__ == "__main__": TestApp().run() <file_sep>/port/settings_options.py import json settings_json = json.dumps([ {'type': 'title', 'title': 'Customize your cellular automata'}, { 'type': 'bool', 'title': 'Wrap-around', 'desc': 'Cells leaving one side of the screen will immediately appear on the opposite side.', 'section': 'initiate', 'key': 'Wrap', }, { 'type': 'scrolloptions', 'title': 'Speed of game', 'desc': 'Adjust the speed of the game in seconds. (Default = Fast)', 'section': 'initiate', 'key': 'Speed', 'options': ['Max Speed', 'Very Fast', 'Faster', 'Fast', 'Above Average', 'Average', 'Slow', 'Slower', 'Very Slow', 'Min Speed'] }, { 'type': 'scrolloptions', 'title': 'Death: Lonely', 'desc': 'Adjust conditions by which a cell dies by loneliness (0 to selected value). (Default is 0-1)', 'section': 'initiate', 'key': 'Lonely', 'options': ['0','1','2','3','4','5','6','7','8'] }, { 'type': 'scrolloptions', 'title': 'Death: Overcrowded', 'desc': 'Adjust conditions by which a cell dies by overcrowdedness (selected value to 7). (Default is 4-7)', 'section': 'initiate', 'key': 'Crowded', 'options': ['0','1','2','3','4','5','6','7','8'] }, { 'type': 'scrolloptions', 'title': 'Birth', 'desc': 'Adjust conditions for a new cell to be born (Set value). (Default is 3)', 'section': 'initiate', 'key': 'Born', 'options': ['0','1','2','3','4','5','6','7','8'] }, { 'type': 'scrolloptions', 'title': 'Color', 'desc': 'Pick the color of the cells!', 'section': 'initiate', 'key': 'Color', 'options': ['Random','White','Red','Blue','Green','Yellow','Orange','Pink','Purple','Cyan'] }, { 'type': 'bool', 'title': 'Music', 'desc': '', 'section': 'initiate', 'key': 'Music', } # { # 'type': 'bool', # 'title': 'Sound', # 'desc': '', # 'section': 'initiate', # 'key': 'Sound', # } ]) <file_sep>/examples/scrollview_example.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.scrollview import ScrollView from kivy.uix.popup import Popup from kivy.core.window import Window from kivy.app import runTouchApp from functools import partial class PopupApp(App): def dismiss_modal(modal, *largs): modal.dismiss() def build(self): board = FloatLayout(size=(Window.width, Window.height)) popup = Popup(title="test popup", size_hint=(0.3,0.8), pos_hint={'x':0.35,'top':0.95}) layout = GridLayout(cols=1, spacing=10, size_hint_y=None) # Make sure the height is such that there is something to scroll. layout.bind(minimum_height=layout.setter('height')) for i in range(100): btn = Button(text=str(i), size_hint_y=None, height=40, on_press=popup.dismiss) layout.add_widget(btn) root = ScrollView(size_hint=(1, 1)) root.add_widget(layout) popup.add_widget(root) # board.add_widget(popup) # popup.open() b1 = Button(text="open",size_hint=(0.2,None),height=45, pos_hint={'x':0.4}) # content = GridLayout(cols=1,spacing=10,size_hint_y=None) # button = Button(text="dismiss") # content.add_widget(button) # popup = Popup(title="test popup", content=content,size_hint=(0.3,0.9)) # button.bind(on_press=popup.dismiss) board.add_widget(b1) b1.bind(on_press=popup.open) return board if __name__ == '__main__': PopupApp().run() <file_sep>/examples/main_menu_example.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.scrollview import ScrollView from kivy.uix.modalview import ModalView from kivy.uix.popup import Popup from kivy.core.window import Window from kivy.app import runTouchApp from functools import partial from kivy.uix.label import Label from kivy.metrics import dp from kivy.uix.widget import Widget class PopupApp(App): restart_menu = None def setup_popup(self, layout, popup,*largs): self.restart_menu.content = layout popup.dismiss() def dismiss_modal(modal, *largs): modal.dismiss() def build(self): board = FloatLayout(size=(Window.width, Window.height)) # popup = main menu main_menu = Popup(title="Main Menu", size_hint=(0.3,0.45), pos_hint={'x':0.35,'top':0.80}) layout = GridLayout(cols=1, spacing=10, size_hint_y=1) button1 = Button(text="Playground Mode", size_hint=(1,None), height=dp(50)) button2 = Button(text="Game Mode",size_hint=(1,None), height=dp(50)) layout.add_widget(Widget(size_hint_y=None, height=dp(25))) layout.add_widget(button1) layout.add_widget(Widget(size_hint_y=None, height=dp(25))) layout.add_widget(button2) main_menu.add_widget(layout) # b1 is bound to board to open restart menu b1 = Button(text="Restart",size_hint=(0.2,None),height=45, pos_hint={'x':0.4}) # restart_menu is a popup self.restart_menu = Popup(title="Restart",size_hint=(0.3,0.45), pos_hint={'x':0.35,'top':0.80}) # setup playground restart menu restart_playground_layout = GridLayout(cols=1, spacing='5dp') scroll_layout = GridLayout(cols=1, spacing=10, size_hint_y=None) # Make sure the height is such that there is something to scroll. scroll_layout.bind(minimum_height=scroll_layout.setter('height')) for i in range(100): btn = Button(text=str(i), size_hint_y=None, height=40, on_press=self.restart_menu.dismiss) scroll_layout.add_widget(btn) scrollview = ScrollView(size_hint=(1, 1)) scrollview.add_widget(scroll_layout) restart_playground_layout.add_widget(Widget(size_hint_y=None, height=dp(2))) restart_playground_layout.add_widget(scrollview) restart_playground_layout.add_widget(Button(text="Main Menu",on_press=main_menu.open, size_hint=(1,None), height=dp(50))) main_menu.bind(on_open=self.restart_menu.dismiss) self.restart_menu.content = restart_playground_layout # setup game restart menu restart_game_layout = BoxLayout(size_hint=(1,1),orientation='vertical') restart_game_label = Label(text="Are you sure you want to restart?") button_container = BoxLayout(size_hint=(1,None), height=dp(50), orientation='horizontal') restart_game_button = Button(text="Restart",on_press=self.restart_menu.dismiss) main_menu_button = Button(text="Main Menu", on_press=main_menu.open) restart_game_layout.add_widget(restart_game_label) button_container.add_widget(restart_game_button) button_container.add_widget(main_menu_button) restart_game_layout.add_widget(button_container) # handle setup of restart menu button1.bind(on_press=partial(self.setup_popup, restart_playground_layout, main_menu)) button2.bind(on_press=partial(self.setup_popup, restart_game_layout, main_menu)) board.add_widget(b1) b1.bind(on_press=self.restart_menu.open) main_menu.open() return board if __name__ == '__main__': PopupApp().run() <file_sep>/examples/igroupexample.py from kivy.app import App from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.core.window import Window from kivy.graphics.instructions import InstructionGroup from kivy.graphics import * from kivy.uix.widget import Widget from functools import partial from random import random def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) pass class Groupings(Widget): blue = InstructionGroup() blue_color = InstructionGroup() blue_instr = Color(0, 0, 1, 1) blue_color.add(blue_instr) blue.add(Rectangle(pos=(0,0), size=(100, 100))) green = InstructionGroup() green_color = InstructionGroup() green_instr = Color(0, 1, 0, 1) green_color.add(green_instr) green.add(Rectangle(pos=(100, 100), size=(100, 100))) def draw_groupings(self,*largs): self.canvas.add(self.green_color) self.canvas.add(self.green) self.canvas.add(self.blue_color) self.canvas.add(self.blue) def change_color(self, groupname, *largs): print "change_color() called" print "color:", groupname if groupname == 'blue': group,color = self.blue_color,self.blue_instr else: group,color = self.green_color,self.green_instr group.remove(color) color = Color(random(),1,1,mode='hsv') group.add(color) class InstructionApp(App): def build(self): board = FloatLayout(size=(Window.width, Window.height)) groupings = Groupings() board.add_widget(groupings) groupings.draw_groupings() button1 = Button(text="d blue", on_press=partial(groupings.change_color, 'blue'), pos=(0,400),size_hint=(None,None), size=(50,45)) button2 = Button(text="d green", on_press=partial(groupings.change_color, 'green'), pos=(51,400),size_hint=(None,None), size=(50,45)) board.add_widget(button1) board.add_widget(button2) return board if __name__ == '__main__': InstructionApp().run() <file_sep>/examples/main_for_dev.py import kivy from kivy.core.window import Window from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * from kivy.uix.label import Label from kivy.clock import Clock from kivy.uix.button import Button from kivy.core.audio import SoundLoader from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from functionality import controls import random # Considerations for user end: # Allow user to toggle between the shapes being 'Ellipse' or 'Rectangle' or ??? (Kivy terminology) # Allow user to adjust the rules for cells to die, live, or become alive def round_down(num): return num - (num%10) def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) pass class board(Widget): sound = SoundLoader.load('img/emotion.wav') if sound: sound.loop = True sound.play() cells = {} count = 0 screen = Window.size w, h = round_down(screen[0]),round_down(screen[1]) def drawGrid(self): # screen = Window.size # w, h = round_down(screen[0]),round_down(screen[1]) with self.canvas: for xx in range(0,self.w-10,10): for yy in range(0,self.h-100,10): self.cells.update({(xx,yy):0}) stat = random.randint(0,1) self.color = Color(1,1,1) self.rect = Rectangle(pos=(5+xx,50+yy), size=(9,9)) self.cells.update({(xx,yy):[self.rect,self.color,stat]}) return self.cells def update_cell(self, *args): for cell in self.cells: self.cells[cell][2]=random.randint(0,1) if self.cells[cell][2] == 1: self.cells[cell][1].rgb = [1,1,1] else: self.cells[cell][1].rgb = [0,0,0] def on_touch_down(self, touch): xtouch = int(round_down(touch.x)-10) ytouch = int(round_down(touch.y)-50) sound = SoundLoader.load('img/button2.wav') if sound: sound.volume = 0.6 sound.play() try: self.cells[(xtouch,ytouch)][1].rgb = [1,0,0] except: pass def logic(self, *args): for cell in self.cells: alive = 0 for xx in [-10,10,0]: for yy in [-10,10,0]: if (xx,yy) != (0,0): try: alive += self.cells[cell][2] except KeyError: pass else: pass if self.cells[cell][2] == 1: if alive < 2 or alive > 3: self.cells[cell][2] = 0 else: self.cells[cell][2] = 1 else: if alive == 3: self.cells[cell][2] = 1 print self.cells[cell][2] class mainGameApp(App): # Use this if you want to test different sizes of the window... # Right now it changes dynamically depending on the system. # Window.size = (1200,1200) def build(self): # self.layout = FloatLayout() # self.layout.add_widget(controls.start) cells = board() allcells = cells.drawGrid() #Figure out a way to allow the user to select the time frame (0->1) Clock.schedule_interval(cells.update_cell, 0.5) return cells if __name__ == '__main__': mainGameApp().run() <file_sep>/functionality.py import math import random import pygame from conway_shapes import click_handler, Conway_Shape black = (0, 0, 0) white = (255,255,255) darkgrey = (40, 40, 40) red = (220,20,60) b_red = (255,0,0) green = (0,200,0) b_green = (0,255,0) def render_textrect(string, font, rect, text_color, background_color, justification=0): """Returns a surface containing the passed text string, reformatted to fit within the given rect, word-wrapping as necessary. The text will be anti-aliased. Takes the following arguments: string - the text you wish to render. \n begins a new line. font - a Font object rect - a rectstyle giving the size of the surface requested. text_color - a three-byte tuple of the rgb value of the text color. ex (0, 0, 0) = BLACK background_color - a three-byte tuple of the rgb value of the surface. justification - 0 (default) left-justified 1 horizontally centered 2 right-justified Returns the following values: Success - a surface object with the text rendered onto it. Failure - raises a TextRectException if the text won't fit onto the surface. """ import pygame final_lines = [] requested_lines = string.splitlines() # Create a series of lines that will fit on the provided # rectangle. for requested_line in requested_lines: if font.size(requested_line)[0] > rect.width: words = requested_line.split(' ') # if any of our words are too long to fit, return. for word in words: if font.size(word)[0] >= rect.width: raise TextRectException, "The word " + word + " is too long to fit in the rect passed." # Start a new line accumulated_line = "" for word in words: test_line = accumulated_line + word + " " # Build the line while the words fit. if font.size(test_line)[0] < rect.width: accumulated_line = test_line else: final_lines.append(accumulated_line) accumulated_line = word + " " final_lines.append(accumulated_line) else: final_lines.append(requested_line) # Let's try to write the text out on the surface. surface = pygame.Surface(rect.size) surface.fill(background_color) accumulated_height = 0 for line in final_lines: if accumulated_height + font.size(line)[1] >= rect.height: raise TextRectException, "Once word-wrapped, the text string was too tall to fit in the rect." if line != "": tempsurface = font.render(line, 1, text_color) if justification == 0: surface.blit(tempsurface, (0, accumulated_height)) elif justification == 1: surface.blit(tempsurface, ((rect.width - tempsurface.get_width()) / 2, accumulated_height)) elif justification == 2: surface.blit(tempsurface, (rect.width - tempsurface.get_width(), accumulated_height)) else: raise TextRectException, "Invalid justification argument: " + str(justification) accumulated_height += font.size(line)[1] return surface def round_up_nearest_ten(n): return int(math.ceil(n / 10.0)) * 10 # returns a random rgb() color tuple from a preset array def random_color(): colors = [(255,0,0),(255,0,255),(135,0,255),(0,0,255),(0,195,255),(0,255,0),(225,255,0),(255,155,0)] return colors[random.randint(0,7)] def button_tone(): button = pygame.mixer.Sound('sound/button2.wav') pygame.mixer.Sound.play(button) def user_select(gridDict, x, y, w, h, click_option): x = round_up_nearest_ten(x) - 10 y = round_up_nearest_ten(y) - 10 # if mouse pos != within banner add square # Banner Dimensions: (0, 470, 500, 30) if w > x > w-w and h-30 > y > h-h: button_tone() if gridDict[x,y].stat == 1: gridDict[x,y].stat = 0 else: # print "Creating %s at [%s,%s]" % (Conway_Shape(click_option).name, x, y) click_handler(gridDict, x, y, click_option) def text_objects(text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def start(display_surface, x, y, pos=(0,0), mstate=(0,0,0)): xanchor = int(x/2.) yanchor = int(y/2.) if xanchor-25+50 > pos[0] > xanchor-25 and y-25+20 > pos[1] > y-25: pygame.draw.rect(display_surface, b_green, (xanchor-25, y-25, 50, 20)) if mstate[0]: run = True button_tone() else: run = False else: pygame.draw.rect(display_surface, green, (xanchor-25, y-25, 50, 20)) run = False smallText = pygame.font.Font("freesansbold.ttf",12) textSurf, textRect = text_objects("START!", smallText) textRect.center = ( (xanchor-25+(50/2)), (y-25+(20/2)) ) display_surface.blit(textSurf, textRect) return run def stop(display_surface, x, y, pos=(0,0), mstate=(0,0,0)): xanchor = int(x/2.) yanchor = int(y/2.) if (xanchor-60+50) > pos[0] > (xanchor-60) and (y-25+20) > pos[1] > y-25: pygame.draw.rect(display_surface, b_red, (xanchor-60, y-25, 50, 20)) if mstate[0]: run = False button_tone() else: run = True else: pygame.draw.rect(display_surface, red, (xanchor-60, y-25, 50, 20)) run = True smallText = pygame.font.Font("freesansbold.ttf",12) textSurf, textRect = text_objects("STOP!", smallText) textRect.center = ( (xanchor-60+(50/2)), (y-25+(20/2)) ) display_surface.blit(textSurf, textRect) return run def reset(display_surface, x, y, run, pos=(0,0), mstate=(0,0,0)): xanchor = int(x/2.) yanchor = int(y/2.) if (xanchor+10+50) > pos[0] > (xanchor+10) and (y-25+20) > pos[1] > y-25: pygame.draw.rect(display_surface, b_red, (xanchor+10, y-25, 50, 20)) if mstate[0]: res_menu = True run = False button_tone() else: res_menu = False pass else: pygame.draw.rect(display_surface, red, (xanchor+10, y-25, 50, 20)) res_menu = False smallText = pygame.font.Font("freesansbold.ttf",12) textSurf, textRect = text_objects("RESET", smallText) textRect.center = ( (xanchor+10+(50/2)), (y-25+(20/2)) ) display_surface.blit(textSurf, textRect) return run, res_menu def info_button(display_surface, x, y, run, pos=(0,0), mstate=(0,0,0)): xanchor = int(x/2.) yanchor = int(y/2.) pygame.draw.circle(display_surface, black, ((x-x+20), (y-25+(20/2))), 10, 2) smallText = pygame.font.Font("freesansbold.ttf",15) textSurf, textRect = text_objects("i", smallText) textRect.center = ( (x-x+20), (y-25+(20/2)+2)) display_surface.blit(textSurf, textRect) # print str((pos[0],pos[1])) if x-x+30 > pos[0] > x-x+10 and y-5 > pos[1] > y-22: if mstate[0]: show_i = True run = False else: show_i = False else: show_i = False return run, show_i def info(display_surface, x, y, pos=(0,0), mstate=(0,0,0)): xanchor = int(x/2.) yanchor = int(y/2.) pygame.draw.rect(display_surface, white, (0, 0, x, y)) smallText = pygame.font.Font("freesansbold.ttf",18) textSurf, textRect = text_objects("Back", smallText) textRect.center = ( x-x+24 , y-y+10 ) display_surface.blit(textSurf, textRect) text_info = """<NAME>'s Cellular Automaton""" text_info2 = """\n\nRules:\n\nEach Cell with one or no neighbors dies.\nEach cell with 4 or more neighbors dies.\nEach cell with two or three neighbors survives.\nEach empty cell with three neighbors becomes populated.\n\nControls:\n\nClick to populate/depopulate a cell.\nClick start to begin model.\nClick stop to end model.\nClick reset to clear or choose preset simulations.\n\nCreated by:\n\n<NAME> & <NAME>\n\ngithub.com/rschenck/game_of_life.git""" # Headers smallText = pygame.font.Font(None,26) back_rect = pygame.Rect((x-x, y-y+60, x, y-50)) rendered_text = render_textrect(text_info, smallText, back_rect, black, white, 1) display_surface.blit(rendered_text, back_rect) # Other Text smallText = pygame.font.Font(None,22) back_rect = pygame.Rect((x-x, y-y+80, x, y-50)) rendered_text = render_textrect(text_info2, smallText, back_rect, black, white, 1) display_surface.blit(rendered_text, back_rect) # print str((pos[0],pos[1])) if x-x+40 > pos[0] > x-x and y-y+18 > pos[1] > y-y: if mstate[0]: show_i = False else: show_i = True else: show_i = True return show_i def reset_options(display_surface, x, y, pos=(0,0), mstate=(0,0,0)): xanchor = int(x/2.) yanchor = int(y/2.) pygame.draw.rect(display_surface, white, (xanchor-(yanchor/2.), 0-(y/4.0)+200, yanchor, 260)) smallText = pygame.font.Font("freesansbold.ttf",18) textSurf, textRect = text_objects("Blank", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+210) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Gun", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+240) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Ten", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+270) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Binary", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+300) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Face", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+330) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Maze", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+360) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Pulsar", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+390) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Gliders", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+420) ) display_surface.blit(textSurf, textRect) textSurf, textRect = text_objects("Random", smallText) textRect.center = ( (xanchor), (0-(y/4.0)+450) ) display_surface.blit(textSurf, textRect) # print str((pos[0],pos[1])) s = 30 # clear if xanchor+30 > pos[0] > xanchor-30 and s+5 > pos[1] > s-10: if mstate[0]: option = 'Blank' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+30+5 > pos[1] > s+30-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Gun' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+60+5 > pos[1] > s+30-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Ten' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+90+5 > pos[1] > s+90-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Binary' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+120+5 > pos[1] > s+120-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Face' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+150+5 > pos[1] > s+150-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Maze' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+180+5 > pos[1] > s+180-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Pulsar' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+210+5 > pos[1] > s+210-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Gliders' else: option = '' elif xanchor+30 > pos[0] > xanchor-30 and s+240+5 > pos[1] > s+240-10: # print str((pos[0],pos[1])) if mstate[0]: option = 'Random' else: option = '' else: option = '' return option def click_creator(display_surface, x, y, click_option, pos=(0,0), mstate=(0,0,0), ): xanchor = int(x/2.) # print str((pos[0],pos[1])) if (x) > pos[0] > (x-50) and (y-25+20) > pos[1] > y-25: pygame.draw.rect(display_surface, (200,200,200), (x-55, y-25, 50, 20)) if mstate[0]: click_option = (click_option + 1) % (Conway_Shape(1).max() + 1) or 1 else: pass else: pygame.draw.rect(display_surface, (150,150,150), (x-55, y-25, 50, 20)) smallText = pygame.font.Font("freesansbold.ttf",12) textSurf, textRect = text_objects(Conway_Shape(click_option).name, smallText) textRect.center = ( x-30, (y-25+(20/2)) ) display_surface.blit(textSurf, textRect) return click_option <file_sep>/examples/test_rect.py import kivy from collections import defaultdict from kivy.app import App from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.graphics import * from kivy.clock import Clock from kivy.graphics.instructions import InstructionGroup from random import random, randint from functools import partial import math def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) pass class LotsRect(Widget): rect_dict = {} on_board = defaultdict(int) def draw_self(self, *largs): for x in range(Window.width / 10): for y in range(Window.height/ 10): rect = InstructionGroup() rect.add(Rectangle(size=(9,9), pos=(x*10,y*10))) self.rect_dict[x,y] = rect self.on_board[x,y] = 1 self.canvas.add(rect) with self.canvas.before: Color(1,1,1,mode="rgb") def update_color(self, *largs): self.canvas.before.clear() with self.canvas.before: Color(random(),random(),random(),mode="rgb") self.canvas.ask_update() def on_touch_down(self, touch): pos_x, pos_y = touch.pos[0], touch.pos[1] x = int(math.floor(pos_x / 10.0)) y = int(math.floor(pos_y / 10.0)) try: if self.on_board[x,y]: self.canvas.remove(self.rect_dict[x,y]) del self.on_board[x,y] else: self.canvas.add(self.rect_dict[x,y]) self.on_board[x,y] = 1 except: pass def update_randomly(self, *largs): for i in range(1200): x,y = randint(0,132), randint(0,74) if self.on_board[x,y]: self.canvas.remove(self.rect_dict[x,y]) del self.on_board[x,y] else: self.canvas.add(self.rect_dict[x,y]) self.on_board[x,y] = 1 class MyApp(App): def build(self): Window.size = (1334,750) board = FloatLayout(size=(Window.width, Window.height)) rectangle = LotsRect(size_hint=(1,1)) board.add_widget(rectangle) rectangle.draw_self() button = Button(text="update color", on_press=rectangle.update_color, size_hint=(0.1,0.1), pos_hint={'x':0, 'y':0}) board.add_widget(button) Clock.schedule_interval(rectangle.update_randomly,0.001) return board if __name__ == '__main__': MyApp().run() <file_sep>/Previous/rs_conway.py import pygame, sys from pygame.locals import * # import numpy as np import math import random import time # Define global variables width = 1200 height = 600 cellsize = 10 fps = 60 # Catch if width and height are valid for board assert width % cellsize == 0 assert height % cellsize == 0 black = (0, 0, 0) white = (255,255,255) darkgrey = (40, 40, 40) red = (220,20,60) # use these to track current cells and updates gridDict = {} otherDict = {} class cell(object): def __init__(self, loc, stat): self.loc = loc self.stat = stat self.x = loc[0] self.y = loc[1] def check_neighbors (self, gridDict): # Make a class method # Looks around just like this # Assigns a status the same way # alive = 0 dead = 0 newStat = 0 # passes x,y of the cell looked up from blanks and returns 0 or 1 for x in [10, -10, 0]: for y in [10, -10, 0]: neighborx = self.x+x neighbory = self.y+y if (x,y) != (0,0): try: alive += gridDict[(neighborx,neighbory)].stat except KeyError: pass if alive < 2: newstat = 0 elif alive > 3: newstat = 0 else: nestat = 1 # print('%s %s') % (alive, dead) if self.stat == 1: # print("ALIVE") if alive < 2: newStat = 0 elif alive > 3: newStat = 0 else: newStat = 1 elif self.stat == 0: # print("DEAD") if alive == 3: newStat = 1 else: pass self.stat = newStat # draw an empty grid for our cells to live in def drawGrid(): for x in range(0, width, cellsize): pygame.draw.line(display_surface, darkgrey, (x,0),(x,height)) for y in range(0, height, cellsize): pygame.draw.line(display_surface, darkgrey, (0,y),(width,y)) return None # fill gridDict will cells, randomly assign cell.stat values def blanks(gridDict): for y in range(0, height, cellsize): for x in range (0, width, cellsize): gridDict[x,y] = cell((x,y), 0) for i in range(600,700, 10): gridDict[i,300] = cell((i,300), 1) # print str(gridDict[(100,100)].loc) + '\t' + str(gridDict[(100,100)].stat) return gridDict # cycles through def tick(gridDict): # newDraw = {} for indcell in gridDict.values(): indcell.check_neighbors(gridDict) # newDraw[item] = check_neighbors(item, gridDict) # check_neighbors(item, gridDict) # gridDict = newDraw.copy() color(gridDict) # draw the cells def color(gridDict): to_col = gridDict for item in to_col: # draw live cells as a colored rect if to_col[item].stat == 1: pygame.draw.rect(display_surface, random_color(), (to_col[item].loc[0],to_col[item].loc[1],cellsize,cellsize)) # draw dead cells as black rect elif to_col[item].stat ==0: pygame.draw.rect(display_surface, black, (to_col[item].loc[0],to_col[item].loc[1],cellsize,cellsize)) def main(gridDict): pygame.init() global display_surface fpsclock = pygame.time.Clock() display_surface = pygame.display.set_mode((width,height)) display_surface.fill(black) pygame.display.set_caption('Game of Life') blanks(gridDict) color(gridDict) drawGrid() pygame.display.update() #time.sleep(20) x = width y = height while True: #main game loop for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() tick(gridDict) # pygame.draw.rect(display_surface, red, (x,y,cellsize,cellsize)) # x -= 10 # y -= 10 drawGrid() pygame.display.update() fpsclock.tick(fps) if __name__ == '__main__': main(gridDict) <file_sep>/examples/blinking.py from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.graphics import Color from kivy.clock import Clock import random class RootWidget(GridLayout): pass class MainApp(App): def build(self): parent = GridLayout(cols=6) for i in (1,2,3,4,5,6): for j in (1,2,3,4,5,6): parent.add_widget(Button(text='%s%s'%(i,j))) Clock.schedule_interval(lambda a:self.update(parent),1) return parent def update(self,obj): print "I am update function" for child in obj.children: c=[0,random.random(),1,random.random()] child.color=c if __name__ == '__main__': MainApp().run()<file_sep>/examples/functionality.py from kivy.uix.button import Button class controls(): start = Button(size_hint = (.09,.1), pos_hint = {'center_x':.5,'y':0}) start.background_normal = 'img/play.png' start.background_down = 'img/play_dn.png' start.border = (0,0,0,0) stop = Button(size_hint = (.09,.1), pos_hint = {'center_x':.7,'y':0}) stop.background_normal = 'img/stop.png' stop.background_down = 'img/stop_dn.png' stop.border = (0,0,0,0) reset = Button(size_hint = (.09,.1), pos_hint = {'center_x':.3,'y':0}) reset.background_normal = 'img/reset.png' reset.background_down = 'img/reset_dn.png' reset.border = (0,0,0,0) info = Button(size_hint = (.09,.1), pos_hint = {'center_x':.1,'y':0}) info.background_normal = 'img/info.png' info.background_down = 'img/info_dn.png' info.border = (0,0,0,0) prsts = Button(size_hint = (.09,.1), pos_hint = {'center_x':.9,'y':0}) prsts.background_normal = 'img/click.png' prsts.background_down = 'img/click_dn.png' prsts.border = (0,0,0,0) sett = Button(size_hint = (.09,.1), pos_hint = {'center_x':.5,'top':1}) sett.background_normal = 'img/sett.png' sett.background_down = 'img/sett_dn.png' sett.border = (0,0,0,0) <file_sep>/examples/main_for_dev_v2.py from kivy.app import App from kivy.core.window import Window from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.widget import Widget from kivy.graphics import * from functionality import controls from kivy.core.audio import SoundLoader from kivy.clock import Clock from kivy.uix.relativelayout import RelativeLayout import random import time def round_down(num): return num - (num%10) def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) pass def song(): sound = SoundLoader.load('img/emotion.wav') if sound: sound.loop = True sound.play() class board(Widget): # sound = SoundLoader.load('img/emotion.wav') # if sound: # sound.loop = True # sound.play() cells = {} count = 0 # gets the overall window.size of the screen screen = Window.size w, h = round_down(screen[0]),int(round_down(screen[1] * .8)) # portion of screen dedicated to the widgets btns = int(round_down(screen[1] * .2)) def drawGrid(self): with self.canvas: for xx in range(0,self.w-10,10): for yy in range(0,self.h,10): self.cells.update({(xx,yy):0}) stat = random.randint(0,1) if stat == 1: self.color = Color(1,1,1) else: self.color = Color(0,0,0) self.rect = Rectangle(pos=(5+xx,int(self.btns/2.)+yy), size=(9,9)) self.cells.update({(xx,yy):[self.rect,self.color,stat]}) return self.cells def update_cell(self, *args): print "Passed" for cell in self.cells: self.cells[cell][2] == random.randint(0,1) if self.cells[cell][2] == 1: self.cells[cell][1].rgb = [1,1,1] else: self.cells[cell][1].rgb = [0,0,0] class boardWidget(GridLayout): def __init__(self, **kwargs): super(boardWidget, self).__init__(**kwargs) # Set up grid size self.cols = 60 self.rows = 40 # Padding on all sides; Spacing between cells self.padding = 0 self.spacing = [0,0] #necessary to properly position the grid in the window self.pos_hint = {'center_x':.5, 'center_y':.5} self.size_hint=(.99,.8) count = 0 for i in range(0,self.cols*self.rows): btn = Button(background_normal='', background_color=(random.randint(0,255),random.randint(0,255),random.randint(0,255)), border = (0,0,0,0)) btn.id = "%s" % (i) btn.stat = random.randint(0,1) # if btn.stat == 1: # btn.background_color = (1,1,1) self.add_widget(btn) class RootWidget(FloatLayout): def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) self.btns = [controls.sett, controls.info, controls.reset, controls.start, controls.stop, controls.prsts] for item in self.btns: self.add_widget(item) w = boardWidget() dump(w) self.add_widget(w) class MyApp(App): def build(self): root = RootWidget() # song() return root if __name__=="__main__": MyApp().run()<file_sep>/port/main.py # coding: latin-1 from collections import defaultdict from functools import partial from kivy.app import App from kivy.clock import Clock from kivy.config import ConfigParser from kivy.core.audio import SoundLoader from kivy.core.window import Window from kivy.graphics import * from kivy.graphics.instructions import InstructionGroup from kivy.metrics import dp from kivy.properties import NumericProperty,BooleanProperty from kivy.storage.jsonstore import JsonStore from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.modalview import ModalView from kivy.uix.popup import Popup from kivy.uix.scrollview import ScrollView from kivy.uix.settings import SettingsWithSpinner, SettingOptions from kivy.uix.togglebutton import ToggleButton from kivy.uix.widget import Widget import math from os.path import join from random import randint from random import uniform from settings_options import settings_json from presets import presets # def dump(obj): # for attr in dir(obj): # print "obj.%s = %s" % (attr, getattr(obj, attr)) # pass cellsize = 10 v_border = (0,0) h_border = (0,0) class Grid(Widget): flash_event = None grid_color = None flash_color = True def draw_grid(self, *largs): self.size = (Window.width, Window.height - 100) # Should be fine to draw off window size self.determine_grid(self.width,self.height) self.pos = (0,50) if self.flash_event: self.stop_flash(True) with self.canvas: self.grid_color = Color(0.5,0.5,0.5, mode='rgb') for x in range(v_border[0],self.width,cellsize): Rectangle(pos=(x,self.y),size=(1,self.height)) for y in range(self.y+h_border[0],self.height+self.y,cellsize): Rectangle(pos=(self.x,y),size=(self.width,1)) Rectangle(pos=(self.x,self.y),size=(v_border[0],self.height)) Rectangle(pos=(self.x,self.y),size=(self.width,h_border[0])) Rectangle(pos=(self.width-v_border[1],self.y),size=(v_border[1],self.height)) Rectangle(pos=(self.x,self.y+self.height-h_border[1]),size=(self.width,h_border[1])) def determine_grid(self,width,height,*largs): global v_border, h_border, cellsize w_mult, h_mult = 80.,30. cellsize = int(width / w_mult) while (height / cellsize) < h_mult: cellsize -= 1 cellsize = 10 if cellsize < 10 else cellsize v_w = (width - 20) % cellsize + 20 h_w = (height - 20) % cellsize + 20 v_border = (int(v_w / 2.),int((v_w + 1 ) / 2.)) h_border = (int(h_w / 2.), int((h_w + 1) / 2.)) def flash(self,*largs): if self.flash_color: self.grid_color.rgb = (1,0,0) self.flash_color = False else: self.grid_color.rgb = (0.5,0.5,0.5) self.flash_color = True def stop_flash(self,grey,*largs): if self.flash_event: self.flash_event.cancel() if grey: self.grid_color.rgb = (0.5,0.5,0.5) else: self.grid_color.rgb = (1,0,0) self.flash_color = True self.flash_event = None def start_flash(self,*largs): if self.flash_event: self.flash_event.cancel() self.flash_event = Clock.schedule_interval(self.flash,0.25) class Cells(Widget): allcols = { 'White': (0,0,1), 'Grey': (0,0,0.25), 'Blue': (0.638888,1,1), 'Green': (0.3333,1,1), 'Black':(0,0,0), 'Red': (1,1,1), 'Orange': (0.06388,1,1), 'Yellow': (.16666,1,1), 'Pink': (0.872222,1,1), 'Purple': (0.76111,.8,.7), 'Cyan': (0.5,1,.9), 'Stem': (0.80555,0.4,1) } speeds = { "Max Speed": 0.0, "Very Fast": 0.01, "Faster": 0.03, "Fast": 0.05, "Above Average": 0.07, "Average": 0.1, "Slow": 0.15, "Slower": 0.25, "Very Slow": 0.5, "Min Speed": 1. } dimensions = None # Use this instead of self.size, which resets each frame rectangles_dict = {} def default_cells(): return {'alive':0,'was':0} on_board = defaultdict(default_cells) changes_dict = {} mid_x,mid_y = 0,0 mouse_positions = [] should_draw = False # allows touches to add rectangles accept_touches = False # Avoid sticky cell from intial click/move all_activated = NumericProperty(0) score = NumericProperty(0) # old_mech = NumericProperty(0) bonus_multiplier = 1 spawn_count = NumericProperty(100) generations = NumericProperty(500) game_over = 0 active_cell_count = NumericProperty(0) game_mode = 0 spawn_adder = NumericProperty(0) cell_color = (0,0,0) main_menu = None cellcount = 0 game_over_message = "You've done better!" wrap = 0 ever_was_alive = 0 non_positive_gens = NumericProperty(10) events = [] stop_iteration = False prevent_update = False first_time = True # Starting Patterns # Each will: # 1) call self.setup_cells() to make sure color, and midpoint are set # 2) Then assign values to self.on_board using midpoint value to center the patterns # 3) call modal.dismiss() --> triggers calls to grid.draw_grid and cells.starting_cells def assign_blank(self, modal, *largs): self.setup_cells() if modal: self.music_control('main', True, True) modal.dismiss() else: self.music_control('main', True, True) pass def place_pattern(self, modal, selection, *largs): self.setup_cells() if selection == 'blank': if modal: modal.dismiss() else: pass elif selection == 'random': for x_y in self.rectangles_dict: # assign 25% chance of life if randint(0,3) == 1: self.on_board[x_y] = {'alive':1, 'was':0} self.active_cell_count += 1 else: for coor in presets[selection]: self.on_board[( self.mid_x + int(coor[0]), self.mid_y + int(coor[1]) )] = {'alive':1, 'was':0} self.active_cell_count += 1 self.music_control('main', True, True) modal.dismiss() def place_viral_cells(self, *largs): for x_y in [(self.mid_x+15,self.mid_y+10),(self.mid_x+15,self.mid_y-10),(self.mid_x-15,self.mid_y+10),(self.mid_x-15,self.mid_y-10),(3,3),(3,self.dimensions[1]/cellsize -4),(self.dimensions[0]/cellsize-4,3),(self.dimensions[0]/cellsize-4,self.dimensions[1]/cellsize-4),(self.mid_x,self.mid_y)]: self.rectangles_dict[x_y]['color'].hsv = self.allcols["Red"] self.canvas.add(self.rectangles_dict[x_y]['color']) self.canvas.add(self.rectangles_dict[x_y]['rect']) self.on_board[x_y] = {'alive':-5} self.ever_was_alive += 1 # Setup functions def determine_borders(self,*largs): width,height = Window.width, Window.height - 100 global v_border, h_border, cellsize w_mult, h_mult = 80.,30. cellsize = int(width / w_mult) while (height / cellsize) < h_mult: cellsize -= 1 cellsize = 10 if cellsize < 10 else cellsize v_w = (width - 20) % cellsize + 20 h_w = (height - 20) % cellsize + 20 v_border = (int(v_w / 2.),int((v_w + 1 )/ 2.)) h_border = (int(h_w / 2.), int((h_w + 1)/2.)) # Create all possible rectangles for the given window size def create_rectangles(self, *largs): self.cellcount = 0 self.determine_borders() v_borders = v_border[0] + v_border[1] h_borders = h_border[0] + h_border[1] self.rectangles_dict.clear() self.dimensions = (Window.width - v_borders, Window.height - 100 - h_borders) self.pos = (v_border[0] + 1, h_border[0] + 51) cell_side = cellsize - 1 for x in range(0,self.dimensions[0]/cellsize): for y in range(0,self.dimensions[1]/cellsize): rect = Rectangle(pos=(self.x + x * cellsize, self.y + y *cellsize), size=(cell_side,cell_side)) color = Color(0,0,0,mode="hsv") self.rectangles_dict[x,y] = {"rect":rect,"color":color} self.cellcount += 1 # set canvas_color, self.pos and cells midpoint def setup_cells(self, *largs): self.set_canvas_color() self.pos = (v_border[0] +1,h_border[0] +51) self.mid_x,self.mid_y = self.dimensions[0]/(2 * cellsize), self.dimensions[1]/(2 * cellsize) # assigns color instruction to canvas.before def set_canvas_color(self, on_request=False, *largs): if self.cellcol == 'Random': self.cell_color = (uniform(0.0,1.0),1,1) else: self.cell_color = self.allcols[self.cellcol] if on_request: self.canvas.ask_update() # add the starting rectangles to the board def starting_cells(self, *largs): for x_y in self.on_board: self.rectangles_dict[x_y]["color"].hsv = self.cell_color self.canvas.add(self.rectangles_dict[x_y]["color"]) self.canvas.add(self.rectangles_dict[x_y]["rect"]) if self.game_mode == 2: self.place_viral_cells() self.should_draw = True self.accept_touches = True # Only first time matters # game logic for each iteration def get_cell_changes(self, *largs): for x in range(0,int(self.dimensions[0]/cellsize)): for y in range(0,int(self.dimensions[1]/cellsize)): # With wrap-around if self.wrap: over_x,over_y = (x + 1) % (self.dimensions[0]/cellsize), (y + 1) % (self.dimensions[1]/cellsize) bel_x, bel_y = (x - 1) % (self.dimensions[0]/cellsize), (y - 1) % (self.dimensions[1]/cellsize) # w/o wrap-around else: over_x,over_y = (x + 1) , (y + 1) bel_x, bel_y = (x - 1) , (y - 1) alive_neighbors = self.on_board[bel_x,bel_y]['alive'] + self.on_board[bel_x,y]['alive'] + self.on_board[bel_x,over_y]['alive'] + self.on_board[x,bel_y]['alive'] + self.on_board[x,over_y]['alive'] + self.on_board[over_x,bel_y]['alive'] + self.on_board[over_x,y]['alive'] + self.on_board[over_x,over_y]['alive'] if self.game_mode == 2: self.mark_changes_survival(x,y,alive_neighbors) else: self.mark_changes(x,y,alive_neighbors) def mark_changes(self,x,y,alive_neighbors,*largs): if self.on_board[x,y]['alive']: if (int(self.lonely) >= alive_neighbors or alive_neighbors >= int(self.crowded)): self.changes_dict[x,y] = 0 else: pass else: if alive_neighbors == int(self.birth): self.changes_dict[x,y] = 1 else: pass def mark_changes_survival(self,x,y,alive_neighbors,*largs): if self.on_board[x,y]['alive'] == 9: self.on_board[x,y]['survival'] -= 1 if self.on_board[x,y]['survival'] == 0: self.changes_dict[x,y] = 0 elif self.on_board[x,y]['alive'] == -5: if alive_neighbors >= 5: self.changes_dict[x,y] = 0 elif self.on_board[x,y]['alive'] == 1: if alive_neighbors < 0: self.changes_dict[x,y] = -1 elif alive_neighbors in [2,3] or alive_neighbors > 8: pass else: self.changes_dict[x,y] = 0 else: if alive_neighbors == int(self.birth) or alive_neighbors > 8: self.changes_dict[x,y] = 1 else: pass # loops through changes from ^^ and adds the rectangles def update_canvas_objects(self,*largs): last_active_cell_count = self.active_cell_count plus, minus = 0,0 for x_y in self.changes_dict: if self.changes_dict[x_y]: self.rectangles_dict[x_y]["color"].hsv = self.cell_color if not self.on_board[x_y]['was']: self.canvas.add(self.rectangles_dict[x_y]["color"]) self.canvas.add(self.rectangles_dict[x_y]["rect"]) self.on_board[x_y]['alive'] = 1 plus += 1 self.active_cell_count += 1 else: self.rectangles_dict[x_y]["color"].hsv = self.allcols["Grey"] self.on_board[x_y] = {'alive':0,'was':1} minus += 1 self.active_cell_count -= 1 self.all_activated += plus self.spawn_adder = self.all_activated / (1000) self.score += ((max(self.active_cell_count - last_active_cell_count,0) * 0.7) + (plus * 0.3)) * self.bonus_multiplier * 10 if self.game_mode: self.check_game_over() self.changes_dict.clear() def update_canvas_survival(self,*largs): last_active_cell_count = self.active_cell_count plus = 0 for x_y in self.changes_dict: if self.changes_dict[x_y] == 2: self.rectangles_dict[x_y]["color"].hsv = self.allcols["Stem"] self.on_board[x_y]['alive'] = 9 self.on_board[x_y]['survival'] = 15 plus += 1 self.active_cell_count += 1 elif self.changes_dict[x_y] == 1: self.rectangles_dict[x_y]["color"].hsv = self.cell_color self.on_board[x_y]['alive'] = 1 plus += 1 self.active_cell_count += 1 elif self.changes_dict[x_y] == -1: self.rectangles_dict[x_y]["color"].hsv = self.allcols["Red"] self.on_board[x_y]['alive'] = -5 self.on_board[x_y]['was'] = 1 self.active_cell_count -= 1 else: self.rectangles_dict[x_y]["color"].hsv = self.allcols["Grey"] self.on_board[x_y] = {'alive':0,'was':1} self.active_cell_count -= 1 if not self.on_board[x_y]['was']: self.canvas.add(self.rectangles_dict[x_y]["color"]) self.canvas.add(self.rectangles_dict[x_y]["rect"]) self.spawn_count += 1 self.ever_was_alive += 1 if not (self.generations % 5): x_y = (randint(0,self.dimensions[0]/cellsize-1), randint(0,self.dimensions[1]/cellsize-1)) while self.on_board[x_y]['alive'] == -5: x_y = (randint(0,self.dimensions[0]/cellsize-1), randint(0,self.dimensions[1]/cellsize-1)) self.rectangles_dict[x_y]["color"].hsv = self.allcols["Red"] if self.on_board[x_y]['alive'] == 1: self.on_board[x_y]['was'] = 1 self.active_cell_count -= 1 self.on_board[x_y]['alive'] = -5 if not self.on_board[x_y]['was']: self.canvas.add(self.rectangles_dict[x_y]["color"]) self.canvas.add(self.rectangles_dict[x_y]["rect"]) self.ever_was_alive += 1 self.all_activated += plus self.spawn_adder = self.all_activated / (1000) bonus = self.bonus_multiplier * (int(self.active_cell_count > last_active_cell_count)) self.score += 1 + bonus if self.active_cell_count <= last_active_cell_count: self.non_positive_gens -= 1 else: self.non_positive_gens = 10 if not self.stop_iteration: self.start_interval() if self.game_mode: self.check_game_over() self.changes_dict.clear() def check_game_over(self,*largs): if not bool(self.changes_dict) and not self.spawn_count: if self.generations > 0: self.game_over_message = "Out of moves!\nUse your spawns wisely." self.game_over = 3 if not self.active_cell_count: if self.spawn_count != 100 and self.generations > 0: self.game_over = 4 self.game_over_message = "All your cells are dead!\nTry placing cells in groups of 3 or more." if self.game_mode == 2: if self.non_positive_gens == 0: self.game_over = 2 self.game_over_message = "10 generations without population growth.\nYou must promote life!" # Our start/step scheduled function def update_cells(self,*largs): if self.prevent_update: self.prevent_update = False else: if self.cellcol == 'Random': self.set_canvas_color(on_request=True) self.get_cell_changes() if self.game_mode == 2: self.update_canvas_survival() if self.non_positive_gens < 5 and not self.stop_iteration: self.step(1.) else: self.update_canvas_objects() if self.generations <= 25 and self.game_mode == 1: if not self.stop_iteration: self.step(0.3) self.update_counters() def add_spawns(self, *largs): if self.game_mode == 2: if self.ever_was_alive >= self.cellcount: self.spawn_count += 10 else: self.spawn_count += 5 def update_counters(self,*largs): if self.game_mode == 2: self.generations += 1 if self.ever_was_alive >= self.cellcount: self.bonus_multiplier = self.generations / 500 else: self.bonus_multiplier = 0 else: if self.game_mode == 1: if self.generations == 1: self.game_over = 1 self.generations -= 1 self.bonus_multiplier = 1 + (self.active_cell_count * 30000 / pow(self.cellcount,2)) def start_interval(self, *largs): self.stop_iteration = False self.should_draw = False if len(self.events) > 0: self.events[-1].cancel() self.events.pop() self.events.append(Clock.schedule_interval(self.update_cells,self.speed)) def stop_interval(self, *largs): self.stop_iteration = True self.prevent_update = True self.should_draw = True if len(self.events) > 0: self.events[-1].cancel() self.events.pop() def step(self, interval, from_button=False,*largs): if from_button: self.stop_iteration = True self.prevent_update = False self.should_draw = True if len(self.events) > 0: self.events[-1].cancel() self.events.pop() Clock.schedule_once(self.update_cells, interval) def reset_interval(self, grid, modal,*largs): for x in largs: if type(x) == Popup: x.dismiss() self.should_draw = False if len(self.events) > 0: self.events[-1].cancel() self.events.pop() self.on_board.clear() self.changes_dict.clear() grid.canvas.clear() self.canvas.clear() self.setup_cells() self.game_over = 0 self.stop_iteration = False self.prevent_update = False if modal: modal.open() self.game_mode = 0 else: self.assign_blank(None) grid.draw_grid() self.starting_cells() def reset_counters(self): self.all_activated = 0 self.active_cell_count = 0 self.spawn_count = 100 self.score = 0 self.game_over_message = "You've done better!" self.spawn_adder = 0 if self.game_mode == 2: self.generations = 1 self.ever_was_alive = 0 self.non_positive_gens = 10 else: self.generations = 500 self.bonus_multiplier = 1 # Touch Handlers # Add rectangles and positive values to on_board when the animation is stopped. # Add values to changes_dict otherwise, rects added on next iteration def on_touch_down(self, touch): pos_x, pos_y = touch.pos[0] - self.x, touch.pos[1] - self.y # print (touch.pos), self.accept_touches pos_x = int(pos_x / cellsize) pos_y = int(pos_y / cellsize) in_bounds = (0 <= pos_x < (self.dimensions[0] / cellsize)) and (0 <= pos_y < (self.dimensions[1] / cellsize)) if self.accept_touches and in_bounds and self.spawn_count > 0: if not self.game_over: if self.game_mode == 2: self.handle_touch_survival(pos_x,pos_y) else: if self.on_board[pos_x,pos_y]['alive'] == 1 and not self.game_mode: if self.should_draw: self.rectangles_dict[pos_x,pos_y]['color'].hsv = self.allcols["Grey"] self.on_board[pos_x,pos_y] = {'alive':0,'was':1} else: self.changes_dict[pos_x,pos_y] = 0 else: self.handle_touch(pos_x,pos_y) def on_touch_move(self, touch): self.mouse_positions.append(touch.pos) # print(touch.pos), self.accept_touches for pos in self.mouse_positions: pos_x, pos_y = touch.pos[0] - self.x, touch.pos[1] - self.y pos_x = int(pos_x / cellsize) pos_y = int(pos_y / cellsize) in_bounds = (0 <= pos_x < (self.dimensions[0] / cellsize)) and (0 <= pos_y < (self.dimensions[1] / cellsize)) if self.accept_touches and in_bounds and self.spawn_count > 0: if not self.game_over: if self.game_mode == 2: self.handle_touch_survival(pos_x,pos_y) else: self.handle_touch(pos_x,pos_y) self.mouse_positions = [] def handle_touch(self, pos_x,pos_y,*largs): try: if not self.on_board[pos_x,pos_y]['alive']: if self.should_draw: self.on_board[pos_x,pos_y]['alive'] = 1 self.rectangles_dict[pos_x,pos_y]["color"].hsv = self.cell_color self.active_cell_count += 1 if not self.on_board[pos_x,pos_y]['was']: self.canvas.add(self.rectangles_dict[pos_x,pos_y]["color"]) self.canvas.add(self.rectangles_dict[pos_x,pos_y]["rect"]) else: self.changes_dict[(pos_x,pos_y)] = 1 if self.game_mode: self.spawn_count -= 1 except KeyError: pass def handle_touch_survival(self,pos_x,pos_y,*largs): try: if self.on_board[pos_x,pos_y]['alive'] == -5 and self.spawn_count >= 5: if self.should_draw: self.rectangles_dict[pos_x,pos_y]['color'].hsv = self.allcols["Grey"] self.on_board[pos_x,pos_y] = {'alive':0,'was':1} else: self.changes_dict[pos_x,pos_y] = 0 self.spawn_count -= 5 elif not self.on_board[pos_x,pos_y]['alive']: if self.should_draw: if randint(0,30) == 30: self.on_board[pos_x,pos_y]['alive'] = 9 self.on_board[pos_x,pos_y]['survival'] = 15 self.rectangles_dict[pos_x,pos_y]['color'].hsv = self.allcols['Stem'] else: self.on_board[pos_x,pos_y]['alive'] = 1 self.rectangles_dict[pos_x,pos_y]["color"].hsv = self.cell_color self.active_cell_count += 1 if 'was' not in self.on_board[pos_x,pos_y] or not self.on_board[pos_x,pos_y]['was']: self.canvas.add(self.rectangles_dict[pos_x,pos_y]["color"]) self.canvas.add(self.rectangles_dict[pos_x,pos_y]["rect"]) self.ever_was_alive += 1 else: if randint(0,30) == 30: self.changes_dict[(pos_x,pos_y)] = 2 else: self.changes_dict[(pos_x,pos_y)] = 1 self.spawn_count -= 1 except KeyError: pass def on_rotate(self): self.loadimg self.reset_interval def on_flip(self): self.loadimg self.reset_interval def info(self, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 # info0 = '''Game modes:\n Select Playground Mode or Game Mode.\n The playground has unlimited cells!\n Change the colors!\n Change the rules!\n''' info1 = '''Rules:\n If a cell has 0-1 neighbors, it dies.\n If a cell has 4 or more neighbors, it dies.\n If a cell has 2-3 neighbors, it survives.\n If a space is surrounded by 3 neighbors, a cell is born.\n\n''' info2 = '''Controls:\n Click or draw to add cells.\n Modify the default rules and more in settings.\n''' info3 = '''\nCreated by:\n <NAME>\n <NAME>''' text_info = Label(text=''.join([info1,info2,info3]),font_size=mysize, size_hint=(1,0.8)) content = BoxLayout(orientation='vertical',spacing='5sp') content.add_widget(text_info) buttons = BoxLayout(orientation='horizontal', spacing='10sp',size_hint=(1,0.2)) tutorial_btn = Button(text='Tutorial', size_hint=(.2,.7)) creation_btn = Button(text='Creation', size_hint=(.2,.7)) survival_btn = Button(text='Survival', size_hint=(.2,.7)) # tutorial_btn.bind(on_press=self.tutorial_main) buttons.add_widget(tutorial_btn) buttons.add_widget(creation_btn) buttons.add_widget(survival_btn) content.add_widget(buttons) popup = Popup(title="GoL: Game of Life", separator_height=0, title_size=titlesize, content=content, size_hint=(.8, .8),title_align='center') self.first_time = False tutorial_btn.bind(on_press=partial(self.tutorial_main, popup)) creation_btn.bind(on_press=partial(self.tutorial_creation, popup)) survival_btn.bind(on_press=partial(self.tutorial_survival, popup)) popup.bind(on_dismiss=partial(self.music_control, 'main', True, True)) self.music_control('options', True, True) popup.open() self.stop_interval() def tutorial_main(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass self.main_menu.open() playground = '''Playground mode allows for infinite play, and rule customization!\n\nCompete in game mode against yourself or others via twitter!\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Main Menu", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(self.tutorial_bottom, popup)) popup.open() def tutorial_bottom(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Here you have the main controls\n\nStart, Stop, Step: progress one generation, and Reset\n\nSettings will allow you to change the rules, but ONLY in Playground Mode.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout() content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Bottom Controls Bar", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, opacity=1, background_color=[0,0,0,.2]) # next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(popup.dismiss, popup)) next_btn.bind(on_release=partial(self.tutorial_grid, popup)) popup.open() def tutorial_grid(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Each cell has 8 neighbors that effect its state for the next generation.\n\nIf 0-1 neighbors are alive, that cell dies.\n\nIf 4 or more neighbors are alive, that cell dies.\n\nIf a cell has 2 or 3 live neighbors, it survives.\n\nA dead cell will animate, if it has exactly 3 live neighbors.''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout() content.add_widget(choose_mode) next_btn_1 = Button(text='Next', size_hint_x=.2, size_hint_y=.17307692, font_size=mysize) next_btn_2 = Button(text='Next', size_hint_x=.2, size_hint_y=.17307692, font_size=mysize) content.add_widget(next_btn_1) popup = Popup(title="Rules of Life", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .65),title_align='center', auto_dismiss=False, opacity=1, background_color=[0,0,0,.2]) # next_btn_2.bind(on_press=self.main_menu.dismiss) next_btn_1.bind(on_release=partial(self.swap_tutorial_grid, next_btn_1,next_btn_2,choose_mode,popup)) next_btn_2.bind(on_release=partial(popup.dismiss, popup)) next_btn_2.bind(on_release=partial(self.tutorial_top, popup)) popup.open() def swap_tutorial_grid(self, btn1, btn2, label, popup, *largs): popup.content.remove_widget(btn1) popup.content.add_widget(btn2) popup.title="Game Play" new_text = '''You may add live cells to the board by using Spawns.\n\nTap or drag your finger to add cells.\n\nAdd cells before or during animation or while paused.\n\nControl the animation with Start, Stop, and Step buttons.\n\nBe aware, groups of less than 3 cells will die.''' label.text = new_text def tutorial_top(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Use this area to track your stats in Game Mode.\n\nYour current Score, High Score, and game status will be displayed.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout() content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Top Score Bar", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, opacity=1, background_color=[0,0,0,.2]) # next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(popup.dismiss, popup)) next_btn.bind(on_release=partial(self.tutorial_score, popup)) popup.open() def tutorial_score(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''There are two game play modes, Creation and Survival.\n\nTake a screenshot when you're done and upload to twitter using #GOLapp\n''' # Creation: find the best patterns to create life and gain points.\n\nBonus points awarded for having more alive cells.\n\nSurvival: Stay alive amidst a viral outbreak.\n\nBonus point awarded once all black spaces are gone.\n\n choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout() content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Game Mode", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, opacity=1, background_color=[0,0,0,.2]) # next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(popup.dismiss, popup)) next_btn.bind(on_release=partial(self.tutorial_end, popup)) popup.open() def tutorial_end(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''If you like it, go give us a 5 star rating!\n\nGo back through the tutorial by clicking info.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout() content.add_widget(choose_mode) next_btn = Button(text='Play', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Have Fun!", separator_height=0, title_size=titlesize, content=content, size_hint=(.7, .4),title_align='center', auto_dismiss=False, opacity=1, background_color=[0,0,0,.2]) # next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(popup.dismiss, popup)) if self.first_time: next_btn.bind(on_press=partial(self.main_menu.open, popup)) popup.open() def tutorial_creation(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Welcome to creation mode!\n\nIn this game mode you play with classic Game of Life rules with a score!\n\nFind the best patterns to create life and gain points.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Creation Mode", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_release=partial(self.tutorial_creation1, popup)) popup.open() def tutorial_creation1(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''You have 500 generations to score!\n\nYou start with 100 spawns and earn more spawns through playing.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Playing", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_release=partial(self.tutorial_creation2, popup)) popup.open() def tutorial_creation2(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Your score is calculated by:\n\nThe change in population size and number of new cells.\n\nBonus points are awarded for having more alive cells.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Play', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Scoring", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_release=partial(popup.dismiss, popup)) popup.open() def tutorial_survival(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Welcome to survival mode!\n\nIn this mode there are some unique cells!\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Survival Mode", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(self.tutorial_survival1, popup)) popup.open() def tutorial_survival1(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Red cells are viral cells.\n\nThese pop up randomly as you play the game.\n\nThey will "infect" your cells.\n\nYou can remove them by tapping or drawing over them.\n\nThis will cost you precious spawns!\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Red Cell Types", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_release=partial(self.tutorial_survival2, popup)) popup.open() def tutorial_survival2(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Pink cells are stem cells.\n\nDiscover these cells as you play.\n\nThey will provide protection to your cells.\n\nThey stay alive for 15 generations.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Next', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Pink Cell Types", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(self.tutorial_survival3, popup)) popup.open() def tutorial_survival3(self, popup, *largs): if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*3.4 mysize = Window.size[1]/100.*3 try: popup.dismiss() except: pass playground = '''Bonus points are awarded once all black spaces are gone.\n\nYour score is the generation count.\n\n-''' + u"\u2206Pop" + ''' is the generations allowed without popuplation growth.\n\nThe game ends if it hits 0.\n''' choose_mode = Label(text=playground, font_size=mysize) content = BoxLayout(pos_hint={'center':1,'center':1}) content.add_widget(choose_mode) next_btn = Button(text='Play', size_hint_x=.2, size_hint_y=.25, font_size=mysize) content.add_widget(next_btn) popup = Popup(title="Scoring", separator_height=0, title_size=titlesize, content=content, size_hint=(.95, .45),title_align='center', auto_dismiss=False, background_color=[0,0,0,.2]) next_btn.bind(on_press=self.main_menu.dismiss) next_btn.bind(on_release=partial(popup.dismiss, popup)) popup.open() def welcome_img(self, first_timer, *largs): content = Image(source='GOL_Welcome.png') popup = Popup(title='', content=content, auto_dismiss=False, separator_height=0,title_size=0, separator_color=[0.,0.,0.,0.], size=(Window.height,Window.width), # border=[20,20,20,20], background='black_thing.png', background_color=[0,0,0,1]) content.bind(on_touch_down=popup.dismiss) popup.bind(on_dismiss=partial(self.tutorial_main, first_timer)) popup.open() def loadimg(self, first_timer, *largs): content = Image(source='IMO_GoL_noText.png') popup = Popup(title='', content=content, auto_dismiss=False, separator_height=0,title_size=0, separator_color=[0.,0.,0.,0.], size=(Window.height,Window.width), # border=[20,20,20,20], background='black_thing.png', background_color=[0,0,0,1]) content.bind(on_touch_down=popup.dismiss) popup.bind(on_dismiss=partial(self.open_main_menu, first_timer)) popup.open() def open_main_menu(self, first_timer ,*largs): if first_timer.exists('tutorial'): self.first_time = False Clock.schedule_once(self.main_menu.open,0) else: first_timer.put('tutorial', done=True) self.first_time = True Clock.schedule_once(self.welcome_img,0) def survival_mode_check(self, survival_first ,*largs): if survival_first.exists('survival_tutorial'): pass else: survival_first.put('survival_tutorial', done=True) Clock.schedule_once(self.tutorial_survival,0) def creation_mode_check(self, creation_first ,*largs): if creation_first.exists('creation_tutorial'): pass else: creation_first.put('creation_tutorial', done=True) Clock.schedule_once(self.tutorial_creation,0) def stop_music(self, *largs): try: sound.stop() except: pass def music_control(self, track, switch, on, *largs): select = {'options':'options_track.wav','main':'main_track.wav','score':'score_track.wav'} if bool(int(self.music)): if on == True and switch == False: sound = SoundLoader.load(select[track]) global sound sound.loop = True sound.volume = 0.5 sound.play() elif on == False and switch == False: sound.stop() if switch == True: try: sound.stop() sound.unload() except: pass sound = None sound = SoundLoader.load(select[track]) global sound sound.loop = True sound.volume = 0.5 sound.play() class SettingScrollOptions(SettingOptions): def _create_popup(self, instance): content = GridLayout(cols=1, spacing='5dp') scrollview = ScrollView( do_scroll_x=False) scrollcontent = GridLayout(cols=1, spacing='5dp', size_hint=(1, None)) scrollcontent.bind(minimum_height=scrollcontent.setter('height')) self.popup = popup = Popup(content=content, title=self.title, title_align='center', size_hint=(0.5, 0.6), auto_dismiss=False) popup.open() content.add_widget(Widget(size_hint_y=None, height=dp(2))) uid = str(self.uid) for option in self.options: state = 'down' if option == self.value else 'normal' btn = ToggleButton(text=option, state=state, group=uid, height=dp(55), size_hint=(1, None)) btn.bind(on_release=self._set_option) scrollcontent.add_widget(btn) scrollview.add_widget(scrollcontent) content.add_widget(scrollview) content.add_widget(Widget(size_hint=(1,0.02))) btn = Button(text='Cancel', size=(popup.width, dp(50)),size_hint=(0.9, None)) btn.bind(on_release=popup.dismiss) content.add_widget(btn) class GameApp(App): game_cells = None highscore = 0 blinky = None def on_pause(self, *largs): return True def on_resume(self, *largs): self.game_cells.reset_interval pass # seconds = 0 def intWithCommas(self, x, *largs): if x < 0: return '-' + intWithCommas(-x) result = '' while x >= 1000: x, r = divmod(x, 1000) result = ",%03d%s" % (r, result) return "%d%s" % (x, result) # def update_score(self,cells, cs, place, *largs): def update_game(self, cells, cs, place, gen, game_end,grid, buttons,*largs): if cells.game_mode: if cells.game_mode == 1: gen.text = str(cells.generations) if cells.generations == 25: grid.start_flash() elif cells.game_mode == 2: gen.text = str(cells.non_positive_gens) place.text = str(cells.spawn_count) else: gen.text = '∞' place.text = '∞' cs.text = self.intWithCommas(self.game_cells.score) if cells.game_over: for button in buttons: button.disabled = True if grid.flash_event: grid.stop_flash(False) else: grid.grid_color.rgb = (1,0,0) cells.stop_interval() cells.music_control('score', True, True) Clock.schedule_once(game_end.open,1.5) def reset_labels(self, csval, gen, genval, placeval, hsval, cells,*largs): csval.text = "--" self.highscore = 0 if cells.game_mode: if cells.game_mode == 1: gen.text = "Gens:" genval.text = "500" if self.highscorejson.exists('creation'): self.highscore = self.highscorejson.get('creation')['best'] elif cells.game_mode == 2: gen.text = "-"+ u'\u2206'+" Pop:" genval.text = "10" if self.highscorejson.exists('survival'): self.highscore = self.highscorejson.get('survival')['best'] placeval.text = "100" else: if self.highscorejson.exists('creation'): self.highscore = self.highscorejson.get('creation')['best'] genval.text = '∞' placeval.text = '∞' hsval.text = str(self.intWithCommas(self.highscore)) def update_score_labels(self, myobject, final_score_label, high_score_label,cells, buttons,*largs): for button in buttons: button.disabled = False self.blinky = Clock.schedule_interval(lambda a:self.colorit(myobject),0.3) # global blinky if self.game_cells.score > self.highscore: self.highscore = cells.score if self.game_cells.game_mode == 1: self.highscorejson.put('creation', best=self.game_cells.score) elif self.game_cells.game_mode == 2: self.highscorejson.put('survival', best=self.game_cells.score) high_score_display = str(self.intWithCommas(self.highscore)) + " New Record!!" else: if cells.game_over == 1: high_score_display = self.add_advice() else: high_score_display = cells.game_over_message high_score_label.text = high_score_display final_score_label.text = "Final Score: " + str(self.intWithCommas(self.game_cells.score)) def add_advice(self, *largs): advices = ["Beware, the borders will stop your cells\nin their tracks.", "Find the best patterns by experimenting\nin Playground Mode.", "Cells only score points if they generate life.\nGet rid of stagnant groups.","Don't wait too long to use your spawns.","With Color set to Random,\neach color represents a generation.","Fill more of the screen for a bigger bonus.","You've done better!","Try pausing the animation before\nusing your spawns."] return advices[randint(0,len(advices) - 1)] def clear_text(self, high_score_label, *largs): high_score_label.text = "" def trigger_game_mode(self, main_menu, cells, grid, csval, gen, genval, placeval, hsval,btn_sett,mode,r_version_button,*largs): r_version_button.text = "Select Version" r_version_button.background_down = 'atlas://data/images/defaulttheme/button_pressed' r_version_button.background_normal = 'atlas://data/images/defaulttheme/button' r_version_button.disabled = False btn_sett.background_down = 'btn_solid.png' btn_sett.text = "---" btn_sett.disabled = True self.game_cells.lonely = 1 self.game_cells.crowded = 4 self.game_cells.birth = 3 self.game_cells.wrap = 0 if mode == 1: self.game_cells.speed = 0.05 self.game_cells.cellcol = self.config._sections['initiate']['color'] elif mode == 2: self.game_cells.speed = 0.1 self.game_cells.cellcol = 'Green' main_menu.dismiss() cells.game_over = 0 cells.game_mode = mode cells.reset_counters() self.reset_labels(csval, gen, genval, placeval, hsval, cells) cells.reset_interval(grid, None) def trigger_playground_mode(self, popup, start_patterns, grid, cells, placeval, gen, genval,btn_sett, r_version_button,*largs): r_version_button.text = '' r_version_button.background_down = 'black_thing.png' r_version_button.background_normal = 'black_thing.png' r_version_button.disabled = True btn_sett.background_down = 'bttn_dn.png' btn_sett.text = "Settings" btn_sett.disabled = False cells.reset_counters() for item in self.config._sections: for x in self.config._sections[item]: if x == 'wrap': self.game_cells.wrap = int(self.config._sections[item][x]) if x == 'speed': self.game_cells.speed = self.game_cells.speeds[self.config._sections[item][x]] if x == 'born': self.game_cells.birth = self.config._sections[item][x] if x == 'lonely': self.game_cells.lonely = self.config._sections[item][x] if x == 'crowded': self.game_cells.crowded = self.config._sections[item][x] popup.dismiss() gen.text = 'Gens:' placeval.text = '∞' genval.text = '∞' cells.reset_interval(grid, start_patterns) def restart_btn_action(self, grid, start_patterns, cells, restart_game, csval, gen,genval, placeval,hsval,*largs): # if grid.flash_event: # grid.stop_flash(True) # else: # grid.grid_color.rgb = (0.5,0.5,0.5) cells.game_over = 0 restart_game.dismiss() cells.reset_counters() self.reset_labels(csval, gen,genval, placeval, hsval, cells) if cells.game_mode: cells.reset_interval(grid,None) else: cells.reset_interval(grid, start_patterns) def check_close_to_end(self, grid, *largs): if self.game_cells.non_positive_gens == 4: grid.start_flash() elif self.game_cells.non_positive_gens == 10: grid.stop_flash(True) def colorit(self, myobject, *largs): myobject.color = [randint(0,1),randint(0,1),randint(0,1),1] # print myobject.color def unscheduleit(self, myobject, *largs): Clock.unschedule(self.blinky) def open_popup(self, to_open, to_close,*largs): to_close.dismiss() to_open.open() def settings(self, *largs): if self.game_cells.game_mode: pass else: self.open_settings() def build(self): global cellsize self.settings_cls = SettingsWithSpinner # dump(self.settings_cls) self.config.items('initiate') self.use_kivy_settings = False data_dir = getattr(self, 'user_data_dir') self.highscorejson = JsonStore(join(data_dir, 'highscore.json')) self.firsttimer = JsonStore(join(data_dir, 'tutorial.json')) self.survival_first = JsonStore(join(data_dir, 'survival.json')) self.creation_first = JsonStore(join(data_dir, 'creation.json')) if self.highscorejson.exists('creation'): if 'creation' in self.highscorejson.get('creation'): self.highscore = self.highscorejson.get('creation')['best'] else: self.highscore = 0 # Delete this once finalized # if Window.width < 667 or Window.height < 375: # Window.size = (1366,1024) if Window.width < Window.height: titlesize = 18 mysize = 18 else: titlesize = Window.size[1]/100.*4 mysize = Window.size[1]/100.*3.4 # make layout and additional widgets board = FloatLayout(size=(Window.width, Window.height)) grid = Grid(size=(Window.width, Window.height - 100), pos=(0,50)) self.game_cells = cells = Cells(size=(Window.width - 20, Window.height - 120), pos=(11,61)) board.add_widget(grid) board.add_widget(cells) cells.create_rectangles() # cells.draw_rectangles() # cells.add_instruction_groups() Clock.schedule_once(partial(cells.loadimg,self.firsttimer), 0) usrgridnum = cells.cellcount / 1000.0 if bool(int(self.game_cells.music)): cells.music_control('options', False, True) else: pass # Main Menu Components main_menu = cells.main_menu = Popup(title="Main Menu", background='black_thing.png', title_font='joystix', title_size=60, separator_height=0, size_hint=(1,1), pos_hint={'center':0.5,'center':0.5}, title_align="center",auto_dismiss=False) main_menu_layout = BoxLayout(orientation='vertical', spacing=dp(100), pos_hint={'center_x':.5,'center_y':.5},size_hint=(0.8,0.7)) main_menu_buttons_box = BoxLayout(size_hint=(0.6,1), pos_hint={'center_x':.5},orientation='vertical',spacing=dp(30)) playground_btn = Button(text="Playground Mode", font_name='joystix',size_hint=(1,0.45),font_size='20sp') game_btn = Button(text="Game Mode", font_name='joystix', size_hint=(1,0.45),font_size='20sp') main_menu_buttons_box.add_widget(playground_btn) main_menu_buttons_box.add_widget(game_btn) main_menu_layout.add_widget(main_menu_buttons_box) main_menu.add_widget(main_menu_layout) # Set start patterns and internal scrolling layout start_patterns = Popup(title="Select Pattern", title_size=32, background='black_thing.png', title_font='joystix', separator_height=0 ,size_hint=(0.5,0.8),title_align='center' ,pos_hint={'center':0.5,'center':0.50}) start_layout = GridLayout(cols=1, spacing='5dp') scroll_layout = GridLayout(cols=1, spacing=10, size_hint_y=None) scroll_layout.bind(minimum_height=scroll_layout.setter('height')) # Set up buttons to go inside the scrolling portion patt_blank = Button(text='BLANK', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'blank')) patt_random = Button(text='RANDOM', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'random')) patt_gun = Button(text='GUN', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'gun')) patt_ten = Button(text='TEN', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'ten')) patt_binary = Button(text='BINARY', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'binary')) patt_face = Button(text='FACE', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'face')) patt_gol = Button(text='GOL', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'gol')) patt_pulsar = Button(text='PULSAR', font_name='joystix' , size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'pulsar')) patt_gliders = Button(text='GLIDERS', font_name='joystix' ,size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'gliders')) patt_imo_6 = Button(text='IMO 6', font_name='joystix' , size_hint_y=None, height=50,on_press=partial(cells.place_pattern, start_patterns, 'imo_6')) patt_omega = Button(text='RESISTANCE', font_name='joystix' , size_hint_y=None, height=50,on_press=partial(cells.place_pattern,start_patterns, 'omega')) patt_maze = Button(text='MAZE', font_name='joystix' , size_hint_y=None, height=50,on_press=partial(cells.place_pattern,start_patterns, 'maze')) # attach buttons to scrolling layout patterns = [patt_blank, patt_imo_6, patt_omega, patt_gol,patt_random,patt_gun,patt_ten,patt_pulsar,patt_gliders,patt_face,patt_binary, patt_maze] for pattern in patterns: scroll_layout.add_widget(pattern) pattern_scroll = ScrollView(size_hint=(1, 1)) pattern_scroll.add_widget(scroll_layout) start_layout.add_widget(Widget(size_hint_y=None, height=dp(2))) start_layout.add_widget(pattern_scroll) start_layout.add_widget(Widget(size_hint_y=None, height=dp(2))) sp_main_menu_button = Button(text="Main Menu", font_name='joystix', on_press=partial(self.open_popup, main_menu, start_patterns), size_hint=(1,None), height=dp(45)) sp_main_menu_button.bind(on_release=partial(cells.music_control, 'options', True, True)) start_layout.add_widget(sp_main_menu_button) start_patterns.add_widget(start_layout) # setup restart game mode popup restart_game = Popup(title="Reset",title_font='joystix',title_size=56,background='black_thing.png',separator_height=0 ,size_hint=(1,1),title_align='center' ,pos_hint={'center':0.5,'center':0}) restart_game_layout = BoxLayout(orientation='vertical', spacing=dp(30), pos_hint={'center_x':.5,'center_y':.375},size_hint=(1,0.75)) restart_cancel_box = BoxLayout(size_hint=(0.9,0.4), pos_hint={'center_x':.5}, orientation='horizontal',spacing=dp(10)) restart_btn = Button(text="Restart", font_name='joystix', font_size='20sp',size_hint=(0.47,1)) cancel_restart_button = Button(text="Cancel", font_name='joystix', on_press=restart_game.dismiss, font_size='20sp',size_hint=(0.47,1)) version_main_box = BoxLayout(size_hint=(0.6,0.35), pos_hint={'center_x':.5},orientation='vertical',spacing=dp(5)) r_version_button = Button(text="", font_name='joystix', size_hint=(1,0.5), font_size='15sp') r_main_menu_button = Button(text="Main Menu", font_name='joystix', on_press=partial(self.open_popup, main_menu, restart_game), size_hint=(1,0.5), font_size='15sp') r_main_menu_button.bind(on_release=partial(cells.music_control, 'options', True, True)) restart_cancel_box.add_widget(restart_btn) restart_cancel_box.add_widget(cancel_restart_button) version_main_box.add_widget(r_version_button) version_main_box.add_widget(r_main_menu_button) restart_game_layout.add_widget(restart_cancel_box) restart_game_layout.add_widget(version_main_box) restart_game.content = restart_game_layout # game buttons btn_start = Button(text='START', font_name='joystix' ,on_press=cells.start_interval, background_normal='black_thing.png', border=[0,0,0,0], background_disabled_down='black_thing.png', background_disabled_normal='black_thing.png') btn_stop = Button(text='Stop', font_name='joystix' ,on_press=cells.stop_interval, background_normal='black_thing.png', border=[0,0,0,0], background_disabled_down='black_thing.png', background_disabled_normal='black_thing.png') btn_step = Button(text='Step', font_name='joystix' ,on_press=partial(cells.step,0.01,True), background_normal='black_thing.png', border=[0,0,0,0], background_disabled_down='black_thing.png', background_disabled_normal='black_thing.png') btn_reset = Button(text='Reset', font_name='joystix' , on_press=restart_game.open, background_normal='black_thing.png', border=[0,0,0,0], background_disabled_down='black_thing.png', background_disabled_normal='black_thing.png') btn_reset.bind(on_press=cells.stop_interval) btn_sett = Button(text='Settings', font_name='joystix' ,on_press=self.settings, background_normal='black_thing.png', border=[0,0,0,0], background_disabled_down='black_thing.png', background_disabled_normal='black_thing.png') btn_info = Button(text='Info', font_name='joystix' ,on_press=cells.info, background_normal='black_thing.png', border=[0,0,0,0], background_disabled_down='black_thing.png', background_disabled_normal='black_thing.png') btn_sett.bind(on_press=cells.stop_interval) buttons = BoxLayout(size_hint=(1, None), height=50, pos_hint={'x':0, 'y':0}) board.bind(size=cells.create_rectangles) board.bind(size=partial(cells.reset_interval,grid,main_menu)) controls =[btn_info,btn_reset,btn_start,btn_stop,btn_step,btn_sett] for btn in controls: buttons.add_widget(btn) controls.pop() start_patterns.bind(on_dismiss=grid.draw_grid) start_patterns.bind(on_dismiss=cells.starting_cells) # Score Label Widgets top_buttons = BoxLayout(size_hint=(1, None), height=50, pos_hint={'x':0, 'top':1}) hs = Button(text='High Score:', font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png', border=[0,0,0,0]) hsval = Button(text=self.intWithCommas(int(self.highscore)), font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) cs = Button(text='Score:', font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) csval = Button(text='--', font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) place = Button(text='Spawns:', font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) placeval = Button(text='100', font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) gen = Button(text='Gens:', font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) genval = Button(text='500', font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) usrgrid = Button(text='Grid: '+ str(round(usrgridnum,1)), font_name='Roboto', font_size=24, color=[1,.25,0,1], background_normal='black_thing.png', background_down='black_thing.png',border=[0,0,0,0]) btns_top = [place, placeval, gen, genval, usrgrid, cs, csval, hs, hsval] for btn in btns_top: top_buttons.add_widget(btn) game_end = Popup(title="Game Over", title_size = 42, title_color=[0,0,0], title_font='joystix', background='black_thing.png', separator_height=0, size_hint=(1,1),title_align='center' ,pos_hint={'center':0.5,'center':0.5},auto_dismiss=False) end_layout = GridLayout(cols=1, spacing=10, size_hint=(1,1)) high_score_label = Label(text="", font_name='Roboto', bold=True, font_size=36, color=[1,.25,0,1],halign="center") final_score_label = Label(text=(""), font_name='Roboto', bold=True, font_size=36,halign="center") play_again = Button(text="Play Again", font_size=42,font_name='joystix', size_hint_y=.5, on_press=partial(self.restart_btn_action, grid,start_patterns, cells,game_end, csval, gen,genval, placeval,hsval)) end_layout.add_widget(high_score_label) end_layout.add_widget(final_score_label) end_layout.add_widget(play_again) game_end.add_widget(end_layout) # setup main menu buttons playground_btn.bind(on_press=partial(self.trigger_playground_mode, main_menu, start_patterns, grid, cells,placeval,gen,genval,btn_sett,r_version_button)) choose_game = Popup(title="Select Version", background='black_thing.png', title_font='joystix', title_size=50, separator_height=0, size_hint=(1,1), pos_hint={'center':0.5,'center':0.5}, title_align="center", auto_dismiss=False) choose_game_layout = BoxLayout(orientation='vertical', spacing=dp(30), pos_hint={'center_x':.5,'center_y':.4}, size_hint=(1,0.8)) survival_creation_box = BoxLayout(size_hint=(0.9,0.4), pos_hint={'center_x':.5}, orientation='horizontal',spacing=dp(10)) choose_game_main_box = BoxLayout(size_hint=(0.6,0.35), pos_hint={'center_x':.5},orientation='vertical',spacing=dp(5)) creation_mode_btn = Button(text="Creation", font_size='20sp', font_name='joystix', size_hint=(0.45,0.9)) survival_mode_btn = Button(text="Survival", font_size='20sp', font_name='joystix', size_hint=(0.45,0.9)) survival_creation_box.add_widget(creation_mode_btn) survival_creation_box.add_widget(survival_mode_btn) choose_game_main_box.add_widget(Button(text='', background_normal='black_thing.png', background_down='black_thing.png',size_hint=(1,0.5))) choose_game_main_box.add_widget(Button(text="Main Menu", font_name='joystix', on_press=partial(self.open_popup,main_menu,choose_game), size_hint=(1,0.5), font_size='15sp')) choose_game_layout.add_widget(survival_creation_box) choose_game_layout.add_widget(choose_game_main_box) choose_game.add_widget(choose_game_layout) creation_mode_btn.bind(on_press=partial(self.trigger_game_mode, choose_game, cells, grid, csval, gen,genval, placeval, hsval,btn_sett,1,r_version_button)) survival_mode_btn.bind(on_press=partial(self.trigger_game_mode,choose_game, cells, grid, csval, gen,genval, placeval, hsval,btn_sett,2,r_version_button)) survival_mode_btn.bind(on_release=partial(self.game_cells.survival_mode_check, self.survival_first)) creation_mode_btn.bind(on_release=partial(self.game_cells.creation_mode_check, self.creation_first)) game_btn.bind(on_press=partial(self.open_popup,choose_game,main_menu)) # cells.bind(a_d_ratio=partial(self.update_score, cells, cs,place)) cells.bind(generations=partial(self.update_game, cells, csval,placeval,genval, game_end, grid, controls)) cells.bind(spawn_count=partial(self.update_game, cells, csval, placeval, genval, game_end, grid, controls)) cells.bind(all_activated=partial(self.update_game, cells, csval, placeval, genval, game_end, grid, controls)) cells.bind(spawn_adder=cells.add_spawns) cells.bind(non_positive_gens=partial(self.check_close_to_end, grid)) start_patterns.bind(on_open=partial(self.reset_labels, csval, gen, genval, placeval, hsval,cells)) restart_btn.bind(on_press=partial(self.restart_btn_action, grid,start_patterns, cells,restart_game, csval, gen,genval, placeval,hsval)) r_version_button.bind(on_press=partial(self.open_popup, choose_game, restart_game)) game_end.bind(on_open=partial(self.update_score_labels, play_again, final_score_label,high_score_label, cells, controls)) game_end.bind(on_dismiss=partial(self.unscheduleit, play_again)) game_end.bind(on_dismiss=partial(self.clear_text, high_score_label)) board.add_widget(top_buttons) board.add_widget(buttons) return board def build_config(self, config): config.setdefaults('initiate', { 'Wrap': 0, 'Speed': 'Fast', 'Lonely': 1, 'Crowded': 4, 'Born': 3, 'Color': 'Random', 'Music': 1, }) config_file = self.get_application_config() config.read(config_file) for item in config._sections: for x in config._sections[item]: if x == 'wrap': Cells.wrap = int(config._sections[item][x]) if x == 'speed': Cells.speed = Cells.speeds[config._sections[item][x]] if x == 'color': Cells.cellcol = config._sections[item][x] if x == 'born': Cells.birth = config._sections[item][x] if x == 'lonely': Cells.lonely = config._sections[item][x] if x == 'crowded': Cells.crowded = config._sections[item][x] if x == 'music': Cells.music = int(config._sections[item][x]) def build_settings(self, settings): settings.register_type('scrolloptions', SettingScrollOptions) settings.add_json_panel('Game Settings', self.config, data=settings_json) def on_config_change(self, config, section, key, value): if key == 'Wrap': self.game_cells.wrap = int(value) if key == 'Speed': self.game_cells.speed = self.game_cells.speeds[value] if key == 'Color': self.game_cells.cellcol = value self.game_cells.set_canvas_color() if key == 'Born': self.game_cells.birth = int(value) if key == 'Lonely': self.game_cells.lonely = int(value) if key == 'Crowded': self.game_cells.crowded = int(value) if key == 'Music': self.game_cells.music = int(value) if self.game_cells.music == 1: self.game_cells.music_control('main', True, True) else: self.game_cells.stop_music() else: pass # print config, section, key, value if __name__ == '__main__': GameApp().run() <file_sep>/examples/color_rect_groups_example.py from kivy.app import App from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.core.window import Window from kivy.graphics.instructions import InstructionGroup from kivy.graphics import * from kivy.uix.widget import Widget from functools import partial from random import random, randint from kivy.clock import Clock from time import time def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) pass class Groupings(Widget): rectangles_dict = {} iterations = 0 def create_rectangles(self, *largs): self.rectangles_dict.clear() self.dimensions = (Window.width - 20, Window.height - 120) self.pos = (11,61) for x in range(0,self.dimensions[0]/10): for y in range(0,self.dimensions[1]/10): color = Color(0,0,1,mode="hsv") rect = Rectangle(pos=(self.x + x * 10, self.y + y *10), size=(9,9)) self.rectangles_dict[x,y] = {"rect": rect, "color": color} def draw_rectangles(self,*largs): for x_y in self.rectangles_dict: self.canvas.add(self.rectangles_dict[x_y]["color"]) self.canvas.add(self.rectangles_dict[x_y]["rect"]) def change_color(self, x_y, hue,*largs): self.rectangles_dict[x_y]['color'].hsv = hue def randomly_change_rects(self, *largs): then = time() for x_y in self.rectangles_dict: if randint(0,1): self.change_color(x_y,(random(),1,1)) self.iterations += 1 print time() - then def dump_one(self, *largs): dump(self.rectangles_dict[1,1]["color"]) class InstructionApp(App): events = [] def schedule(self, fxn, time, *largs): if len(self.events) > 0: self.events[-1].cancel() self.events.pop() self.events.append(Clock.schedule_interval(fxn,float(time))) def unschedule(self,*largs): if len(self.events) > 0: self.events[-1].cancel() self.events.pop() def build(self): if Window.width < 1334 and Window.height < 750: Window.size = (1334,750) board = FloatLayout(size=(Window.width, Window.height)) groupings = Groupings(size=(Window.width - 20, Window.height - 120), pos=(11,61)) board.add_widget(groupings) groupings.create_rectangles() groupings.draw_rectangles() groupings.dump_one() button = Button(text="change 'em", on_press=partial(self.schedule, groupings.randomly_change_rects, 0.001), pos=(100,0),size_hint=(None,None), size=(150,45)) button2 = Button(text="stop 'em'", on_press=self.unschedule, pos=(300,0),size_hint=(None,None), size=(150,45)) board.add_widget(button) board.add_widget(button2) return board if __name__ == '__main__': InstructionApp().run() <file_sep>/README.md Built using Python 2.7.11 Requires: pygame 1.9.2b6; <file_sep>/conway_shapes.py from enum import Enum import random class Conway_Shape(Enum): Dot = 1 Plus = 2 Tub = 3 Boat = 4 Ship = 5 Pond = 6 Glider = 7 LWSS = 8 MWSS = 9 HWSS = 10 def max(self): count = 0 for item in Conway_Shape: count = count + 1 return count def change_stats(gridDict, coords): for tup in coords: try: gridDict[tup].stat = 1 except KeyError: pass def create_glider(gridDict, x, y): coords = [] # assign one of four glider orientation coordinates direction = random.randint(0,3) if direction == 0: coords = [(x,y),(x+10,y-10),(x+20,y+10),(x+20,y),(x+20,y-10)] elif direction == 1: coords = [(x,y),(x-10,y-10),(x-10,y-20),(x,y-20),(x+10,y-20)] elif direction == 2: coords = [(x,y),(x-10,y+10),(x-20,y+10),(x-20,y),(x-20,y-10)] else: coords = [(x,y),(x+10,y+10),(x+10,y+20),(x,y+20),(x-10,y+20)] # try to update each coordinate if it's in the gridDict change_stats(gridDict, coords) def create_lwss(gridDict, x, y): coords = [(x,y-20),(x-10,y-10),(x+30,y-20),(x-10,y),(x+30,y),(x-10,y+10),(x,y+10),(x+10,y+10),(x+20,y+10)] change_stats(gridDict, coords) def create_mwss(gridDict, x, y): coords = [(x+10,y-20),(x-10,y-10),(x+30,y-10),(x-20,y),(x-20,y+10),(x+30,y+10),(x-20,y+20),(x-10,y+20),(x,y+20),(x+10,y+20),(x+20,y+20)] change_stats(gridDict, coords) def create_hwss(gridDict, x, y): coords = [(x,y-20),(x+10,y-20),(x-20,y-10),(x+30,y-10),(x-30,y),(x-30,y+10),(x+30,y+10),(x-30,y+20),(x-20,y+20),(x-10,y+20),(x,y+20),(x+10,y+20),(x+20,y+20)] change_stats(gridDict, coords) def create_boat(gridDict, x, y): coords = [(x-10,y-10),(x,y-10),(x-10,y),(x+10,y),(x,y+10)] change_stats(gridDict, coords) def create_ship(gridDict, x, y): coords = [(x-10,y-10),(x,y-10),(x-10,y),(x+10,y),(x,y+10),(x+10,y+10)] change_stats(gridDict, coords) def create_pond(gridDict, x, y): coords = [(x-10,y-10),(x,y-10),(x-20,y),(x+10,y),(x-20,y+10),(x+10,y+10),(x-10,y+20),(x,y+20)] change_stats(gridDict, coords) def create_plus(gridDict, x, y): coords = [(x,y-10),(x-10,y),(x,y),(x+10,y),(x,y+10)] change_stats(gridDict, coords) def create_tub(gridDict, x, y): coords = [(x,y-10),(x-10,y),(x+10,y),(x,y+10)] change_stats(gridDict, coords) def click_handler(gridDict, x, y, click_option): choice = click_option if choice == 1: gridDict[x,y].stat = 1; elif choice == 2: create_plus(gridDict, x, y) elif choice == 3: create_tub(gridDict, x, y) elif choice == 4: create_boat(gridDict, x, y) elif choice == 5: create_ship(gridDict, x, y) elif choice == 6: create_pond(gridDict, x, y) elif choice == 7: create_glider(gridDict, x, y) elif choice == 8: create_lwss(gridDict, x, y) elif choice == 9: create_mwss(gridDict, x, y) elif choice == 10: create_hwss(gridDict, x, y) else: pass <file_sep>/examples/gridCell.py from kivy.app import App from kivy.core.window import Window from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.widget import Widget from kivy.graphics import * from functionality import controls from kivy.core.audio import SoundLoader from kivy.clock import Clock from kivy.uix.relativelayout import RelativeLayout import random import time def round_down(num): return num - (num%10) def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) pass class board(Widget): # sound = SoundLoader.load('img/emotion.wav') # if sound: # sound.loop = True # sound.play() cells = {} count = 0 # gets the overall window.size of the screen screen = Window.size w, h = round_down(screen[0]),int(round_down(screen[1] * .8)) # portion of screen dedicated to the widgets btns = int(round_down(screen[1] * .2)) def drawGrid(self): with self.canvas: for xx in range(0,self.w-10,10): for yy in range(0,self.h,10): self.cells.update({(xx,yy):0}) stat = random.randint(0,1) if stat == 1: self.color = Color(1,1,1) else: self.color = Color(0,0,0) self.rect = Rectangle(pos=(5+xx,int(self.btns/2.)+yy), size=(9,9)) self.cells.update({(xx,yy):[self.rect,self.color,stat]}) return self.cells def update_cell(self, *args): print "Passed" for cell in self.cells: self.cells[cell][2] == random.randint(0,1) if self.cells[cell][2] == 1: self.cells[cell][1].rgb = [1,1,1] else: self.cells[cell][1].rgb = [0,0,0] class boardWidget(GridLayout): def __init__(self, **kwargs): super(boardWidget, self).__init__(**kwargs) self.screen = Window.size self.w, self.h = self.screen[0],self.screen[1] self.cols = 20 self.rows = 10 self.padding = 5 self.pos = (0,int(self.h*.1)) for i in range(0,200): btn = Button(background_color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) self.add_widget(btn) class RootWidget(FloatLayout): def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) self.btns = [controls.sett, controls.info, controls.reset, controls.start, controls.stop, controls.prsts] for item in self.btns: self.add_widget(item) w = boardWidget() dump(w) self.add_widget(w) # grid = boardWidget() # self.add_widget(grid) # Adds the area for the cells # theboard = board() # self.add_widget(theboard) # cells = theboard.drawGrid() # print cells class MyApp(App): def build(self): '''Older version''' self.root = root = RootWidget() # test = RootWidget() # test.update_cell() return self.root '''New version?''' # self.layout = RootWidget() # theboard = board() # self.layout.add_widget(theboard) # cells = theboard.drawGrid() # theboard.update_cell() # Clock.schedule_interval(theboard.update_cell, 0.5) # return self.layout if __name__=="__main__": MyApp().run()<file_sep>/presets.py import random def blank(gridDict): for item in gridDict: gridDict[item].stat = 0 def rando(gridDict): for item in gridDict: val = random.randint(0,1) gridDict[item].stat = val def gun(gridDict): # far left four squares gridDict[390-300,200].stat = 1 gridDict[400-300,200].stat = 1 gridDict[390-300,210].stat = 1 gridDict[400-300,210].stat = 1 # middle left gridDict[470-300,210].stat = 1 gridDict[470-300,220].stat = 1 gridDict[480-300,220].stat = 1 gridDict[480-300,200].stat = 1 gridDict[490-300,200].stat = 1 gridDict[490-300,210].stat = 1 #middle-middle gridDict[550-300,220].stat = 1 gridDict[550-300,230].stat = 1 gridDict[550-300,240].stat = 1 gridDict[560-300,220].stat = 1 gridDict[570-300,230].stat = 1 #middle-top gridDict[610-300,210-20].stat = 1 gridDict[610-300,220-20].stat = 1 gridDict[620-300,220-20].stat = 1 gridDict[620-300,200-20].stat = 1 gridDict[630-300,200-20].stat = 1 gridDict[630-300,210-20].stat = 1 #middle-bottom gridDict[630-300,210-20+110].stat = 1 gridDict[630-300,220-20+110].stat = 1 gridDict[640-300,210-20+110].stat = 1 gridDict[650-300,210-20+110].stat = 1 gridDict[640-300,210-20+130].stat = 1 #right bottom gridDict[740-300,250].stat = 1 gridDict[740-300,250+10].stat = 1 gridDict[740-300,250+20].stat = 1 gridDict[750-300,250].stat = 1 gridDict[760-300,250+10].stat = 1 #far right four squares gridDict[730-300,180].stat = 1 gridDict[740-300,180].stat = 1 gridDict[730-300,190].stat = 1 gridDict[740-300,190].stat = 1 def tens(gridDict): for i in range(0,100, 10): gridDict[200+i,240].stat = 1 # create a conway glider def create_glider(gridDict, x, y): x = round_up_nearest_ten(x) y = round_up_nearest_ten(y) #catches when drawn pixels are off of screen try: # draw one of four orientations for glider direction = random.randint(0,3) if direction == 0: gridDict[x,y].stat = 1 gridDict[x+10,y-10].stat = 1 gridDict[x+20,y+10].stat = 1 gridDict[x+20,y].stat = 1 gridDict[x+20,y-10].stat = 1 elif direction == 1: gridDict[x,y].stat = 1 gridDict[x-10,y-10].stat = 1 gridDict[x-10,y-20].stat = 1 gridDict[x,y-20].stat = 1 gridDict[x+10,y-20].stat = 1 elif direction == 2: gridDict[x,y].stat = 1 gridDict[x-10,y+10].stat = 1 gridDict[x-20,y+10].stat = 1 gridDict[x-20,y].stat = 1 gridDict[x-20,y-10].stat = 1 else: gridDict[x,y].stat = 1 gridDict[x+10,y+10].stat = 1 gridDict[x+10,y+20].stat = 1 gridDict[x,y+20].stat = 1 gridDict[x-10,y+20].stat = 1 except KeyError: pass def binary_101(gridDict): gridDict[180,110].stat = 1 gridDict[190,110].stat = 1 gridDict[200,110].stat = 1 gridDict[90,170].stat = 1 gridDict[100,170].stat = 1 gridDict[100,180].stat = 1 gridDict[90,180].stat = 1 gridDict[90,210].stat = 1 gridDict[100,210].stat = 1 gridDict[100,220].stat = 1 gridDict[90,220].stat = 1 gridDict[120,160].stat = 1 gridDict[120,150].stat = 1 gridDict[130,140].stat = 1 gridDict[140,140].stat = 1 gridDict[140,150].stat = 1 gridDict[140,180].stat = 1 gridDict[140,190].stat = 1 gridDict[140,200].stat = 1 gridDict[140,210].stat = 1 gridDict[120,170].stat = 1 gridDict[120,180].stat = 1 gridDict[120,190].stat = 1 gridDict[120,200].stat = 1 gridDict[120,210].stat = 1 gridDict[120,220].stat = 1 gridDict[120,230].stat = 1 gridDict[120,240].stat = 1 gridDict[130,250].stat = 1 gridDict[140,250].stat = 1 gridDict[140,240].stat = 1 gridDict[160,190].stat = 1 gridDict[160,200].stat = 1 gridDict[170,210].stat = 1 gridDict[180,210].stat = 1 gridDict[170,180].stat = 1 gridDict[180,180].stat = 1 gridDict[190,190].stat = 1 gridDict[190,200].stat = 1 gridDict[210,180].stat = 1 gridDict[210,190].stat = 1 gridDict[210,200].stat = 1 gridDict[210,210].stat = 1 gridDict[210,150].stat = 1 gridDict[210,140].stat = 1 gridDict[220,140].stat = 1 gridDict[230,150].stat = 1 gridDict[230,160].stat = 1 gridDict[230,170].stat = 1 gridDict[230,180].stat = 1 gridDict[230,190].stat = 1 gridDict[230,200].stat = 1 gridDict[230,210].stat = 1 gridDict[230,220].stat = 1 gridDict[230,230].stat = 1 gridDict[230,240].stat = 1 gridDict[220,250].stat = 1 gridDict[210,250].stat = 1 gridDict[210,240].stat = 1 gridDict[250,170].stat = 1 gridDict[260,170].stat = 1 gridDict[260,180].stat = 1 gridDict[250,180].stat = 1 gridDict[250,210].stat = 1 gridDict[260,210].stat = 1 gridDict[260,220].stat = 1 gridDict[250,220].stat = 1 def faces(gridDict): gridDict[230,370].stat = 1 gridDict[240,370].stat = 1 gridDict[240,360].stat = 1 gridDict[250,360].stat = 1 gridDict[260,360].stat = 1 gridDict[270,360].stat = 1 gridDict[280,360].stat = 1 gridDict[290,360].stat = 1 gridDict[300,360].stat = 1 gridDict[310,360].stat = 1 gridDict[310,370].stat = 1 gridDict[320,370].stat = 1 gridDict[310,380].stat = 1 gridDict[300,380].stat = 1 gridDict[290,380].stat = 1 gridDict[280,380].stat = 1 gridDict[270,380].stat = 1 gridDict[260,380].stat = 1 gridDict[250,380].stat = 1 gridDict[240,380].stat = 1 gridDict[250,390].stat = 1 gridDict[260,390].stat = 1 gridDict[270,390].stat = 1 gridDict[280,390].stat = 1 gridDict[290,390].stat = 1 gridDict[300,390].stat = 1 gridDict[300,350].stat = 1 gridDict[290,350].stat = 1 gridDict[280,350].stat = 1 gridDict[270,350].stat = 1 gridDict[260,350].stat = 1 gridDict[250,350].stat = 1 gridDict[260,340].stat = 1 gridDict[270,340].stat = 1 gridDict[280,340].stat = 1 gridDict[290,340].stat = 1 gridDict[260,400].stat = 1 gridDict[270,400].stat = 1 gridDict[280,400].stat = 1 gridDict[290,400].stat = 1 gridDict[260,310].stat = 1 gridDict[270,310].stat = 1 gridDict[280,300].stat = 1 gridDict[270,290].stat = 1 gridDict[250,300].stat = 1 gridDict[300,300].stat = 1 gridDict[310,300].stat = 1 gridDict[310,310].stat = 1 gridDict[300,310].stat = 1 gridDict[300,260].stat = 1 gridDict[310,250].stat = 1 gridDict[310,240].stat = 1 gridDict[310,230].stat = 1 gridDict[300,220].stat = 1 gridDict[290,220].stat = 1 gridDict[290,260].stat = 1 gridDict[280,250].stat = 1 gridDict[280,240].stat = 1 gridDict[280,230].stat = 1 gridDict[230,230].stat = 1 gridDict[230,240].stat = 1 gridDict[230,250].stat = 1 gridDict[220,220].stat = 1 gridDict[210,220].stat = 1 gridDict[200,230].stat = 1 gridDict[200,240].stat = 1 gridDict[200,250].stat = 1 gridDict[210,260].stat = 1 gridDict[220,260].stat = 1 def maze(gridDict): gridDict[210,130].stat = 1 gridDict[210,120].stat = 1 gridDict[220,120].stat = 1 gridDict[230,150].stat = 1 gridDict[240,150].stat = 1 gridDict[240,140].stat = 1 gridDict[190,130].stat = 1 gridDict[180,140].stat = 1 gridDict[190,150].stat = 1 gridDict[210,170].stat = 1 gridDict[220,180].stat = 1 gridDict[230,170].stat = 1 def pulsar(gridDict): gridDict[150,300].stat = 1 gridDict[160,300].stat = 1 gridDict[170,300].stat = 1 gridDict[180,280].stat = 1 gridDict[180,270].stat = 1 gridDict[180,260].stat = 1 gridDict[170,250].stat = 1 gridDict[160,250].stat = 1 gridDict[150,250].stat = 1 gridDict[130,260].stat = 1 gridDict[130,270].stat = 1 gridDict[130,280].stat = 1 gridDict[200,260].stat = 1 gridDict[200,270].stat = 1 gridDict[200,280].stat = 1 gridDict[210,250].stat = 1 gridDict[220,250].stat = 1 gridDict[230,250].stat = 1 gridDict[250,260].stat = 1 gridDict[250,270].stat = 1 gridDict[250,280].stat = 1 gridDict[210,300].stat = 1 gridDict[220,300].stat = 1 gridDict[230,300].stat = 1 gridDict[230,230].stat = 1 gridDict[220,230].stat = 1 gridDict[210,230].stat = 1 gridDict[200,220].stat = 1 gridDict[200,210].stat = 1 gridDict[200,200].stat = 1 gridDict[250,220].stat = 1 gridDict[250,210].stat = 1 gridDict[250,200].stat = 1 gridDict[210,180].stat = 1 gridDict[220,180].stat = 1 gridDict[230,180].stat = 1 gridDict[180,220].stat = 1 gridDict[180,210].stat = 1 gridDict[180,200].stat = 1 gridDict[170,230].stat = 1 gridDict[160,230].stat = 1 gridDict[150,230].stat = 1 gridDict[130,220].stat = 1 gridDict[130,210].stat = 1 gridDict[130,200].stat = 1 gridDict[170,180].stat = 1 gridDict[160,180].stat = 1 gridDict[150,180].stat = 1 def gliders(gridDict): gridDict[120,160].stat = 1 gridDict[130,160].stat = 1 gridDict[140,160].stat = 1 gridDict[140,150].stat = 1 gridDict[140,140].stat = 1 gridDict[180,180].stat = 1 gridDict[190,180].stat = 1 gridDict[200,180].stat = 1 gridDict[190,190].stat = 1 gridDict[240,200].stat = 1 gridDict[250,200].stat = 1 gridDict[260,200].stat = 1 gridDict[240,210].stat = 1 gridDict[240,220].stat = 1
941a124502c26cf0d7379d8f7974af2fd478093e
[ "Markdown", "Python" ]
19
Python
rschenck/game_of_life
09d616ad5c53826eee770742ef87f92131e4559d
d5d4aab46702a557fea2b5db9bf8731cdf9d2d4f
refs/heads/master
<file_sep>import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.layers.recurrent import LSTM from keras.models import load_model import math import datetime min_max_scaler = preprocessing.MinMaxScaler() class TFTutorial(object): def main(self): print(">>> main start...") input = self.load_data() print(input.tail()) #self.plot_initial_data(input) input_nrm = self.normalize_data(input) print(input_nrm.head()) seq_len = 22 X_train, y_train, X_test, y_test = self.prepare(input_nrm) print(X_train, X_test) shape = [4, seq_len, 1] # feature, window, output neurons = [128, 128, 32, 1] d = 0.2 model = self.create_model(shape, neurons, d) model.fit(X_train, y_train, batch_size=512, epochs=300, validation_split=0.1, verbose=1) self.model_score(model, X_train, y_train, X_test, y_test) p = self.percentage_difference(model, X_test, y_test) print("percentage_difference:", p) model.save('model.h5') print("<<< main end!") def percentage_difference(model, X_test, y_test): print(">>> percentage_difference start...") percentage_diff = [] p = model.predict(X_test) for u in range(len(y_test)): # for each data index in test data pr = p[u][0] # pr = prediction on day u percentage_diff.append((pr - y_test[u] / pr) * 100) print(">>> percentage_difference end!") return p def model_score(model, X_train, y_train, X_test, y_test): print(">>> model_score start...") trainScore = model.evaluate(X_train, y_train, verbose=0) print('Train Score: %.5f MSE (%.2f RMSE)' % (trainScore[0], math.sqrt(trainScore[0]))) testScore = model.evaluate(X_test, y_test, verbose=0) print('Test Score: %.5f MSE (%.2f RMSE)' % (testScore[0], math.sqrt(testScore[0]))) print(">>> model_score end!") return trainScore[0], testScore[0] def create_model(self, layers, neurons, d = 0.2): print(">>> create_model start.....") model = Sequential() model.add(LSTM(neurons[0], input_shape=(layers[1], layers[0]), return_sequences=True)) model.add(Dropout(d)) model.add(LSTM(neurons[1], input_shape=(layers[1], layers[0]), return_sequences=False)) model.add(Dropout(d)) model.add(Dense(neurons[2], kernel_initializer="uniform", activation='relu')) model.add(Dense(neurons[3], kernel_initializer="uniform", activation='linear')) # model = load_model('my_LSTM_stock_model1000.h5') # adam = keras.optimizers.Adam(decay=0.2) model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) model.summary() print("<<< create_model end!") return model def prepare(self, input_nrm, seq_len = 22): print(">>> prepare start...") no_of_features = len(input_nrm.columns) print(no_of_features) data = input_nrm.as_matrix() sequence_length = seq_len + 1 # index starting from 0 result = [] for index in range(len(data) - sequence_length): # maxmimum date = lastest date - sequence length result.append(data[index: index + sequence_length]) # index : index + 22days result = np.array(result) row = round(0.9 * result.shape[0]) # 90% split train = result[:int(row), :] # 90% date X_train = train[:, :-1] # all data until day m y_train = train[:, -1][:, -1] # day m + 1 adjusted close price X_test = result[int(row):, :-1] y_test = result[int(row):, -1][:, -1] X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], no_of_features)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], no_of_features)) print("<<< prepare end!") return X_train, y_train, X_test, y_test def normalize_data(self, input): print(">>> normalize data start...") df = pd.DataFrame(data = input, columns=['Date', 'Open Price', 'High Price', 'Low Price']) df['Open Price'] = min_max_scaler.fit_transform(df['Open Price'].values.reshape(-1,1)) df['High Price'] = min_max_scaler.fit_transform(df['High Price'].values.reshape(-1, 1)) df['Low Price'] = min_max_scaler.fit_transform(df['Low Price'].values.reshape(-1, 1)) print("<<< normalize data end!") return df def load_data(self): print(">>> load_data start...") input = pd.read_csv("data/TCS_01012017_30062017.csv", parse_dates=['Date']) print(">>> load_data end!") return input def plot_initial_data(self, input): print(">>> plot initial data start...") # plt.plot(input['High Price']) #plots only y axis plt.plot(input['Date'], input['High Price']) # plots x and y axis plt.plot(input['Date'], input['Low Price']) plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.title("TCS Share Price") plt.show() print(">>> plot initial data end!") if __name__ == "__main__": TFTutorial().main()
7e237319901f415432a7cc4ba25cef41c9d71d1b
[ "Python" ]
1
Python
ravishbhupesh/aiml
9a652cff6e0d03e582cd2b6edaaee7f211b8b1df
fdf4118ea2eec0352297bf1aaca24a6c54291aff
refs/heads/main
<file_sep>#include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <memory.h> #include "parsing.h" #include "memory.h" #include "memory.c" #include "parsing.c" #include "fs.c" struct PowerPlantsRow { uint32_t plantID; const char *plantName; const char *plantType; float maxRatedCapacity; float avgProductionCost; }; struct DailyStatisticsRow { uint32_t reportID; uint32_t plantID; float dailyProduction; float avgSalesPrice; uint32_t dateEpoch; }; // These will be populated while parsing database files struct PowerPlantsRow **powerPlants; struct DailyStatisticsRow **dailyReports; // These will be incremented while parsing database files int n_powerPlants = 0; int n_dailyStatistics = 0; // #################### // ### FILE PARSING ### // #################### uint8_t __readDatabaseString(const char **c, char buffer[], char **o) { // If field doesn't start with double quotes if(**c != '"') { return 0; } nextChar(c); *o = buffer; while(*o-buffer < 255 && **c != 0 && **c != '"') { if(**c == '\\') { (*c)++; if(**c == '"') { **o = **c; (*o)++; } else { (*c)--; **o = **c; } } else { **o = **c; (*o)++; } (*c)++; } // Add null-termiantor **o = 0; // If no closing double quotes if(!eat(c, '"')) { return 0; } return 1; } uint8_t __readDatabaseInteger(const char **c, char buffer[], char **o) { // If field doesn't start with a number if(**c < '0' || **c > '9') { return 0; } *o = buffer; while(*o-buffer < 255 && **c != 0 && (**c >= '0' && **c <= '9')) { **o = **c; (*o)++; (*c)++; } // Add null-termiantor **o = 0; return 1; } uint8_t __readDatabaseFloat(const char **c, char buffer[], char **o) { // If field doesn't start with a number if(**c < '0' || **c > '9') { return 0; } *o = buffer; while(*o-buffer < 255 && **c != 0 && (**c >= '0' && **c <= '9')) { **o = **c; (*o)++; (*c)++; } // Read decimal places if(**c == '.') { **o = '.'; (*o)++; (*c)++; while(*o-buffer < 255 && **c != 0 && (**c >= '0' && **c <= '9')) { **o = **c; (*o)++; (*c)++; } } // Add null-termiantor **o = 0; return 1; } struct PowerPlantsRow* __loadPowerPlantDatabaseFileLine(const char **c) { struct PowerPlantsRow *row = malloc(sizeof(struct PowerPlantsRow)); trim(c); char buffer[256]; // aka output: points to current character in buffer char *o; // ### Plant ID ### if(!__readDatabaseInteger(c, buffer, &o)) return 0; row->plantID = atoi(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Plant name ### if(!__readDatabaseString(c, buffer, &o)) return 0; row->plantName = copyStringToHeap(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Plant type ### if(!__readDatabaseString(c, buffer, &o)) return 0; row->plantType = copyStringToHeap(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Maximum rated capacity ### if(!__readDatabaseFloat(c, buffer, &o)) return 0; row->maxRatedCapacity = atof(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Avg production cost ### if(!__readDatabaseFloat(c, buffer, &o)) return 0; row->avgProductionCost = atof(buffer); return row; } uint8_t loadPowerPlantDatabaseFile(const char *raw) { const char *c = raw; trim(&c); char buffer[256]; // aka output: points to current character in buffer char *o; if(!__readDatabaseInteger(&c, buffer, &o)) return 0; n_powerPlants = atoi(buffer); powerPlants = calloc(n_powerPlants, sizeof(struct PowerPlantsRow*)); if(powerPlants == 0) { return 0; } int i = 0; int line = 1; do { line++; trim(&c); // If end-of-file if(*c == 0) break; struct PowerPlantsRow* row = __loadPowerPlantDatabaseFileLine(&c); if(row == 0) { printf("problem on line %d\n", line); // Skip this line while(*c != '\n') c++; continue; } if(powerPlants[row->plantID] != 0) { printf("duplicate PK %d on line %d\n", row->plantID, line); // Skip this line while(*c != '\n') c++; continue; } powerPlants[row->plantID] = row; space(&c); } while(*c == '\n'); return 1; } int database_test_old(int argc, const char *args[]) { int r = loadPowerPlantDatabaseFile(readEntireFile(args[1])); printf("================\n"); printf("return code: %d\n", r); for (int i = 0; i < n_powerPlants; i++) { struct PowerPlantsRow *row = powerPlants[i]; if(row == 0) continue; printf("power plant no %d:\n", i); printf("plant ID: %d\n", row->plantID); printf("plant name: %s\n", row->plantName); printf("plant type: %s\n", row->plantType); printf("max rated capacity: %f\n", row->maxRatedCapacity); printf("avg production cost: %f\n", row->avgProductionCost); } }<file_sep> char* readEntireFile(const char* name);<file_sep>#include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <memory.h> #include "parsing.h" #include "memory.h" #include "memory.c" #include "vector.c" #include "table.c" #include "fs.c" #include "csv.c" uint8_t __readDatabaseString(const char **c, char buffer[], char **o); uint8_t __readDatabaseInteger(const char **c, char buffer[], char **o); uint8_t __readDatabaseFloat(const char **c, char buffer[], char **o); struct PowerPlantsRow* __loadPowerPlantDatabaseFileLine(const char **c); uint8_t __powerPlantIDMatcher(void* data, void* args); uint8_t loadPowerPlantDatabaseFile(struct Table *powerPlants, const char *raw); struct PowerPlantsRow { uint32_t plantID; const char *plantName; const char *plantType; float maxRatedCapacity; float avgProductionCost; }; struct DailyStatisticsRow { uint32_t reportID; uint32_t plantID; float dailyProduction; float avgSalesPrice; uint32_t dateEpoch; }; void __freePowerPlantReference(void* data, void* args) { printf("free-ing references of %p\n", data); struct PowerPlantsRow* row = data; free((void*)row->plantName); free((void*)row->plantType); } void __freeDailyStatsReference(void* data, void* args) { struct DailyStatisticsRow* row = data; } // ################################ // ### POWER PLANT DATA PARSING ### // ################################ struct PowerPlantsRow* __loadPowerPlantDatabaseFileLine(const char **c) { struct PowerPlantsRow *row = malloc(sizeof(struct PowerPlantsRow)); trim(c); char buffer[256]; // aka output: points to current character in buffer char *o; // ### Plant ID ### space(c); if(!__readDatabaseInteger(c, buffer, &o)) return 0; row->plantID = atoi(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Plant name ### space(c); if(!__readDatabaseString(c, buffer, &o)) return 0; row->plantName = copyStringToHeap(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Plant type ### space(c); if(!__readDatabaseString(c, buffer, &o)) return 0; row->plantType = copyStringToHeap(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Maximum rated capacity ### space(c); if(!__readDatabaseFloat(c, buffer, &o)) return 0; row->maxRatedCapacity = atof(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Avg production cost ### space(c); if(!__readDatabaseFloat(c, buffer, &o)) return 0; row->avgProductionCost = atof(buffer); return row; } uint8_t __powerPlantIDMatcher(void* data, void* args) { return ((struct PowerPlantsRow*) data)->plantID == *(u_int32_t*)args; } uint8_t loadPowerPlantDatabaseFile(struct Table *powerPlants, const char *raw) { const char *c = raw; int line = 0; do { line++; trim(&c); // If end-of-file if(*c == 0) break; // Skip comment lines if(*c == '#') { while(*c != '\n') c++; continue; } struct PowerPlantsRow* row = __loadPowerPlantDatabaseFileLine(&c); // If pointer is invalid, then that file probably had a syntax error // Skip this line if(row == 0) { printf("problem on line %d\n", line); // Skip this line while(*c != '\n') c++; continue; } // PK isn't allowed to be zero if(row->plantID == 0) { printf("power plant's PK can't be 0, skipping line %d\n", line); // Skip this line while(*c != '\n') c++; continue; } // Duplicate PK-s aren't allowed if(tableHasMatch(powerPlants, __powerPlantIDMatcher, (void*)&row->plantID)) { printf("duplicate PK %d on line %d\n", row->plantID, line); // Skip this line while(*c != '\n') c++; continue; } // Store the parsed power plant information in given table tableInsert(powerPlants, row->plantID, row); free(row); space(&c); } while(*c == '\n'); return 1; } uint8_t readPowerPlantDatabaseFile(struct Table *powerPlants, char *file) { char* data = readEntireFile(file); if(data == 0) { return 1; } int r = loadPowerPlantDatabaseFile(powerPlants, data); free(data); return r; } // ########################## // ### DAILY LOGS PARSING ### // ########################## struct DailyStatisticsRow* __loadDailyLogDatabaseFileLine(const char **c) { struct DailyStatisticsRow *log = malloc(sizeof(struct DailyStatisticsRow)); trim(c); char buffer[256]; // aka output: points to current character in buffer char *o; // ### Log ID ### space(c); if(!__readDatabaseInteger(c, buffer, &o)) return 0; log->reportID = atoi(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Plant ID ### space(c); if(!__readDatabaseInteger(c, buffer, &o)) return 0; log->plantID = atoi(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Daily production ### space(c); if(!__readDatabaseFloat(c, buffer, &o)) return 0; log->dailyProduction = atof(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Avg. sales price ### space(c); if(!__readDatabaseFloat(c, buffer, &o)) return 0; log->avgSalesPrice = atof(buffer); // If no comma after field if(!eat(c, ',')) { return 0; } // ### Date time epoch ### space(c); if(!__readDatabaseInteger(c, buffer, &o)) return 0; log->dateEpoch = atoi(buffer); return log; } uint8_t __dailyLogIDMatcher(void* data, void* args) { return ((struct DailyStatisticsRow*) data)->reportID == *(u_int32_t*)args; } uint8_t loadDailyLogDatabaseFile(struct Table *dailyLogs, const char *raw) { const char *c = raw; int line = 0; do { line++; trim(&c); // If end-of-file if(*c == 0) break; // Skip comment lines if(*c == '#') { while(*c != '\n') c++; continue; } struct DailyStatisticsRow* log = __loadDailyLogDatabaseFileLine(&c); // If pointer is invalid, then that file probably had a syntax error // Skip this line if(log == 0) { printf("problem on line %d\n", line); // Skip this line while(*c != '\n') c++; continue; } // PK isn't allowed to be zero if(log->reportID == 0) { printf("report's PK can't be 0, skipping line %d\n", line); // Skip this line while(*c != '\n') c++; continue; } // Duplicate PK-s aren't allowed if(tableHasMatch(dailyLogs, __dailyLogIDMatcher, (void*)&log->reportID)) { printf("duplicate PK %d on line %d\n", log->reportID, line); // Skip this line while(*c != '\n') c++; continue; } // Store the parsed power plant information in given table tableInsert(dailyLogs, log->reportID, log); free(log); space(&c); } while(*c == '\n'); return 1; } uint8_t readDailyLogDatabaseFile(struct Table *dailyLogs, char *file) { char* data = readEntireFile(file); if(data == 0) { return 1; } int r = loadDailyLogDatabaseFile(dailyLogs, data); free(data); return r; } int database_test(int argc, const char *args[]) { struct Table table = tableCreate(sizeof(struct PowerPlantsRow)); char* file = readEntireFile(args[1]); if(file == 0) { return 1; } int r = loadPowerPlantDatabaseFile(&table, file); free(file); printf("================\n"); printf("return code: %d\n", r); for (int i = 0; i < table.size; i++) { struct PowerPlantsRow *row = (struct PowerPlantsRow*)tableGet(&table, i); if(row->plantID == 0) { printf("\nno power plant #%d\n", i); continue; } printf("\npower plant #%d:\n", i); printf("plant ID: %d\n", row->plantID); printf("plant name: %s\n", row->plantName); printf("plant type: %s\n", row->plantType); printf("max rated capacity: %f\n", row->maxRatedCapacity); printf("avg production cost: %f\n", row->avgProductionCost); } return 0; }<file_sep># Summary Date : 2021-05-26 17:06:45 Directory /home/mx007/projects/TalTechKursused/IAG0584/hw2/src Total : 14 files, 1431 codes, 120 comments, 495 blanks, all 2046 lines [details](details.md) ## Languages | language | files | code | comment | blank | total | | :--- | ---: | ---: | ---: | ---: | ---: | | C | 11 | 1,420 | 120 | 491 | 2,031 | | C++ | 3 | 11 | 0 | 4 | 15 | ## Directories | path | files | code | comment | blank | total | | :--- | ---: | ---: | ---: | ---: | ---: | | . | 14 | 1,431 | 120 | 495 | 2,046 | [details](details.md)<file_sep># Summary Date : 2021-05-24 20:20:59 Directory /home/mx007/projects/TalTechKursused/IAG0584/hw2/src Total : 14 files, 1274 codes, 94 comments, 433 blanks, all 1801 lines [details](details.md) ## Languages | language | files | code | comment | blank | total | | :--- | ---: | ---: | ---: | ---: | ---: | | C | 11 | 1,263 | 94 | 429 | 1,786 | | C++ | 3 | 11 | 0 | 4 | 15 | ## Directories | path | files | code | comment | blank | total | | :--- | ---: | ---: | ---: | ---: | ---: | | . | 14 | 1,274 | 94 | 433 | 1,801 | [details](details.md)<file_sep>#include <string.h> #include <stdlib.h> #include <ctype.h> #include <inttypes.h> uint8_t contains(const char* haystack, const char* needle) { int str1_len = strlen(haystack)+1; int str2_len = strlen(needle)+1; char* str1_lowercase = malloc(str1_len * sizeof(char)); char* str2_lowercase = malloc(str2_len * sizeof(char)); char* str1_lowercase_pointer = str1_lowercase; char* str2_lowercase_pointer = str2_lowercase; const char* str1_pointer = haystack; const char* str2_pointer = needle; while(*str1_pointer != 0) { *str1_lowercase_pointer = tolower(*str1_pointer); str1_lowercase_pointer++; str1_pointer++; } *str1_lowercase_pointer = 0; while(*str2_pointer != 0) { *str2_lowercase_pointer = tolower(*str2_pointer); str2_lowercase_pointer++; str2_pointer++; } *str2_lowercase_pointer = 0; char* result = strstr(str1_lowercase, str2_lowercase); free(str1_lowercase); free(str2_lowercase); return result != 0; }<file_sep>#include <features.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct Table tableCreate(int unitSize); struct Table tableCreateAdv(int unitSize, int initialSize, float growthRate); void __tableGrow(struct Table *table, int target); void tablePack(struct Table *table); int tableInsert(struct Table *table, int index, void *data); void tableRemove(struct Table *table, int index); void tableChange(struct Table *table, int index, void *data); uint8_t tableHasMatch(struct Table *table, uint8_t (*matcher)(void* data, void* args), void* args); int tableCountMatches(struct Table *table, uint8_t (*matcher)(void* data, void* args), void* args); void tableShrink(struct Table *table, uint8_t (*tester)(void* data)); void tableForEach(struct Table *table, void (*action)(void* data, void* args), void* args); void __freeReferences(void* data, void* args); void tableClear(struct Table *table); uint8_t isNumber5(void* data, void* args); uint8_t numberTester(void* data); struct Table { int __actualSize; int size; int __unitSize; float __overheadRatio; void *__data; }; struct Table tableCreate(int unitSize) { struct Table table; table.__unitSize = unitSize; table.__actualSize = 0; table.size = 0; table.__overheadRatio = 1.5f; table.__data = malloc(table.__unitSize * table.__actualSize); return table; } struct Table tableCreateAdv(int unitSize, int initialSize, float growthRate) { struct Table table; table.__unitSize = unitSize; table.__actualSize = initialSize; table.size = 0; table.__overheadRatio = growthRate; table.__data = malloc(table.__unitSize * table.__actualSize); return table; } void __tableGrow(struct Table *table, int target) { target++; if(target < table->size) { printf("internal error: attempting to shrink table\n"); abort(); } // Store old values int oldEnd = table->size * table->__unitSize; int oldSize = table->__actualSize; // Update information table->__actualSize = target * table->__overheadRatio; // Reallocate new memory space if(table->__data == 0) table->__data = malloc(table->__actualSize * table->__unitSize); else table->__data = realloc(table->__data, table->__actualSize * table->__unitSize); if(table->__data == 0) { printf("Couldn't resize table\n"); abort(); } // Initialize the expanded area memset(table->__data + oldEnd, 0, (table->__actualSize - oldSize) * table->__unitSize); } void tablePack(struct Table *table) { table->__actualSize = table->size; table->__data = realloc(table->__data, table->__actualSize * table->__unitSize); } int tableInsert(struct Table *table, int index, void *data) { if(index < 0) { printf("Table index out of bounds\n"); abort(); } if(index >= table->size) { __tableGrow(table, index); } void *dest = table->__data + index * table->__unitSize; memcpy(dest, data, table->__unitSize); if(++index > table->size) table->size = index; return index; } void tableRemove(struct Table *table, int index) { if(index < 0 || index >= table->size) { printf("Table index out of bounds\n"); abort(); } void *loc = table->__data + index * table->__unitSize; memset(loc, 0, table->__unitSize); } void tableChange(struct Table *table, int index, void *data) { if(index < 0 || index >= table->size) { printf("Table index out of bounds\n"); abort(); } void *dest = table->__data + index * table->__unitSize; memcpy(dest, data, table->__unitSize); } void* tableGet(struct Table *table, int index) { if(index < 0 || index >= table->size) { printf("Table index out of bounds\n"); abort(); } return table->__data + index * table->__unitSize; } // matcher(..) has to return either 1 or 0 uint8_t tableHasMatch(struct Table *table, uint8_t (*matcher)(void* data, void* args), void* args) { int result; for(int i = 0; i < table->size; i++) { result = matcher(tableGet(table, i), args); if(result) return 1; } return 0; } // matcher(..) has to return either 1 or 0 int tableCountMatches(struct Table *table, uint8_t (*matcher)(void* data, void* args), void* args) { int matches = 0; for(int i = 0; i < table->size; i++) { matches += matcher(tableGet(table, i), args); } return matches; } // matcher(..) has to return 0 if that element doesn't exist / == NULL // Iterates from back to front and shrinks the table until the first found non-uninitialized element void tableShrink(struct Table *table, uint8_t (*tester)(void* data)) { if(table->size == 0) return; int last; for(last = table->size-1; last >= 0; last--) { if(tester(tableGet(table, last))) { break; } } last++; table->__actualSize = last; table->size = last; table->__data = realloc(table->__data, last * table->__unitSize); } void tableForEach(struct Table *table, void (*action)(void* data, void* args), void* args) { if(table == 0) return; if(table->size == 0) return; for(int i = 0; i < table->size; i++) { void* p = tableGet(table, i); action(p, args); } } void tableRemoveIf(struct Table *table, uint8_t (*condition)(void* data, void* args), void* args) { int limit = table->size; for(int i = 0; i < limit; i++) { if(condition(tableGet(table, i), args)) { tableRemove(table, i); limit = table->size; } } } void actionForEachElement(void* data, void* args) { int num = *(int*) data; if(num != 0) { printf("%d\n", num); } } void __freeReferences(void* data, void* args) { free(*(void**)data); } void tableClear(struct Table *table) { memset(table->__data, 0, table->size*table->__unitSize); table->size = 0; } void tableDelete(struct Table *table) { free(table->__data); } uint8_t isNumber5(void* data, void* args) { int num = *(int*) data; return num == 5; } uint8_t numberTester(void* data) { int num = *(int*) data; return num != 0; } int table_test(int argc, char **args) { struct Table table = tableCreate(sizeof(int)); int tmp; tmp = 5; printf("inserting '5' at 0\n"); tableInsert(&table, 0, &tmp); printf("1: size: %d\n", table.size); printf("1: actual size: %d\n", table.__actualSize); tmp = 5; printf("inserting '5' at 10\n"); tableInsert(&table, 10, &tmp); printf("2: size: %d\n", table.size); printf("2: actual size: %d\n", table.__actualSize); tmp = 0; printf("inserting '0' at 100\n"); tableInsert(&table, 100, &tmp); printf("3: size: %d\n", table.size); printf("3: actual size: %d\n", table.__actualSize); printf("printing all non-zero elements: \n"); tableForEach(&table, actionForEachElement, 0); printf("number of 5-s: %d\n", tableCountMatches(&table, isNumber5, 0)); printf("packing...\n"); tablePack(&table); printf("actual size after packing: %d\n", table.__actualSize); printf("shrinking...\n"); tableShrink(&table, numberTester); printf("actual size after shrinking: %d\n", table.__actualSize); printf("reading element at 0: %d\n", *(int*) tableGet(&table, 0)); printf("reading element at 10: %d\n", *(int*) tableGet(&table, 0)); printf("reading element at 11 (not set, should be 0): %d\n", *(int*) tableGet(&table, 11)); printf("reading element at 101 (should abort): \n"); printf("%d\n", *(int*) tableGet(&table, 101)); return 0; }<file_sep>#include <features.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct Vector vectorCreate(int unitSize); struct Vector vectorCreateAdv(int unitSize, int initialSize, float growthRate); void __vectorGrow(struct Vector *vector); void vectorPack(struct Vector *vector); int vectorAdd(struct Vector *vector, void *data); void vectorRemove(struct Vector *vector, int index); void vectorChange(struct Vector *vector, int index, void *data); void* vectorGet(struct Vector *vector, int index); uint8_t vectorHasMatch(struct Vector *vector, uint8_t (*matcher)(void* data, void* args), void* args); int vectorCountMatches(struct Vector *vector, uint8_t (*matcher)(void* data, void* args), void* args); void vectorForEach(struct Vector *vector, void (*action)(void* data, void* args), void* args); struct Vector { int __actualSize; int size; int __unitSize; float __growthRatio; void *__data; }; struct Vector vectorCreate(int unitSize) { struct Vector vector; vector.__unitSize = unitSize; vector.__actualSize = 10; vector.size = 0; vector.__growthRatio = 1.5f; vector.__data = malloc(vector.__unitSize * vector.__actualSize); return vector; } struct Vector vectorCreateAdv(int unitSize, int initialSize, float growthRate) { struct Vector vector; vector.__unitSize = unitSize; vector.__actualSize = initialSize; vector.size = 0; vector.__growthRatio = growthRate; vector.__data = malloc(vector.__unitSize * vector.__actualSize); return vector; } void __vectorGrow(struct Vector *vector) { if(vector->__actualSize == 0) { printf("Array size is zero\n"); abort(); } vector->__actualSize *= vector->__growthRatio; vector->__data = realloc(vector->__data, vector->__actualSize * vector->__unitSize); if(vector->__data == 0) { printf("Couldn't resize vector\n"); abort(); } } void vectorPack(struct Vector *vector) { vector->__actualSize = vector->size; vector->__data = realloc(vector->__data, vector->__actualSize * vector->__unitSize); if(vector->__data == 0) { printf("Couldn't resize vector\n"); abort(); } } int vectorAdd(struct Vector *vector, void *data) { if(vector->size >= vector->__actualSize) { __vectorGrow(vector); } int index = vector->size; void *dest = vector->__data + index * vector->__unitSize; memcpy(dest, data, vector->__unitSize); vector->size++; return index; } void vectorRemove(struct Vector *vector, int index) { if(index < 0 || index >= vector->size) { printf("Array index out of bounds\n"); abort(); } void *loc = vector->__data + index * vector->__unitSize; memcpy(loc, loc + vector->__unitSize, (vector->size - index - 1) * vector->__unitSize); vector->size--; } void vectorChange(struct Vector *vector, int index, void *data) { if(index < 0 || index >= vector->size) { printf("Array index out of bounds\n"); abort(); } void *dest = vector->__data + index * vector->__unitSize; memcpy(dest, data, vector->__unitSize); } void* vectorGet(struct Vector *vector, int index) { if(index < 0 || index >= vector->size) { printf("Array index out of bounds\n"); abort(); } return vector->__data + index * vector->__unitSize; } // matcher(..) has to return either 1 or 0 uint8_t vectorHasMatch(struct Vector *vector, uint8_t (*matcher)(void* data, void* args), void* args) { int result; for(int i = 0; i < vector->size; i++) { result = matcher(vectorGet(vector, i), args); if(result) return 1; } return 0; } // matcher(..) has to return either 1 or 0 int vectorCountMatches(struct Vector *vector, uint8_t (*matcher)(void* data, void* args), void* args) { int matches = 0; for(int i = 0; i < vector->size; i++) { matches += matcher(vectorGet(vector, i), args); } return matches; } void __freeReferences(void* data, void* args); void vectorForEach(struct Vector *vector, void (*action)(void* data, void* args), void* args) { int limit = vector->size; for(int i = 0; i < limit; i++) { void* p = vectorGet(vector, i); action(p, args); limit = vector->size; } } void vectorRemoveIf(struct Vector *vector, uint8_t (*condition)(void* data, void* args), void* args) { int limit = vector->size; for(int i = 0; i < limit; i++) { if(condition(vectorGet(vector, i), args)) { vectorRemove(vector, i); limit = vector->size; } } } void vectorClear(struct Vector *vector) { memset(vector->__data, 0, vector->size*vector->__unitSize); vector->size = 0; } void vectorDelete(struct Vector *vector) { free(vector->__data); } int vector_test(int argc, char **args) { struct Vector vector = vectorCreate(sizeof(int)); int tmp; tmp = 5; vectorAdd(&vector, &tmp); tmp = 8; vectorAdd(&vector, &tmp); tmp = 7; vectorAdd(&vector, &tmp); tmp = 3; vectorAdd(&vector, &tmp); printf("%d\n", vector.size); vectorRemove(&vector, 0); tmp = 13; vectorAdd(&vector, &tmp); printf("%d\n", vector.size); printf("%d\n", *(int*)vectorGet(&vector, 2)); tmp = 10; vectorChange(&vector, 2, &tmp); printf("%d\n", vector.size); printf("actual size: %d\n", vector.__actualSize); tmp = 69; vectorAdd(&vector, &tmp); tmp = 42; vectorAdd(&vector, &tmp); vectorRemove(&vector, vector.size-1); vectorRemove(&vector, vector.size-1); printf("actual size before: %d\n", vector.__actualSize); vectorPack(&vector); printf("actual size after: %d\n", vector.__actualSize); return 0; }<file_sep># Details Date : 2021-05-26 22:48:09 Directory /home/mx007/projects/TalTechKursused/IAG0584/hw2/src Total : 15 files, 1502 codes, 121 comments, 515 blanks, all 2138 lines [summary](results.md) ## Files | filename | language | code | comment | blank | total | | :--- | :--- | ---: | ---: | ---: | ---: | | [src/__database.c](/src/__database.c) | C | 171 | 27 | 66 | 264 | | [src/cli.c](/src/cli.c) | C | 571 | 20 | 165 | 756 | | [src/csv.c](/src/csv.c) | C | 66 | 8 | 17 | 91 | | [src/database.c](/src/database.c) | C | 219 | 46 | 97 | 362 | | [src/fs.c](/src/fs.c) | C | 17 | 2 | 9 | 28 | | [src/fs.h](/src/fs.h) | C++ | 1 | 0 | 2 | 3 | | [src/logging.c](/src/logging.c) | C | 0 | 0 | 1 | 1 | | [src/main.c](/src/main.c) | C | 0 | 0 | 1 | 1 | | [src/memory.c](/src/memory.c) | C | 13 | 0 | 6 | 19 | | [src/memory.h](/src/memory.h) | C++ | 3 | 0 | 1 | 4 | | [src/parsing.c](/src/parsing.c) | C | 37 | 8 | 11 | 56 | | [src/parsing.h](/src/parsing.h) | C++ | 7 | 0 | 1 | 8 | | [src/string_utils.c](/src/string_utils.c) | C | 30 | 0 | 9 | 39 | | [src/table.c](/src/table.c) | C | 205 | 8 | 73 | 286 | | [src/vector.c](/src/vector.c) | C | 162 | 2 | 56 | 220 | [summary](results.md)<file_sep>#include <stdint.h> #include <stdio.h> #include <sys/types.h> #include "parsing.h" /* Skip leading whitespaces and new lines */ void trim(const char **c) { while(**c == ' ' || **c == '\n') nextChar(c); } /* Skip leading whitespaces */ void space(const char **c) { while(**c == ' ') nextChar(c); } /* Increment the pointer (char *c) */ void nextChar(const char **c) { (*c)++; if(**c == 0) { printf("Input end reached\n"); } } /* Increment the pointer (char *c) and return the new character */ char next(const char **c) { char next = **c; nextChar(c); return next; } /* Increments pointer and returns true if next character equals T Skips leading whitespaces and new lines. */ u_int8_t eat(const char **c, char t) { trim(c); if(**c == t) { nextChar(c); return 1; } return 0; } /* Trims the input and returns the following character. */ char get(const char **c) { trim(c); return **c; } /* Trims the input and returns the current character and then steps forward. */ char read(const char **c) { trim(c); return *(*c++); } <file_sep>#include <stdio.h> #include <stdlib.h> char* readEntireFile(const char* name) { FILE *file = fopen(name, "rb"); if(file == 0) { printf("file doesnt' exist\n"); return 0; } // Find file size fseek(file, 0, SEEK_END); long fsize = ftell(file); fseek(file, 0, SEEK_SET); // Allocate big enough buffer (+ null-termiator) char *buffer = malloc(fsize + 1); fread(buffer, 1, fsize, file); buffer[fsize] = 0; fclose(file); return buffer; } <file_sep># Summary Date : 2021-05-26 22:48:09 Directory /home/mx007/projects/TalTechKursused/IAG0584/hw2/src Total : 15 files, 1502 codes, 121 comments, 515 blanks, all 2138 lines [details](details.md) ## Languages | language | files | code | comment | blank | total | | :--- | ---: | ---: | ---: | ---: | ---: | | C | 12 | 1,491 | 121 | 511 | 2,123 | | C++ | 3 | 11 | 0 | 4 | 15 | ## Directories | path | files | code | comment | blank | total | | :--- | ---: | ---: | ---: | ---: | ---: | | . | 15 | 1,502 | 121 | 515 | 2,138 | [details](details.md)<file_sep>#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <errno.h> #include <sys/types.h> // #include "memory.h" // #include "memory.c" #include "database.c" #include "string_utils.c" struct State { struct Table* powerPlants; struct Table* dailyStats; struct Vector* selectedPowerPlants; struct Vector* selectedDailyStats; }; const char* prompt(const char *question); const char* promptFile(const char *question); // Vector<char*> struct Vector readWords(); u_int8_t executeCommand(struct State *state); void command_import(struct State *state, struct Vector *words); void command_export(struct State *state, struct Vector *words); const char* syntax_select = "syntax: SELECT (power-plants / logs) WHERE <column> (CONTAINS <string> / EQUALS <value>)"; void command_selection(struct State *state, struct Vector *words); void command_select(struct State *state, struct Vector *words, void(*action)(void*, void*)); void command_insert(struct State *state, struct Vector *words); const char* syntax_delete = "syntax: DELETE (power-plants / logs)"; void command_delete(struct State *state, struct Vector *words); void command_logs(struct State *state, struct Vector *words); void command_plants(struct State *state, struct Vector *words); void command_list(struct State *state, struct Vector *words); enum INSTRUCTION { SELECT, DESELECT }; enum FIELD { PLANT_PK, PLANT_NAME, PLANT_TYPE, PLANT_CAPACITY, PLANT_PRODUCTION_COST, LOG_PK, LOG_FK, LOG_PRODUCTION, LOG_SELL_PRICE, LOG_DATE }; enum DATA_TYPE { STRING, INT, FLOAT }; struct __MATCHER_DATA { enum INSTRUCTION instruction; enum FIELD field; char* matchString; void (*action)(void*, void*); struct Vector *dest; }; void __selectionMatcherAction_select(void* data, void* args); void __selectionMatcherAction_deselect(void* data, void* args); void __selectionMatcher_contains(void* data, void* args); void __selectionMatcher_equals(void* data, void* args); void __selectionMatcher_passthrough(void* data, void* args); void flushAndExit(); // Used for debugging void printWords(void* data, void* args) { printf("word1: %s\n", *(char **) data); } void printVector(struct Vector *vector) { vectorForEach(vector, printWords, 0); } void printTable(struct Table *table) { tableForEach(table, printWords, 0); } u_int8_t executeCommand(struct State *state) { uint8_t ret = 1; // ### READ USER INPUT ### printf(" > "); struct Vector words = readWords(); if(words.size != 0) { char** firstWord = vectorGet(&words, 0); if(!strcmp("EXIT", *firstWord)) { ret = 0; } else if (!strcmp("IMPORT", *firstWord)) { command_import(state, &words); } else if (!strcmp("EXPORT", *firstWord)) { command_export(state, &words); } else if ((!strcmp("SELECT", *firstWord)) || (!strcmp("DESELECT", *firstWord))) { command_selection(state, &words); } else if (!strcmp("INSERT", *firstWord)) { command_insert(state, &words); } else if (!strcmp("DELETE", *firstWord)) { command_delete(state, &words); } else if (!strcmp("LOGS", *firstWord)) { command_logs(state, &words); } else if (!strcmp("PLANTS", *firstWord)) { command_plants(state, &words); } else if (!strcmp("LIST", *firstWord)) { command_list(state, &words); } else { printf("Unknown command\n"); } } vectorForEach(&words, __freeReferences, 0); vectorDelete(&words); return ret; } void command_import(struct State *state, struct Vector *words) { if(words->size < 2) { printf("import syntax: <file name>\n"); return; } uint8_t success = readPowerPlantDatabaseFile(state->powerPlants, vectorGet(words, 1)); if(!success) { printf("failed to read database file\n"); } } void command_export(struct State *state, struct Vector *words) { } void command_selection(struct State *state, struct Vector *words) { if(words->size < 1) { return; } char* command = *(char**)vectorGet(words, 0); if(!strcmp(command, "SELECT")) { command_select(state, words, __selectionMatcherAction_select); } else if(!strcmp(command, "DESELECT")) { command_select(state, words, __selectionMatcherAction_deselect); } else { printf("Unknown command\n"); return; } } void command_select(struct State *state, struct Vector *words, void(*action)(void*, void*)) { if(words->size < 2) { printf("%s\n", syntax_select); return; } // "power-plants" or "logs" char* sourceName = *(char**)vectorGet(words, 1); struct Table* source; struct Vector* dest; if(!strcmp(sourceName, "power-plants")) { source = state->powerPlants; dest = state->selectedPowerPlants; } else if(!strcmp(sourceName, "logs")) { source = state->dailyStats; dest = state->selectedDailyStats; } else { printf("err: unknown table \"%s\"\n", sourceName); return; } char* matcherName = 0; char* matcherString = 0; void (*matcher)(void*, void*); struct __MATCHER_DATA data; enum FIELD field = 0; // if "CONTAINS" or "EQUALS" not present if(words->size == 2) { matcher = __selectionMatcher_passthrough; data = (struct __MATCHER_DATA){ SELECT, 0, 0, action, dest }; goto findMatches; } else if(words->size < 6) { printf("%s\n", syntax_select); return; } if(strcmp(*(char**)vectorGet(words, 2), "WHERE")) { printf("%s\n", syntax_select); return; } char* columnName = *(char**)vectorGet(words, 3); if(source == state->powerPlants) { if(!strcmp(columnName, "id")) field = PLANT_PK; else if(!strcmp(columnName, "name")) field = PLANT_NAME; else if(!strcmp(columnName, "type")) field = PLANT_TYPE; else if(!strcmp(columnName, "capacity")) field = PLANT_CAPACITY; else if(!strcmp(columnName, "cost")) field = PLANT_PRODUCTION_COST; } else { if(!strcmp(columnName, "id")) field = LOG_PK; else if(!strcmp(columnName, "plant")) field = LOG_FK; else if(!strcmp(columnName, "production")) field = LOG_PRODUCTION; else if(!strcmp(columnName, "sales")) field = LOG_SELL_PRICE; else if(!strcmp(columnName, "date")) field = LOG_DATE; } // if "CONTAINS" or "EQUALS" present matcherName = *(char**)vectorGet(words, 4); matcherString = *(char**)vectorGet(words, 5); if(!strcmp(matcherName, "CONTAINS")) { matcher = __selectionMatcher_contains; } else if(!strcmp(matcherName, "EQUALS")) { matcher = __selectionMatcher_equals; } else { printf("%s\n", syntax_select); return; } findMatches: if(field == 0 || matcherString == 0) printf("err: invalid parameters\n"); data = (struct __MATCHER_DATA){ SELECT, field, matcherString, action, dest }; tableForEach(source, matcher, &data); printf("\n%d power plants and %d daily reports in selection.\n\n", state->selectedPowerPlants->size, state->selectedDailyStats->size); } void command_deselect(struct State *state, struct Vector *words) { if(words->size < 2) { printf("select syntax: \"power plants\"/\"daily stats\" [contains <string> / matches <pattern>]\n"); return; } } void command_insert(struct State *state, struct Vector *words) { } uint8_t __isIDNonZero(void* data, void* args) { return *(u_int32_t*)data != 0; } int __countRows(struct Table* table) { return tableCountMatches(table, __isIDNonZero, 0); } uint8_t __deleter(void* data, void* args) { // works on both, power plants and logs, as the PK is the first elemnt in both structs return *(uint32_t*)data == *(uint32_t*)args; } void __deleteElementsFromTable(void* data, void* args) { tableRemoveIf(args, __deleter, data); } void command_delete(struct State *state, struct Vector *words) { char* sourceName = *(char**)vectorGet(words, 1); int plantsDeleted = 0; int logsDeleted = 0; if(!strcmp(sourceName, "power-plants")) { plantsDeleted = __countRows(state->powerPlants); vectorForEach(state->selectedPowerPlants, __deleteElementsFromTable, state->powerPlants); vectorClear(state->selectedPowerPlants); plantsDeleted -= __countRows(state->powerPlants); } else if(!strcmp(sourceName, "logs")) { logsDeleted = __countRows(state->dailyStats); vectorForEach(state->selectedDailyStats, __deleteElementsFromTable, state->dailyStats); vectorClear(state->selectedPowerPlants); logsDeleted -= __countRows(state->dailyStats); } else { printf("err: unknown table \"%s\"\n", sourceName); return; } printf("\nDeleted %d power plants and %d daily reports.\n\n", plantsDeleted, logsDeleted); } void command_logs(struct State *state, struct Vector *words) { } void command_plants(struct State *state, struct Vector *words) { } void printPowerPlant(void* data, void* args) { struct PowerPlantsRow *row = data; printf("Power plant ID: %d\n", row->plantID); printf("Power plant name: %s\n", row->plantName); printf("Power plant fuel: %s\n", row->plantType); printf("Max. rated capacity: %f\n", row->maxRatedCapacity); printf("Avg. production cost: %f\n", row->avgProductionCost); printf("\n"); } void printDailyStats(void* data, void* args) { struct DailyStatisticsRow *row = data; printf("Report ID: %d\n", row->reportID); printf("Power plant ID: %d\n", row->plantID); printf("Daily production: %f\n", row->dailyProduction); printf("Avg. sales price: %f\n", row->avgSalesPrice); printf("Report Date: %d\n", row->dateEpoch); } void command_list(struct State *state, struct Vector *words) { printf("\n%d power plants and %d daily reports in selection.\n\n", state->selectedPowerPlants->size, state->selectedDailyStats->size); printf("Plant ID, plant name, plant type, rated capacity, production cost\n\n"); vectorForEach(state->selectedPowerPlants, printPowerPlant, 0); } void __powerPlantSelected(void* data, void* args) { struct { uint8_t* found; uint32_t id; }* info = args; struct PowerPlantsRow* row = data; if(row->plantID == info->id) { *info->found = 1; return; } } void __selectionMatcherAction_select(void* data, void* args) { struct __MATCHER_DATA* mdata = args; // check if power plant isn't already selected uint8_t selected = 0; struct { uint8_t* found; uint32_t id; } info; info.found = &selected; info.id = *(uint32_t*)data; vectorForEach(mdata->dest, __powerPlantSelected, &info); // don't select if already selected if(!selected) vectorAdd(mdata->dest, data); } uint8_t __deselector(void* data, void* args) { // works on both, power plants and logs, as the PK is the first elemnt in both structs return *(uint32_t*)data == *(uint32_t*)args; } void __selectionMatcherAction_deselect(void* data, void* args) { struct __MATCHER_DATA* mdata = args; vectorRemoveIf(mdata->dest, __deselector, data); } void __selectionMatcher_contains(void* data, void* args) { struct __MATCHER_DATA* mdata = args; struct PowerPlantsRow* plant = data; int callAction = 0; // works on both, power plants and logs, as the PK is the first elemnt in both structs if(plant->plantID == 0) return; switch (mdata->field) { case PLANT_PK: case PLANT_CAPACITY: case PLANT_PRODUCTION_COST: case LOG_PK: case LOG_FK: case LOG_PRODUCTION: case LOG_SELL_PRICE: printf("err: 'CONTAINS' cannot be used on this column\n"); return; case PLANT_NAME: callAction = contains(plant->plantName, mdata->matchString); break; case PLANT_TYPE: callAction = contains(plant->plantType, mdata->matchString); break; default: printf("fatal err: unknown column\n"); exit(EXIT_FAILURE); return; } if(callAction) mdata->action(data, args); } void __selectionMatcher_equals(void* data, void* args) { struct __MATCHER_DATA* mdata = args; struct PowerPlantsRow* plant = data; struct DailyStatisticsRow* log = data; // works on both, power plants and logs, as the PK is the first element in both structs if(plant->plantID == 0) return; enum DATA_TYPE type = STRING; float valFloat; uint64_t valInt; char* valString; // ### READ DATA TYPE ### { valString = mdata->matchString; errno = 0; char* endptr = valString; valFloat = strtof(valString, &endptr); if(errno == 0) { type = FLOAT; } errno = 0; endptr = valString; valInt = strtoul(valString, &endptr, 10); if(errno == 0) { type = INT; } } switch (mdata->field) { case PLANT_PK: if(type == INT) { if(valInt == plant->plantID) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case PLANT_NAME: if(type == STRING) { if(!strcmp(valString, plant->plantName)) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case PLANT_TYPE: if(type == STRING) { if(!strcmp(valString, plant->plantType)) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case PLANT_CAPACITY: if(type == FLOAT) { if(valFloat == plant->maxRatedCapacity) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case PLANT_PRODUCTION_COST: if(type == FLOAT) { if(valFloat == plant->avgProductionCost) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case LOG_PK: if(type == INT) { if(valInt == log->reportID) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case LOG_FK: if(type == INT) { if(valInt == log->plantID) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case LOG_PRODUCTION: if(type == FLOAT) { if(valFloat == log->dailyProduction) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case LOG_SELL_PRICE: if(type == FLOAT) { if(valFloat == log->avgSalesPrice) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; case LOG_DATE: if(type == INT) { if(valInt == log->dateEpoch) { mdata->action(data, args); } } else printf("err: incompatible data types\n"); break; default: printf("fatal err: unknown column\n"); exit(EXIT_FAILURE); return; } } void __selectionMatcher_passthrough(void* data, void* args) { struct __MATCHER_DATA* mdata = args; struct PowerPlantsRow* plant = data; if(plant->plantID == 0) return; mdata->action(data, args); } void flushAndExit(struct State *state) { tableForEach(state->powerPlants, __freePowerPlantReference, 0); tableForEach(state->dailyStats, __freeDailyStatsReference, 0); tableDelete(state->powerPlants); tableDelete(state->dailyStats); } const char* prompt(const char *question) { printf("%s: \n> ", question); char buffer[256]; char *o = buffer; char c; while((c = fgetc(stdin)) != '\n' && o-buffer < 255 && c != 0) { *o = c; o++; } *o = 0; return copyStringToHeap(buffer); } const char* promptFile(const char *question) { const char* input = prompt(question); const char *c = input; while(*c != 0) { switch (*c) { case '\\': case '/': case ':': case '*': case '?': case '"': case '<': case '>': case '|': printf("Invalid file name, file name cannot contain ASCII's control characters nor one of those: \\/:*?\"<>|\n"); free((char*)input); return promptFile(question); default: c++; } } return input; } struct Vector readWords() { struct Vector words = vectorCreate(sizeof(char *)); char buffer[256]; char c; do { char *o = buffer; int escaping = 0; int inString = 0; while(((c = fgetc(stdin)) != ' ' || inString) && o-buffer < 512 && c != 0 && c != '\n') { if(c =='"') { inString = !inString; continue; } if(inString) { if(escaping) { switch (c) { case 'n': *o = '\n'; continue; break; case '"': *o = '"'; continue; break; default: break; } escaping = 0; } if(c == '\\') { escaping = 1; continue; } } *o = c; o++; } *o = 0; const char* string = copyStringToHeap(buffer); vectorAdd(&words, &string); } while(c != '\n'); vectorPack(&words); return words; } int main(int argc, char **args) { struct Table plants = tableCreate(sizeof(struct PowerPlantsRow)); struct Table logs = tableCreate(sizeof(struct DailyStatisticsRow)); struct Vector selectedPlants = vectorCreate(sizeof(struct PowerPlantsRow)); struct Vector selectedLogs = vectorCreate(sizeof(struct DailyStatisticsRow)); const char* fileName = promptFile("Enter power plant data file"); if(fileName == 0) { printf("invalid file name\n"); return 1; } char* file = readEntireFile(fileName); if(file == 0) { printf("failed to read file\n"); return 1; } loadPowerPlantDatabaseFile(&plants, file); free((char*)fileName); free(file); printf("POWER PLANTS: ==============\n"); for (int i = 0; i < plants.size; i++) { struct PowerPlantsRow *row = tableGet(&plants, i); // break instead of continue because once there's a null // pointer, everything after that will be too if(row == 0) continue; printf("power plant no %d:\n", i); printf("plant ID: %d\n", row->plantID); printf("plant name: %s\n", row->plantName); printf("plant type: %s\n", row->plantType); printf("max rated capacity: %f\n", row->maxRatedCapacity); printf("avg production cost: %f\n", row->avgProductionCost); } fileName = promptFile("Enter daily statistics log file"); if(fileName == 0) { printf("invalid file name\n"); return 1; } file = readEntireFile(fileName); if(file == 0) { printf("failed to read file\n"); return 1; } loadDailyLogDatabaseFile(&logs, file); free((char*)fileName); free(file); printf("DAILY LOGS: ==============\n"); for (int i = 0; i < logs.size; i++) { struct DailyStatisticsRow *row = tableGet(&logs, i); // break instead of continue because once there's a null // pointer, everything after that will be too if(row == 0) continue; printf("report no %d:\n", i); printf("report ID: %d\n", row->reportID); printf("plant ID: %d\n", row->plantID); printf("daily production: %f\n", row->dailyProduction); printf("avg sales price: %f\n", row->avgSalesPrice); printf("date epoch: %d\n", row->dateEpoch); } struct State state; state.powerPlants = &plants; state.dailyStats = &logs; state.selectedPowerPlants = &selectedPlants; state.selectedDailyStats = &selectedLogs; while(1) { if(!executeCommand(&state)) { break; } } tableForEach(&plants, __freePowerPlantReference, 0); tableForEach(&logs, __freeDailyStatsReference, 0); tableDelete(&plants); tableDelete(&logs); vectorDelete(&selectedPlants); vectorDelete(&selectedLogs); }<file_sep>#include <inttypes.h> #include "parsing.c" uint8_t __readDatabaseString(const char **c, char buffer[], char **o) { // If field doesn't start with double quotes if(**c != '"') { return 0; } nextChar(c); *o = buffer; while(*o-buffer < 255 && **c != 0 && **c != '"') { if(**c == '\\') { (*c)++; if(**c == '"') { **o = **c; (*o)++; } else { (*c)--; **o = **c; } } else { **o = **c; (*o)++; } (*c)++; } // Add null-termiantor **o = 0; // If no closing double quotes if(!eat(c, '"')) { return 0; } return 1; } uint8_t __readDatabaseInteger(const char **c, char buffer[], char **o) { // If field doesn't start with a number if(**c < '0' || **c > '9') { return 0; } *o = buffer; while(*o-buffer < 255 && **c != 0 && (**c >= '0' && **c <= '9')) { **o = **c; (*o)++; (*c)++; } // Add null-termiantor **o = 0; return 1; } uint8_t __readDatabaseFloat(const char **c, char buffer[], char **o) { // If field doesn't start with a number if(**c < '0' || **c > '9') { return 0; } *o = buffer; while(*o-buffer < 255 && **c != 0 && (**c >= '0' && **c <= '9')) { **o = **c; (*o)++; (*c)++; } // Read decimal places if(**c == '.') { **o = '.'; (*o)++; (*c)++; while(*o-buffer < 255 && **c != 0 && (**c >= '0' && **c <= '9')) { **o = **c; (*o)++; (*c)++; } } // Add null-termiantor **o = 0; return 1; }<file_sep>#include <sys/types.h> const char* copyBufferToHeap(char buffer[], size_t buffer_size); const char* copyStringToHeap(char buffer[]);<file_sep>#define u_int8_t unsigned char void trim(const char **c); void nextChar(const char **c); char next(const char **c); u_int8_t eat(const char **c, char t); char get(const char **c); char read(const char **c);<file_sep>#compiler name cc :=gcc #remove command RM := rm -rf #source files SOURCES :=database.c fs.c parsing.c SRCS :=$(addprefix src/,$(SOURCES)) #object files OBJS :=$(addprefix build/,$(SOURCES:.c=.o)) #main target main: $(OBJS) $(CC) $^ -o $@ %.o: %.c $(CC) -c $< -o $@ .PHONY: clean clean: $(RM) *.o main<file_sep>#include <memory.h> #include <stdlib.h> const char* copyBufferToHeap(char buffer[], size_t buffer_size) { char *c = malloc(sizeof(char) * buffer_size); memcpy(c, buffer, sizeof(char) * buffer_size); return (const char *) c; } const char* copyStringToHeap(char buffer[]) { unsigned long bytes = strlen(buffer) + 1; char *c = malloc(sizeof(char) * bytes); memcpy(c, buffer, sizeof(char) * bytes); return (const char *) c; }
b1d8c0c9650e2c018aeaff206e44b1129aea3411
[ "Markdown", "C", "Makefile" ]
18
C
Matrx007/IAG0584-HW2
4be7d028bf25f44e4b764c92c327760c5e5bd9f5
72786aabb5cc9ae4476c819840c348a747d3e0ea
refs/heads/main
<repo_name>elbert-git/tui-theme-journal<file_sep>/Notes/notes.md tui journals online on our main server it's a bash script journal (base command) - checks what date it is - if file for today already exists then just open that file in vim - else create a new file in designated directory and pipe in the template text then open in vim designated journal directory journal bash script /JournalsLogs/ - all journal file files go here /JournalConfigs/ - journal configs like configs and templates <file_sep>/README.md # tui-theme-journal A TUI implementation of the Cortex podcast's theme journal ## What is this Just my own implementation of the CGP grey's theme system. ## How does this work I want to to be able to call the program and immediate bring up a template document in vim for me to fill in ## What does the current version do? Just what I've written at the top lmao ## What's the roadmap for this [ ] adding an initial startup process. as of now it only works if i set up all the configs manually [ ] throwbacks maybe randomly show a random journal log to you. kinda like google photos how they show you youre past/recent memories <file_sep>/MainDirectory/journal.sh #/bin/sh # --- functions main_program () { # --- get today's date TODAY=$(python3 ./JournalModules/GetDate.py) # --- check if journal file exists for current date if [ -f "./JournalLogs/${TODAY}.md" ] then #file exists #open the file in vim vim ./JournalLogs/${TODAY}.md else #file doesnt exist #create a file with proper name touch ./JournalLogs/${TODAY}.md #cat template into file cat ./JournalConfigs/CurrentTemplate.md > ./JournalLogs/${TODAY}.md #open file in vim vim ./JournalLogs/${TODAY}.md fi } main_program <file_sep>/MainDirectory/JournalModules/GetDate.py from datetime import datetime now = datetime.now() print(now.strftime("%Y%m%d"))
f8e82512340c517866b45aa283ca95519e8cb306
[ "Markdown", "Python", "Shell" ]
4
Markdown
elbert-git/tui-theme-journal
1aa5cd5255eba371d0b5b6fa21cc3df93edaddcd
0aafa2f9913d6aae25a42244a27487720ee2403e
refs/heads/main
<file_sep># MTG-Card-Guessing-Game 1/2/2021 This Game gives the player six cards(facing down) to choose from. Each card is part of a pair, and if they guess correctly, they get a point. The front facing sides of the cards are pulled randomly from the MTG API (https://magicthegathering.io/). The player can guess as many times as they would like. In other words, there is no losing condition, only a win condition. I've enjoyed working on this as I am a long-time Magic: The Gathering fan. It was also good practice. Will make more finishing touches tomorrow. 1/3/2021 Added a timeout to allow the player to see the cards chosen for a few seconds before reseting the card images, if their guess was incorrect. I also added a fallback image for each card image class if two of the image urls are identical or if there is no image url for one of the three particular cards that are randomly pulled. 1/7/2021 I added a couple of the best planeswalkers of MTG to the background, Sorin and Elspeth! Also, just generally made the UI look a bit more pleasant.<file_sep>let score = 0; //Card images will not change until gameReady is equal to true. let gameReady = false; let url = "https://api.magicthegathering.io/v1/cards?supertypes=legendary&types=creature&colors=red"; let card1 = document.getElementById("card1"); let card2 = document.getElementById("card2"); let card3 = document.getElementById("card3"); let card4 = document.getElementById("card4"); let card5 = document.getElementById("card5"); let card6 = document.getElementById("card6"); let scoreNum = document.getElementById("score-num"); let ready = document.getElementById("ready"); //These three variables will hold the image url fetched from the MTG API. //These card images can be colors other than R, B, or G, but the colors make it easier for me to differentiate between them. let cardRed; let cardBlue; let cardGreen; //The prevCard object will contain the previous card clicked, as well as the function associated with that card. let prevCard = { previous: null, click: null } let cardArr = [card1, card2, card3, card4, card5, card6]; let classArr = ["classRed", "classRed", "classBlue", "classBlue", "classGreen", "classGreen"]; function arrayShuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } arrayShuffle(classArr); console.log(classArr) for(let i = 0; i < cardArr.length; i++) { cardArr[i].className = classArr[i]; }; scoreNum.innerText = `Score: ${score}` //Fetches three image urls from the MTGAPI. function fetchRandom() { fetch(url) .then(response=> response.json()) .then(function(data) { console.log(data.cards[0], data.cards[0].imageUrl); cardRed = data.cards[Math.floor(Math.random() * data.cards.length)].imageUrl; cardBlue = data.cards[Math.floor(Math.random() * data.cards.length)].imageUrl; cardGreen = data.cards[Math.floor(Math.random() * data.cards.length)].imageUrl; if(cardRed === undefined || cardRed === cardBlue || cardRed === cardGreen){ console.log("CardRed was undefined!") cardRed = "https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=489504&type=card" } if(cardBlue === undefined || cardBlue === cardGreen || cardBlue === cardRed){ console.log("CardBlue was undefined!") cardBlue = "https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=460980&type=card" } if(cardGreen === undefined || cardGreen === cardRed || cardGreen === cardBlue){ console.log("CardGreen was undefined!") cardGreen = "https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=4566&type=card" } console.log("RED: " + cardRed, "BLUE: " + cardBlue, cardBlue, "GREEN: " + cardGreen); gameReady = true; ready.innerText = 'Ready!' }) } fetchRandom() //These are the functions called when the card images are clicked. //The functions are called when the card of the corresponding number is clicked (For ex., clicking card1 will trigger cardClick1). function cardClick1() { if(gameReady === true){ if(prevCard.previous === null) { prevCard.previous = card1; prevCard.click = cardClick1; if (card1.className === "classRed") { card1.src = cardRed } else if (card1.className === "classBlue") { card1.src = cardBlue } else { card1.src = cardGreen } } else { if(prevCard.previous.className === card1.className){ if (card1.className === "classRed") { card1.src = cardRed } else if (card1.className === "classBlue") { card1.src = cardBlue } else { card1.src = cardGreen } card1.removeEventListener("click", cardClick1); prevCard.previous.removeEventListener("click", prevCard.click); score += 1; scoreNum.innerText = `Score: ${score}`; prevCard.previous = null; prevCard.click = null; if(score >= 3){ alert("Omg!!???!! You're so smart, you win!!!!") } } else { alert("Sorry pal, those don't match."); //Event listeners are removed her while the user gets to look at the non-matching cards. card1.removeEventListener("click", cardClick1); card2.removeEventListener("click", cardClick2); card3.removeEventListener("click", cardClick3); card4.removeEventListener("click", cardClick4); card5.removeEventListener("click", cardClick5); card6.removeEventListener("click", cardClick6); if (card1.className === "classRed") { card1.src = cardRed } else if (card1.className === "classBlue") { card1.src = cardBlue } else { card1.src = cardGreen } setTimeout(()=> { prevCard.previous.src = "https://i.redd.it/qnnotlcehu731.jpg"; card1.src = "https://i.redd.it/qnnotlcehu731.jpg"; prevCard.previous = null; prevCard.click = null; card1.addEventListener("click", cardClick1, false); card2.addEventListener("click", cardClick2, false); card3.addEventListener("click", cardClick3, false); card4.addEventListener("click", cardClick4, false); card5.addEventListener("click", cardClick5, false); card6.addEventListener("click", cardClick6, false); }, 3000); } } } }; function cardClick2() { if(gameReady === true){ if(prevCard.previous === null) { prevCard.previous = card2; prevCard.click = cardClick2; if (card2.className === "classRed") { card2.src = cardRed } else if (card2.className === "classBlue") { card2.src = cardBlue } else { card2.src = cardGreen } } else { if(prevCard.previous.className === card2.className){ if (card2.className === "classRed") { card2.src = cardRed } else if (card2.className === "classBlue") { card2.src = cardBlue } else { card2.src = cardGreen } card2.removeEventListener("click", cardClick2); prevCard.previous.removeEventListener("click", prevCard.click); score += 1; scoreNum.innerText = `Score: ${score}`; prevCard.previous = null; prevCard.click = null; if(score >= 3){ alert("Omg!!???!! You're so smart, you win!!!!") } } else { alert("Sorry pal, those don't match."); card1.removeEventListener("click", cardClick1); card2.removeEventListener("click", cardClick2); card3.removeEventListener("click", cardClick3); card4.removeEventListener("click", cardClick4); card5.removeEventListener("click", cardClick5); card6.removeEventListener("click", cardClick6); if (card2.className === "classRed") { card2.src = cardRed } else if (card2.className === "classBlue") { card2.src = cardBlue } else { card2.src = cardGreen } setTimeout(()=> { prevCard.previous.src = "https://i.redd.it/qnnotlcehu731.jpg"; card2.src = "https://i.redd.it/qnnotlcehu731.jpg"; prevCard.previous = null; prevCard.click = null; card1.addEventListener("click", cardClick1, false); card2.addEventListener("click", cardClick2, false); card3.addEventListener("click", cardClick3, false); card4.addEventListener("click", cardClick4, false); card5.addEventListener("click", cardClick5, false); card6.addEventListener("click", cardClick6, false); }, 3000); } } } }; function cardClick3() { if(gameReady === true){ if(prevCard.previous === null) { prevCard.previous = card3; prevCard.click = cardClick3; if (card3.className === "classRed") { card3.src = cardRed } else if (card3.className === "classBlue") { card3.src = cardBlue } else { card3.src = cardGreen } } else { if(prevCard.previous.className === card3.className){ if (card3.className === "classRed") { card3.src = cardRed } else if (card3.className === "classBlue") { card3.src = cardBlue } else { card3.src = cardGreen } card3.removeEventListener("click", cardClick3); prevCard.previous.removeEventListener("click", prevCard.click); score += 1; scoreNum.innerText = `Score: ${score}`; prevCard.previous = null; prevCard.click = null; if(score >= 3){ alert("Omg!!???!! You're so smart, you win!!!!") } } else { alert("Sorry pal, those don't match."); card1.removeEventListener("click", cardClick1); card2.removeEventListener("click", cardClick2); card3.removeEventListener("click", cardClick3); card4.removeEventListener("click", cardClick4); card5.removeEventListener("click", cardClick5); card6.removeEventListener("click", cardClick6); if (card3.className === "classRed") { card3.src = cardRed } else if (card3.className === "classBlue") { card3.src = cardBlue } else { card3.src = cardGreen } setTimeout(()=> { prevCard.previous.src = "https://i.redd.it/qnnotlcehu731.jpg"; card3.src = "https://i.redd.it/qnnotlcehu731.jpg"; prevCard.previous = null; prevCard.click = null; card1.addEventListener("click", cardClick1, false); card2.addEventListener("click", cardClick2, false); card3.addEventListener("click", cardClick3, false); card4.addEventListener("click", cardClick4, false); card5.addEventListener("click", cardClick5, false); card6.addEventListener("click", cardClick6, false); }, 3000); } } }}; function cardClick4() { if(gameReady === true){ if(prevCard.previous === null) { prevCard.previous = card4; prevCard.click = cardClick4; if (card4.className === "classRed") { card4.src = cardRed } else if (card4.className === "classBlue") { card4.src = cardBlue } else { card4.src = cardGreen } } else { if(prevCard.previous.className === card4.className){ if (card4.className === "classRed") { card4.src = cardRed } else if (card4.className === "classBlue") { card4.src = cardBlue } else { card4.src = cardGreen } card4.removeEventListener("click", cardClick4); prevCard.previous.removeEventListener("click", prevCard.click); score += 1; scoreNum.innerText = `Score: ${score}`; prevCard.previous = null; prevCard.click = null; if(score >= 3){ alert("Omg!!???!! You're so smart, you win!!!!") } } else { alert("Sorry pal, those don't match."); card1.removeEventListener("click", cardClick1); card2.removeEventListener("click", cardClick2); card3.removeEventListener("click", cardClick3); card4.removeEventListener("click", cardClick4); card5.removeEventListener("click", cardClick5); card6.removeEventListener("click", cardClick6); if (card4.className === "classRed") { card4.src = cardRed } else if (card4.className === "classBlue") { card4.src = cardBlue } else { card4.src = cardGreen } setTimeout(()=> { prevCard.previous.src = "https://i.redd.it/qnnotlcehu731.jpg"; card4.src = "https://i.redd.it/qnnotlcehu731.jpg"; prevCard.previous = null; prevCard.click = null; card1.addEventListener("click", cardClick1, false); card2.addEventListener("click", cardClick2, false); card3.addEventListener("click", cardClick3, false); card4.addEventListener("click", cardClick4, false); card5.addEventListener("click", cardClick5, false); card6.addEventListener("click", cardClick6, false); }, 3000); } } }}; function cardClick5() { if(gameReady === true){ if(prevCard.previous === null) { prevCard.previous = card5; prevCard.click = cardClick5; if (card5.className === "classRed") { card5.src = cardRed } else if (card5.className === "classBlue") { card5.src = cardBlue } else { card5.src = cardGreen } } else { if(prevCard.previous.className === card5.className){ if (card5.className === "classRed") { card5.src = cardRed } else if (card5.className === "classBlue") { card5.src = cardBlue } else { card5.src = cardGreen } card5.removeEventListener("click", cardClick5); prevCard.previous.removeEventListener("click", prevCard.click); score += 1; scoreNum.innerText = `Score: ${score}`; prevCard.previous = null; prevCard.click = null; if(score >= 3){ alert("Omg!!???!! You're so smart, you win!!!!") } } else { alert("Sorry pal, those don't match."); card1.removeEventListener("click", cardClick1); card2.removeEventListener("click", cardClick2); card3.removeEventListener("click", cardClick3); card4.removeEventListener("click", cardClick4); card5.removeEventListener("click", cardClick5); card6.removeEventListener("click", cardClick6); if (card5.className === "classRed") { card5.src = cardRed } else if (card5.className === "classBlue") { card5.src = cardBlue } else { card5.src = cardGreen } setTimeout(()=> { prevCard.previous.src = "https://i.redd.it/qnnotlcehu731.jpg"; card5.src = "https://i.redd.it/qnnotlcehu731.jpg"; prevCard.previous = null; prevCard.click = null; card1.addEventListener("click", cardClick1, false); card2.addEventListener("click", cardClick2, false); card3.addEventListener("click", cardClick3, false); card4.addEventListener("click", cardClick4, false); card5.addEventListener("click", cardClick5, false); card6.addEventListener("click", cardClick6, false); }, 3000); } } }}; function cardClick6() { if(gameReady === true){ if(prevCard.previous === null) { prevCard.previous = card6; prevCard.click = cardClick6; if (card6.className === "classRed") { card6.src = cardRed } else if (card6.className === "classBlue") { card6.src = cardBlue } else { card6.src = cardGreen } } else { if(prevCard.previous.className === card6.className){ if (card6.className === "classRed") { card6.src = cardRed } else if (card6.className === "classBlue") { card6.src = cardBlue } else { card6.src = cardGreen } card6.removeEventListener("click", cardClick6); prevCard.previous.removeEventListener("click", prevCard.click); score += 1; scoreNum.innerText = `Score: ${score}`; prevCard.previous = null; prevCard.click = null; if(score >= 3){ alert("Omg!!???!! You're so smart, you win!!!!") } } else { alert("Sorry pal, those don't match."); card1.removeEventListener("click", cardClick1); card2.removeEventListener("click", cardClick2); card3.removeEventListener("click", cardClick3); card4.removeEventListener("click", cardClick4); card5.removeEventListener("click", cardClick5); card6.removeEventListener("click", cardClick6); if (card6.className === "classRed") { card6.src = cardRed } else if (card6.className === "classBlue") { card6.src = cardBlue } else { card6.src = cardGreen } setTimeout(()=> { prevCard.previous.src = "https://i.redd.it/qnnotlcehu731.jpg"; card6.src = "https://i.redd.it/qnnotlcehu731.jpg"; prevCard.previous = null; prevCard.click = null; card1.addEventListener("click", cardClick1, false); card2.addEventListener("click", cardClick2, false); card3.addEventListener("click", cardClick3, false); card4.addEventListener("click", cardClick4, false); card5.addEventListener("click", cardClick5, false); card6.addEventListener("click", cardClick6, false); }, 3000); } } } }; console.log(prevCard) card1.addEventListener("click", cardClick1, false); card2.addEventListener("click", cardClick2, false); card3.addEventListener("click", cardClick3, false); card4.addEventListener("click", cardClick4, false); card5.addEventListener("click", cardClick5, false); card6.addEventListener("click", cardClick6, false);
5f014c9359eb9345ede158bb58ef5fc7b89737f6
[ "Markdown", "JavaScript" ]
2
Markdown
impypots/MTG-Card-Guessing-Game
01c4335a14dcaec4b3c89b2d2f74116c7f4f2db7
04bdc657a260b806fd81a24b2c642b1742c43896
refs/heads/master
<repo_name>Dghistani/HW_W04_D01<file_sep>/hw.js ​// ------ FOR ALL THE EXCERCISES ONLY USE ARROW FUNCTIONS ----- // ​ // PART 1: USE MAP IN THE FOLLOWING EXCERCISES // // A) write a function called swapCase that takes a string of words and uses .map and your newly written capitalize() // function to return a string where every other word is in all caps. // Hint: look up Array.prototype.map on MDN and see what arguments the .map callback can take. // ex: swapCase('hello stranger , what do we have today? ') // => " HELLO stranger , WHAT do WE have TODAY ?" // Codeeeee var swapCase = (string) => { string = string.split(' ') string = string.map(function(index,item){ if ( item % 2 != 0) { index = index.toUpperCase() } return index }) console.log( string.join(" ") ) }; swapCase('hello stranger , what do we have today?') ​ // B) Write a function shiftLetters that takes a string and uses .map to return an encoded string with each letter shifted down the // alphabet by one. Hint: Use Look up the JS functions String.fromCharCode() and String. . // see if you can use Ascii code to acomplish this // ex. shiftLetters('hello') // => 'ifmmp' // ex. (shiftLetters('abcxyz') // => "bcdyz{" // code! var shiftLetters = (string)=> { // code! string = string.split('') string = string.map(function(item){ let encode= item.charCodeAt(0); encode = encode + 1 encode =String.fromCharCode(encode) // console.log(encode) return encode }) // console.log(String.charCodeAt(0)); console.log(string.toString()) }; shiftLetters('hello') // PART 2: USE FOREACH IN THE FOLLOWING EXCERCISES // A) Build a Deck // Use a forEach() loop within another forEach() loop to build an array representing a deck of cards. A deck consists of 52 cards - 13 ranks in each of 4 suits. // Then, display a list of every card in the deck. (Hint: Each element of the array should read something like "ace of spades" or "4 of hearts"). // The start of your output should look something like this: // - ace of clubs // - 2 of clubs // - 3 of clubs // - 4 of clubs // - 5 of clubs // - 6 of clubs // - 7 of clubs // - 8 of clubs // - 9 of clubs // - 10 of clubs // - jack of clubs // - queen of clubs // - king of clubs // - ace of diamonds // - 2 of diamonds // - 3 of diamonds suits = ["Heart", "Clubs", "Dimonds", "Spades"] numbers = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "Jack", "Queen", "King"] suits.forEach(function(suit){ numbers.forEach(function(number){ console.log( number + " of " + suit) } ) }); // B) Word Play // Create a form where users may enter a sentence. // Turn that sentence into an array using the split method. // Then, loop through this array to build a new array out of every word in the sentence that is 3 or more characters in length. // Finally, reverse the order of the new array, join it back together into a string, and display it to the user.
8f97f31351894268233b8757574367ec95ce76cc
[ "JavaScript" ]
1
JavaScript
Dghistani/HW_W04_D01
fd623cdfd497bc9e9c73be70dcf03bd3b1d42e34
60e57f8d36413d59d81e6f5b6f547336439613bd
refs/heads/main
<file_sep>const Transport = require("./transport") const config = require("./config.json") const http = require("http") const net = require("net") net.createServer(socket => { const transport = new Transport(socket) http.createServer(async (req, res) => { res.end(await transport.call(req)) }).listen(config.public) }).listen(config.forward.port)<file_sep>const Transport = require("./transport") const config = require("./config.json") const http = require("http") const net = require("net") const transport = new Transport( net.connect(config.forward) ) transport.on((req, callback) => { const reqer = http.request({ port: config.private, url: req.url, method: req.method, headers: req.headers, }, res => { let buf = Buffer.alloc(0) res.on("data", chunk => { buf = Buffer.concat([ buf, chunk ]) }) res.on("end", () => { callback(buf) }) }) reqer.write(req.body) reqer.end() })
4c2a6c9717cba3a27e430cbaa61f48d5e022ec0a
[ "JavaScript" ]
2
JavaScript
DrFascial/server_forward
820c9244ef3a5eb056a06d115a4dd6acf232288f
16afcf3313fb904c139aff1c6b62150c0a335436
refs/heads/master
<repo_name>roovenier/gulp-fonsta<file_sep>/index.js var Promise = require('es6-promise').Promise; var through = require('through2'); var gutil = require('gulp-util'); var fonsta = require('fonsta/lib/commands/install'); function gulpFonsta(fonts, options) { options = options || {}; var flags = { isSave: (typeof options.saveDeps !== 'boolean') ? false : options.saveDeps, noCss: (typeof options.noCss !== 'boolean') ? false : options.noCss }; var stream = through(); if(typeof fonts !== 'object') { try { fonts = require(fonts); } catch(e) { stream.emit('error', new gutil.PluginError('gulp-fonsta', e.message)); } } var fontsArray = Object.keys(fonts); if(fontsArray.length === 0) { setTimeout(function() { stream.emit('end'); }, 0); } fontsArray.reduce(function(prom, font, fontIndex) { return prom.then(function() { return new Promise(function(resolve, reject) { fonsta(font, fonts[font], flags, false, options).then(function(result) { result = result.replace(/\r?\n/, '').split(/\r\n|\n|\r/); for(var i=0; i<result.length; i++) { gutil.log('gulp-fonsta:', result[i]); } if(fontIndex === fontsArray.length - 1) { stream.emit('end'); } resolve(); }, function(err) { gutil.log('gulp-fonsta:', err.message.replace(/\r?\n/, '')); if(fontIndex === fontsArray.length - 1) { stream.emit('end'); } resolve(); }); }); }); }, Promise.resolve()); return stream; } module.exports = gulpFonsta; <file_sep>/README.md # gulp-fonsta Use [Fonsta](https://github.com/roovenier/fonsta) within gulp task manager. [![Build Status](https://travis-ci.org/roovenier/gulp-fonsta.svg?branch=master)](https://travis-ci.org/roovenier/gulp-fonsta) [![npm version](https://badge.fury.io/js/gulp-fonsta.svg)](https://www.npmjs.com/package/gulp-fonsta) ## Install ```sh $ npm install gulp-fonsta --save-dev ``` ## Examples ```javascript var gulp = require('gulp'); var fonsta = require('gulp-fonsta'); // Pass font list as object and save it into dependencies file gulp.task('fonsta', function() { return fonsta( { nobile: ['medium'], roboto: ['regular', 'italic'], 'pt-sans': ['bold'], 'open-sans': ['bold'] }, { saveDeps: true } ); }); // Pass fonts from a json dependency file gulp.task('fonsta:deps', function() { return fonsta(__dirname + '/fonsta.deps.json') }); // Provide fonsta config options gulp.task('fonsta:options', function() { return fonsta( __dirname + '/fonsta.deps.json', { saveDeps: false, noCss: true, tmpDir: '/temp/fonts', fontsDir: '/vendor/fonts', cssDir: '/vendor/css', cssFile: 'vendor.css' } ); }); ```
e772ee3a43705b22aa7774c32f5752254b04a230
[ "JavaScript", "Markdown" ]
2
JavaScript
roovenier/gulp-fonsta
667ba4a464d16d5a9811761d2dfc75f48feecf26
51467ecbcebdeb3cfa81f290263e77b854b4ea32
refs/heads/master
<repo_name>ipapadop/pal<file_sep>/include/pal.h #pragma once #include "pal_base.h" #include "pal_math.h" #include "pal_dsp.h" #include "pal_image.h" #include "pal_fft.h" #ifdef PAL_SOURCE # include "common.h" #endif #ifdef __epiphany__ /* Static library. Force a dependency so __pal_init/fini always will be * included in built binary. Not pretty but works. */ extern void __pal_init(); void (*__pal_init_p) (void) __attribute__((weak)) = __pal_init; #endif <file_sep>/src/math/p_minmax.c #include <pal.h> /** * * Finds the minimum and maximum values in vector 'a'. Returns the min and max * values and the indices of the minimum and maximum values. * * @param a Pointer to input vector * * @param c1 Pointer to output scalar (minimum) * * @param c2 Pointer to output scalar (maximum) * * @param[out] index1 Pointer to return index of min * * @param[out] index2 Pointer to return index of max * * @param n Size of 'a' vector. * * @return None * */ void PSYM(p_minmax)(const PTYPE *a, PTYPE *c1, PTYPE *c2, int *index1, int *index2, int n) { int pos_min = 0; int pos_max = 0; PTYPE min = *a; PTYPE max = *a; int i; for (i = 1; i < n; i++) { if (*(a + i) < min) { pos_min = i; min = *(a + i); } else if (*(a + i) > max) { pos_max = i; max = *(a + i); } } *c1 = min; *c2 = max; *index1 = pos_min; *index2 = pos_max; } <file_sep>/src/base/devices/epiphany/loader.h #pragma once struct team; struct prog; extern int epiphany_load(struct team *team, struct prog *prog, int start, int size, int flags, int argn, const p_arg_t *args, const char *function); extern void epiphany_start(struct team *team, int start, int size, int flags); extern int epiphany_soft_reset(struct team *team, int start, int size); int epiphany_reset_system(struct epiphany_dev *epiphany); <file_sep>/benchmark/math/p_minmax_f32.c #include "../bench_tmpl.h" void bench_p_minmax_f32(const struct p_bench_specification *spec) { p_minmax_f32(spec->mem.i1.p_float, spec->mem.i2.p_float, spec->mem.i3.p_float, spec->mem.o1.p_int, spec->mem.o2.p_int, spec->current_size); } const struct p_bench_item benchmark_items[] = { item(p_minmax_f32), { NULL, NULL } }; <file_sep>/tests/math/p_minmax.c #include <math.h> #include "check_p_minmax.h" void generate_ref(PTYPE *outValue1, PTYPE *outValue2, int *outIndex1, int *outIndex2, size_t n) { int i; *outIndex1 = 0; *outIndex2 = 0; *outValue1 = ai[0]; *outValue2 = ai[0]; for (i = 1; i < n; i++) { if (ai[i] < *outValue1) { *outIndex1 = i; *outValue1 = ai[i]; } if (ai[i] > *outValue2) { *outIndex2 = i; *outValue2 = ai[i]; } } } <file_sep>/tests/math/check_p_minmax.c /* p_minmax has a different signature from all other math functions in the PAL. It has 1 input vector and 2 output scalars and 2 output indices. As a result, it needs a distinct test infrastructure. */ #include <utest.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <stdbool.h> #include <string.h> #include <pal.h> /* TODO: This relative path include is fragile */ #include "../src/base/pal_base_private.h" #include <common.h> #include "check_p_minmax.h" #ifndef FUNCTION #error FUNCTION must be defined #endif #define GOLD_PATH XSTRING(gold/FUNCTION.gold.h) #include GOLD_PATH PTYPE *ai, *result1, *result2; int *resultIndex1, *resultIndex2; struct gold *gold = builtin_gold; size_t gold_size = ARRAY_SIZE(builtin_gold); /* For detecting erroneous overwrites */ #define OUTPUT_END_MARKER ((PTYPE)60189537703610376.0) bool equals(PTYPE x, PTYPE y) { PTYPE err; if (fabs(x - y) <= EPSILON_MAX) return true; if (fabs(x) > fabs(y)) err = fabs((x - y) / x); else err = fabs((x - y) / y); return err <= EPSILON_RELMAX; } int setup(struct ut_suite *suite) { size_t i; (void) suite; ai = calloc(gold_size, sizeof(PTYPE)); /* Allocate one extra element for res and add end marker so overwrites can * be detected */ result1 = calloc(2, sizeof(PTYPE)); result1[1] = OUTPUT_END_MARKER; resultIndex1 = calloc(1, sizeof(int)); result2 = calloc(2, sizeof(PTYPE)); result2[1] = OUTPUT_END_MARKER; resultIndex2 = calloc(1, sizeof(int)); for (i = 0; i < gold_size; i++) { ai[i] = gold[i].ai; } return 0; } int teardown(struct ut_suite *suite) { free(ai); free(result1); free(result2); free(resultIndex1); free(resultIndex2); return 0; } int tc_against_gold_e(struct ut_suite *suite, struct ut_tcase *tcase) { /* Run FUNCTION against gold input here so results are available * for all test cases. */ FUNCTION(ai, result1, result2, resultIndex1, resultIndex2, gold_size); return 0; } int tc_against_gold_v(struct ut_suite *suite, struct ut_tcase *tcase) { ut_assert_msg(equals(result1[0], gold[0].gold1), "%s: result 1: %f != %f", XSTRING(FUNCTION), result1[0], gold[0].gold1); ut_assert_msg(equals(result2[0], gold[0].gold2), "%s: result 2: %f != %f", XSTRING(FUNCTION), result2[0], gold[0].gold2); ut_assert_msg(result1[1] == OUTPUT_END_MARKER, "Output end marker was overwritten"); ut_assert_msg(result2[1] == OUTPUT_END_MARKER, "Output end marker was overwritten"); // Skip checking the index return 0; } int tc_against_ref_v(struct ut_suite *suite, struct ut_tcase *tcase) { if (gold_size == 0) return 0; PTYPE reference1, reference2; int indexOfReference1, indexOfReference2; generate_ref(&reference1, &reference2, &indexOfReference1, &indexOfReference2, gold_size); ut_assert_msg(equals(reference1, gold[0].gold1), "%s: result 1: %f != %f", XSTRING(FUNCTION), result1[0], reference1); ut_assert_msg(equals(reference2, gold[0].gold2), "%s: result 2: %f != %f", XSTRING(FUNCTION), result2[0], reference2); ut_assert_msg(resultIndex1[0] == indexOfReference1, "%s: index 1: %d != %d", XSTRING(FUNCTION), resultIndex1[0], indexOfReference1); ut_assert_msg(resultIndex2[0] == indexOfReference2, "%s: index 2: %d != %d", XSTRING(FUNCTION), resultIndex2[0], indexOfReference2); return 0; } DECLARE_UT_TCASE(tc_against_gold, tc_against_gold_e, tc_against_gold_v, NULL); DECLARE_UT_TCASE(tc_against_ref, NULL, tc_against_ref_v, NULL); DECLARE_UT_TCASE_LIST(tcases, &tc_against_gold, &tc_against_ref); #define FUNCTION_SUITE XCONCAT2(FUNCTION,_suite) DECLARE_UT_SUITE(FUNCTION_SUITE, setup, teardown, false, tcases, NULL); int main(int argc, char *argv[]) { int ret; char buf[1024] = { 0 }; struct ut_suite *suite; suite = &FUNCTION_SUITE; ret = ut_run(suite); ut_report(buf, ARRAY_SIZE(buf), suite, true); printf("%s", buf); return ret; } <file_sep>/src/base/p_run.c #include <pal.h> /** * * Runs(launches) the program 'prog' on all of the members of 'team'. * * @param prog Pointer to the program to run that was loaded with p_load() * * @param function Name of function within 'prog' to run * * @param team Team to run with. * * @param start Relative starting processor within team * * @param size Total number of processors within team to run * * @param nargs Number of arguments to be supplied to 'function' * * @param args An array of pointers to function arguments * * @param flags Bitfield mask type flags * * @return Returns 0 if successful. * */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include "pal_base.h" #include "pal_base_private.h" int p_run(p_prog_t prog, const char *function, p_team_t team, int start, int count, int nargs, const p_arg_t *args, int flags) { int err; struct team *pteam = (struct team *) team; struct prog *pprog = (struct prog *) prog; struct dev *pdev; if (p_ref_is_err(prog) || p_ref_is_err(team)) return -EINVAL; pdev = pteam->dev; if (nargs > P_RUN_MAX_ARGS) return -E2BIG; err = pdev->dev_ops->run(pdev, pteam, pprog, function, start, count, nargs, args, flags); if (err) return err; if (!(flags & P_RUN_NONBLOCK)) return p_wait((p_team_t) team); // Inconsistent with flags to this function return 0; } <file_sep>/src/base/devices/epiphany/loader.c /* TODO: All addresses etc. are hardcoded. Assumes Parallella-16 memory map */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/mman.h> #include <assert.h> #include <stdint.h> #include <stdbool.h> #include <alloca.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <elf.h> #include "config.h" #include <pal.h> #include <common.h> #include "../../pal_base_private.h" #include "dev_epiphany.h" #include "epiphany-abi.h" #include "epiphany-kernel-abi.h" #define MMR_R0 0xf0000 #define MMR_CONFIG 0xf0400 #define MMR_STATUS 0xf0404 #define MMR_PC 0xf0408 #define MMR_DEBUGSTATUS 0xf040c #define MMR_LC 0xf0414 #define MMR_LS 0xf0418 #define MMR_LE 0xf041c #define MMR_IRET 0xf0420 #define MMR_IMASK 0xf0424 #define MMR_ILAT 0xf0428 #define MMR_ILATST 0xf042c #define MMR_ILATCL 0xf0430 #define MMR_IPEND 0xf0434 #define MMR_CTIMER0 0xf0438 #define MMR_CTIMER1 0xf043c #define MMR_FSTATUS 0xf0440 #define MMR_DEBUGCMD 0xf0448 #define MMR_DMA0CONFIG 0xf0500 #define MMR_DMA0STRIDE 0xf0504 #define MMR_DMA0COUNT 0xf0508 #define MMR_DMA0SRCADDR 0xf050c #define MMR_DMA0DSTADDR 0xf0510 #define MMR_DMA0AUTODMA0 0xf0514 #define MMR_DMA0AUTODMA1 0xf0518 #define MMR_DMA0STATUS 0xf051c #define MMR_DMA1CONFIG 0xf0520 #define MMR_DMA1STRIDE 0xf0524 #define MMR_DMA1COUNT 0xf0528 #define MMR_DMA1SRCADDR 0xf052c #define MMR_DMA1DSTADDR 0xf0530 #define MMR_DMA1AUTODMA0 0xf0534 #define MMR_DMA1AUTODMA1 0xf0538 #define MMR_DMA1STATUS 0xf053c #define MMR_MEMSTATUS 0xf0604 #define MMR_MEMPROTECT 0xf0608 #define MMR_MESHCONFIG 0xf0700 #define MMR_MULTICAST 0xf0704 #define MMR_DMASTART MMR_DMA0CONFIG #define MMR_DMAEND 0xf0540 #define E_SYS_BASE 0x70000000 #define MMR_LINKCFG 0xf0300 #define MMR_LINKTXCFG 0xf0304 #define MMR_LINKRXCFG 0xf0308 // Epiphany system registers typedef enum { E_SYS_RESET = 0x0040, E_SYS_CFGTX = 0x0044, E_SYS_CFGRX = 0x0048, E_SYS_CFGCLK = 0x004c, E_SYS_COREID = 0x0050, E_SYS_VERSION = 0x0054, E_SYS_GPIOIN = 0x0058, E_SYS_GPIOOUT = 0x005c } e_sys_reg_id_t; typedef union { unsigned int reg; struct { unsigned int enable:1; unsigned int mmu:1; unsigned int mode:2; // 0=Normal, 1=GPIO unsigned int ctrlmode:4; unsigned int clkmode:4; // 0=Full speed, 1=1/2 speed unsigned int resvd:20; }; } e_syscfg_tx_t; typedef union { unsigned int reg; struct { unsigned int enable:1; unsigned int mmu:1; unsigned int path:2; // 0=Normal, 1=GPIO, 2=Loopback unsigned int monitor:1; unsigned int resvd:27; }; } e_syscfg_rx_t; typedef union { unsigned int reg; struct { unsigned int divider:4; // 0=off, 1=F/64 ... 7=F/1 unsigned int pll:4; // TBD unsigned int resvd:24; }; } e_syscfg_clk_t; typedef union { unsigned int reg; struct { unsigned int col:6; unsigned int row:6; unsigned int resvd:20; }; } e_syscfg_coreid_t; typedef union { unsigned int reg; struct { unsigned int revision:8; unsigned int type:8; unsigned int platform:8; unsigned int generation:8; }; } e_syscfg_version_t; #define EM_ADAPTEVA_EPIPHANY 0x1223 /* Adapteva's Epiphany architecture. */ #define COREID(_addr) ((_addr) >> 20) struct symbol_info { const char *name; bool found; Elf32_Sym sym; }; static inline bool is_local(uint32_t addr) { return COREID(addr) == 0; } static bool is_on_chip(uint32_t addr) { uint32_t row, col; row = (COREID(addr) >> 6) & 0x3f; col = (COREID(addr) ) & 0x3f; return is_local(addr) || ((0x20 <= row && row < 0x24) && (0x08 <= col && row < 0x0c)); } static inline bool is_in_eram(uint32_t addr) { return (0x8e000000 <= addr && addr < 0x90000000); } static inline bool is_valid_addr(uint32_t addr, uint32_t coreid) { /* Only allow loading to current core */ return is_local(addr) || (is_on_chip(addr) && COREID(addr) == coreid) || is_in_eram(addr); } static inline bool is_epiphany_exec_elf(Elf32_Ehdr *ehdr) { return ehdr && memcmp(ehdr->e_ident, ELFMAG, SELFMAG) == 0 && ehdr->e_ident[EI_CLASS] == ELFCLASS32 && ehdr->e_type == ET_EXEC && ehdr->e_version == EV_CURRENT && ehdr->e_machine == EM_ADAPTEVA_EPIPHANY; } /* Assumes 32 bit ... */ /* Assumes core is valid */ /* Assumes core mem and regs are cleared, core is idle / halted */ /* Assumes valid elf file */ static int process_elf(const void *file, struct epiphany_dev *epiphany, unsigned coreid) { Elf32_Ehdr *ehdr; Elf32_Phdr *phdr; void *dst; const uint8_t *src = (uint8_t *) file; ehdr = (Elf32_Ehdr *) &src[0]; phdr = (Elf32_Phdr *) &src[ehdr->e_phoff]; for (unsigned i = 0; i < ehdr->e_phnum; i++) { // TODO: should this be p_paddr instead of p_vaddr? if (!is_valid_addr(phdr[i].p_vaddr, coreid)) return -EINVAL; } for (unsigned i = 0; i < ehdr->e_phnum; i++) { // TODO: should this be p_paddr instead of p_vaddr? uint32_t addr = phdr[i].p_vaddr; dst = is_local(addr) ? (void *) ((coreid << 20) | addr) : (void *) addr; memcpy(dst, &src[phdr[i].p_offset], phdr[i].p_filesz); /* This is where we would have cleared .bss (p_memsz - p_filesz), but * since we assume SRAM is already cleared there's no need for that. */ } return 0; } static inline uint32_t reg_read(volatile void *base, uintptr_t offset) { volatile uint32_t *reg = (uint32_t *) ((uintptr_t) base + offset); return *reg; } static inline uint32_t reg_write(volatile void *base, uintptr_t offset, uint32_t val) { volatile uint32_t *reg = (uint32_t *) ((uintptr_t) base + offset); *reg = val; } int ecore_soft_reset_dma(struct epiphany_dev *epiphany, unsigned coreid) { uint32_t config; bool fail0, fail1; int i; /* HACK: Depends on that we do an explicit mmap of Epiphany addresses space * in device.c:mmap_chip_mem() */ volatile void *core = (void *) (coreid << 20); /* pause DMA */ config = reg_read(core, MMR_CONFIG) | 0x01000000; reg_write(core, MMR_CONFIG, config); reg_write(core, MMR_DMA0CONFIG, 0); reg_write(core, MMR_DMA0STRIDE, 0); reg_write(core, MMR_DMA0COUNT, 0); reg_write(core, MMR_DMA0SRCADDR, 0); reg_write(core, MMR_DMA0DSTADDR, 0); reg_write(core, MMR_DMA0STATUS, 0); reg_write(core, MMR_DMA1CONFIG, 0); reg_write(core, MMR_DMA1STRIDE, 0); reg_write(core, MMR_DMA1COUNT, 0); reg_write(core, MMR_DMA1SRCADDR, 0); reg_write(core, MMR_DMA1DSTADDR, 0); reg_write(core, MMR_DMA1STATUS, 0); /* unpause DMA */ config &= ~0x01000000; reg_write(core, MMR_CONFIG, config); fail0 = true; for (i = 0; i < 1000; i++) { if (!(reg_read(core, MMR_DMA0STATUS) & 7)) { fail0 = false; break; } usleep(10); } if (fail0) /* warnx("%s(): (%d) DMA0 NOT IDLE after dma reset", __func__, coreid); */ ; fail1 = true; for (i = 0; i < 1000; i++) { if (!(reg_read(core, MMR_DMA1STATUS) & 7)) { fail1 = false; break; } usleep(10); } if (fail1) /* warnx("%s(): (%d) DMA1 NOT IDLE after dma reset", __func__, coreid); */ ; return (fail0 || fail1) ? -EIO : 0; } int ecore_reset_regs(struct epiphany_dev *epiphany, unsigned coreid, bool reset_dma) { unsigned i; /* HACK: Depends on that we do an explicit mmap of Epiphany addresses space * in device.c:mmap_chip_mem() */ volatile void *core = (void *) (coreid << 20); /* General purpose registers */ memset((void *) ((uintptr_t) core + MMR_R0), 0, 64 * 4); if (reset_dma) if (ecore_soft_reset_dma(epiphany, coreid)) return -EIO; /* Enable clock gating */ reg_write(core, MMR_CONFIG, 0x00400000); reg_write(core, MMR_FSTATUS, 0); /* reg_write(core, MMR_PC, 0); */ reg_write(core, MMR_LC, 0); reg_write(core, MMR_LS, 0); reg_write(core, MMR_LE, 0); reg_write(core, MMR_IRET, 0); /* Mask all but SYNC irq */ reg_write(core, MMR_IMASK, ~1); reg_write(core, MMR_ILATCL, ~0); reg_write(core, MMR_CTIMER0, 0); reg_write(core, MMR_CTIMER1, 0); reg_write(core, MMR_MEMSTATUS, 0); reg_write(core, MMR_MEMPROTECT, 0); /* Enable clock gating */ reg_write(core, MMR_MESHCONFIG, 2); return 0; } void ecore_clear_sram(struct epiphany_dev *epiphany, unsigned coreid) { const unsigned ivt_size = 9 * 4; const uint32_t insn = 0xffe017e2; /* entry: trap #5; b.s entry; */ unsigned i; /* HACK: Depends on that we do an explicit mmap of Epiphany addresses space * in device.c:mmap_chip_mem() */ union { void *v; uint32_t *u32; uint8_t *u8; } core = { .v = (void *) (coreid << 20) }; /* Set IVT entries to a safe instruction */ for (i = 0; i < ivt_size / 4; i++) core.u32[i] = insn; memset(&core.u8[ivt_size], 0, 32768 - ivt_size); } static uint8_t soft_reset_payload[] = { 0xe8, 0x16, 0x00, 0x00, 0xe8, 0x14, 0x00, 0x00, 0xe8, 0x12, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0xe8, 0x0e, 0x00, 0x00, 0xe8, 0x0c, 0x00, 0x00, 0xe8, 0x0a, 0x00, 0x00, 0xe8, 0x08, 0x00, 0x00, 0xe8, 0x06, 0x00, 0x00, 0xe8, 0x04, 0x00, 0x00, 0xe8, 0x02, 0x00, 0x00, 0x1f, 0x15, 0x02, 0x04, 0x7a, 0x00, 0x00, 0x03, 0xd2, 0x01, 0xe0, 0xfb, 0x92, 0x01, 0xb2, 0x01, 0xe0, 0xfe }; /* * ivt: * 0: b.l clear_ipend * 4: b.l clear_ipend * 8: b.l clear_ipend * c: b.l clear_ipend * 10: b.l clear_ipend * 14: b.l clear_ipend * 18: b.l clear_ipend * 1c: b.l clear_ipend * 20: b.l clear_ipend * 24: b.l clear_ipend * 28: b.l clear_ipend * clear_ipend: * 2c: movfs r0, ipend * 30: orr r0, r0, r0 * 32: beq 1f * 34: rti * 36: b clear_ipend * 1: * 38: gie * 3a: idle * 3c: b 1b */ static int ecore_soft_reset(struct epiphany_dev *epiphany, unsigned coreid) { int i; uint32_t status; bool fail; /* HACK: Depends on that we do an explicit mmap of Epiphany addresses space * in device.c:mmap_chip_mem() */ volatile void *core = (void *) (coreid << 20); /* (TODO: Wait for dma to complete??? istead of cancelling transfers ???) */ /* Assumes no Write-after-Write or Read-after-Write hazards */ if (!(reg_read(core, MMR_DEBUGSTATUS) & 1)) { /* WARN: No clean previous exit */ reg_write(core, MMR_DEBUGCMD, 1); } /* Wait for external fetch */ fail = true; for (i = 0; i < 1000; i++) { if (!(reg_read(core, MMR_DEBUGSTATUS) & 2)) { fail = false; break; } usleep(10); } if (fail) { /* warnx("%s(): (%d) stuck. Full system reset needed", __func__, coreid); */ return -EIO; } if (reg_read(core, MMR_DMA0STATUS) & 7) /* warnx("%s(): (%d) DMA0 NOT IDLE", __func__, coreid); */ ; if (reg_read(core, MMR_DMA1STATUS) & 7) /* warnx("%s(): (%d) DMA1 NOT IDLE", __func__, coreid); */ ; /* Abort DMA transfers */ if (ecore_soft_reset_dma(epiphany, coreid)) return -EIO; /* Disable timers */ reg_write(core, MMR_CONFIG, 0); reg_write(core, MMR_ILATCL, ~0); reg_write(core, MMR_IMASK, 0); reg_write(core, MMR_IRET, 0x2c); /* clear_ipend */ reg_write(core, MMR_PC, 0x2c); /* clear_ipend */ memcpy((void *) core, soft_reset_payload, sizeof(soft_reset_payload)); /* Set active bit */ reg_write(core, MMR_FSTATUS, 1); reg_write(core, MMR_DEBUGCMD, 0); fail = true; for (i = 0; i < 10000; i++) { if (!reg_read(core, MMR_IPEND) && !reg_read(core, MMR_ILAT) && !(reg_read(core, MMR_STATUS) & 1)) { fail = false; break; } usleep(10); } if (fail) { /* warnx("%s: (%d) Not idle", __func__, coreid); */ return -EIO; } /* Reset regs, excluding DMA (already done above) */ if (ecore_reset_regs(epiphany, coreid, false)) return -EIO; ecore_clear_sram(epiphany, coreid); return 0; } static inline struct epiphany_dev *to_epiphany_dev(struct dev *dev) { return container_of(dev, struct epiphany_dev, dev); } int epiphany_soft_reset(struct team *team, int start, int size) { int ret; struct epiphany_dev *epiphany = to_epiphany_dev(team->dev); for (unsigned i = (unsigned) start; i < (unsigned) (start + size); i++) { unsigned row = 32 + i / 4; unsigned col = 8 + i % 4; unsigned coreid = (row << 6) | col; ret = ecore_soft_reset(epiphany, coreid); if (ret) return ret; } return 0; } static void lookup_symbols(const void *file, size_t file_size, struct symbol_info *tbl, size_t tbl_size) { uint8_t *elf; unsigned shnum; Elf32_Ehdr *ehdr; Elf32_Phdr *phdr; Elf32_Shdr *shdrs, *shdr, *shdr_symstrtab; const char *strtab; elf = (uint8_t *) file; ehdr = (Elf32_Ehdr *) &elf[0]; phdr = (Elf32_Phdr *) &elf[ehdr->e_phoff]; shdr = (Elf32_Shdr *) &elf[ehdr->e_shoff]; shdrs = (Elf32_Shdr *) &elf[ehdr->e_shoff]; shnum = ehdr->e_shnum; for (shnum = ehdr->e_shnum; shnum; shnum--, shdr++) { Elf32_Sym *sym; const char *sym_strtab; int symbol_count; if (shdr->sh_type != SHT_SYMTAB) continue; if (!shdr->sh_size || !shdr->sh_entsize) continue; shdr_symstrtab = &shdrs[shdr->sh_link]; sym_strtab = &elf[shdr_symstrtab->sh_offset]; symbol_count = shdr->sh_size / shdr->sh_entsize; sym = (Elf32_Sym *) &elf[shdr->sh_offset]; for (; symbol_count; symbol_count--, sym++) { const char *sym_name = &sym_strtab[sym->st_name]; if (sym->st_shndx == SHN_UNDEF) continue; switch (ELF32_ST_BIND(sym->st_info)) { default: continue; case STB_GLOBAL: case STB_WEAK: ; } for (unsigned i = 0; i < tbl_size; i++) { if (strcmp(sym_name, tbl[i].name) != 0) continue; if (tbl[i].found && ELF32_ST_BIND(tbl[i].sym.st_info) == STB_GLOBAL) continue; tbl[i].found = true; memcpy(&tbl[i].sym, sym, sizeof(*sym)); } } } } static inline bool is_passed_by_value(const p_arg_t *arg) { return (arg->is_primitive && arg->size <= 8); } static void setup_function_args(struct epiphany_dev *epiphany, unsigned coreid, int argn, const p_arg_t *args, uint32_t function_addr, uint32_t *loader_args_ptr) { unsigned rel_row = (coreid - 0x808) >> 6; unsigned rel_col = (coreid - 0x808) & 0x3f; unsigned rel_coreid = (rel_row << 2) + rel_col; struct loader_args *loader_args = &epiphany->ctrl->loader_args[rel_coreid]; uint32_t *regs = &loader_args->r0; unsigned arg = 0; /* TODO: Obviously this doesn't work with more than one core */ uint8_t *argstackp = (uint8_t *) epiphany->ctrl; /* Set cores's args ptr */ *loader_args_ptr = (uint32_t) loader_args; memset(loader_args, 0 , sizeof(*loader_args)); loader_args->function_ptr = function_addr; /* Set up register args */ for (unsigned reg = 0; reg < 4 && arg < argn; /* nop */) { if (is_passed_by_value(&args[arg])) { if (reg & 1 && args[arg].size > 4) { reg++; if (reg > 2) break; memcpy(&regs[reg], args[arg].ptr, args[arg].size); arg++; /* No more register slots */ break; } else { memcpy(&regs[reg], args[arg].ptr, args[arg].size); reg += args[arg].size > 4 ? 2 : 1; arg++; } } else { /* Argument is passed by reference */ /* No need to copy arg if it's already accessible by core */ if (is_valid_addr((uint32_t) args[arg].ptr, coreid) && /* On the off chance the host ptr is in the first 1M */ !is_local((uint32_t) args[arg].ptr)) { regs[reg] = (uint32_t) args[arg].ptr; } else { argstackp -= (args[arg].size + 7) & (~7); memcpy(argstackp, args[arg].ptr, args[arg].size); regs[reg] = (uint32_t) argstackp; } reg++; arg++; } } /* No stack spill */ if (arg == argn) return; uint32_t ptrslot[P_RUN_MAX_ARGS]; /* Copy rest of args that are passed by reference onto argsstack */ for (unsigned i = arg; i < argn; i++) { /* Don't need to copy arguments passed by value */ if (is_passed_by_value(&args[i])) continue; /* No need to copy arg if it's already accessible by core */ if (is_valid_addr((uint32_t) args[i].ptr, coreid) && /* On the off chance the host ptr is in the first 1M */ !is_local((uint32_t) args[i].ptr)) { ptrslot[i] = (uint32_t) args[i].ptr; } else { argstackp -= (args[i].size + 7) & (~7); memcpy(argstackp, args[i].ptr, args[i].size); ptrslot[i] = (uint32_t) argstackp; } } /* Allocate the maximum possible size for actual stack arguments, * 8 bytes / entry. */ argstackp -= (argn - arg) * 8; loader_args->stack_spill_ptr = (uint32_t) argstackp; for (; arg < argn; arg++) { if (is_passed_by_value(&args[arg])) { if (args[arg].size > 4) argstackp = (uint8_t *) (((uintptr_t) &argstackp[7]) & (~7)); memcpy(argstackp, args[arg].ptr, args[arg].size); argstackp += (args[arg].size + 3) & (~3); } else { memcpy(argstackp, &ptrslot[arg], 4); argstackp += 4; } } /* Align size on 8-byte boundary, */ argstackp = (uint8_t *) (((uintptr_t) &argstackp[7]) & (~7)); loader_args->stack_spill_size = (uint32_t) ((uintptr_t) argstackp - loader_args->stack_spill_ptr); } /* Data needed by device (e-lib and crt0) */ static int set_core_config(struct epiphany_dev *epiphany, unsigned coreid, const void *file, size_t file_size, int argn, const p_arg_t *args, const char *function) { uint8_t *corep = (uint8_t *) (coreid << 20); uint8_t *nullp = (uint8_t *) 0; e_group_config_t *e_group_config; e_emem_config_t *e_emem_config; uint32_t *loader_flags, *loader_args_ptr; uint32_t function_addr; char *function_plt; { size_t function_len = strlen(function); function_plt = alloca(function_len + sizeof("@PLT")); memcpy(&function_plt[function_len], "@PLT", sizeof("@PLT")); } struct symbol_info tbl[] = { { .name = "e_group_config" }, { .name = "e_emem_config" }, { .name = "__loader_args_ptr" }, { .name = "__loader_flags" }, { .name = function }, { .name = function_plt }, }; lookup_symbols(file, file_size, tbl, ARRAY_SIZE(tbl)); /* Check everything except PLT entry (only exists when compiled w/ -fpic) */ for (unsigned i; i < ARRAY_SIZE(tbl) - 1; i++) { if (!tbl[i].found) return -ENOENT; /* ???: Should perhaps only allow local addresses */ if (!is_valid_addr(tbl[i].sym.st_value, coreid)) return -EINVAL; } e_group_config = is_local(tbl[0].sym.st_value) ? (e_group_config_t *) &corep[tbl[0].sym.st_value] : (e_group_config_t *) &nullp[tbl[0].sym.st_value]; e_emem_config = is_local(tbl[1].sym.st_value) ? (e_emem_config_t *) &corep[tbl[1].sym.st_value] : (e_emem_config_t *) &nullp[tbl[1].sym.st_value]; loader_args_ptr = is_local(tbl[2].sym.st_value) ? (uint32_t *) &corep[tbl[2].sym.st_value] : (uint32_t *) &nullp[tbl[2].sym.st_value]; loader_flags = is_local(tbl[3].sym.st_value) ? (uint32_t *) &corep[tbl[3].sym.st_value] : (uint32_t *) &nullp[tbl[3].sym.st_value]; /* Prefer PLT entry */ /* No need to adjust function address if it's local */ if (tbl[5].found && is_valid_addr(tbl[5].sym.st_value, coreid)) function_addr = tbl[5].sym.st_value; else function_addr = tbl[4].sym.st_value; /* No trivial way to emulate workgroups??? Pretend each core is its own * separate group for now. */ e_group_config->objtype = E_EPI_GROUP; e_group_config->chiptype = E_E16G301; /* TODO: Or E_64G501 */ e_group_config->group_id = coreid; e_group_config->group_row = coreid >> 6; e_group_config->group_col = coreid & 0x3f; e_group_config->group_rows = 1; e_group_config->group_cols = 1; e_group_config->core_row = 0; e_group_config->core_col = 0; e_group_config->alignment_padding = 0xdeadbeef; e_emem_config->objtype = E_EXT_MEM; e_emem_config->base = 0x8e000000; setup_function_args(epiphany, coreid, argn, args, function_addr, loader_args_ptr); // Instruct crt0 .bss is cleared and that we've provided custom args. *loader_flags = LOADER_BSS_CLEARED_FLAG | LOADER_CUSTOM_ARGS_FLAG; return 0; } int epiphany_load(struct team *team, struct prog *prog, int start, int size, int flags, int argn, const p_arg_t *args, const char *function) { int rc; int fd; struct stat st; void *file; struct epiphany_dev *epiphany = to_epiphany_dev(team->dev); /* TODO: File opening should be done in p_load() */ fd = open(prog->path, O_RDONLY); if (fd == -1) return -errno; if (fstat(fd, &st) == -1) { close(fd); return -errno; } file = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (file == MAP_FAILED) { close(fd); return -errno; } if (!is_epiphany_exec_elf((Elf32_Ehdr *) file)) { rc = -EINVAL; goto out; } for (unsigned i = (unsigned) start; i < (unsigned) (start + size); i++) { unsigned row = 32 + i / 4; unsigned col = 8 + i % 4; unsigned coreid = (row << 6) | col; rc = process_elf(file, epiphany, coreid); if (rc) goto out; rc = set_core_config(epiphany, coreid, file, st.st_size, argn, args, function); if (rc) goto out; } out: munmap(file, st.st_size); close(fd); return rc; } void epiphany_start(struct team *team, int start, int size, int flags) { struct epiphany_dev *epiphany = to_epiphany_dev(team->dev); for (unsigned i = (unsigned) start; i < (unsigned) (start + size); i++) { unsigned row = 32 + i / 4; unsigned col = 8 + i % 4; unsigned coreid = (row << 6) | col; volatile uint32_t *corep = (uint32_t *) (coreid << 20); reg_write(corep, MMR_ILATST, 1); } } int epiphany_reset_system(struct epiphany_dev *epiphany) { if (ioctl(epiphany->epiphany_fd, E_IOCTL_RESET)) return -errno; return 0; } <file_sep>/src/base/devices/epiphany/device.c #include <string.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdbool.h> #include "config.h" #include "dev_epiphany.h" #include "ctrl.h" #include "pal_base.h" #include <common.h> #include "../../pal_base_private.h" #include "loader.h" /* TODO: Obtain from device-tree or ioctl() call */ #define ERAM_SIZE (32*1024*1024) #define ERAM_BASE 0x8e000000 #define ERAM_PHY_BASE 0x3e000000 #define CHIP_BASE 0x80800000 #define CHIP_ROWS 4 #define CHIP_COLS 4 #define CORE_MEM_REGION 0x00100000 #define EPIPHANY_DEV "/dev/epiphany/mesh0" struct core_map_table { off_t base; size_t size; } static core_map_table[] = { { 0x00000, 0x08000 }, /* SRAM */ { 0xf0000, 0x01000 }, /* MMR */ }; static inline struct epiphany_dev *to_epiphany_dev(struct dev *dev) { return container_of(dev, struct epiphany_dev, dev); } /* Returns 0 on success */ static int mmap_eram(struct dev *dev) { struct epiphany_dev *dev_data = to_epiphany_dev(dev); long page_size; unsigned npages; unsigned char dummy; uintptr_t addr; int ret; page_size = sysconf(_SC_PAGESIZE); if (0 > page_size) return -EINVAL; /* Check that address space is not already mapped */ addr = ERAM_BASE; npages = ERAM_SIZE / page_size; for (int i = 0; i < npages; i++, addr += page_size) { again: ret = mincore((void *) addr, page_size, &dummy); if (ret == -1 && errno == EAGAIN) goto again; /* This is what we want (page is unmapped) */ if (ret == -1 && errno == ENOMEM) continue; return -ENOMEM; } dev_data->eram = mmap((void *) ERAM_BASE, ERAM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, dev_data->epiphany_fd, ERAM_BASE); if (dev_data->eram == MAP_FAILED) return -errno; return 0; } /* Returns 0 on success */ static int mmap_chip_mem(struct dev *dev) { struct epiphany_dev *dev_data = to_epiphany_dev(dev); void *ptr; long page_size; unsigned npages; unsigned char dummy; uintptr_t addr; int row, col, region; int ret; page_size = sysconf(_SC_PAGESIZE); if (0 > page_size) return -EINVAL; /* Check that address space is not already mapped */ for (row = 0; row < CHIP_ROWS; row++) { for (col = 0; col < CHIP_COLS; col++, addr += CORE_MEM_REGION) { for (region = 0; region < ARRAY_SIZE(core_map_table); region++) { addr = CHIP_BASE + (64 * row + col) * CORE_MEM_REGION + core_map_table[region].base; npages = core_map_table[region].size / page_size; for (int i = 0; i < npages; i++, addr += page_size) { again: ret = mincore((void *) addr, page_size, &dummy); if (ret == -1 && errno == EAGAIN) goto again; /* This is what we want (page is unmapped) */ if (ret == -1 && errno == ENOMEM) continue; return -ENOMEM; } } } } /* Allow R/W access to core regions */ /* Do 1:1 mapping w/ chip for now */ addr = CHIP_BASE; for (row = 0; row < CHIP_ROWS; row++) { for (col = 0; col < CHIP_COLS; col++, addr += CORE_MEM_REGION) { for (region = 0; region < ARRAY_SIZE(core_map_table); region++) { addr = CHIP_BASE + (64 * row + col) * CORE_MEM_REGION + core_map_table[region].base; ptr = mmap((void *) addr, core_map_table[region].size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, dev_data->epiphany_fd, addr); if (ptr == MAP_FAILED) return -errno; if (ptr != (void *) addr) return -ENOMEM; } } } dev_data->chip = (void *) CHIP_BASE; return 0; } static int dev_early_init(struct dev *dev) { int ret; struct epiphany_dev *dev_data = to_epiphany_dev(dev); dev_data->epiphany_fd = open(EPIPHANY_DEV, O_RDWR | O_SYNC); if (dev_data->epiphany_fd == -1) return -errno; ret = mmap_eram(dev); if (ret) return ret; ret = mmap_chip_mem(dev); if (ret) return ret; dev_data->initialized = true; return 0; } static void dev_late_fini(struct dev *dev) { struct epiphany_dev *dev_data = to_epiphany_dev(dev); if (!dev_data->initialized) return; munmap(dev_data->eram, ERAM_SIZE); /* TODO: unmap chip here */ close(dev_data->epiphany_fd); dev_data->initialized = false; } static p_dev_t dev_init(struct dev *dev, int flags) { int err; struct epiphany_dev *epiphany = to_epiphany_dev(dev); if (!epiphany->initialized) return p_ref_err(ENODEV); /* Be idempotent if already initialized. It might be a better idea to * return EBUSY instead */ if (epiphany->opened) return dev; epiphany->ctrl = (struct epiphany_ctrl_mem *) CTRL_MEM_EADDR; #if 0 /* I don't think this is needed here, soft reset on load should be enough */ err = epiphany_reset_system(epiphany); if (err) return p_ref_err(-err); #endif /* Clear control structure */ memset(epiphany->ctrl, 0 , sizeof(*epiphany->ctrl)); epiphany->opened = true; return dev; } static void dev_fini(struct dev *dev) { struct epiphany_dev *data = to_epiphany_dev(dev); if (data->opened) { data->opened = false; } } static int dev_query(struct dev *dev, int property) { if (!dev) return -EINVAL; switch (property) { case P_PROP_TYPE: return P_DEV_EPIPHANY; case P_PROP_NODES: return 16; case P_PROP_TOPOLOGY: return 2; case P_PROP_ROWS: return 4; case P_PROP_COLS: return 4; case P_PROP_PLANES: return 4; case P_PROP_CHIPROWS: return 4; case P_PROP_CHIPCOLS: return 4; case P_PROP_SIMD: return 1; case P_PROP_MEMSIZE: return 32768; case P_PROP_MEMBASE: return 0x80800000; case P_PROP_VERSION: return 0xdeadbeef; case P_PROP_MEMARCH: case P_PROP_WHOAMI: return -ENOSYS; } return -EINVAL; } static struct team *dev_open(struct dev *dev, struct team *team, int start, int count) { struct epiphany_dev *data = to_epiphany_dev(dev); /* Only support opening entire chip for now */ if (start != 0 || count != 16) return p_ref_err(EINVAL); /* Open was done in init */ if (!data->opened) return p_ref_err(EBADF); team->dev = dev; return team; } static int dev_run(struct dev *dev, struct team *team, struct prog *prog, const char *function, int start, int size, int argn, const p_arg_t *args, int flags) { int err; int i; struct epiphany_dev *epiphany = to_epiphany_dev(dev); if (start < 0 || size <= 0) return -EINVAL; /* Assume we have entire chip for now */ if (16 < start + size) return -EINVAL; if (!epiphany->opened) return -EBADF; err = epiphany_soft_reset(team, start, size); if (err) { /* WARN: soft reset failed */ return err; } err = epiphany_load(team, prog, start, size, flags, argn, args, function); if (err) return err; /* Mark as scheduled */ for (i = start; i < start + size; i++) epiphany->ctrl->status[i] = STATUS_SCHEDULED; epiphany_start(team, start, size, flags); return 0; } static int dev_wait(struct dev *dev, struct team *team) { unsigned i; bool need_wait = true; struct epiphany_dev *data = to_epiphany_dev(dev); while (true) { need_wait = false; for (i = 0; i < 16; i++) { switch (data->ctrl->status[i]) { case STATUS_SCHEDULED: /* TODO: Time out if same proc is in scheduled state too long. * If program does not start immediately something has gone * wrong. */ case STATUS_RUNNING: need_wait = true; break; case STATUS_NONE: case STATUS_DONE: default: continue; } } if (!need_wait) break; /* Don't burn CPU. Need HW/Kernel support for blocking wait */ usleep(1000); } return 0; } static void *dev_map_member(struct team *team, int member, unsigned long offset, unsigned long size) { /* HACK */ unsigned coreid, row, col; uintptr_t addr; if (member < 0 || 15 < member) return NULL; if (offset >= (1 << 20) || (offset + size) > (1 << 20)) row = member / 4; col = member % 4; coreid = 0x808 + (row << 6 | col << 0); addr = coreid << 20 | offset; return (void *) addr; } static int dev_unmap(struct team *team, void *addr) { /* HACK */ return 0; } static struct dev_ops epiphany_dev_ops = { .init = dev_init, .fini = dev_fini, .query = dev_query, .open = dev_open, .run = dev_run, .wait = dev_wait, .early_init = dev_early_init, .late_fini = dev_late_fini, .map_member = dev_map_member, .unmap = dev_unmap, }; struct epiphany_dev __pal_dev_epiphany = { .dev = { .dev_ops = &epiphany_dev_ops, }, }; <file_sep>/src/base/devices/devices.h #pragma once #if ENABLE_DEV_EPIPHANY #include "epiphany/dev_epiphany.h" #endif #if ENABLE_DEV_GRID /* TODO */ #endif #if ENABLE_DEV_SMP /* TODO */ #endif #if ENABLE_DEV_FPGA /* TODO */ #endif #if ENABLE_DEV_GPU /* TODO */ #endif #if ENABLE_DEV_DEMO /* TODO */ #endif <file_sep>/src/base/devices/epiphany/dev_epiphany.h #pragma once #include "pal_base.h" #include "../../pal_base_private.h" #include "ctrl.h" struct epiphany_args_header { uint32_t nargs; uint32_t __pad1; uint32_t size[P_RUN_MAX_ARGS]; } __attribute__((packed)); struct epiphany_dev { struct dev dev; /* Generic device */ bool initialized; /* True if dev_early_init() succeeded */ bool opened; /* Opened by user call to p_init() */ struct epiphany_ctrl_mem *ctrl; struct epiphany_args_header *args_header; int epiphany_fd; /* File descriptor for epiphany device */ void *eram; void *chip; }; extern struct epiphany_dev __pal_dev_epiphany; <file_sep>/src/base/devices/epiphany/epiphany-abi.h #pragma once #include <stdint.h> /* Structs needed by e-lib */ #ifndef __epiphany__ /* These are already defined by e-lib.h */ typedef enum { E_NULL = 0, E_EPI_PLATFORM = 1, E_EPI_CHIP = 2, E_EPI_GROUP = 3, E_EPI_CORE = 4, E_EXT_MEM = 5, E_MAPPING = 6, E_SHARED_MEM = 7 } e_objtype_t; typedef enum { E_E16G301 = 0, E_E64G401 = 1, } e_chiptype_t; typedef struct { uint32_t objtype; // 0x28 uint32_t chiptype; // 0x2c uint32_t group_id; // 0x30 uint32_t group_row; // 0x34 uint32_t group_col; // 0x38 uint32_t group_rows; // 0x3c uint32_t group_cols; // 0x40 uint32_t core_row; // 0x44 uint32_t core_col; // 0x48 uint32_t alignment_padding; // 0x4c } __attribute__((packed)) e_group_config_t; typedef struct { uint32_t objtype; // 0x50 uint32_t base; // 0x54 } __attribute__((packed)) e_emem_config_t; #endif struct loader_args { uint32_t r0; uint32_t r1; uint32_t r2; uint32_t r3; uint32_t function_ptr; uint32_t function_ptr_hi32; // upper 32 bits uint32_t stack_spill_size; // (8-byte aligned) uint32_t __pad; // Reserved, must be 0 uint32_t stack_spill_ptr; // (8-byte aligned) uint32_t stack_spill_ptr_hi32; // upper 32 bits } __attribute__((packed)); // Loader flags for crt0 #define LOADER_BSS_CLEARED_FLAG 1 #define LOADER_CUSTOM_ARGS_FLAG 2 #if 0 /* Already defined by e-hal.h */ #ifdef __epiphany__ extern const e_group_config_t e_group_config; extern const e_emem_config_t e_emem_config; #endif #endif <file_sep>/src/base/boilerplate.c #include "config.h" #include <stdio.h> #include <string.h> #include <pal.h> #include <common.h> #include "pal_base_private.h" #include "devices/devices.h" #if __epiphany__ #include "devices/epiphany/ctrl.h" #include <e-lib.h> #endif __attribute__((constructor)) void __pal_init(void); __attribute__((destructor)) void __pal_fini(void); /* Defining the table this way statically compile time depends on devs being in * the right order. If we We could do this in the constructor * too... */ #ifdef __epiphany__ struct pal_global __pal_global __attribute__ ((section (".data_bank0"))) = { #else struct pal_global __pal_global = { #endif .devs = { NULL, #if ENABLE_DEV_EPIPHANY &__pal_dev_epiphany.dev, #else NULL, #endif #if ENABLE_DEV_GRID &__pal_dev_grid.dev, #else NULL, #endif #if ENABLE_DEV_SMP &__pal_dev_smp.dev, #else NULL, #endif #if ENABLE_DEV_FPGA &__pal_dev_fpga.dev, #else NULL, #endif #if ENABLE_DEV_GPU &__pal_dev_gpu.dev, #else NULL, #endif #if ENABLE_DEV_DEMO &__pal_dev_demo.dev, #else NULL, #endif }, .teams_head = NULL, .teams_tail = NULL, .progs_head = NULL, .progs_tail = NULL, /* We might want to use another PRNG for some platforms */ #ifdef TINYMT32_H .random = { .status = {0}, .mat1 = 0, .mat2 = 0, .tmat = 0 } #endif }; static void early_device_init() { for (int i = 0; i < ARRAY_SIZE(__pal_global.devs); i++) { struct dev *dev = __pal_global.devs[i]; if (dev && dev->dev_ops->early_init) dev->dev_ops->early_init(dev); } } static void late_device_fini() { for (int i = 0; i < ARRAY_SIZE(__pal_global.devs); i++) { struct dev *dev = __pal_global.devs[i]; if (dev && dev->dev_ops->late_fini) dev->dev_ops->late_fini(dev); } } __attribute__((constructor)) void __pal_init() { #if __epiphany__ /* Platform specifics should probably go into separate file ? */ // Assume team is entire chip const uint32_t coreid = e_get_coreid(); const uint32_t row = e_group_config.core_row; const uint32_t col = e_group_config.core_col; const uint32_t rank = row * e_group_config.group_cols + col; struct epiphany_ctrl_mem *ctrl = (struct epiphany_ctrl_mem *) CTRL_MEM_EADDR; __pal_global.rank = rank; ctrl->status[rank] = STATUS_RUNNING; #else __pal_global.rank = 0; early_device_init(); #endif } __attribute__((destructor)) void __pal_fini() { #if __epiphany__ // Assume team is entire chip const uint32_t coreid = e_get_coreid(); const uint32_t row = e_group_config.core_row; const uint32_t col = e_group_config.core_col; const uint32_t rank = row * e_group_config.group_cols + col; struct epiphany_ctrl_mem *ctrl = (struct epiphany_ctrl_mem *) CTRL_MEM_EADDR; ctrl->status[rank] = STATUS_DONE; #else struct team *team, *next_team; struct prog *prog, *next_prog; team = __pal_global.teams_head; while (team) { next_team = team->next; // team_fini(team); team = next_team; } prog = __pal_global.progs_head; while (prog) { next_prog = prog->next; // prog_fini(prog); prog = next_prog; } late_device_fini(); memset(&__pal_global, 0, sizeof(struct pal_global)); #endif }
82bd87247bbb33ebb38186fc8bfc2a5f6f572adb
[ "C" ]
13
C
ipapadop/pal
44daa6e3b87dbd5d31455d69e3ea1922f84ca409
b6549cb4ea984d328318bc08a23db48c0176074b
refs/heads/main
<repo_name>marcusslee95/stephen-grider-advanced-react-and-redux<file_sep>/testing/src/components/__tests__/CommentBox.test.js import React from 'react' import CommentBox from "../CommentBox"; import { mount } from 'enzyme' import Root from '../../Root' let commentBoxcomponent beforeEach(() => { commentBoxcomponent = mount( <Root> <CommentBox/> </Root>);//we'll be initializing a new Comment Box component to work w/before ever test so just pulled it out here }) afterEach(() => { commentBoxcomponent.unmount() //we'll also be removing the CommentBox component from the JSDom after every test -> because unlike shallow and static render methods, fullDom render method actually puts component into the JSDom -> if we don't do this every test we'll be adding another instance of the CommentBox component to the DOM -> that will make tests slower and might interfere with tests }) it('shows a textarea and a button', () => { // console.log(commentBoxcomponent.debug()) // console.log(commentBoxcomponent.find('textarea').debug()) expect(commentBoxcomponent.find('textarea').length).toEqual(1) //so find method can not only find childComponents but also normal html elements inside a component expect(commentBoxcomponent.find('button').length).toEqual(2) }) describe('tests that test the textarea', () => { beforeEach(() => { commentBoxcomponent.find('textarea') //select the textarea html element .simulate('change', { target:{ value: 'new comment' } }) //triggers a fake change event - aka. user typing something into textarea - and passes custom object in 2nd argument as argument to event handler function causing setState to be called w/value we provided commentBoxcomponent.update() //even thogh the event handler gets called eventually resulting in state changing and component getting updated w/new value in textArea... -> this happens asynchronously aka. it's non blocking -> so there's no guarantee the state has changed and component has updated w/new textarea value by this line. So we'll tell component 'yo component I know you want to change state and then whenever you wanna you'll rerender the component but I'm tellying you nuh-uh you're going to rerender w/new state now!" so that when I write my expectation below I'll know the textarea value will be of that new state // console.log(commentBoxcomponent.debug()) }) it('shows whatever user typed into textarea', () => { expect(commentBoxcomponent.find('textarea').props().value).toEqual('new comment') //props() just gets the attributes of the textarea html element in 1 object }) it('clears out the textarea after user submits form', () => { //to know that we clear out textarea.... we have to first populate textarea w/some text -> we can check if it really is populated -> this way when we try to clear out textarea after submit we can see if textarea was really cleared out //Part1: populating -> just copy paste poulating code from above test -> already executed in beforeEach expect(commentBoxcomponent.find('textarea').props().value).toEqual('new comment') //Part2: trigger submit event and see if that causes clearout to happen commentBoxcomponent.find('form') .simulate('submit') commentBoxcomponent.update() //also force rerender of component -> otherwise no guarantee component has been rerendered by this line -> rerender doesn't happen right after state changes but whenever component wants to // console.log(commentBoxcomponent.find('form').debug()) expect(commentBoxcomponent.find('textarea').props().value).toEqual('') }) }) <file_sep>/README.md # stephen-grider-advanced-react-and-redux originally started to practice react testing before interviews <file_sep>/testing/src/actions/types.js //this file stores all the action types as const variables so we can't make typo errors const SAVE_COMMENT = 'SAVE COMMENT' const FETCH_COMMENTS = 'FETCH COMMENTS' export { SAVE_COMMENT, FETCH_COMMENTS } <file_sep>/testing/src/components/__tests__/App.test.js //Will write tests using enzyme -> using react testing library would be ideal because that's gaining steam while there are signs enzyme loosing steam (i.e. Airbnb created enzyme but now letting open source maintain it + they're using more and more of react testing library + enzyme doesnt have an adapter for react v17 available yet which is why i'm using an unofficial version) but that would mean I'd have to figure out react testing library way to do everything grider does which might take too much time (esp given tight window until interview) import React from 'react' import App from '../App' import CommentBox from '../CommentBox' import CommentList from '../CommentList' import { shallow } from 'enzyme' let shallowVersionOfTheComponent; beforeEach(() => {//code that runs before every test shallowVersionOfTheComponent = shallow(<App/>) //renders everything inside the App component besides child components inside it (though it does create a bookmark / placeholder saying a child component does exist here) -> returns an object of the stuff we rendered }) it('shows the CommentBox component', () => { expect(shallowVersionOfTheComponent.find(CommentBox).length).toEqual(1) }) it('shows the CommentList component', () => { expect(shallowVersionOfTheComponent.find(CommentList).length).toEqual(1) }) //No testing library version of the 1st test I created // it('shows the CommentBox component', () => { // const div = document.createElement('div') //create a div element in JSDom // ReactDOM.render(<App/>, div) //put App component inside div we just created -> now that we have our App component on the JSDom in code below we can check to see if it is working liked we want it to // console.log(div.innerHTML) // // console.log(div) // expect(div.innerHTML).toContain('Comment Box') //assumes knowledge about another component - that CommentBox component has 'Comment Box' inside it - tests like these are to be avoided // ReactDOM.unmountComponentAtNode(div) // deletes App component from div element -> for cleanup // }) //React testing library version of the 1st test I created // import { render, screen } from '@testing-library/react' //gives us stuff that makes it easier to write tests // import '@testing-library/jest-dom'; //gives us cool matching functions like toContainElement // it ('shows the CommentBox component', () => { // // https://testing-library.com/docs/react-testing-library/example-intro // render(<App/>) // "The render method renders a React element into the DOM." // // https://testing-library.com/docs/react-testing-library/example-intro/ // const app = screen.getByTestId('app') //I'm guessing screen is the dom // console.log(app.innerHTML) // const commentBox = screen.getByTestId('comment-box') // console.log(commentBox.innerHTML) // // https://www.npmjs.com/package/@testing-library/jest-dom#tocontainelement // expect(app).toContainElement(commentBox) // })<file_sep>/testing/src/reducers/commentsReducer.js //supposed to be in charge of the state for comments //what is a reducer at it's core -> a function that takes an action object and then change state according to it import { SAVE_COMMENT, FETCH_COMMENTS } from '../actions/types' const commentsReducer = (state = [], action) => { //state does not refer to the entire global state object but just the part of state that the reducer is in charge of changing -> which in this case is comments switch (action.type){ case SAVE_COMMENT: // console.log(state, action) return [...state, action.payload] //add comment to comments propperty / variable in state case FETCH_COMMENTS: // console.log(action.payload) const arrOfNameStrings = action.payload.data.map(commentObject => commentObject.name) //take each commentObject in the array and replace it with the name string in that object so at the end you won't have arr of objects but arr of strings // console.log(arrOfNameStrings) return [...state, ...arrOfNameStrings] default: return state } } export default commentsReducer<file_sep>/testing/src/components/CommentBox.js import React, { Component } from 'react' import { connect } from 'react-redux' import { saveComment, fetchComments } from '../actions' import axios from 'axios' class CommentBox extends Component { state = { comment: '' } handleChange = (event) => {//event will refer to the change event aka. user typed in something this.setState({comment: event.target.value}) } handleSubmit = (event) => {//event will refer to the submit event event.preventDefault() //submit event by default causes page to reload -> we don't want that //TODO - change state-> add this new comment to commentList this.props.saveComment(this.state.comment) //remember all the action creators and state are passed as props into the component this.setState({comment: ''}) //after user submits a comment clear out the text area } render() { return ( <div> <form onSubmit={this.handleSubmit}> <h4>Add a Comment</h4> <textarea onChange={this.handleChange} value={this.state.comment}/> <div><button>Submit Comment</button></div> </form> {/* <button onClick={async () => {//b4: my version of FETCH_COMMENTS that doesn't use asynchronous action creator by sending the network request before calling action creator and passing in the response into the action creator const response = await axios.get('https://jsonplaceholder.typicode.com/comments') // console.log(response.data) const arrOfNameStrings = response.data.map(commentObject => commentObject.name) //take each commentObject in the array and replace it with the name string in that object so at the end you won't have arr of objects but arr of strings // console.log(arrOfNameStrings) this.props.fetchComments(arrOfNameStrings) }}>Fetch Comments</button> */} <button className='fetch-comments' onClick={this.props.fetchComments}>Fetch Comments</button> </div> ) } } export default connect(null, //we don't need anything from global state { saveComment, fetchComments } //all you want is the ability to change the state which you need to create actions for aka. objects that reducers receive and use to change state )(CommentBox) // //version i used to work w/react testing library // const CommentBox = () => { // return ( // <div data-testid="comment-box"> // Comment Box // </div> // ) // } // export default CommentBox<file_sep>/testing/src/reducers/__tests__/commentsReducer.test.js import commentsReducer from "../commentsReducer" import { SAVE_COMMENT} from '../../actions/types' it ('handles actions of type SAVE_COMMENT aka. takes comment user submitted and adds it to list of comments in global state', () => {//testing a reducer is ez -> it's a function -> just provide some input and see if it results in output you'd expect - in this case it's the changed state you'd expect const action = { type: SAVE_COMMENT, payload: 'New Comment' } const newStateJustThePartCommentsReducerIsInChargeOfAkaComments = commentsReducer([], action) //just setting comments state to be aempty arrray so that when add new comment just have to check if comments state is [theNewComment] expect(newStateJustThePartCommentsReducerIsInChargeOfAkaComments).toEqual(['New Comment']) }) it('doesnt error when action of unknown type happens', () => { const newStateJustThePartCommentsReducerIsInChargeOfAkaComments = commentsReducer([], {type: 'rando'}) //obviously this line of code shouldn't error expect(newStateJustThePartCommentsReducerIsInChargeOfAkaComments).toEqual([]) //since should have gone through default case where we just return previous state of comments })<file_sep>/testing/src/actions/index.js //this file stores all the action creators related to comments aka. all the functions that take some input and create an action out of it import axios from 'axios' import { SAVE_COMMENT, FETCH_COMMENTS } from './types' const saveComment = (commentUserSubmitted) => { //an action is just a object w/a type and a payload that will be received by reducers to change state return { type: SAVE_COMMENT, payload: commentUserSubmitted } } // //B4: my non async action creator // const fetchComments = (arrOfStringsWeGetBackFromApi) => { // return { // type: FETCH_COMMENTS, // payload: arrOfStringsWeGetBackFromApi // } // } // //AFTER: my non async action creator // const fetchComments = async () => { // const response = await axios.get('https://jsonplaceholder.typicode.com/comments') // // console.log(response.data) // return { // type: FETCH_COMMENTS, // payload: response // } // } const fetchComments = () => { //my async way didn't work.... weird const response = axios.get('http://jsonplaceholder.typicode.com/comments'); return { type: FETCH_COMMENTS, payload: response }; } export { saveComment, fetchComments } //not exporting saveComment as default because what if I want to export more actionCreators
27bd2fa8ded9ad895b75259e2e62d4d21e289102
[ "JavaScript", "Markdown" ]
8
JavaScript
marcusslee95/stephen-grider-advanced-react-and-redux
7838790d2509470b13a8c3186495f0c6923bd555
368871cd1320ed3866ffd74fc8b05ea43435dbd4
refs/heads/main
<file_sep><?php #echo "working"; $host="localhost"; $user="root"; $password=""; $db="emandi"; $mysqli = mysqli_connect($host,$user,$password,$db); # mysqli_select_db($db); if(isset($_POST['username'])){ $uname=$_POST['username']; $password=$_POST['password']; $rpass = $_POST['rpassword']; $sql1="SELECT * FROM `civilian` where aadhar_no='".$uname."' limit 1"; $sql2="SELECT * FROM `farmer` where aadhar_no ='".$uname."' limit 1"; $sql3="SELECT * FROM `retailler` where aadhar_no='".$uname."' limit 1"; $sql4="SELECT * FROM `wholeseller` where aadhar_no='".$uname."' limit 1"; $result1=mysqli_query($mysqli,$sql1); $result2=mysqli_query($mysqli,$sql2); $result3=mysqli_query($mysqli,$sql3); $result4=mysqli_query($mysqli,$sql4); #$row = mysqli_fetch_array($result); $row1 = mysqli_num_rows($result1); $row2 = mysqli_num_rows($result2); $row3 = mysqli_num_rows($result3); $row4 = mysqli_num_rows($result4); #$total = $row[0]; #echo $result; if($rpass != $password){ echo '<script>alert("repeat password does not match")</script>'; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else if($row1 == 1){ $sql1="UPDATE `civilian` set password = '".$password."' WHERE aadhar_no ='".$uname."'"; mysqli_query($mysqli,$sql1); echo '<script>alert("password changed ")</script>';; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else if($row2 == 1){ $sql1="UPDATE `farmer` set password = '".$password."' WHERE aadhar_no ='".$uname."'"; mysqli_query($mysqli,$sql1); echo '<script>alert("password changed ")</script>';; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else if($row3 == 1){ $sql1="UPDATE `retailler` set password = '".$password."' WHERE aadhar_no ='".$uname."'"; mysqli_query($mysqli,$sql1); echo '<script>alert("password changed ")</script>';; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else if($row4 == 1){ $sql1="UPDATE `wholeseller` set password = '".$password."' WHERE aadhar_no ='".$uname."'"; mysqli_query($mysqli,$sql1); echo '<script>alert("password changed ")</script>';; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else { echo '<script>alert("record does not exists")</script>';; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); } } ?><file_sep><?php #echo "working"; $host="localhost"; $user="root"; $password=""; $db="emandi"; $mysqli = mysqli_connect($host,$user,$password,$db); # mysqli_select_db($db); if(isset($_POST['username'])){ $uname=$_POST['username']; $password=$_POST['password']; $sql1="SELECT * FROM `civilian` where username='".$uname."'AND password='".$password."' limit 1"; $sql2="SELECT * FROM `farmer` where username='".$uname."'AND password='".$password."' limit 1"; $sql3="SELECT * FROM `retailler` where username='".$uname."'AND password='".$password."' limit 1"; $sql4="SELECT * FROM `wholeseller` where username='".$uname."'AND password='".$password."' limit 1"; $result1=mysqli_query($mysqli,$sql1); $result2=mysqli_query($mysqli,$sql2); $result3=mysqli_query($mysqli,$sql3); $result4=mysqli_query($mysqli,$sql4); #$row = mysqli_fetch_array($result); $row1 = mysqli_num_rows($result1); $row2 = mysqli_num_rows($result2); $row3 = mysqli_num_rows($result3); $row4 = mysqli_num_rows($result4); #$total = $row[0]; #echo $result; if($row1 == 1 || $row2 == 1 ||$row3 == 1 ||$row4 == 1 ){ //echo '<script>alert("succesfully logged in")</script>'; echo "<script> window.location.assign('role.html'); </script>"; //header('Location: login.html'); mysqli_free_result($result); mysqli_close($mysqli); exit(); } else{ echo '<script>alert("Incorrect username or password")</script>';; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); //header('Location: login.html'); exit(); } } ?><file_sep># E-mandi It’s an electronic vegetable market making the vegetable market more convenient for the use of civilian and even to keep the transparency in the whole market system from retailer to the whole seller. The main objective of this project is build a website which will help civilian, retailer, whole seller and even the framer to get the best from his inputs. With the help of this a farmer will be able to know the best value for his vegetable and will not be fooled by the marketers. It will help in keeping the transparency between the whole seller and retailer and also the selection for civilian for his requirement become easy .so this will help in eradicating black marketing and inflation. Users of the system: - director-admin. - user-farmer, whole seller, retailer, civilian - computer professionals - any other users ## Functional components of the project: * People can register to have a complete view of the market including the pricing of vegetables, pricing difference between whole seller and retailer, actual pricing stated by government, best possible retailer in the market for civilian in his area,revenue generated last month and a period of time * Non registered can have a overview of these facilities excluding some. * Feedback or complaint facilities directly connected to government bodies to keep a view on the market .but mentioning the unique id of the complainer * Admin should be able to see all record from any users. * The records shown for selling should be available in a format of Quantity name, Quantity available, price * The database should be robust enough to handle all the online transactions which will be happening * Help section for those who are unable to understand the website or any of its part. <file_sep><?php $rname = $_POST['name']; $runame = $_POST['username']; $rpass = $_POST['<PASSWORD>']; $ral = $_POST['aadhar_no']; $rgen = $_POST['gender']; $rsname = $_POST['shopname']; $rphone = $_POST['phone']; $radd = $_POST['address']; $rrole = $_POST['role']; /* 0 - male 1 - female 1 - civillian 2 - farmer 3 - retailler 4 - wholeseller */ $host="localhost"; $user="root"; $password=""; $db="emandi"; $mysqli = mysqli_connect($host,$user,$password,$db); # mysqli_select_db($db); if(isset($rrole)){ if($rrole == 2){ $sql="SELECT * FROM `farmer` where aadhar_no ='".$ral."' limit 1"; $result=mysqli_query($mysqli,$sql); $row = mysqli_num_rows($result); if($rgen == 0){ $rgen = "male"; }else{ $rgen = "female"; } $insert="INSERT INTO `farmer` values ('".$ral."','".$runame."','".$rpass."','".$rname."','".$radd."','".$rphone."','".$rgen."')"; if($row == 1){ echo '<script>alert("record exists")</script>'; echo "<script> window.location.assign('register.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else{ mysqli_query($mysqli,$insert); echo '<script>alert("registered")</script>'; echo "<script> window.location.assign('role.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); } }else if ( $rrole == 1){ //echo "working 1"; $sql="SELECT * FROM `civilian` where aadhar_no ='".$ral."' limit 1"; $result=mysqli_query($mysqli,$sql); $row = mysqli_num_rows($result); if($rgen == 0){ $rgen = "male"; }else{ $rgen = "female"; } $insert="INSERT INTO `civilian` values ('".$ral."','".$runame."','".$rpass."','".$rname."','".$radd."','".$rphone."','".$rgen."')"; if($row == 1){ echo '<script>alert("record exists")</script>'; echo "<script> window.location.assign('register.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else{ mysqli_query($mysqli,$insert); echo '<script>alert("registered")</script>'; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); } }else if($rrole == 3){ //echo "working 3"; $sql="SELECT * FROM `retailler` where aadhar_no ='".$ral."' limit 1"; $result=mysqli_query($mysqli,$sql); $row = mysqli_num_rows($result); if($rgen == 0){ $rgen = "male"; }else{ $rgen = "female"; } $insert="INSERT INTO `retailler` values ('".$ral."','".$runame."','".$rpass."','".$rname."','".$radd."','".$rphone."','".$rgen."','".$rsname."')"; if($row == 1){ echo '<script>alert("record exists")</script>'; echo "<script> window.location.assign('register.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else{ mysqli_query($mysqli,$insert); echo '<script>alert("registered")</script>'; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); } }else if ($rrole == 4){ //echo "working 4"; $sql="SELECT * FROM `wholeseller` where aadhar_no ='".$ral."' limit 1"; $result=mysqli_query($mysqli,$sql); $row = mysqli_num_rows($result); if($rgen == 0){ $rgen = "male"; }else{ $rgen = "female"; } $insert="INSERT INTO `wholeseller` values ('".$ral."','".$runame."','".$rpass."','".$rname."','".$radd."','".$rphone."','".$rgen."','".$rsname."')"; if($row == 1){ echo '<script>alert("record exists")</script>'; echo "<script> window.location.assign('register.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); }else{ mysqli_query($mysqli,$insert); echo '<script>alert("registered")</script>'; echo "<script> window.location.assign('login.html'); </script>"; mysqli_free_result($result); mysqli_close($mysqli); exit(); } } }else{ echo '<script>alert("choose role")</script>'; echo "<script> window.location.assign('register.html'); </script>"; } ?><file_sep><?php //echo "working"; $cnum = $_POST['lastname']; $cmonth = $_POST['month']; $ccvv = $_POST['cvv']; $chname = $_POST['firstname']; $camount = $_POST['rs']; $bname = $_POST['bank']; $cardt = $_POST['card']; $date = date('d F, Y (l)'); $time = date('h:i:s A'); $status = 0; //echo $date , $time; $host="localhost"; $user="root"; $password=""; $db="emandi"; $mysqli = mysqli_connect($host,$user,$password,$db); $sql="SELECT * FROM `transaction`;"; $result=mysqli_query($mysqli,$sql); $id = mysqli_num_rows($result) + 1; //echo $id; mysqli_free_result($result); $insert="INSERT INTO `transaction` values ('".$id."','".$date."','".$time."','".$status."','".$cardt."','".$bname."','".$cnum."','".$cmonth."','".$ccvv."','".$chname."','".$camount."')"; mysqli_query($mysqli,$insert); echo '<script>alert("Transaction Under Review ! Redirecting to homepage")</script>'; echo "<script> window.location.assign('start.html'); </script>"; mysqli_close($mysqli); exit(); ?><file_sep><?php //echo "working"; $rname = $_POST['name']; $ral = $_POST['aadhar_no']; $rphone = $_POST['phone']; $rmes = $_POST['message']; $host="localhost"; $user="root"; $password=""; $db="emandi"; $mysqli = mysqli_connect($host,$user,$password,$db); $sql="INSERT INTO `complaints` values ('".$rname."','".$ral."','".$rphone."','".$rmes."')"; mysqli_query($mysqli,$sql); echo "<script> window.location.assign('index.html'); </script>"; mysqli_close($mysqli); exit(); ?><file_sep><?php //echo "working"; $ad = $_POST['Addhaar']; $name = $_POST['name']; $category = $_POST['category']; $item = $_POST['bank1']; $ph = $_POST['Mobile']; $addr = $_POST['Address']; $price = $_POST['Price']; $quan = $_POST['Quantity']; /* <option value="dem">Select your crop name</option> <option value="sbi">Rice</option> <option value="hdfc">Wheat</option> <option value="BoB">Maize</option> <option value="PNB">Lentils</option> <option value="icici">Onion</option> <option value="other">Potato</option> <option value="dem">Turmeric</option> <option value="sbi">Apple</option> <option value="hdfc">Grapes</option> <option value="BoB">Bringal</option> <option value="PNB">Orange</option> <option value="icici">Cauliflower</option> <option value="other">Cashew</option> */ if($item == "sbi"){ $item = "Rice"; }else if($item == "hdfc"){ $item = "Wheat"; }else if($item == "Bob"){ $item = "Maize"; }else if($item == "PNB"){ $item = "Lentils"; }else if($item == "icici"){ $item = "Onion"; }else if($item == "other"){ $item = "Potato"; } $host="localhost"; $user="root"; $password=""; $db="emandi"; $mysqli = mysqli_connect($host,$user,$password,$db); $sql="SELECT * FROM `transaction`;"; $result=mysqli_query($mysqli,$sql); $id = mysqli_num_rows($result) + 1; //echo $id; mysqli_free_result($result); $insert="INSERT INTO `add_request` values ('".$ad."','".$name."','".$category."','".$item."','".$ph."','".$addr."','".$price."','".$quan."')"; mysqli_query($mysqli,$insert); echo '<script>alert("Wait untill Admin reviews your request")</script>'; echo "<script> window.location.assign('start.html'); </script>"; mysqli_close($mysqli); exit(); ?>
c94c910bc9fa49865d34f99ae45d9d924253318d
[ "Markdown", "PHP" ]
7
PHP
karan0046/e-mandi
0d0420cb19e32c175bcee68b3d351833e9b8196e
c6e34568a688524cd3801863582e59d51ecaaca6
refs/heads/master
<repo_name>yangzod/NumberPuzzle<file_sep>/V1.0/JS/pageControl.js document.onkeydown=function(e) { e=window.event||e; var keycode=e.keyCode||e.which; if(e.ctrlKey||e.altKey||e.shiftKey||keycode>=112&&keycode<=123) { if(window.event) { try { e.keyCode=0; } catch(e){} e.returnValue=false; } else { e.preventDefault(); } } }//禁用f5<file_sep>/V1.0/changePassword.php <?php require('requires.php'); ?> <?php $db=new Database($smarty); $db->connect(); $usr=new User($smarty,$db,$_POST['id'],$_POST['oldpassword']); if($usr->validate()) { $usr->changePassword($_POST['password']); report($smarty,'login.php',"修改成功!");//如果用户输入原密码正确则允许修改密码 } else { report($smarty,'changePasswordIndex.php',"原密码错误!");//否则不允许修改,并向用户报错 } ?><file_sep>/V1.0/timeOut.php <?php require('requires.php'); ?> <?php session_start(); $gm=$_SESSION['gm']; $smarty->assign('gm',$gm); $smarty->display('endGame.tpl');//如果用户超时则直接结束游戏 ?><file_sep>/V1.0/registerIndex.php <?php require('requires.php'); ?> <?php $smarty->display('registerIndex.tpl'); ?><file_sep>/V1.0/report.php <?php function report($s,$action,$report)//向用户报告信息 { $s->assign('action',$action); $s->assign('report',$report); $s->display('report.tpl'); } ?><file_sep>/V1.0/changePasswordIndex.php <?php require('requires.php'); ?> <?php $smarty->display('changePasswordIndex.tpl'); ?><file_sep>/V1.0/login.php <?php require('requires.php'); ?> <?php $smarty->display('login.tpl'); ?><file_sep>/V1.0/index.php <?php require('requires.php'); ?> <?php $smarty->display('index.tpl'); ?><file_sep>/V1.0/JS/rePassword.js function rePassword(field) { if((!(field.password.value==null||field.password.value==""))&&(!(field.repassword.value==null||field.repassword.value==""))) { if(field.password.value==field.repassword.value) { return true; } else { return false; } } else { return false; } }//判断两次输入密码是否相同<file_sep>/V1.0/Database.php <?php class Database { private $link,$smarty; function Database($s) { $this->smarty=$s; } function connect()//链接数据库 { $this->link=mysql_connect("127.0.0.1","root",""); mysql_select_db("numberpuzzle",$this->link); mysql_query("SET NAMES utf8"); } function querySQL($sql)//执行sql语句 { $result=mysql_query($sql,$this->link); return $result; } } ?><file_sep>/V1.0/requires.php <?php require('smartyProject.php'); $smarty=new smartyProject;//应用smarty require('report.php'); require('error.php'); require('Database.php'); require('User.php'); require('Game.php'); ?><file_sep>/V1.0/welcome.php <?php require('requires.php'); ?> <?php $db=new Database($smarty); $db->connect(); $usr=new User($smarty,$db,$_POST['id'],$_POST['password']); if($usr->validate()) { session_start(); $gm=new Game($usr); $gm->newLevel(); $usr->loadMsg(); $_SESSION['gm']=$gm; $smarty->assign('gm',$gm); $smarty->display('welcomeT.tpl');//如登录信息正确则开始游戏 } else { report($smarty,"index.php","错误的登录信息!");//登录信息错误则报错 } ?><file_sep>/V1.0/error.php <?php function error($errorInformation)//显示错误 { $smarty->assign('errorInformation',$errorInformation); $smarty->display('Error.tpl'); die();//报告致命错误 } ?><file_sep>/V1.0/SmartyProject.php <?php require('Smarty/libs/Smarty.class.php'); class SmartyProject extends Smarty { function __construct() { parent::__construct(); $this->template_dir='templates/'; //指定模板存放目录 $this->config_dir='config/';//指定配置文件目录 $this->cache_dir='Smarty/cache/';//指定缓存目录 $this->compile_dir='Smarty/templates_c/';//指定编译后的模板目录 } } ?><file_sep>/V1.0/User.php <?php class User { private $password=0,$time=0,$smarty=0,$database=0; public $userid=0,$score=0,$level=1; function User($s,$db,$id,$psw)//构造user对象 { $this->smarty=$s; $this->database=$db; $this->userid=$id; $this->password=$psw; } function validate()//判定该用户能否正常登陆 { $this->database->connect(); $user=$this->database->querySQL("SELECT * FROM usersdb where `id`='$this->userid' AND `password`='$this->password'"); $flag=false; $msg=0; while($msg=mysql_fetch_row($user)) { $flag=true; return $msg; } if(!$flag) { return $flag; } } function exist()//判定该用户是否存在 { $this->database->connect(); $user=$this->database->querySQL("SELECT * FROM usersdb where `id`='$this->userid'"); $flag=false; while($msg=mysql_fetch_row($user)) { $flag=true; return true; } if(!$flag) { return false; } } function save()//将用户信息存入数据库 { if($this->validate()) { $this->database->querySQL("DELETE FROM `usersdb` WHERE `id`='$this->userid'"); } $this->database->querySQL("INSERT INTO `usersdb`(`id`, `password`, `score`, `level`, `time`) VALUES ('$this->userid','$this->password','$this->score','$this->level','$this->time')"); } function setScore($s,$l)//设置得分 { $this->score=$s; $this->level=$l; $this->time=time(); } function changePassword($psw)//修改密码 { if($this->validate()) { $this->database->querySQL("UPDATE `usersdb` SET `password`='<PASSWORD>' WHERE `id`='$this->userid'"); } $this->password=$psw; } function loadMsg()//从数据库中读取用户信息 { $msg=$this->validate(); if($msg) { $this->userid=$msg[0]; $this->password=$msg[1]; $this->score=$msg[2]; $this->level=$msg[3]; $this->time=$msg[4]; } } function renew() { $this->score=0; $this->level=1; $this->time=0; $this->save(); } } ?><file_sep>/V1.0/inGame.php <?php require('requires.php'); ?> <?php session_start(); $gm=$_SESSION['gm']; if(isset($_POST['answer'])) { if(!$gm->input($_POST['answer'])) { $smarty->assign('gm',$gm); $smarty->display('endGame.tpl');//如果用户输入错误则结束游戏 die(); } } $smarty->assign('gm',$gm); $smarty->display('inGame.tpl');//否则继续游戏 ?><file_sep>/V1.0/Game.php <?php class Equation { private $answer=0; public $left=0,$right=0,$result=0; function Equation()//游戏中显示的等式 { srand(time()); $this->left=rand(11,99); $this->right=rand(11,99); $temp=rand(1,100); if($temp<20) { $this->result=$this->left+$this->right; } else { $this->result=rand(22,198); }//随机生成等式 if($this->result==$this->left+$this->right) { $this->answer=true; } else { $this->answer=false; }//判断等式是否正确 } function input($ipt) { if($ipt==$this->answer) { return true; } else { return false; } }//检测用户判断 } ?> <?php class Game { private $score,$level=0,$preTime; public $player,$eqt,$timeLeft; function Game($plr) { $this->player=$plr; $this->player->renew(); } function newLevel()//升级 { if($this->level<15) { $this->timeLeft=18-$this->level; } else { $this->timeLeft=3; }//计算剩余时间 $this->preTime=time(); $this->level=$this->level+1; $this->eqt=new Equation(); } function input($ipt)//用户输入答案,并判断答案是否正确 { $rst=$this->eqt->input($ipt); $scoreToAdd=$this->level*($this->timeLeft-(time()-$this->preTime)); if($scoreToAdd<0) { $scoreToAdd=0; }//算出应加的分数 if($rst) { $this->newLevel(); $this->score=$this->score+$scoreToAdd; }//如果正确则升级 else { $this->level=0; } $this->player->setScore($this->score,$this->level); $this->player->save();//存储用户信息 return $rst;//返回判断结果 } }<file_sep>/V1.0/register.php <?php require('requires.php'); ?> <?php $db=new Database($smarty); $db->connect(); $usr=new User($smarty,$db,$_POST['id'],$_POST['password']); if($usr->exist()) { report($smarty,'registerIndex.php',"该用户已存在!");//如该用户存在则报错 } else { $usr->save(); report($smarty,'login.php',"注册成功!");//否则即成功注册 } ?>
6554b8cf4407fde375de12bbbfceeb616e392d59
[ "JavaScript", "PHP" ]
18
JavaScript
yangzod/NumberPuzzle
9455bbe08ff4f72d0eab7d7fd549b7ee67444c66
3804ae950956cba41b38a8c64c5946cabadf5121
refs/heads/main
<repo_name>maxim19295/BanzayClient<file_sep>/src/components/pages/Basket/BasketTable/TotalCell/TotalCell.jsx export const TotalCell = ({total}) =>{ return <td>{total} грн</td> }<file_sep>/src/components/pages/Main/PostsBlock/PostsBlock.jsx import { faCalendarAlt } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { useEffect } from 'react'; import {connect} from 'react-redux'; import { getPostsAC } from '../../../../redux/postsReducer'; import p from './PostsBlock.module.css'; const PostsBlock = ({postList,getPosts}) =>{ useEffect(()=>{getPosts()},[]); if(postList){const Posts = postList.map(el=><div> <img src={el.picture} alt='postPic'/> <div className={p.header}>{el.title}</div> <div className={p.date}><FontAwesomeIcon icon={faCalendarAlt}/>{el.date}</div> <div>{el.text}</div> </div>) return <div className={p.postBlock}> <div> <div className='content'>Ежедневная доставка вкуснейших суши и роллов с 11:00 до 22:00</div> </div> <div className='content'> {Posts} </div> </div>} else{ return null; } } const mapStateToProps = (state) =>({ ...state.posts }); const mapDispatchToProps = (dispatch) =>({ getPosts: ()=>dispatch(getPostsAC()) }) export default connect(mapStateToProps,mapDispatchToProps)(PostsBlock);<file_sep>/src/components/pages/AccountPage/AccountBlock/ConsolePage/ConsolePage.jsx export const ConsolePage = () =>{ return <div> ConsolePage </div> }<file_sep>/src/components/pages/Requests/RequestsList/RequestBlock/RequestBlock.jsx import { useState } from "react"; import { Request } from "../Request/Request" import r from './RequestBlock.module.css'; export const RequestBlock = ({request,getCommentsHandler}) =>{ const handleClick = () =>{ if(show){ setShow(false); } else{ setShow(true); getCommentsHandler(request.n_request); } } const [show,setShow] = useState(false); return <div className={r.requestBlock}> <Request autor={request.autor} date={request.str_time} text={request.content}/> <button onClick={handleClick}>{show ? 'Скрыть' : 'Показать'} комментарии</button> { (request.comments && show) && request.comments.map((el,index)=><div key={index} className={r.commentBlock}> <Request autor={el.autor} date={el.str_time} text={el.content}/> </div>)} </div> }<file_sep>/src/components/Header/Header.jsx import { NavLink } from "react-router-dom" import h from './Header.module.css'; import './../../App.css'; export const Header = () =>{ return <div id={h.header}> <div className='content'> <div><NavLink to='/'>Заказы принимаем с 11:00 до 22:00!</NavLink></div> <div className={h.phones}> <div> <a href='tel:+380937257955'>(093) 725-79-55</a> </div> <div> <a href='tel:+380684257655'>(068) 425-76-55</a> </div> <div> <a href='tel:+380662358855'>(066) 235-88-55</a> </div> </div> </div> </div> }<file_sep>/src/components/pages/AccountPage/AccountBlock/DetailsPage/DetailsPage.jsx export const DetailsPage = () =>{ return <div> DetailsPage </div> }<file_sep>/src/components/Footer/FooterPic/FooterPic.jsx import sushi_footer from '../../../assets/sushi-footer.jpg'; export const FooterPic = () =>{ return <div> <img src={sushi_footer} alt='sushi footer'/> </div> }<file_sep>/src/redux/basketReducer.js const GET_BASKET = 'GET_BASKET'; const initState = { basket: null } const basket = [ { id: 1, title: 'Roll s ugrem', price: 666, quantity: 1 }, { id: 3, title: 'Roll s lososem', price: 248, quantity: 4 } ]; export const basketReducer = (state = initState, action) =>{ switch(action.type){ case GET_BASKET: return {...state, basket: action.basket} default: return state; } } export const getBasketAC = () => ({type: GET_BASKET, basket});<file_sep>/src/components/pages/Main/SlidersBlock/SlidersBlock.jsx import { useEffect } from "react"; import { connect } from "react-redux" import { getSlidersAC } from "../../../../redux/sliderReducer"; import {Slider} from "./Slider/Slider"; const SlidersBlock = ({slidersArray,getSliders}) =>{ useEffect(()=>{getSliders()},[]); if(slidersArray){const sliders = slidersArray.map(el=><Slider title={el.title} items={el.array}/>); return <div> {sliders} </div>}else{ return null; } } const mapStateToProps = (state) =>({ ...state.sliders }); const mapDispatchToProps = (dispatch) =>({ getSliders: ()=>{dispatch(getSlidersAC())} }); export default connect(mapStateToProps,mapDispatchToProps)(SlidersBlock); <file_sep>/src/components/pages/Sign/WarningField/WarningField.jsx export const WarningField = ({type,message}) =>{ const color = type === 'error' ? 'red' : type==='success' ? 'green' : 'black'; return <div style={{color, fontWeight: 'bold'}}> {message} </div> }<file_sep>/src/App.js import { BrowserRouter, Redirect, Route, Switch } from "react-router-dom"; import { Banner } from "./components/Banner/Banner"; import {Body} from "./components/Body/Body"; import b from './components/Body/Body.module.css'; import { Footer } from "./components/Footer/Footer"; import { Header } from "./components/Header/Header"; import './App.css'; import GoodPage from "./components/pages/GoodPage/GoodPаge"; import Menu from "./components/pages/Menu/Menu"; import { useEffect } from "react"; import { getAuth } from "./redux/authReducer"; import { connect } from "react-redux"; import { AccountPage } from "./components/pages/AccountPage/AccountPage"; import * as axios from 'axios'; const App = (props) =>{ useEffect(()=>{ props.getAuth(); },[]) return (<BrowserRouter> <div className="app"> <Header/> <Banner isAuth={props.isAuth} credentials={props.credentials}/> <Switch> <Route path='/account' exact render={()=>{ if(props.isAuth===true){return <> <div id={b.bodyHeader}><div className='content'>мой аккаунт</div></div> <AccountPage auth={{...props}}/></>} else{ return <Redirect to='/sign' /> } }}/> <Route path='/account/:name' exact render={()=>{ if(props.isAuth===true){return <> <div id={b.bodyHeader}><div className='content'>мой аккаунт</div></div> <AccountPage auth={{...props}}/></>} else{ return <Redirect to='/sign' /> } }}/> <Route path='/:name' exact render={()=><Body auth={{...props}}/>}/> <Route path='/menu/:name' exact render={()=><Menu/>}/> <Route path='/menu/:name/:good_name' exact render={()=><GoodPage/>}/> <Route path='/' exact render={()=><Body/>}/> </Switch> <Footer/> </div> </BrowserRouter> ); } const mapStateToProps = (state) =>({ ...state.auth }); const mapDispatchToProps = (dispatch) =>({ getAuth: ()=>dispatch(getAuth()) }) export default connect(mapStateToProps,mapDispatchToProps)(App); <file_sep>/src/components/pages/Basket/BasketTable/BasketTable.jsx import {DeleteCell} from './DeleteCell/DeleteCell'; import {ImageCell} from './ImageCell/ImageCell'; import {PriceCell} from './PriceCell/PriceCell'; import {QuantityCell} from './QuantityCell/QuantityCell'; import {TitleCell} from './TitleCell/TitleCell'; import {TotalCell} from './TotalCell/TotalCell'; import {connect} from 'react-redux'; import b from './BasketTable.module.css'; import { getBasketAC } from '../../../../redux/basketReducer'; import { useEffect } from 'react'; const BasketTable = ({basket,getBasket}) =>{ useEffect(()=>{ getBasket(); }) if(basket){ let total = 0; for(let i =0; i<basket.length;i++){ total+=basket[i].quantity*basket[i].price; } const tableBody = basket.map( (el,index)=>{ return <tr height='60px'> <DeleteCell/> <ImageCell/> <TitleCell title={el.title}/> <PriceCell price={el.price}/> <QuantityCell quantity={el.quantity}/> <TotalCell total={el.price*el.quantity}/> </tr> } ); return <table className={b.basketTable}> <thead></thead> <tbody> <tr height="40px"> <th></th> <th></th> <th>Название</th> <th>Цена</th> <th>Количество</th> <th>Итого</th> </tr> {tableBody} <tr> <td colSpan={6}> <div style={{display: 'flex', flexDirection: 'row-reverse'}}> <div style={{padding: '5px 15px'}}> Всего: <b>{total} грн</b> </div> </div> </td> </tr> <tr><td colSpan={6}><div style={{display: 'flex', flexDirection: 'row-reverse'}}> <button onClick={()=>{}} style={{margin: 10, backgroundColor: 'red', border: 'none', color: 'white', padding: '5 15'}}>ОЧИСТИТЬ КОРЗИНУ</button></div></td></tr> <tr><td colSpan={6}><div style={{display: 'flex', flexDirection: 'row-reverse'}}><a href="#"><button onClick={()=>{}} style={{margin: 10, backgroundColor: 'orange', border: 'none', color: 'white', padding: '5 15'}}>ОФОРМИТЬ ЗАКАЗ</button></a></div></td></tr> </tbody> <tfoot></tfoot> </table> } else{ return null; } } let mapStateToProps = (state) =>({ ...state.basket }); let mapDispatchToProps = (dispatch) =>({ getBasket: ()=>{dispatch(getBasketAC())} }) export default connect(mapStateToProps,mapDispatchToProps)(BasketTable);<file_sep>/src/components/pages/Sign/Sign.jsx import SignIn from "./SignIn/SignIn" import SignUp from "./SignUp/SignUp" import s from './Sign.module.css'; export const Sign = () =>{ return <div className='content'> <div className={s.sign}> <SignIn/> <SignUp/> </div> </div> }<file_sep>/src/components/pages/Menu/Menu.jsx import b from '../../Body/Body.module.css'; import {connect} from 'react-redux'; import { useEffect } from 'react'; import { Redirect, useParams } from 'react-router-dom'; import GoodList from './GoodList/GoodList'; import { getMenuAC } from '../../../redux/menuReducer'; const Menu = ({menuList,getMenu}) =>{ const {name} = useParams(); useEffect(()=>{getMenu()},[]); if(menuList){ const matchEl = menuList.find(el=>el.to===name); if(matchEl){ return <div> <div id={b.bodyHeader}><div className='content'>{matchEl.title}</div></div> <GoodList menu={matchEl}/> </div>} else{ return <Redirect path='/'/> }} else{ return null; } } let mapStateToProps = (state) =>({ ...state.menu }); let mapDispatchToProps = (dispatch) =>({ getMenu: ()=>dispatch(getMenuAC()) }) export default connect(mapStateToProps,mapDispatchToProps)(Menu);<file_sep>/src/components/pages/Main/SlidersBlock/Slider/SliderItem/SliderItem.jsx import set from '../../../../../../72.jpg'; export const SliderItem = ({title,price}) =>{ return <div className='item'> <div><img src={set} /> <div>{title}</div> <div>{price} uah</div> </div> <div> <button>в корзину</button> </div> </div>}<file_sep>/src/components/Banner/Navigation/Navigation.jsx import { NavLink } from "react-router-dom"; import n from './Navigation.module.css'; export const Navigation = (props) =>{ const authLink = { title: props.isAuth===true ? props.credentials.username :'Войти', to: props.isAuth===true ? '/account' : '/sign' } const menu = [ { title: 'Главная', to: '/glavnaya' }, { title: 'Меню', to: { to: '/menu', submenu: [ { title: 'Суши', to: '/sushi' }, { title: 'Маки', to: '/maki' }, { title: 'Роллы', to: '/rolly' }, { title: 'Сеты', to: '/sety' }, { title: 'Салаты', to: '/salaty' }, { title: 'Напитки', to: '/napitki' } ]} }, { title: 'О нас', to: '/onas' }, { title: 'Доставка и оплата', to: '/dostavka' }, { title: 'Отзывы', to: '/otzyvy' }, { title: 'Корзина', to: '/korzina' }, authLink ]; return <div id={n.navigation}> {menu.map((el,index)=>{ const to = typeof el.to === 'string' ? el.to : '#'; const submenu = typeof el.to !== 'string' ? <div key={index} id={n.submenu}>{ el.to.submenu.map((subel,index)=>{ return <div key={index}><NavLink to={`${el.to.to}${subel.to}`}>{subel.title}</NavLink></div> }) }</div> : null; return <div key={index}><NavLink to={to}>{el.title}</NavLink> { submenu }</div> })} </div> }<file_sep>/src/components/pages/Basket/BasketTable/QuantityCell/QuantityCell.jsx import q from './QuantityCell.module.css'; export const QuantityCell = ({quantity}) =>{ return <td> <div style={{display: 'inline-block'}}> <input type="button" className={q.quantityEdit} value="-" onClick={()=>{}} disabled={false}/> <input className={q.quantityEdit} type="text" minLength="1" maxLength="3" value={quantity} onChange={()=>{}}/> <input type="button" className={q.quantityEdit} value="+" onClick={()=>{}} disabled={false}/> </div> </td> }<file_sep>/src/redux/sliderReducer.js const GET_SLIDERS = 'GET_SLIDERS'; const initState = { slidersArray: null } const slidersArray = [ { title: 'топ продаж', array: [ { id: 1, title: 'Set Kantri', price: '666', assortCode: 4 }, { id: 2, title: 'Set Fila XL', price: '666', assortCode: 4 }, { id: 3, title: 'Set Sity', price: '666', assortCode: 4 }, { id: 4, title: 'Set Filla', price: '666', assortCode: 4 }, { id: 5, title: 'Set s ugrem', price: '666', assortCode: 4 }, { id: 6, title: 'Set Kali', price: '666', assortCode: 4 }, { id: 7, title: 'Set Syrnyj', price: '666', assortCode: 4 }, { id: 8, title: 'Set hungry student', price: '666', assortCode: 4 }, { id: 9, title: 'felix red ikra', price: '666', assortCode: 1 }, { id: 10, title: 'felix perepil egg', price: '666', assortCode: 1 } ]}, { title: 'роллы', array: [ { id: 1, title: 'chees roll', price: '666', assortCode: 3 }, { id: 2, title: 'roll black dragon', price: '666', assortCode: 3 }, { id: 3, title: 'roll child', price: '666', assortCode: 3 }, { id: 4, title: 'roll ebi', price: '666', assortCode: 3 }, { id: 5, title: 'roll fila de luxe', price: '666', assortCode: 3 }, { id: 6, title: 'roll ssl losos', price: '666', assortCode: 2 }, { id: 7, title: 'roll s ugrem', price: '666', assortCode: 2 }, { id: 8, title: 'roll s tuncom', price: '666', assortCode: 2 }, { id: 9, title: 'roll kopch chiken', price: '666', assortCode: 2 }, { id: 10, title: 'roll avokado', price: '666', assortCode: 2 }]} ]; export const sliderReducer = (state=initState,action) =>{ switch(action.type){ case GET_SLIDERS: return {...state, slidersArray: action.slidersArray} default: return state; } } export const getSlidersAC = () => ({type: GET_SLIDERS, slidersArray});<file_sep>/src/components/pages/AccountPage/AccountBlock/AdminPages/JournalPage/JournalPage.jsx export const JournalPage = () =>{ return <div> JournalPage </div> }<file_sep>/src/components/pages/AccountPage/AccountBlock/OrdersPage/OrdersPage.jsx export const OrdersPage = () =>{ return <div> OrdersPage </div> }<file_sep>/src/components/pages/Basket/BasketTable/ImageCell/ImageCell.jsx import { NavLink } from 'react-router-dom'; import sushi from '../../../../../72.jpg'; export const ImageCell = () =>{ return <td> <NavLink to='/sushi'> <img src={sushi} alt="gfjfjjf" style={{height: 60}}/> </NavLink> </td> }<file_sep>/src/components/pages/Requests/NewRequestForm/NewRequestForm.jsx import n from './NewRequestForm.module.css'; export const NewRequestForm = () =>{ return <div className={n.formNewRequest}> <p className={n.header}>Оставить отзыв</p> <p>Ваш электронный адрес не будет опубликован.</p> <div> <textarea placeholder='Сообщение'/> </div> <div className={n.signatureNewRequest}> <div> <input id='name' type='text' placeholder='Имя'/> </div> <div> <input id='email' type='email' placeholder='E-mail (необязательно)'/> </div> </div> <div><button>отправить коментарий</button></div> </div> }<file_sep>/src/components/pages/About/About.jsx import a from './About.module.css'; export const About = () =>{ return <div id={a.about}> <div className='content'> <p>5 причин сделать заказ в суши-баре «Банзай»</p> <ol> <li> <span> Только свежие и качественные суши и роллы: </span> <ul> <li>Блюда готовят исключительно после получения заказа. Доставка происходит сразу после приготовления!</li> <li>Ваш заказ готовят на профессиональном оборудовании!</li> <li>Доставка суши производится в специальной термической упаковке, сохраняющей форму, температуру и вкусовые качества блюда!</li> <li>Наш шеф-повар постоянно работает над улучшением и доработкой меню, добавляя новые суши и роллы!</li> </ul> </li> <li> <span>Большие порции и точный вес:</span> <ul> <li>Наши суши и роллы ДЕЙСТВИТЕЛЬНО большие и весят РОВНО столько, сколько указано в меню!</li> <li>Начинки в наших суши и роллах ДЕЙСТВИТЕЛЬНО много!</li> <li>Соевый соус, имбирь, васаби и палочки прилагаются к каждому заказу БЕСПЛАТНО в установленном количестве!</li> </ul> </li> <li> <span>Удобство заказа:</span> <ul> <li>Сделать заказ суши на дом или в офис Вы можете, позвонив нам либо оставив заказ онлайн! Определиться с заказом Вам помогут опытные операторы!</li> <li>Доставка суши на дом или в офис производится в удобное для Вас время!</li> </ul> </li> <li>Бесплатная доставка суши в пределах Харькова (за исключением некоторых районов) при заказе свыше 220 гривен*! <p style={{fontWeight: 'normal', color: 'black', fontSize: '14px'}}>*бесплатная доставка осуществляется в период с 11.30 до 22.30</p></li> <li>Большое количество акций, позволяющих сэкономить на заказе Ваших любимых суши! </li> </ol> <p style={{fontSize: '14px', color: 'black'}}>С любовью к своим клиентам,<br/> Ваш «Банзай»</p> </div> </div> }<file_sep>/src/components/pages/AccountPage/AccountPage.jsx import { Redirect, useParams } from "react-router-dom" import { AccountBlock } from "./AccountBlock/AccountBlock"; import { AccountMenu } from "./AccountMenu/AccountMenu"; import ap from './AccountPage.module.css'; export const AccountPage = (props) =>{ const {name} = useParams(); if(props.auth.isAuth){ if(props.auth.isAuth!=='no_checked'){return <div><div className='content'><div className={ap.accountPage}> <AccountMenu/> <AccountBlock name={name}/> </div></div></div>} else{ return null; } } else{ return <Redirect to='/'/> } }<file_sep>/src/redux/authReducer.js import * as axios from 'axios'; const GET_AUTH_SUCCESS = 'GET_AUTH_SUCCESS'; const GET_AUTH_FAIL = 'GET_AUTH_FAIL'; const SIGN_UP = 'SIGN_UP'; const SIGN_IN = 'SIGN_IN'; const CHECK_MATCH_LOGIN = 'CHECK_MATCH_LOGIN'; const CHECK_MATCH_EMAIL = 'CHECK_MATCH_EMAIL'; export const authReducer = (state={isAuth: 'no_checked', isMatchLogin: 'no_checked', isMatchEmail: 'no_checked', credentials: {login: null, email: null, password: null}}, action)=>{ switch(action.type){ case GET_AUTH_SUCCESS: return {...state, isAuth: true, credentials: {...action.credentials}}; case GET_AUTH_FAIL: return {...state, isAuth: false} case SIGN_UP: return state; case SIGN_IN: return {...state, isAuth: true, credentials: action.credentials}; case CHECK_MATCH_LOGIN: return {...state, isMatchLogin: action.isMatch} case CHECK_MATCH_EMAIL: return {...state, isMatchEmail: action.isMatch} default: return state; } } const signInAC = (credentials) =>({type: SIGN_IN, credentials}); const checkMatchLoginAC = (isMatch) =>({type: CHECK_MATCH_LOGIN, isMatch}) const checkMatchEmailAC = (isMatch) =>({type: CHECK_MATCH_EMAIL, isMatch}) const getAuthSuccess = (credentials) =>({type: GET_AUTH_SUCCESS, credentials}) const getAuthFail = () => ({type: GET_AUTH_FAIL}); export const signIn = ({loginOrEmail, password}) =>(dispatch) =>{ axios.post(`/auth/login`,{loginOrEmail, password}).then(result=>{ if(result.status===200) { localStorage.setItem('user',(result.data.token)) dispatch(signInAC(result.data));} }) } export const signUp = ({username,email,password}) =>(dispatch)=>{ axios.post('/auth/register',{username,email,password}) } export const checkMatch = (checkField,value) =>(dispatch)=>{ switch(checkField){ case 'login':{ axios.get(`/match/login/${value}`).then( result=>{ result.data ? dispatch(checkMatchLoginAC(true)) : dispatch(checkMatchLoginAC(false)) } ) } break; case 'email':{ axios.get(`/match/email/${value}`).then( result=>{ result.data ? dispatch(checkMatchEmailAC(true)) : dispatch(checkMatchEmailAC(false)) } ) } default:{ } } } export const getAuth = () =>(dispatch) =>{ const authorization = localStorage.getItem('user'); axios.get('/auth/me',{headers: {authorization}}).then( result=>{ if(result.status===200){ dispatch(getAuthSuccess(result.data)); } else{ dispatch(getAuthFail()) } } ) }<file_sep>/src/components/pages/Requests/RequestsList/RequestList.jsx import { RequestBlock } from "./RequestBlock/RequestBlock" import {connect} from 'react-redux'; import { getComments, getRequestsForAll } from "../../../../redux/requestsReducer"; import { useEffect } from "react"; const RequestsList = ({requestList,getRequestsForAll,getComments}) =>{ const getCommentsHandler = (number) =>{ getComments(number); } useEffect(()=>{getRequestsForAll()},[]); if(requestList){ const Requests = requestList.map((el,index)=><RequestBlock key={index} getCommentsHandler = {getCommentsHandler} request={el}/>) return <div> {Requests} </div>} else { return null; } } const mapStateToProps = (state) =>({ ...state.requests }); const mapDispatchToProps = (dispatch) =>({ getRequestsForAll: ()=>{dispatch(getRequestsForAll())}, getComments: (number)=>{dispatch(getComments(number));} }) export default connect(mapStateToProps,mapDispatchToProps)(RequestsList);<file_sep>/src/components/Body/Body.jsx import { Redirect, Route, Switch, useParams } from "react-router-dom" import { About } from "../pages/About/About"; import { Main } from "../pages/Main/Main"; import {DeliveryInfo} from '../pages/DeliveryInfo/DeliveryInfo'; import {Requests} from '../pages/Requests/Requests'; import { Basket } from '../pages/Basket/Basket'; import b from './Body.module.css'; import '../../App.css' import { Sign } from "../pages/Sign/Sign"; import { AccountPage } from "../pages/AccountPage/AccountPage"; export const Body = ({auth}) =>{ const {name} = useParams(); if(name){ return <div> <Switch> <Route path='/glavnaya' render={()=><> <Main/> </>}/> <Route path='/onas' render={()=><> <div id={b.bodyHeader}><div className='content'>о нас</div></div> <About/> </>}/> <Route path='/dostavka' render={()=><> <div id={b.bodyHeader}><div className='content'>доставка и оплата</div></div> <DeliveryInfo/> </>}/> <Route path='/otzyvy' render={()=><> <div id={b.bodyHeader}><div className='content'>отзывы</div></div> <Requests/> </>}/> <Route path='/korzina' render={()=><> <div id={b.bodyHeader}><div className='content'>корзина</div></div> <Basket/> </>}/> {<Route path='/sign' render={()=>{ if(auth.isAuth!==true) {return <> <div id={b.bodyHeader}><div className='content'>войти/зарегистрироваться</div></div> <Sign/> </>} else {return <Redirect to = '/account'/>} }}/>} </Switch> </div>} else { return <div> <Main/> </div> } }<file_sep>/src/components/Footer/Footer.jsx import { Contacts } from "./Contacts/Contacts" import { FooterPic } from "./FooterPic/FooterPic" import { GetOrder } from "./GetOrder/GetOrder" import f from './Footer.module.css'; import './../../App.css'; export const Footer = () =>{ return <div id={f.footer}> <div className='content'> <Contacts/> <GetOrder/> <FooterPic/> </div> </div> }<file_sep>/src/components/Banner/Banner.jsx import { Logo } from "./Logo/Logo" import { Navigation } from "./Navigation/Navigation" import b from './Banner.module.css'; import './../../App.css'; export const Banner = (props) =>{ return <div id={b.banner}> <div className='content'> <Logo/> <Navigation {...props}/> </div> </div> }<file_sep>/src/components/pages/AccountPage/AccountBlock/AddressPage/AddressPage.jsx export const AddressPage = () =>{ return <div> AddressPage </div> }<file_sep>/src/components/Footer/Contacts/Contacts.jsx import f from './../Footer.module.css'; export const Contacts = () =>{ return <div className={f.list}> <p>Контакты</p> <div>Суши-бар «Банзай»</div> <div>Украина, г. Харьков</div> <div><EMAIL></div> </div> }<file_sep>/src/components/pages/Basket/Basket.jsx import BasketTable from './BasketTable/BasketTable'; export const Basket = () =>{ return <div className='content'> <BasketTable/> </div> }<file_sep>/src/components/pages/Basket/BasketTable/DeleteCell/DeleteCell.jsx import { faTimes, faTimesCircle } from "@fortawesome/free-solid-svg-icons" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import d from './DeleteCell.module.css'; export const DeleteCell = () =>{ return <td> <div style={{display: 'inline-block'}} title="Удалить из корзины"> <div className={d.delIcon}> <div className={d.in}> <FontAwesomeIcon icon={faTimesCircle}/> </div> <div className={d.out}> <FontAwesomeIcon icon={faTimes}/> </div> </div> </div> </td> }<file_sep>/src/redux/store.js import { basketReducer } from "./basketReducer"; import { menuReducer } from "./menuReducer"; import { requestReducer } from "./requestsReducer"; import { sliderReducer } from "./sliderReducer"; import thunk from 'redux-thunk'; const { combineReducers, createStore, applyMiddleware } = require("redux"); const { goodsReducer } = require("./goodsReducer"); const { postsReducer } = require("./postsReducer"); const { authReducer } = require("./authReducer"); const reducers = combineReducers({ goods: goodsReducer, posts: postsReducer, basket: basketReducer, requests: requestReducer, menu: menuReducer, sliders: sliderReducer, auth: authReducer }) export const store = createStore(reducers,applyMiddleware(thunk)); window.state=store;<file_sep>/src/components/pages/Requests/RequestsList/Request/Request.jsx import ava from '../../../../../assets/avatar.png'; import r from './Request.module.css'; export const Request = (props) => { return <div className={r.request}> <div className={r.ava}><img src={ava} alt='ava'/></div> <div className={r.textPanel}> <div className={r.infoPanel}> <div> <div>{props.autor} - </div> <div className={r.timeRequest}>{props.date}</div> </div> <div>Ответить</div> </div> <div>{props.text}</div> </div> </div> }<file_sep>/src/components/pages/Main/SlidersBlock/Slider/Slider.jsx import OwlCarousel from 'react-owl-carousel'; import 'owl.carousel/dist/assets/owl.carousel.css'; import 'owl.carousel/dist/assets/owl.theme.default.css'; import './CarouselOwnStyle.css'; import { SliderItem } from './SliderItem/SliderItem'; export const Slider = ({title,items}) =>{ const sliderItems = items.map(el=><SliderItem key={el.id} title={el.title} price={el.price}/>); return <div> <div className='content'> <div className='sliderHeader'>{title}</div> <OwlCarousel className="owl-theme" items={4} loop margin={10} nav> {sliderItems} </OwlCarousel> </div> </div> }<file_sep>/src/components/pages/Main/Main.jsx import m from './Main.module.css'; import best_sushi from '../../../assets/best_sushi.jpg'; import sushi from '../../../assets/tovary/sushi.png'; import maki from '../../../assets/tovary/maki.png'; import rolly from '../../../assets/tovary/rolly.png'; import sety from '../../../assets/tovary/sety.png'; import salaty from '../../../assets/tovary/salaty.png'; import napitki from '../../../assets/tovary/napitki.png'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import {faQuoteLeft } from '@fortawesome/free-solid-svg-icons'; import PostsBlock from './PostsBlock/PostsBlock'; import SlidersBlock from './SlidersBlock/SlidersBlock'; export const Main = () =>{ return <div> <div> <img src={best_sushi} alt='best_sushi' /> </div> <div className='content'> <div className={m.tovary}> <div> <img src={sushi}/> <p>Суши</p> </div> <div> <img src={maki}/> <p>Маки</p> </div> <div> <img src={rolly}/> <p>Роллы</p> </div> <div> <img src={sety}/> <p>Сеты</p> </div> <div> <img src={salaty}/> <p>Салаты</p> </div> <div> <img src={napitki}/> <p>Напитки</p> </div> </div> <div> </div> </div> <div className={m.requestsBlock}> <p>Что говорят наши клиенты</p> <div className='content'> <div> <FontAwesomeIcon icon={faQuoteLeft} color='gray' size='2x'/> заказывали 4 сета. муж поехал забрал. еще 10% скидка. суши просто бомба) ребята молодцы)) главное все свежее) теперь только в БАНЗАЙ будем заказывать)) СУШИ - БАР БАНЗАЙ: Спасибо за отзыв. Рады, что Вы остались довольны. Стараемся быть лучше, для Вас!) <br/> <NAME> 23:04:45 02-17-2018 </div> <div> <FontAwesomeIcon icon={faQuoteLeft} color='gray' size='2x'/> Вот уже как 2 года Вам не изменяем)))пер епробовали все сеты))очень очень вкусные суши, доставка быстрая, все аккуратно, только один минус - в меню нет супа, а так хотелось бы((. СУШИ - БАР БАНЗАЙ: Спасибо за отзыв. Рады, что Вы остаётесь с нами. Ваше предложение будет рассмотрено. <br/> <NAME> 18:29:31 01-30-2018 </div> <div> <FontAwesomeIcon icon={faQuoteLeft} color='gray' size='2x'/> Заказали сет голодный студент, спасибо большое это супер вкусно, быстро и очень удобно для салтовчан!!! Ещё и скидочка за самовывоз 10 процентов), получше чем в Якитории и в мафии , я довольна!!! СУШИ - БАР БАНЗАЙ: Спасибо за отзыв. Рады, что Вы остались довольны. Стараемся быть лучше, для Вас! <br/> <NAME> 15:08:31 02-02-2018 </div> </div> </div> <SlidersBlock/> <PostsBlock/> </div> }<file_sep>/src/redux/postsReducer.js import post1 from '../assets/discount.png'; import post2 from '../assets/bansai-sushi-na-dom-banzay.jpg'; import post3 from '../assets/domashnie-rolly-banzay.jpg'; const GET_POSTS = 'GET_POSTS'; const postList = [ { id: 1, title: 'акции от банзай суши', picture: post1, date: '2018-02-21', text: '1) Скидка ВСЕМ! Воспользуйтесь услугой «Самовывоз» и автоматически получите скидку 10% на всё меню. Заказы принимаются по телефону и через корзину сайта banzay.kh.ua. Забрать свои заказы Вы можете с Салтовки (ул. Героев труда 9, кафе на территории аз[...]' }, { id: 2, title: 'поздравление любимых клиенток с 8 марта', picture: post2, date: '2018-02-21', text: 'Суши-бар «Банзай» поздравляет своих любимых клиенток с 8 Марта! Только 08.03.2019 года — к каждому заказу на сумму свыше 500 гривен — ролл в подарок! Милые девушки, женщины, мамы! Коллектив суши-бара «Банзай» от всей души поздравляет вас с 8 Марта[...]' }, { id: 3, title: 'о пользе суши', picture: post3, date: '2018-02-21', text: 'История возникновения суши. Суши или суси, как их иногда называют, приобрели широкую популярность во всем мире с начала 1980-х годов. В нашей стране сегодня это блюдо любят и едят очень многие. Суши невозможно сравнить ни с одним рыбным блюдом русск[...]' } ]; const initState = { postList: null } export const postsReducer = (state=initState, action)=>{ switch(action.type){ case GET_POSTS: return {...state, postList: action.postList} default: return state; } } export const getPostsAC = () =>{ return {type: GET_POSTS, postList} }<file_sep>/src/redux/goodsReducer.js import * as axios from 'axios'; const GET_GOODS = 'GET_GOODS'; const initState = { goodList: null } const godList = [{ id: 1, title: 'Roll s ugrem', price: 666, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 3 }, { id: 2, title: 'Roll s lososem', price: 554, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 3 }, { id: 3, title: 'Sushi s kuricey', price: 455, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 1 }, { id: 4, title: 'Set fila XXL', price: 234, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 4 }, { id: 5, title: 'Maki Yellow dragon', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 2 }, { id: 6, title: 'Salat <NAME>', price: 663, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 5 }, { id: 7, title: 'baltika 9', price: 333, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 6 }, { id: 8, title: 'krusovice black', price: 333, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 6 }, { id: 9, title: 'sandora', price: 333, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 6 }, { id: 10, title: 'Salat oliv\'e', price: 428, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 5 }, { id: 11, title: '<NAME>', price: 663, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 5 }, { id: 12, title: '<NAME>', price: 663, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 5 }, { id: 13, title: '<NAME>', price: 333, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 6 }, { id: 14, title: 'Maki Black dragon', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 2 }, { id: 15, title: 'Maki Red dragon', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 2 }, { id: 16, title: 'Maki Gold dragon', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 2 }, { id: 17, title: 'heineken', price: 333, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 6 }, { id: 18, title: '<NAME>', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 1 }, { id: 19, title: '<NAME>', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 1 }, { id: 20, title: 'Felix c ugrem', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 1 }, { id: 21, title: 'Set Kali', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 4 }, { id: 22, title: 'Set c ugrem', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 4 }, { id: 23, title: 'Set sushi', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 4 }, { id: 24, title: 'Set losos', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 4 }, { id: 25, title: 'Salat wakame', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 5 }, { id: 26, title: 'Sushi ogurec', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 1 }, { id: 27, title: '<NAME>', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 2 }, { id: 28, title: 'Roll s ogurcem', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 3 }, { id: 29, title: 'Roll syrnij', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 3 }, { id: 30, title: 'Sushi ogurec', price: 634, weight: 444, sostav: 'Sostav', about: 'Этот ролл с нежной начинкой из японского омлета и сливочного сыра, покрытый вкуснейшим угрем, сделает Ваш романтический вечер незабываемым! заказать в Харькове роллы и сеты ресторан Банзай.', assortCode: 3 } ]; export const goodsReducer = (state=initState, action)=>{ switch(action.type){ case GET_GOODS: return {...state, goodList: action.goodList} default: return state; } }; const getGoodsAC = (goodList) =>({type: GET_GOODS, goodList}); export const getGoods = () => (dispatch) =>{ axios.get('/tovary').then((result)=>dispatch(getGoodsAC(result.data))); //axios.post('/api/login',{email: '<EMAIL>', password: '<PASSWORD>'},{headers: {'Content-Type': 'application/json'}}) /* все ок axios.post('/api/register', {phone: '+380954517921', name: 'maxiksx',email: '<EMAIL>', password: '<PASSWORD>'}, {headers: {'Content-Type': 'application/json'}})*/ //не передаются хидеры (пидоры) axios.get('/api/me',{},{headers: {'Authorization': '<KEY>', 'Content-Type': 'application/json'}}) //все ок axios.get('/api/items') //все ок axios.get('/api/items/2') //все ок axios.put('/api/items/1',{title: 'Notebook'},{headers: {'Authorization': '<KEY>'}}); //все ок, только хидеры axios.delete('/api/items/2',{},{headers: {'Authorization': '<KEY>'}}) //все ок axios.post('/api/items',{title: 'TV center', price: 14999},{headers: {'Authorization': '<KEY>', 'Content-Type': 'application/json'}}) } <file_sep>/src/components/pages/Sign/SignUp/SignUp.jsx import { RequireSign } from "../RequireSign/RequireSign"; import { WarningField } from "../WarningField/WarningField"; import s from '../Sign.module.css'; import {Field, Form, Formik } from "formik"; import { checkMatch, signUp } from "../../../../redux/authReducer"; import { connect } from "react-redux"; import { useState } from "react/cjs/react.development"; const validateUsername = (value) =>{ if(!value){ return 'Обязательное поле!' } if(value.length<6){ return 'Минимум 6 символов' } return null } const validateEmail = (value) =>{ if (!value) { return 'Обязательное поле'; } if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) { return 'Некорректно введен email'; } return null; } const validatePassword = (value)=>{ if(!value){ return 'Обязательное поле'; } if(value.length<8){ return 'Минимум 8 символов' } return null; } const SignUp = ({checkMatch,isMatchLogin,isMatchEmail,signUp}) =>{ const [passwordsAreEquals,setEqualsOfPasswords] = useState(false); const checkEqualsOfPasswords = (password, repeatPassword) =>{ } const checkMatchLoginHandler = (value) =>{ checkMatch('login',value); } const checkMatchEmailHandler = (value) =>{ checkMatch('email',value); } return <div> <h2>Регистрация</h2> <Formik initialValues = {{username: null, email: null, password: <PASSWORD>, repeatPassword: null}} onSubmit = {(values)=>signUp(values)} > {({values,errors,touched})=><Form> <div className={s.signForm}> <div><WarningField/></div> <div><label>Имя пользователя <RequireSign/></label></div> <div><Field type='text' name='username'/></div> {errors.username && touched.username && <div><WarningField type='error' message={`${errors.username}`}/></div>} <div><div id='checkLogin' onClick={()=>checkMatchLoginHandler(values.username)}>Проверить имя пользователя</div></div> {isMatchLogin==='no_checked' ? null : isMatchLogin ? <WarningField type='error' message='Такое имя пользователя уже существует'/> : <WarningField type='success' message='Имя пользователя свободно'/>} <div><label>E-mail <RequireSign/></label></div> <div><Field type='email' name='email'/></div> {errors.email && touched.email && <div><WarningField type='error' message={`${errors.email}`}/></div>} <div><div onClick={()=>checkMatchEmailHandler(values.email)}>Проверить e-mail</div></div> {isMatchEmail==='no_checked' ? null : isMatchEmail ? <WarningField type='error' message='Такой электронный адрес уже зарегистрирован'/> : <WarningField type='success' message='Электронный адрес свободен'/>} <div><label>Пароль <RequireSign/></label></div> {errors.password && touched.password && <div><WarningField type='error' message={`${errors.password}`}/></div>} <div><Field style={{borderColor: (!values.password && !values.repeatPassword) ? 'gray' : (values.password === values.repeatPassword) ? 'lightgreen' : 'red'}} type='password' name='password' validate={validatePassword}/></div> <div><label>Повторите пароль <RequireSign/></label></div> <div><Field style={{borderColor: (!values.password && !values.repeatPassword) ? 'gray' : (values.password === values.repeatPassword) ? 'lightgreen' : 'red'}} type='password' name='repeatPassword' validate={validatePassword}/></div> <div><button className='buttonForm' type="submit">РЕГИСТРАЦИЯ</button></div> </div> </Form>} </Formik> </div> } const mapStateToProps = (state) =>({ ...state.auth }); const mapDispatchToProps = (dispatch) =>({ checkMatch: (field, value)=>dispatch(checkMatch(field, value)), signUp: (object)=>dispatch(signUp(object)) }); export default connect(mapStateToProps,mapDispatchToProps)(SignUp);<file_sep>/src/components/pages/Sign/SignIn/SignIn.jsx import { RequireSign } from "../RequireSign/RequireSign"; import { WarningField } from "../WarningField/WarningField"; import s from '../Sign.module.css'; import {Field, Form, Formik } from "formik"; import { checkMatch, signIn } from "../../../../redux/authReducer"; import { connect } from "react-redux"; const validateUsername = (value) =>{ if(!value){ return 'Обязательное поле!' } if(value.length<6){ return 'Минимум 6 символов' } return null } const validatePassword = (value) =>{ if(!value){ return 'Обязательное поле!' } if(value<6){ return 'Минимум 6 символов' } return null } const SignIn = ({signIn}) =>{ return <div> <h2>Авторизация</h2> <Formik initialValues={{loginOrEmail: '',password:'',remember: false}} onSubmit = { (values)=>signIn(values) } > {({errors, touched})=>(<Form> <div className={s.signForm}> {errors.loginOrEmail && touched.loginOrEmail && <div><WarningField type='error' message={`${errors.loginOrEmail}`}/></div>} <div><label>Имя пользователя или e-mail <RequireSign/></label></div> <div><Field type='text' name='loginOrEmail' validate={validateUsername}/></div> <div><label>Пароль <RequireSign/></label></div> {errors.password && touched.password && <div><WarningField type='error' message={`${errors.password}`}/></div>} <div><Field type='password' name='password' validate={validatePassword}/></div> <div><button type='submit' className='buttonForm'>АВТОРИЗАЦИЯ</button> <Field type='checkbox' name='remember'/> <label>Запомнить меня</label></div> </div> </Form>)} </Formik> </div> } const mapStateToProps = (state) =>({ ...state.auth }); const mapDispatchToProps = (dispatch) =>({ signIn: (credentials)=>dispatch(signIn(credentials)), checkMatch: (field, value)=>dispatch(checkMatch) }) export default connect(mapStateToProps,mapDispatchToProps)(SignIn);
bdff27f4bf12c47b75d0d18d092c1502c28d917a
[ "JavaScript" ]
41
JavaScript
maxim19295/BanzayClient
8c889aeb304f3dc471dcd9e44dad34046af2685b
81b8dea4a0e9acfba6877fa9b8ef1faf736bfb57
refs/heads/master
<repo_name>elisbyberi/BigSecret<file_sep>/Cipher/src/edu/utdallas/bigsecret/hash/JavaxHasher.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.hash; /** * This class extends abstract class Hasher. Subclasses of this abstract class uses Javax.Crypto library. */ public abstract class JavaxHasher extends Hasher { /** * SecretKeySpec instance that holds key */ protected javax.crypto.spec.SecretKeySpec m_keySpec; /** * Mac instance */ protected javax.crypto.Mac m_mac; /** * Class constructor * @throws Exception */ public JavaxHasher() throws Exception { } } <file_sep>/Cipher/src/edu/utdallas/bigsecret/hash/test/TestSha256.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.hash.test; import static org.junit.Assert.*; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import edu.utdallas.bigsecret.hash.Sha256; /** * Test class for Sha 256 class. */ public class TestSha256 { public static void printArray(byte[] arr) { for(int a = 0; a<arr.length; a++) System.out.print(arr[a] + " "); System.out.println(); } @Test public void testWithoutTrim() { byte[] key = Bytes.toBytes("1234566"); try { Sha256 h = new Sha256(key); byte[] data = Bytes.toBytes("why do we fall?"); byte[] hash = h.getHash(data); printArray(hash); System.out.println("Size of the digest is: " + h.hashSize()); } catch (Exception e) { fail("Sha256 without trim test failed."); e.printStackTrace(); } } @Test public void testWithTrim() { byte[] key = Bytes.toBytes("1234566"); try { Sha256 h = new Sha256(key, 10); byte[] data = Bytes.toBytes("what doesn't kill you makes you stranger"); byte[] hash = h.getHash(data); printArray(hash); System.out.println("Size of the digest is: " + h.hashSize()); } catch (Exception e) { fail("Sha256 with trim test failed."); e.printStackTrace(); } } } <file_sep>/Proxy/src/edu/utdallas/bigsecret/crypter/test/TestCrypterMode1.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.crypter.test; import static org.junit.Assert.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import edu.utdallas.bigsecret.bucketizer.ByteBucketizer; import edu.utdallas.bigsecret.bucketizer.HBaseBucketizer; import edu.utdallas.bigsecret.bucketizer.LongBucketizer; import edu.utdallas.bigsecret.cipher.AesCtr; import edu.utdallas.bigsecret.cipher.AesEcb; import edu.utdallas.bigsecret.cipher.Cipher; import edu.utdallas.bigsecret.crypter.CrypterBase; import edu.utdallas.bigsecret.crypter.CrypterMode1; public class TestCrypterMode1 { public static String rowBucketizerId = "row1"; public static String famBucketizerId = "fam1"; public static String quaBucketizerId = "qua1"; public static String tsBucketizerId = "ts1"; @BeforeClass public static void testSetup() { Configuration conf = HBaseConfiguration.create(); try { ByteBucketizer rowBucketizer = new ByteBucketizer(conf, rowBucketizerId, 8); rowBucketizer.createBuckets(); rowBucketizer.close(); ByteBucketizer famBucketizer = new ByteBucketizer(conf, famBucketizerId, 8); famBucketizer.createBuckets(); famBucketizer.close(); ByteBucketizer quaBucketizer = new ByteBucketizer(conf, quaBucketizerId, 8); quaBucketizer.createBuckets(); quaBucketizer.close(); LongBucketizer tsBucketizer = new LongBucketizer(conf, tsBucketizerId, 0, 1024*1024, 1024); tsBucketizer.createBuckets(); tsBucketizer.close(); } catch (Exception e) { e.printStackTrace(); fail("Test failed."); } } @AfterClass public static void testCleanUp() { Configuration conf = HBaseConfiguration.create(); try { ByteBucketizer rowBucketizer = new ByteBucketizer(rowBucketizerId, conf); rowBucketizer.removeBuckets(); rowBucketizer.close(); ByteBucketizer famBucketizer = new ByteBucketizer(famBucketizerId, conf); famBucketizer.removeBuckets(); famBucketizer.close(); ByteBucketizer quaBucketizer = new ByteBucketizer(quaBucketizerId, conf); quaBucketizer.removeBuckets(); quaBucketizer.close(); LongBucketizer tsBucketizer = new LongBucketizer(tsBucketizerId, conf); tsBucketizer.removeBuckets(); tsBucketizer.close(); } catch (Exception e) { e.printStackTrace(); fail("Test failed."); } } @Test public void testAll() { try { Configuration conf = HBaseConfiguration.create(); HBaseBucketizer rowBucketizer = new ByteBucketizer(rowBucketizerId, conf); HBaseBucketizer famBucketizer = new ByteBucketizer(famBucketizerId, conf); HBaseBucketizer quaBucketizer = new ByteBucketizer(quaBucketizerId, conf); HBaseBucketizer tsBucketizer = new LongBucketizer(tsBucketizerId, conf); Cipher keyCipher = new AesEcb(Bytes.toBytes("1234567890123454")); Cipher valCipher = new AesCtr(Bytes.toBytes("1234567890123454")); CrypterBase cr = new CrypterMode1(rowBucketizer, famBucketizer, quaBucketizer, tsBucketizer, keyCipher, valCipher); String rowData = "12341"; String familyData = "fam123"; String qualifierData = "qua161"; long timestampData = 100; long valueData = 100689; byte[] row = Bytes.toBytes(rowData); byte[] family = Bytes.toBytes(familyData); byte[] qualifier = Bytes.toBytes(qualifierData); byte[] value = Bytes.toBytes(valueData); KeyValue testItem = new KeyValue(row, family, qualifier, timestampData, value); KeyValue encItem = new KeyValue(cr.wrapRow(testItem), cr.wrapFamily(testItem), cr.wrapQualifier(testItem), cr.wrapTimestamp(testItem), cr.wrapValue(testItem)); String decRow = Bytes.toString(cr.unwrapRow(encItem)); String decFam = Bytes.toString(cr.unwrapFamily(encItem)); String decQua = Bytes.toString(cr.unwrapQualifier(encItem)); long decTs = cr.unwrapTimestamp(encItem); long decVal = Bytes.toLong(cr.unwrapValue(encItem)); if(!rowData.equals(decRow)) { fail("row-keys are not equal"); } else if(!familyData.equals(decFam)) { fail("families are not equal"); } else if(!qualifierData.equals(decQua)) { fail("qualifiers are not equal"); } else if(timestampData != decTs) { fail("timestamps are not equal"); } else if(valueData != decVal) { fail("values are not equal"); } cr.close(); } catch (Exception e) { e.printStackTrace(); fail("Not yet implemented"); } } } <file_sep>/Proxy/src/edu/utdallas/bigsecret/proxy/ProxyBase.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.proxy; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import edu.utdallas.bigsecret.crypter.CrypterBase; import edu.utdallas.bigsecret.util.ByteArray; /** * This class is the one that does all the mumbo jumbo :).<br> * All derivations of this class supports Put, Get, Delete.<br> * Depending on the Model used (look at BigSecret paper), it may support Scan.<br> */ public abstract class ProxyBase { /** * Configuration object for HBase connection to data server */ protected Configuration m_confData; /** * Configuration object for HBase connection to bucket data server */ protected Configuration m_confBucket; /** * Crypter object */ protected CrypterBase m_crypter; /** * HTable instance that connects to Table where data resides */ protected HTable m_table; /** * Constructor for the class. * @param confData Configuration instance for Data Server. * @param confBucket Configuration instance for Bucket Server. */ public ProxyBase(Configuration confData, Configuration confBucket) { m_confData = confData; m_confBucket = confBucket; } /** * Closes connection to the HBase data table. * @throws Exception May throw exception based on other classes. */ public void close() throws Exception { //close table object m_table.close(); //close crypter object m_crypter.close(); } /** * Connect to the HBase Data Table for the given table. * @param tableName Name of table to connect to. * @throws Exception */ public void connect(String tableName) throws Exception { m_table = new HTable(m_confData, tableName); m_table.setAutoFlush(false); } /** * Flush all data. * @throws Exception */ public void flushAll() throws Exception { m_table.flushCommits(); } /** * Getter for the Crypter object in use. * @return */ public CrypterBase getCrypter() { return m_crypter; } /** * Create table with the given name, and list of families. * @param tableName Name of the table. * @param families Set of families to create. * @throws Exception */ public abstract void createTable(String tableName, Set<String> families) throws Exception; /** * Remove given table. * @throws Exception */ public void deleteTable(String tableName) throws Exception { //create hbase admin instance HBaseAdmin admin = new HBaseAdmin(m_confData); //check if table exists if(admin.tableExists(tableName)) { admin.disableTable(tableName); admin.deleteTable(tableName); } admin.close(); } /** * Get name of the table, that is currently connected to. * @return */ public byte[] getTableName() { return m_table.getTableName(); } /** * Performs a delete operation on the HBase Data Table. * @param arg0 * @throws Exception */ public abstract void delete(Delete arg0) throws Exception; /** * This function is called internally, if Scan needs to be performed on encrypted data.<br> * It is assumed that encRowSet contains encrypted row representations of a single plain row.<br> * @param scanItem Original Scan item. * @param encRowSet Set of encrypted representations of a single row. * @return Result for Key-Value entries that satisfy the scanItem. * @throws Exception */ public abstract Result getForScan(Scan scanItem, Set<ByteArray> encRowSet) throws Exception; /** * Get Scanner instance for the given Scan item. * @param arg0 Scan instance. * @return ResultScanner for the given Scan instance. * @throws Exception */ public abstract ResultScanner getScanner(Scan arg0) throws Exception; /** * Perform a Put operation on the currently connected table. * @param arg0 Put instance. * @throws Exception */ public abstract void put(Put arg0) throws Exception; /** * Perform a Get operation on the currently connected table. * @param arg0 Get instance. * @return Set of results for the given Get instance. * @throws Exception */ public abstract Result get(Get arg0) throws Exception; /** * Given a family map, check if given <family, qualifier> data exists in it.<br> * If there is no family, method returns true for every pair<br> * Else if family is in family map as inserted family, then for any qualifier, method returns true<br> * Else if <family, qualifier> pair exists, method returns true<br> * Return false otherwise * @param familyMap Family Map data * @param family Family data * @param qualifier Qualifier data * @return true if pair exists, false otherwise * @throws Exception */ protected boolean doesFamilyQualifierExist(Map<byte[], NavigableSet<byte[]>> familyMap, byte[] family, byte[] qualifier) throws Exception { //check inputs if(familyMap == null) throw new Exception("Family map object is null"); else if(family == null) throw new Exception("Family is null"); else if(qualifier == null) throw new Exception("Qualifier is null"); //get qualifier list for the family Set<byte[]> qualifierList = familyMap.get(family); if(familyMap.isEmpty()) { return true; } else if(! familyMap.containsKey(family)) { //if family is not included, return false return false; } else if(qualifierList == null) { //if it is, then return true since any qualifier is requested originally return true; } else if(qualifierList.contains(qualifier)) { //check if qualifier exists //if so, return true return true; } else { //otherwise return false; return false; } } /** * Add KeyValue to the list. This is a recursive function, and does binary search. * @param low Low index * @param high High index * @param newItem Item to be inserted * @param list List that item will be inserted */ protected void addKeyValueToList(int low, int high, KeyValue newItem, List<KeyValue> list) { if(low > high) { list.add(low, newItem); } else { KeyValue.KVComparator cmp = new KeyValue.KVComparator(); int mid = (low + high) / 2; if(cmp.compare(newItem, list.get(mid)) < 0) addKeyValueToList(low, mid-1, newItem, list); else addKeyValueToList(mid+1, high, newItem, list); } } } <file_sep>/Utilities/src/edu/utdallas/bigsecret/util/Cache.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.util; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; /** * Bucketizer instances may need a lot of communication, since they need a bucketValue<br> * for a specific bucketId. To reduce this, we implemented this class as an intermediate cache.<br> * To limit number of values hold in this cache, a value can be given in the constructed.<br> * Two data structures are utilized in this class. First we use a FIFO queue due to limited cache<br> * size. Secondly, we use hash map to get data for a specific pair. */ public class Cache { /** * Hash map instance to hold values for a bucketId-bucketValue pair. */ protected HashMap<ByteArray, ByteArray> m_hashmap; /** * FIFO queue for the incoming bucketId queries. */ protected Queue<ByteArray> m_queue; /** * Number of elements that the cache holds */ protected int m_cacheSize; /** * Default constructor. Size of cache is 64K. */ public Cache() { this(1024*64); } /** * Constructor with cache size parameter. * @param cacheSize Number of elements that cache holds. */ public Cache(int cacheSize) { m_cacheSize = cacheSize; m_hashmap = new HashMap<ByteArray, ByteArray>(m_cacheSize); m_queue = new LinkedList<ByteArray>(); } /** * Returns the size of the cache. * @return Size of the cache. */ public int getSize() { return m_cacheSize; } /** * Get a bucketValue for a bucketId * @param input BucketId * @return BucketValue for the corresponding BucketId, if it exists.<br> * Returns null otherwise. */ public byte[] get(byte[] input) { ByteArray temp = new ByteArray(input); ByteArray result = m_hashmap.get(temp); if(result == null) { return null; } else { return result.getData(); } } /** * Puts a bucketId-bucketValue pair to the cache.<br> * If the cache is full, removes the oldest pair, and puts this new input. * @param key BucketId * @param data BucketValue */ public void put(byte[] key, byte[] data) { ByteArray tempKey = new ByteArray(key); ByteArray tempData = new ByteArray(data); if(m_hashmap.containsKey(tempKey)) { m_hashmap.put(tempKey, tempData); } else { if(m_queue.size() == m_cacheSize) { ByteArray removedItem = m_queue.poll(); if(removedItem != null) { m_hashmap.remove(removedItem); } } m_hashmap.put(tempKey, tempData); m_queue.add(tempKey); } } }<file_sep>/Proxy/src/edu/utdallas/bigsecret/proxy/ProxyMode3.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Result; import edu.utdallas.bigsecret.cipher.Cipher; import edu.utdallas.bigsecret.crypter.CrypterMode3; import edu.utdallas.bigsecret.hash.Hasher; import edu.utdallas.bigsecret.util.ByteArray; /** * This model of BigSecret supports Get, Put, and Delete.<br> * Details of the model are presented in the BigSecret paper. */ public class ProxyMode3 extends ProxyBase { /** * Constructor for this class. * @param confData Configuration instance that points to HBase that holds actual data. * @param confBucket Configuration instance that points to HBase that holds bucket data. * @param rowHasher Hasher for the row key-part. * @param keyCipher Cipher for the whole key. * @param valCipher Cipher for the value part. * @throws Exception */ public ProxyMode3(Configuration confData, Configuration confBucket, Hasher rowHasher, Cipher keyCipher, Cipher valCipher) throws Exception { super(confData, confBucket); m_crypter = new CrypterMode3(rowHasher, keyCipher, valCipher); } /** * {@inheritDoc} */ public void createTable(String tableName, Set<String> families) throws Exception { //check inputs if(tableName == null) throw new Exception("Table name is null"); else if(families == null || families.size() == 0) throw new Exception("Familiy set is null or has no data"); //create hbase admin instance HBaseAdmin admin = new HBaseAdmin(m_confData); //check if table exists if(admin.tableExists(tableName)) { admin.close(); return; } //create table descriptor HTableDescriptor desc = new HTableDescriptor(tableName); //add each family name //create family descriptor and add it HColumnDescriptor colDesc = new HColumnDescriptor(m_crypter.getIndexFamilyData(null)); desc.addFamily(colDesc); //create table admin.createTable(desc); admin.close(); } /** * {@inheritDoc} */ public void delete(Delete deleteItem) throws Exception { if(deleteItem == null) throw new Exception("No item to delete"); byte[] plainRow = deleteItem.getRow(); Map<byte[], List<KeyValue>> famMap = deleteItem.getFamilyMap(); List<Delete> deleteList = new ArrayList<Delete>(); if(famMap.size() == 0) { long timestamp = deleteItem.getTimeStamp(); delete(deleteList, plainRow, null, null, timestamp, false); } else { Set<byte[]> famSet = famMap.keySet(); Iterator<byte[]> itrFam = famSet.iterator(); while(itrFam.hasNext()) { byte[] plainFam = itrFam.next(); List<KeyValue> plainKeyList = famMap.get(plainFam); for(int a = 0; a<plainKeyList.size(); a++) { KeyValue currentKV = plainKeyList.get(a); if(currentKV.getType() == KeyValue.Type.DeleteFamily.getCode()) { long plainTs = currentKV.getTimestamp(); delete(deleteList, plainRow, plainFam, null, plainTs, false); } else if(currentKV.getType() == KeyValue.Type.DeleteColumn.getCode()) { long plainTs = currentKV.getTimestamp(); byte[] plainQua = currentKV.getQualifier(); delete(deleteList, plainRow, plainFam, plainQua, plainTs, true); } else if(currentKV.getType() == KeyValue.Type.Delete.getCode()) { long plainTs = currentKV.getTimestamp(); byte[] plainQua = currentKV.getQualifier(); delete(deleteList, plainRow, plainFam, plainQua, plainTs, false); } } } } m_table.delete(deleteList); } private void delete(List<Delete> deleteList, byte[] row, byte[] fam, byte[] qua, long timestamp, boolean allQual) throws Exception { byte[] encRow = m_crypter.getIndexRowData(row); Get getItem = new Get(encRow); Result result = m_table.get(getItem); if(result == null) return; List<KeyValue> keyList = result.list(); if(keyList == null) return; if(fam == null && qua == null && timestamp == HConstants.LATEST_TIMESTAMP && allQual == false) { for(int a = 0; a<keyList.size(); a++) { byte[] decRow = m_crypter.unwrapRow(keyList.get(a)); if(Arrays.equals(decRow, row)) { byte[] encFam = keyList.get(a).getFamily(); byte[] encQua = keyList.get(a).getQualifier(); long encTs = keyList.get(a).getTimestamp(); Delete tempDelete = new Delete(encRow); tempDelete.deleteColumn(encFam, encQua, encTs); deleteList.add(tempDelete); } } } else if(fam == null && qua == null && timestamp != HConstants.LATEST_TIMESTAMP && allQual == false) { for(int a = 0; a<keyList.size(); a++) { byte[] decRow = m_crypter.unwrapRow(keyList.get(a)); long decTs = m_crypter.unwrapTimestamp(keyList.get(a)); if(Arrays.equals(decRow, row) && decTs <= timestamp) { byte[] encFam = keyList.get(a).getFamily(); byte[] encQua = keyList.get(a).getQualifier(); long encTs = keyList.get(a).getTimestamp(); Delete tempDelete = new Delete(encRow); tempDelete.deleteColumn(encFam, encQua, encTs); deleteList.add(tempDelete); } } } else if(fam != null && qua == null && timestamp == HConstants.LATEST_TIMESTAMP && allQual == false) { for(int a = 0; a<keyList.size(); a++) { byte[] decRow = m_crypter.unwrapRow(keyList.get(a)); byte[] decFam = m_crypter.unwrapFamily(keyList.get(a)); if(Arrays.equals(decRow, row) && Arrays.equals(decFam, fam)) { byte[] encFam = keyList.get(a).getFamily(); byte[] encQua = keyList.get(a).getQualifier(); long encTs = keyList.get(a).getTimestamp(); Delete tempDelete = new Delete(encRow); tempDelete.deleteColumn(encFam, encQua, encTs); deleteList.add(tempDelete); } } } else if(fam != null && qua == null && timestamp != HConstants.LATEST_TIMESTAMP && allQual == false) { for(int a = 0; a<keyList.size(); a++) { byte[] decRow = m_crypter.unwrapRow(keyList.get(a)); long decTs = m_crypter.unwrapTimestamp(keyList.get(a)); byte[] decFam = m_crypter.unwrapFamily(keyList.get(a)); if(Arrays.equals(decRow, row) && decTs <= timestamp && Arrays.equals(decFam, fam)) { byte[] encFam = keyList.get(a).getFamily(); byte[] encQua = keyList.get(a).getQualifier(); long encTs = keyList.get(a).getTimestamp(); Delete tempDelete = new Delete(encRow); tempDelete.deleteColumn(encFam, encQua, encTs); deleteList.add(tempDelete); } } } else if(fam != null && qua != null && timestamp == HConstants.LATEST_TIMESTAMP && allQual == true) { for(int a = 0; a<keyList.size(); a++) { byte[] decRow = m_crypter.unwrapRow(keyList.get(a)); byte[] decFam = m_crypter.unwrapFamily(keyList.get(a)); byte[] decQua = m_crypter.unwrapQualifier(keyList.get(a)); if(Arrays.equals(decRow, row) && Arrays.equals(decFam, fam) && Arrays.equals(decQua, qua)) { byte[] encFam = keyList.get(a).getFamily(); byte[] encQua = keyList.get(a).getQualifier(); long encTs = keyList.get(a).getTimestamp(); Delete tempDelete = new Delete(encRow); tempDelete.deleteColumn(encFam, encQua, encTs); deleteList.add(tempDelete); } } } else if(fam != null && qua != null && timestamp != HConstants.LATEST_TIMESTAMP && allQual == true) { for(int a = 0; a<keyList.size(); a++) { byte[] decRow = m_crypter.unwrapRow(keyList.get(a)); byte[] decFam = m_crypter.unwrapFamily(keyList.get(a)); byte[] decQua = m_crypter.unwrapQualifier(keyList.get(a)); long decTs = m_crypter.unwrapTimestamp(keyList.get(a)); if(Arrays.equals(decRow, row) && decTs <= timestamp && Arrays.equals(decFam, fam) && Arrays.equals(decQua, qua)) { byte[] encFam = keyList.get(a).getFamily(); byte[] encQua = keyList.get(a).getQualifier(); long encTs = keyList.get(a).getTimestamp(); Delete tempDelete = new Delete(encRow); tempDelete.deleteColumn(encFam, encQua, encTs); deleteList.add(tempDelete); } } } else if(fam != null && qua != null && timestamp != HConstants.LATEST_TIMESTAMP && allQual == false) { for(int a = 0; a<keyList.size(); a++) { byte[] decRow = m_crypter.unwrapRow(keyList.get(a)); byte[] decFam = m_crypter.unwrapFamily(keyList.get(a)); byte[] decQua = m_crypter.unwrapQualifier(keyList.get(a)); long decTs = m_crypter.unwrapTimestamp(keyList.get(a)); if(Arrays.equals(decRow, row) && decTs == timestamp && Arrays.equals(decFam, fam) && Arrays.equals(decQua, qua)) { byte[] encFam = keyList.get(a).getFamily(); byte[] encQua = keyList.get(a).getQualifier(); long encTs = keyList.get(a).getTimestamp(); Delete tempDelete = new Delete(encRow); tempDelete.deleteColumn(encFam, encQua, encTs); deleteList.add(tempDelete); } } } else if(fam != null && qua != null && timestamp == HConstants.LATEST_TIMESTAMP && allQual == false) { //This part is way too long :) We need to sort and take the latest KeyValue item. } } /** * {@inheritDoc} */ public Result get(Get getItem) throws Exception { //check inputs if(getItem == null) throw new Exception("Get item is null"); //plain text row key byte[] plainRowKey = getItem.getRow(); byte[] encRowKey = m_crypter.getIndexRowData(plainRowKey); //resulting keyvalue data List<KeyValue> resultKeyValues = new ArrayList<KeyValue>(); //encrypted time stamp min and max values long plainMinTimestamp = getItem.getTimeRange().getMin(); long plainMaxTimestamp = getItem.getTimeRange().getMax(); Get encGet = new Get(encRowKey); //get family map from plain text get item Map<byte[], NavigableSet<byte[]>> familyMap = getItem.getFamilyMap(); Result result = m_table.get(encGet); List<KeyValue> encKeyValues = result.list(); if(encKeyValues != null) { Iterator<KeyValue> itrKeyValue = encKeyValues.iterator(); while(itrKeyValue.hasNext()) { KeyValue currentValue = itrKeyValue.next(); byte[] decRow = m_crypter.unwrapRow(currentValue); if(Arrays.equals(decRow, plainRowKey)) { long decTimestamp = m_crypter.unwrapTimestamp(currentValue); if(plainMinTimestamp <= decTimestamp && decTimestamp <= plainMaxTimestamp) { byte[] decFamily = m_crypter.unwrapFamily(currentValue); byte[] decQualifier = m_crypter.unwrapQualifier(currentValue); if(doesFamilyQualifierExist(familyMap, decFamily, decQualifier)) { KeyValue decTempItem = new KeyValue(plainRowKey, decFamily, decQualifier, decTimestamp, m_crypter.unwrapValue(currentValue)); addKeyValueToList(0, resultKeyValues.size()-1, decTempItem, resultKeyValues); } } } } } //if there are no result keys, return empty Result object //otherwise return result keys. if(resultKeyValues.size() == 0) return new Result(); else return new Result(resultKeyValues); } /** * {@inheritDoc} */ public void put(Put putItem) throws Exception { //check inputs if(putItem == null) throw new Exception("Put item is null"); //get family map from plain text put item Map<byte[], List<KeyValue>> familyMap = putItem.getFamilyMap(); //for every family in mapping Set<byte[]> keySet = familyMap.keySet(); Iterator<byte[]> itr = keySet.iterator(); byte[] encRow = null; encRow = m_crypter.wrapRow(putItem.getRow(), null, null, 0, null); Put newPut = new Put(encRow); while(itr.hasNext()) { //get entry list for that family List<KeyValue> entryList = familyMap.get(itr.next()); //for every entry in a family Iterator<KeyValue> entryItr = entryList.iterator(); //get system time long sysTime = System.currentTimeMillis(); while(entryItr.hasNext()) { KeyValue tempItem = entryItr.next(); //wrap family name byte[] encFamily = m_crypter.wrapFamily(tempItem); //wrap value byte[] encValue = m_crypter.wrapValue(tempItem); long encTs; byte[] encQualifier; if(tempItem.getTimestamp() == HConstants.LATEST_TIMESTAMP) { //wrap qualifier encQualifier = m_crypter.wrapQualifier(tempItem.getRow(), tempItem.getFamily(), tempItem.getQualifier(), sysTime, null); //wrap time stamp encTs = m_crypter.wrapTimestamp(null, null, null, sysTime, null); } else { //wrap time stamp encQualifier = m_crypter.wrapQualifier(tempItem); //wrap value encTs = m_crypter.wrapTimestamp(tempItem); } //add entry to encPutItem newPut.add(encFamily, encQualifier, encTs, encValue); } } m_table.put(newPut); } /** * This function is not used in this class. */ public Result getForScan(Scan scanItem, Set<ByteArray> encRowSet) throws Exception { return null; } /** * This function is not used in this class. */ public ResultScanner getScanner(Scan arg0) throws Exception { return null; } } <file_sep>/Proxy/src/edu/utdallas/bigsecret/proxy/test/TestProxyMode1.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.proxy.test; import static org.junit.Assert.*; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import edu.utdallas.bigsecret.bucketizer.ByteBucketizer; import edu.utdallas.bigsecret.bucketizer.HBaseBucketizer; import edu.utdallas.bigsecret.bucketizer.LongBucketizer; import edu.utdallas.bigsecret.cipher.AesCtr; import edu.utdallas.bigsecret.cipher.AesEcb; import edu.utdallas.bigsecret.cipher.Cipher; import edu.utdallas.bigsecret.proxy.ProxyMode1; public class TestProxyMode1 { public static String rowBucketizerId = "row1"; public static String famBucketizerId = "fam1"; public static String quaBucketizerId = "qua1"; public static String tsBucketizerId = "ts1"; public static String tableName = "Proxy1"; @BeforeClass public static void testSetup() { Configuration conf = HBaseConfiguration.create(); try { ByteBucketizer rowBucketizer = new ByteBucketizer(conf, rowBucketizerId, 8); rowBucketizer.createBuckets(); rowBucketizer.close(); ByteBucketizer famBucketizer = new ByteBucketizer(conf, famBucketizerId, 8); famBucketizer.createBuckets(); famBucketizer.close(); ByteBucketizer quaBucketizer = new ByteBucketizer(conf, quaBucketizerId, 8); quaBucketizer.createBuckets(); quaBucketizer.close(); LongBucketizer tsBucketizer = new LongBucketizer(conf, tsBucketizerId, 0, 9223372036854775805L, 1024*64); tsBucketizer.createBuckets(); tsBucketizer.close(); } catch (Exception e) { e.printStackTrace(); fail("Test failed."); } } @AfterClass public static void testCleanUp() { Configuration conf = HBaseConfiguration.create(); try { ByteBucketizer rowBucketizer = new ByteBucketizer(rowBucketizerId, conf); rowBucketizer.removeBuckets(); rowBucketizer.close(); ByteBucketizer famBucketizer = new ByteBucketizer(famBucketizerId, conf); famBucketizer.removeBuckets(); famBucketizer.close(); ByteBucketizer quaBucketizer = new ByteBucketizer(quaBucketizerId, conf); quaBucketizer.removeBuckets(); quaBucketizer.close(); LongBucketizer tsBucketizer = new LongBucketizer(tsBucketizerId, conf); tsBucketizer.removeBuckets(); tsBucketizer.close(); } catch (Exception e) { e.printStackTrace(); fail("Test failed."); } } @Test public void testAll() throws Exception { Configuration confData = HBaseConfiguration.create(); Configuration confBucket = HBaseConfiguration.create(); HBaseBucketizer rowBucketizer = new ByteBucketizer(rowBucketizerId, confBucket); HBaseBucketizer famBucketizer = new ByteBucketizer(famBucketizerId, confBucket); HBaseBucketizer quaBucketizer = new ByteBucketizer(quaBucketizerId, confBucket); HBaseBucketizer tsBucketizer = new LongBucketizer(tsBucketizerId, confBucket); Cipher keyCipher = new AesEcb(Bytes.toBytes("1234567890123459")); Cipher valCipher = new AesCtr(Bytes.toBytes("1234567890123454")); ProxyMode1 proxy = new ProxyMode1(confData, confBucket, rowBucketizer, famBucketizer, quaBucketizer, tsBucketizer, keyCipher, valCipher); Set<String> families = new HashSet<String>(); families.add("fam1"); proxy.createTable(tableName, families); proxy.connect(tableName); //Test Put Put putItem = new Put(Bytes.toBytes("dark knight")); putItem.add(Bytes.toBytes("fam1"), Bytes.toBytes("car"), 1001L, Bytes.toBytes("batmobile")); putItem.add(Bytes.toBytes("fam1"), Bytes.toBytes("plane"), 1023L, Bytes.toBytes("the bat")); proxy.put(putItem); Put putItem2 = new Put(Bytes.toBytes("superman")); putItem2.add(Bytes.toBytes("fam1"), Bytes.toBytes("car"), 4000L,Bytes.toBytes("himself")); putItem2.add(Bytes.toBytes("fam1"), Bytes.toBytes("plane"), 2000L, Bytes.toBytes("himself again")); putItem2.add(Bytes.toBytes("fam1"), Bytes.toBytes("girlfriend"), 300L, Bytes.toBytes("none")); putItem2.add(Bytes.toBytes("fam1"), Bytes.toBytes("girlfriend"), 400L, Bytes.toBytes("was it Jane?")); proxy.put(putItem2); Put putItem3 = new Put(Bytes.toBytes("neo")); putItem3.add(Bytes.toBytes("fam1"), Bytes.toBytes("plane"), 200L, Bytes.toBytes("matrix")); proxy.put(putItem3); Put putItem4 = new Put(Bytes.toBytes("aragorn")); putItem4.add(Bytes.toBytes("fam1"), Bytes.toBytes("car"), 2300L, Bytes.toBytes("not yet invented")); putItem4.add(Bytes.toBytes("fam1"), Bytes.toBytes("girlfriend"), 33220L, Bytes.toBytes("liv tyler")); proxy.put(putItem4); proxy.flushAll(); //Test Delete Delete del = new Delete(Bytes.toBytes("superman")); //del.setTimestamp(3000L); del.deleteColumns(Bytes.toBytes("fam1"), Bytes.toBytes("girlfriend"), 301L); //del.deleteFamily(Bytes.toBytes("fam1"), 1000L); proxy.delete(del); proxy.flushAll(); //Test Get Get getItem = new Get(Bytes.toBytes("superman")); Result res = proxy.get(getItem); System.out.println(Bytes.toString(res.getValue(Bytes.toBytes("fam1"), Bytes.toBytes("car")))); System.out.println(Bytes.toString(res.getValue(Bytes.toBytes("fam1"), Bytes.toBytes("plane")))); System.out.println(Bytes.toString(res.getValue(Bytes.toBytes("fam1"), Bytes.toBytes("girlfriend")))); //Test Scan Scan sc = new Scan(); ResultScanner rs = proxy.getScanner(sc); for(Result res2 = rs.next(); res2 != null; res2 = rs.next()) { List<KeyValue> list = res2.list(); for(int a = 0; a<list.size(); a++) { KeyValue temp = list.get(a); System.out.println("----------"); System.out.println("row: " + Bytes.toString(temp.getRow())); System.out.println("family: " + Bytes.toString(temp.getFamily())); System.out.println("qualifier: " + Bytes.toString(temp.getQualifier())); System.out.println("timestamp: " + temp.getTimestamp()); System.out.println("value: " + Bytes.toString(temp.getValue())); System.out.println("----------"); } } rs.close(); //close proxy proxy.close(); //delete current table proxy.deleteTable(tableName); } } <file_sep>/Cipher/src/edu/utdallas/bigsecret/cipher/Cipher.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.cipher; /** * Abstract class to perform encryption, decryption, and decryption by an offset. */ public abstract class Cipher { /** * Default constructor. * @throws Exception */ public Cipher() throws Exception { } /** * Encrypt input data. * @param data Input data. * @return Encryption result. * @throws Exception */ public abstract byte[] encrypt(byte[] data) throws Exception; /** * Decrypt input data. * @param data Input data. * @return Decryption result. * @throws Exception */ public abstract byte[] decrypt(byte[] data) throws Exception; /** * Decrypt input data starting from index offset. * @param data Input data. * @param offset Starting index for decryption. * @return Decryption result. * @throws Exception */ public abstract byte[] decrypt(byte[] data, int offset) throws Exception; } <file_sep>/Bucketizer/src/edu/utdallas/bigsecret/bucketizer/BucketizerBase.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.bucketizer; /** * Abstract class for the bucketization process. */ public abstract class BucketizerBase { /** * Default constructor * @throws Exception */ public BucketizerBase() throws Exception { } /** * Get bucket value for the input. * @param input Input byte array. * @return Byte array representation of bucket. * @throws Exception */ public abstract byte[] getBucketValue(byte[] input) throws Exception; /** * Get next bucket value for the input * @param input input byte array * @return null if there is no next bucket, otherwise return byte array representation of next bucket * @throws Exception */ public abstract byte[] getNextBucketValue(byte[] input) throws Exception; /** * Get previous bucket value for the input * @param input input byte array * @return null if there is no previous bucket, otherwise return byte array representation of next bucket * @throws Exception */ public abstract byte[] getPrevBucketValue(byte[] input) throws Exception; /** * Get byte size of a bucket value * @return number of bytes to represent a bucket value */ public abstract int getBucketValueSize(); /** * Create buckets for this bucketizer * @throws Exception */ public abstract void createBuckets() throws Exception; /** * Removes buckets for this bucketizer. * @throws Exception */ public abstract void removeBuckets() throws Exception; } <file_sep>/Proxy/src/edu/utdallas/bigsecret/crypter/CrypterMode2.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.crypter; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.ArrayUtils; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.util.Bytes; import edu.utdallas.bigsecret.cipher.Cipher; import edu.utdallas.bigsecret.hash.Hasher; import edu.utdallas.bigsecret.util.Utilities; /** * This crypter is based on Model-2 of the BigSecret paper. <br> * It uses Hasher for the first four key-parts, and Cipher <br> * for the complete Key part and Value part. <br> * Here is the wrapping of each key-part <br> * row = H(row)<br> * fam = H(fam)<br> * qua = H(qua) || Ed(row||fam||qua||ts)<br> * ts = H(ts)<br> * val = Ep(val) */ public class CrypterMode2 extends CrypterBase { /** * Hasher for row. */ private Hasher m_rowHasher; /** * Hasher for family. */ private Hasher m_famHasher; /** * Hasher for qualifier. */ private Hasher m_quaHasher; /** * Hasher for timestamp. */ private Hasher m_tsHasher; /** * Cipher for the all key. */ private Cipher m_keyCipher; /** * Cipher for the value part. */ private Cipher m_valCipher; /** * Constructor for this class. * @param rowHasher Hasher for row key-part. * @param famHasher Hasher for family key-part. * @param quaHasher Hasher for qualifier key-part. * @param tsHasher Hasher for timestamp key-part. * @param keyCipher Cipher for the whole key. * @param valCipher Cipher for the value part. * @throws Exception Throws exception if any of the inputs is null. */ public CrypterMode2(Hasher rowHasher, Hasher famHasher, Hasher quaHasher, Hasher tsHasher, Cipher keyCipher, Cipher valCipher) throws Exception { //check inputs if(rowHasher == null) throw new Exception("Row Hasher is null"); else if(famHasher == null) throw new Exception("Family Hasher is null"); else if(quaHasher == null) throw new Exception("Qualifier Hasher is null"); else if(tsHasher == null) throw new Exception("Timestamp Hasher is null"); else if(valCipher == null) throw new Exception("Value cipher is null"); else if(keyCipher == null) throw new Exception("Key cipher is null"); m_rowHasher = rowHasher; m_famHasher = famHasher; m_quaHasher = quaHasher; m_tsHasher = tsHasher; m_keyCipher = keyCipher; m_valCipher = valCipher; } /** * {@inheritDoc} */ public void close() throws Exception { } /** * {@inheritDoc} */ public byte[] getRowHash(byte[] data) throws Exception { //return row hasher's result return m_rowHasher.getHash(data); } /** * {@inheritDoc} */ public byte[] getIndexRowData(byte[] row) throws Exception { //check necessary inputs to this function if(row == null || row.length == 0) throw new Exception("Row data is null or has no data"); //get bucket data and encode it in Base64.UrlSafe byte[] hashData = getRowHash(row); //return bucket data return hashData; } /** * {@inheritDoc} */ public int getIndexRowDataSize() { //return total return m_rowHasher.hashSize(); } /** * {@inheritDoc} */ public byte[] wrapRow(KeyValue data) throws Exception { //call overloaded function return wrapRow(data.getRow(), null, null, 0, null); } /** * {@inheritDoc} */ public byte[] wrapRow(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { //check necessary inputs to this function if(row == null || row.length == 0) throw new Exception("Row data is null or has no data"); //concatenate bucket output with row cipher's encryption return getIndexRowData(row); } /** * {@inheritDoc} */ public byte[] unwrapRow(KeyValue data) throws Exception { //call overloaded function return unwrapRow(null, null, data.getQualifier(), 0, null); } /** * {@inheritDoc} */ public byte[] unwrapRow(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if(qualifier == null || qualifier.length == 0) throw new Exception("Qualifier data null or no data"); int qualifierIndexSize = getIndexQualifierDataSize(); byte[] completeData = m_keyCipher.decrypt(qualifier, qualifierIndexSize); int rowSize = Bytes.toInt(completeData, 0, 4); return ArrayUtils.subarray(completeData, 12, 12 + rowSize); } /** * {@inheritDoc} */ public byte[] getFamilyHash(byte[] data) throws Exception { //return family hasher's result return m_famHasher.getHash(data); } /** * {@inheritDoc} */ public byte[] getIndexFamilyData(byte[] family) throws Exception { return Base64.encodeBase64URLSafe(getFamilyHash(family)); } /** * {@inheritDoc} */ public int getIndexFamilyDataSize() { int hashOutputSize = m_famHasher.hashSize(); return ((hashOutputSize*8)+5)/6; } /** * {@inheritDoc} */ public byte[] wrapFamily(KeyValue data) throws Exception { //call overloaded function return wrapFamily(null, data.getFamily(), null, 0, null); } /** * {@inheritDoc} */ public byte[] wrapFamily(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { //check necessary inputs to this function if(family == null || family.length == 0) throw new Exception("Family data is null or has no data"); //just encrypt family data return getIndexFamilyData(family); } /** * {@inheritDoc} */ public byte[] unwrapFamily(KeyValue data) throws Exception { //call overloaded function return unwrapFamily(null, null, data.getQualifier(), 0, null); } /** * {@inheritDoc} */ public byte[] unwrapFamily(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if(qualifier == null || qualifier.length == 0) throw new Exception("Qualifier data null or no data"); int qualifierIndexSize = getIndexQualifierDataSize(); byte[] completeData = m_keyCipher.decrypt(qualifier, qualifierIndexSize); int rowSize = Bytes.toInt(completeData, 0, 4); int famSize = Bytes.toInt(completeData, 4, 4); return ArrayUtils.subarray(completeData, 12+rowSize, 12+rowSize+famSize); } /** * {@inheritDoc} */ public byte[] getQualifierHash(byte[] data) throws Exception { //return qualifier hasher's result on data return m_quaHasher.getHash(data); } /** * {@inheritDoc} */ public byte[] getIndexQualifierData(byte[] qualifier) throws Exception { //check necessary inputs to this function if(qualifier == null || qualifier.length == 0) throw new Exception("Qualifier data is null or has no data"); //get bucket data byte[] hashValue = getQualifierHash(qualifier); //return bucket value return hashValue; } /** * {@inheritDoc} */ public int getIndexQualifierDataSize() { return m_quaHasher.hashSize(); } /** * {@inheritDoc} */ public byte[] wrapQualifier(KeyValue data) throws Exception { return wrapQualifier(data.getRow(), data.getFamily(), data.getQualifier(), data.getTimestamp(), null); } /** * {@inheritDoc} */ public byte[] wrapQualifier(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if(row == null || row.length == 0) throw new Exception("Row is null or has no data"); else if(family == null || family.length == 0) throw new Exception("Family is null or has no data"); else if(qualifier == null || qualifier.length == 0) throw new Exception("Qualifier is null or has no data"); byte[] qualifierIndex = getIndexQualifierData(qualifier); byte[] sizeArray = Bytes.toBytes(row.length); sizeArray = ArrayUtils.addAll(sizeArray, Bytes.toBytes(family.length)); sizeArray = ArrayUtils.addAll(sizeArray, Bytes.toBytes(qualifier.length)); byte[] completeData = ArrayUtils.addAll(sizeArray, row); completeData = ArrayUtils.addAll(completeData, family); completeData = ArrayUtils.addAll(completeData, qualifier); completeData = ArrayUtils.addAll(completeData, Bytes.toBytes(ts)); completeData = m_keyCipher.encrypt(completeData); return ArrayUtils.addAll(qualifierIndex, completeData); } /** * {@inheritDoc} */ public byte[] unwrapQualifier(KeyValue data) throws Exception { return unwrapQualifier(null, null, data.getQualifier(), 0, null); } /** * {@inheritDoc} */ public byte[] unwrapQualifier(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if(qualifier == null || qualifier.length == 0) throw new Exception("Qualifier data null or no data"); int qualifierIndexSize = getIndexQualifierDataSize(); byte[] completeData = m_keyCipher.decrypt(qualifier, qualifierIndexSize); int rowSize = Bytes.toInt(completeData, 0, 4); int famSize = Bytes.toInt(completeData, 4, 4); int quaSize = Bytes.toInt(completeData, 8, 4); return ArrayUtils.subarray(completeData, 12+rowSize+famSize, 12+rowSize+famSize+quaSize); } /** * {@inheritDoc} */ public byte[] getTimestampHash(long data) throws Exception { return m_tsHasher.getHash(Bytes.toBytes(data)); } /** * {@inheritDoc} */ public byte[] getIndexTimestampData(long timestamp) throws Exception { return getTimestampHash(timestamp); } /** * {@inheritDoc} */ public int getIndexTimestampDataSize() { //actually normal size of timestampindex is m_bucketizer.size(). //but we append bucket value with 0 //final index data has size 8 return 8; } /** * {@inheritDoc} */ public long wrapTimestamp(KeyValue data) throws Exception { //call overloaded function return wrapTimestamp(null, null, null, data.getTimestamp(), null); } /** * {@inheritDoc} */ public long wrapTimestamp(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { //get bucket result byte[] tsHashResult = getIndexTimestampData(ts); //return long representation of the concatenation return Utilities.getLong(tsHashResult); } /** * {@inheritDoc} */ public long unwrapTimestamp(KeyValue data) throws Exception { //call overloaded function return unwrapTimestamp(null, null, data.getQualifier(), 0, null); } /** * {@inheritDoc} */ public long unwrapTimestamp(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if(qualifier == null || qualifier.length == 0) throw new Exception("Qualifier data null or no data"); int qualifierIndexSize = getIndexQualifierDataSize(); byte[] completeData = m_keyCipher.decrypt(qualifier, qualifierIndexSize); int rowSize = Bytes.toInt(completeData, 0, 4); int famSize = Bytes.toInt(completeData, 4, 4); int quaSize = Bytes.toInt(completeData, 8, 4); return Bytes.toLong(ArrayUtils.subarray(completeData, 12+rowSize+famSize+quaSize, 12+rowSize+famSize+quaSize+8)); } /** * {@inheritDoc} */ public byte[] encryptValue(byte[] data) throws Exception { //return value cipher's result on data return m_valCipher.encrypt(data); } /** * {@inheritDoc} */ public byte[] decryptValue(byte[] data) throws Exception { //return value cipher's result on data return m_valCipher.decrypt(data); } /** * {@inheritDoc} */ public byte[] wrapValue(KeyValue data) throws Exception { return wrapValue(null, null, null, 0, data.getValue()); } /** * {@inheritDoc} */ public byte[] wrapValue(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if(value == null || value.length == 0) throw new Exception("Value is null or has no data"); byte[] encVal = encryptValue(value); return encVal; } /** * {@inheritDoc} */ public byte[] unwrapValue(KeyValue data) throws Exception { return unwrapValue(null, null, null, 0, data.getValue()); } /** * {@inheritDoc} */ public byte[] unwrapValue(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if(value == null || value.length == 0) throw new Exception("Value is null or has no data"); return decryptValue(value); } }<file_sep>/Bucketizer/src/edu/utdallas/bigsecret/bucketizer/LongBucketizer.java /** * Copyright (c) 2013 The University of Texas at Dallas, Data Security and Privacy Lab. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. See accompanying * LICENSE file. */ package edu.utdallas.bigsecret.bucketizer; import java.security.SecureRandom; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.util.Bytes; import edu.utdallas.bigsecret.util.Utilities; /** * This class is used to bucketize long values.<br> * Number of bucket ids is limited to 2^30. */ public class LongBucketizer extends HBaseBucketizer { /** * Number of buckets in this bucketizer */ protected int m_numberOfBuckets; /** * Domain of a partitioned bucket. */ protected long m_divisor; /** * Minimum value in the long domain. */ protected long m_minValue; /** * Maximum value in the long domain. */ protected long m_maxValue; /** * Constructor that can be used for creating buckets. This constructor should not be used in Proxy. * @param conf Configuration instance for HBase connection. * @param id Bucketizer ID. * @param minValue Minimum value that will be bucketized. * @param maxValue Maximum value that will be bucketized. * @param numberOfBuckets Number of buckets * @throws Exception Throws exception if min or max values are invalid.<br> * Throws exception number of buckets is invalid.<br> * Throws exception if another bucketizer exists with the given id, but with different info. */ public LongBucketizer(Configuration conf, String id, long minValue, long maxValue, int numberOfBuckets) throws Exception { //call super class constructor super(id, conf); //check inputs if(minValue >= maxValue) throw new Exception("Min value should be smaller than max value"); else if(numberOfBuckets <= 0) throw new Exception("Number of buckets can not be non positive"); //set parameters m_minValue = minValue; m_maxValue = maxValue; m_numberOfBuckets = numberOfBuckets; m_divisor = (m_maxValue - m_minValue) / m_numberOfBuckets; if(doesExist()) { //check if min value is true byte[] hdata = getBucketInfoFromHBase(Bytes.toBytes("min")); if(hdata == null) { throw new Exception("min data does not exist for bucketizer id=" + id); } else { if(Bytes.toLong(hdata) != m_minValue) { throw new Exception("Bucketizer info does not match. Different min values"); } } //check if max value is true hdata = getBucketInfoFromHBase(Bytes.toBytes("max")); if(hdata == null) { throw new Exception("max data does not exist for bucketizer id=" + id); } else { if(Bytes.toLong(hdata) != m_maxValue) { throw new Exception("Bucketizer info does not match. Different max values"); } } //check if divisor value is true hdata = getBucketInfoFromHBase(Bytes.toBytes("divisor")); if(hdata == null) { throw new Exception("divisor data does not exist for bucketizer id=" + id); } else { if(Bytes.toLong(hdata) != m_divisor) { throw new Exception("Bucketizer info does not match. Different divisor values"); } } //check if number of buckets value is true hdata = getBucketInfoFromHBase(Bytes.toBytes("buckets")); if(hdata == null) { throw new Exception("buckets data does not exist for bucketizer id=" + id); } else { if(Bytes.toInt(hdata) != m_numberOfBuckets) { throw new Exception("Bucketizer info does not match. Different buckets values"); } } } } /** * Constructor for use in Proxy. * @param conf Configuration instance for HBase connection. * @param id Bucketizer ID. * @throws Exception Throws exception if a long bucketizer does not exist with the given ID. */ public LongBucketizer(String id, Configuration conf) throws Exception { this(id, 1024 * 64, conf); } /** * Constructor for use in Proxy. * @param conf Configuration instance for HBase connection. * @param id Bucketizer ID. * @param cacheSize Size of the cache. * @throws Exception Throws exception if a long bucketizer does not exist with the given ID. */ public LongBucketizer(String id, int cacheSize, Configuration conf) throws Exception { //call super constructor super(id, cacheSize, conf); if(doesExist()) { //check if min value is true byte[] hdata = getBucketInfoFromHBase(Bytes.toBytes("min")); if(hdata == null) { throw new Exception("min data does not exist for bucketizer id=" + id); } else { m_minValue = Utilities.getLong(hdata); } //check if max value is true hdata = getBucketInfoFromHBase(Bytes.toBytes("max")); if(hdata == null) { throw new Exception("max data does not exist for bucketizer id=" + id); } else { m_maxValue = Utilities.getLong(hdata); } //check if divisor value is true hdata = getBucketInfoFromHBase(Bytes.toBytes("divisor")); if(hdata == null) { throw new Exception("divisor data does not exist for bucketizer id=" + id); } else { m_divisor = Utilities.getLong(hdata); } //check if number of buckets value is true hdata = getBucketInfoFromHBase(Bytes.toBytes("buckets")); if(hdata == null) { throw new Exception("buckets data does not exist for bucketizer id=" + id); } else { m_numberOfBuckets = Bytes.toInt(hdata); } } else { throw new Exception("Bucketizer with id=" + id + " does not exist"); } } @Override public byte[] getBucketValue(byte[] input) throws Exception { int bucketId = getBucketId(input); if(bucketId >= m_numberOfBuckets) bucketId = m_numberOfBuckets - 1; else if(bucketId < 0) bucketId = 0; byte[] result = getBucketValueFromHBase(Bytes.toBytes(bucketId)); return result; } @Override public byte[] getNextBucketValue(byte[] input) throws Exception { //check input if(input == null || input.length == 0) throw new Exception("Bucket ID is null or has no data"); //calculate bucket id for this input int bucketId = getBucketId(input); //check if that is the last bucket id if(bucketId >= m_numberOfBuckets - 1 || bucketId < 0) { //if so, return null return null; } else { //otherwise return next bucket id's value return getBucketValueFromHBase(Bytes.toBytes(bucketId + 1)); } } @Override public byte[] getPrevBucketValue(byte[] input) throws Exception { //check input if(input == null || input.length == 0) throw new Exception("Bucket ID is null or has no data"); //calculate bucket id for this input int bucketId = getBucketId(input); //check if that is the first bucket id if(bucketId <= 0 || bucketId >= m_numberOfBuckets) { //if so, return null return null; } else { //otherwise return prev bucket id's value return getBucketValueFromHBase(Bytes.toBytes(bucketId - 1)); } } /** * Given an input, calculate bucket ID. If length of input is smaller then number of <br> * bytes for input, append least significant bits with 0. <br> * If input's size is larger, then get the most significant bytes. Otherwise, return input as is. * @param input Byte array input * @return Bucket ID */ private int getBucketId(byte[] input) throws Exception { //check input if(input == null || input.length == 0) throw new Exception("Input bucket id is null or has no data"); long inputLong = Utilities.getLong(input); int bucketId = (int)((inputLong - m_minValue)/m_divisor); return bucketId; } @Override public int getBucketValueSize() { //size of long return 4; } @Override public void createBuckets() throws Exception { //check if there is already information about this bucketizer if(doesExist()) { throw new Exception("Bucketizer already exists"); } //put bucketizer info to hbase putBucketInfoToHBase(Bytes.toBytes("min"), Bytes.toBytes(m_minValue)); putBucketInfoToHBase(Bytes.toBytes("max"), Bytes.toBytes(m_maxValue)); putBucketInfoToHBase(Bytes.toBytes("divisor"), Bytes.toBytes(m_divisor)); putBucketInfoToHBase(Bytes.toBytes("buckets"), Bytes.toBytes(m_numberOfBuckets)); int bucketId = 0; int bucketValue = -1; int bitDiff = 8; SecureRandom ranGen = new SecureRandom(); for(; bucketId<m_numberOfBuckets; bucketId++) { if(bucketId % 10000 == 0) System.out.println("Finished number of buckets: " + bucketId); bucketValue += 1 + ranGen.nextInt(bitDiff); putBucketValueToHBase(Bytes.toBytes(bucketId), Bytes.toBytes(bucketValue)); } m_tableBucketInfo.flushCommits(); m_tableBucketMap.flushCommits(); } /** * Remove this bucketizer's data from the bucket table. */ public void removeBuckets() throws Exception { if(doesExist()) { removeBucketInfoFromHBase(); for(int a = 0; a<m_numberOfBuckets; a++) removeBucketValueFromHBase(Bytes.toBytes(a)); } } }
a505d5c2490c1a4e84ccf128a8e4d902205230b2
[ "Java" ]
11
Java
elisbyberi/BigSecret
dc070d08a4336b768cc6aac881bf4ad91fd62e12
c39a61a330fd2882e0dd64c6078465702a026afe
refs/heads/master
<repo_name>Webundle/PuzzleApiExpertise<file_sep>/Entity/Project.php <?php namespace Puzzle\Api\ExpertiseBundle\Entity; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as JMS; use Hateoas\Configuration\Annotation as Hateoas; use Puzzle\OAuthServerBundle\Traits\PrimaryKeyable; use Knp\DoctrineBehaviors\Model\Blameable\Blameable; use Knp\DoctrineBehaviors\Model\Sluggable\Sluggable; use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable; use Puzzle\OAuthServerBundle\Traits\Nameable; use Puzzle\OAuthServerBundle\Traits\Describable; /** * Expertise Project * * @ORM\Table(name="expertise_project") * @ORM\Entity() * @JMS\ExclusionPolicy("all") * @JMS\XmlRoot("expertise_project") * @Hateoas\Relation( * name = "self", * href = @Hateoas\Route( * "get_expertise_project", * parameters = {"id" = "expr(object.getId())"}, * absolute = true, * )) * @Hateoas\Relation( * name = "gallery", * exclusion = @Hateoas\Exclusion(excludeIf = "expr(object.getGallery() === null)"), * href = @Hateoas\Route( * "get_media_folder", * parameters = {"id" = "expr(object.getGallery().getId())"}, * absolute = true, * )) * @Hateoas\Relation( * name = "service", * embedded = "expr(object.getService())", * exclusion = @Hateoas\Exclusion(excludeIf = "expr(object.getService() === null)"), * href = @Hateoas\Route( * "get_expertise_service", * parameters = {"id" = "expr(object.getService().getId())"}, * absolute = true, * )) */ class Project { use PrimaryKeyable, Sluggable, Timestampable, Blameable, Nameable, Describable ; /** * @ORM\Column(name="slug", type="string", length=255) * @var string * @JMS\Expose * @JMS\Type("string") */ protected $slug; /** * @ORM\Column(type="string", length=255, nullable=true) * @JMS\Expose * @JMS\Type("string") */ private $picture; /** * @var string * @ORM\Column(name="client", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $client; /** * @var \DateTime * @ORM\Column(name="started_at", type="datetime", nullable=true) * @JMS\Expose * @JMS\Type("DateTime<'Y-m-d'>") */ private $startedAt; /** * @var \DateTime * @ORM\Column(name="ended_at", type="datetime", nullable=true) * @JMS\Expose * @JMS\Type("DateTime<'Y-m-d'>") */ private $endedAt; /** * @var string * @ORM\Column(name="location", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $location; /** * @var string * @ORM\Column(name="gallery", type="string", length=255, nullable=true) * @JMS\Expose * @JMS\Type("gallery") */ private $gallery; /** * @ORM\ManyToOne(targetEntity="Service", inversedBy="projects", fetch="EAGER", cascade={"persist"}) * @ORM\JoinColumn(name="service_id", referencedColumnName="id") */ private $service; public function getSluggableFields() { return [ 'name' ]; } public function setClient($client) : self { $this->client = $client; return $this; } public function getClient() :? string { return $this->client; } public function setStartedAt(\DateTime $startedAt) : self { $this->startedAt = $startedAt; return $this; } public function getStartedAt() :? \DateTime { return $this->startedAt; } public function setEndedAt(\DateTime $endedAt) : self { $this->endedAt = $endedAt; return $this; } public function getEndedAt() :? \DateTime { return $this->endedAt; } public function setLocation($location) : self { $this->location = $location; return $this; } public function getLocation() :? string { return $this->location; } public function setPicture($picture) : self { $this->picture = $picture; return $this; } public function getPicture() :? string { return $this->picture; } public function setGallery($gallery) : self { $this->gallery = $gallery; return $this; } public function getGallery() :? string { return $this->gallery; } public function setService(Service $service = null) : self { $this->service = $service; return $this; } public function getService() :? Service { return $this->service; } } <file_sep>/Entity/Testimonial.php <?php namespace Puzzle\Api\ExpertiseBundle\Entity; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as JMS; use Hateoas\Configuration\Annotation as Hateoas; use Puzzle\OAuthServerBundle\Traits\PrimaryKeyable; use Knp\DoctrineBehaviors\Model\Blameable\Blameable; use Puzzle\OAuthServerBundle\Traits\Pictureable; use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable; /** * Expertise Testimonial * * @ORM\Table(name="expertise_testimonial") * @ORM\Entity() * @JMS\ExclusionPolicy("all") * @JMS\XmlRoot("expertise_testimonial") * @Hateoas\Relation( * name = "self", * href = @Hateoas\Route( * "get_expertise_testimonial", * parameters = {"id" = "expr(object.getId())"}, * absolute = true, * )) */ class Testimonial { use PrimaryKeyable, Pictureable, Timestampable, Blameable; /** * @var string * @ORM\Column(name="author", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $author; /** * @var string * @ORM\Column(name="company", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $company; /** * @var string * @ORM\Column(name="position", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $position; /** * @var string * @ORM\Column(name="message", type="text") * @JMS\Expose * @JMS\Type("string") */ private $message; public function setAuthor($author) : self { $this->author = $author; return $this; } public function getAuthor() :? string { return $this->author; } public function setCompany($company) : self { $this->company = $company; return $this; } public function getCompany() :? string { return $this->company; } public function setPosition($position) : self { $this->position = $position; return $this; } public function getPosition() :? string { return $this->position; } public function setMessage($message) : self { $this->message = $message; return $this; } public function getMessage() :? string { return $this->message; } } <file_sep>/Controller/ProjectController.php <?php namespace Puzzle\Api\ExpertiseBundle\Controller; use Puzzle\Api\ExpertiseBundle\Entity\Project; use Puzzle\Api\ExpertiseBundle\Entity\Service; use Puzzle\Api\MediaBundle\PuzzleApiMediaEvents; use Puzzle\Api\MediaBundle\Event\FileEvent; use Puzzle\Api\MediaBundle\Util\MediaUtil; use Puzzle\OAuthServerBundle\Controller\BaseFOSRestController; use Puzzle\OAuthServerBundle\Service\Utils; use Puzzle\OAuthServerBundle\Util\FormatUtil; use Symfony\Component\HttpFoundation\Request; /** * * @author <NAME> <<EMAIL>> * */ class ProjectController extends BaseFOSRestController { public function __construct(){ parent::__construct(); $this->fields = ['name', 'location', 'service', 'client', 'startedAt', 'endedAt', 'description']; } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/projects") */ public function getExpertiseProjectsAction(Request $request) { $query = Utils::blameRequestQuery($request->query, $this->getUser()); /** @var Puzzle\OAuthServerBundle\Service\Repository $repository */ $repository = $this->get('papis.repository'); $response = $repository->filter($query, Project::class, $this->connection); return $this->handleView(FormatUtil::formatView($request, $response)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/projects/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("project", class="PuzzleApiExpertiseBundle:Project") */ public function getExpertiseProjectAction(Request $request, Project $project) { if ($project->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->accessDenied($request)); } return $this->handleView(FormatUtil::formatView($request, $project)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Post("/projects") */ public function postExpertiseProjectAction(Request $request) { /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get('doctrine')->getManager($this->connection); $data = $request->request->all(); $data['service'] = $em->getRepository(Service::class)->find($data['service']); $data['startedAt'] = is_string($data['startedAt']) ? new \DateTime($data['startedAt']) : $data['startedAt']; $data['endedAt'] = is_string($data['endedAt']) ? new \DateTime($data['endedAt']) : $data['endedAt']; /** @var Project $project */ $project = Utils::setter(new Project(), $this->fields, $data); $em->persist($project); if (isset($data['picture']) && $data['picture']) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Project::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($project){$project->setPicture($filename);} ])); } $em->flush(); return $this->handleView(FormatUtil::formatView($request, $project)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Put("/projects/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("project", class="PuzzleApiExpertiseBundle:Project") */ public function putExpertiseProjectAction(Request $request, Project $project) { $user = $this->getUser(); if ($project->getCreatedBy()->getId() !== $user->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get('doctrine')->getManager($this->connection); $data = $request->request->all(); $data['startedAt'] = is_string($data['startedAt']) ? new \DateTime($data['startedAt']) : $data['startedAt']; $data['endedAt'] = is_string($data['endedAt']) ? new \DateTime($data['endedAt']) : $data['endedAt']; if (isset($data['service']) && $data['service'] !== null) { $data['service'] = $em->getRepository(Service::class)->find($data['service']); } /** @var Project $project */ $project = Utils::setter($project, $this->fields, $data); if (isset($data['picture']) && $data['picture'] !== $project->getPicture()) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Project::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($project){$project->setPicture($filename);} ])); } $em->flush(); return $this->handleView(FormatUtil::formatView($request, $project)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Delete("/projects/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("project", class="PuzzleApiExpertiseBundle:Project") */ public function deleteExpertiseProjectAction(Request $request, Project $project) { if ($project->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } $em = $this->get('doctrine')->getManager($this->connection); $em->remove($project); $em->flush(); return $this->handleView(FormatUtil::formatView($request, null, 204)); } }<file_sep>/Entity/Staff.php <?php namespace Puzzle\Api\ExpertiseBundle\Entity; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as JMS; use Hateoas\Configuration\Annotation as Hateoas; use Puzzle\OAuthServerBundle\Traits\PrimaryKeyable; use Knp\DoctrineBehaviors\Model\Blameable\Blameable; use Puzzle\OAuthServerBundle\Traits\Taggable; use Doctrine\Common\Collections\Collection; use Puzzle\OAuthServerBundle\Traits\Pictureable; use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable; /** * Expertise Staff * * @ORM\Table(name="expertise_staff") * @ORM\Entity() * @JMS\ExclusionPolicy("all") * @JMS\XmlRoot("expertise_staff") * @Hateoas\Relation( * name = "self", * href = @Hateoas\Route( * "get_expertise_staff", * parameters = {"id" = "expr(object.getId())"}, * absolute = true, * )) * @Hateoas\Relation( * name = "service", * embedded = "expr(object.getService())", * exclusion = @Hateoas\Exclusion(excludeIf = "expr(object.getService() === null)"), * href = @Hateoas\Route( * "get_expertise_service", * parameters = {"id" = "expr(object.getService().getId())"}, * absolute = true, * )) */ class Staff { use PrimaryKeyable, Pictureable, Timestampable, Blameable; /** * @var string * @ORM\Column(name="full_name", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $fullName; /** * @var string * @ORM\Column(name="biography", type="text", nullable=true) * @JMS\Expose * @JMS\Type("string") */ private $biography; /** * @var string * @ORM\Column(name="position", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $position; /** * @var array * @ORM\Column(name="contacts", type="array", nullable=true) * @JMS\Expose * @JMS\Type("array") */ private $contacts; /** * @var integer * @ORM\Column(name="ranking", type="integer", nullable=true) * @JMS\Expose * @JMS\Type("integer") */ private $ranking; /** * @ORM\ManyToOne(targetEntity="Service", inversedBy="staffs", fetch="EAGER", cascade={"persist"}) * @ORM\JoinColumn(name="service_id", referencedColumnName="id") */ private $service; public function setFullName($fullName) : self { $this->fullName = $fullName; return $this; } public function getFullName() :? string { return $this->fullName; } public function setBiography($biography) : self { $this->biography = $biography; return $this; } public function getBiography() :? string { return $this->biography; } public function setPosition($position) : self { $this->position = $position; return $this; } public function getPosition() :? string { return $this->position; } public function setContacts($contacts = null) : self { $contacts = $contacts && is_string($contacts) ? explode(',', $contacts) : $contacts; if ($this->contacts) { foreach ($contacts as $contact) { $this->addContact($contact); } }else { $this->contacts = $contacts; } return $this; } public function addContact($contact) { $this->contacts = array_unique(array_merge($this->contacts, [$contact])); return $this; } public function removeContact($contact) : self { $this->contacts = array_diff($this->contacts, [$contact]); return $this; } public function getContacts() :? array { return $this->contacts; } public function setRanking($ranking) : self { $this->ranking = $ranking; return $this; } public function getRanking():? int { return $this->ranking; } public function setService(Service $service = null) : self { $this->service = $service; return $this; } public function getService() :? Service{ return $this->service; } } <file_sep>/PuzzleApiExpertiseBundle.php <?php namespace Puzzle\Api\ExpertiseBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PuzzleApiExpertiseBundle extends Bundle { } <file_sep>/Controller/StaffController.php <?php namespace Puzzle\Api\ExpertiseBundle\Controller; use Puzzle\Api\ExpertiseBundle\Entity\Service; use Puzzle\Api\ExpertiseBundle\Entity\Staff; use Puzzle\Api\MediaBundle\PuzzleApiMediaEvents; use Puzzle\Api\MediaBundle\Event\FileEvent; use Puzzle\Api\MediaBundle\Util\MediaUtil; use Puzzle\OAuthServerBundle\Controller\BaseFOSRestController; use Puzzle\OAuthServerBundle\Service\Utils; use Puzzle\OAuthServerBundle\Util\FormatUtil; use Symfony\Component\HttpFoundation\Request; /** * * @author <NAME> <<EMAIL>> * */ class StaffController extends BaseFOSRestController { public function __construct(){ parent::__construct(); $this->fields = ['fullName', 'position', 'contacts', 'ranking', 'service', 'biography']; } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/staffs") */ public function getExpertiseStaffsAction(Request $request) { $query = Utils::blameRequestQuery($request->query, $this->getUser()); /** @var Puzzle\OAuthServerBundle\Service\Repository $repository */ $repository = $this->get('papis.repository'); $response = $repository->filter($query, Staff::class, $this->connection); return $this->handleView(FormatUtil::formatView($request, $response)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/staffs/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("staff", class="PuzzleApiExpertiseBundle:Staff") */ public function getExpertiseStaffAction(Request $request, Staff $staff) { if ($staff->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->accessDenied($request)); } return $this->handleView(FormatUtil::formatView($request, ['resources' => $staff])); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Post("/staffs") */ public function postExpertiseStaffAction(Request $request) { /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get('doctrine')->getManager($this->connection); $data = $request->request->all(); $data['service'] = $em->getRepository(Service::class)->find($data['service']); /** @var Puzzle\Api\ExpertiseBundle\Entity\Staff $staff */ $staff = Utils::setter(new Staff(), $this->fields, $data); $em->persist($staff); if (isset($data['picture']) && $data['picture']) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Staff::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($staff){$staff->setPicture($filename);} ])); } $em->flush(); return $this->handleView(FormatUtil::formatView($request, $staff)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Put("/staffs/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("staff", class="PuzzleApiExpertiseBundle:Staff") */ public function putExpertiseStaffAction(Request $request, Staff $staff) { $user = $this->getUser(); if ($staff->getCreatedBy()->getId() !== $user->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get('doctrine')->getManager($this->connection); $data = $request->request->all(); if (isset($data['service']) && $data['service'] !== null) { $data['service'] = $em->getRepository(Service::class)->find($data['service']); } /** @var Staff $staff */ $staff = Utils::setter($staff, $this->fields, $data); if (isset($data['picture']) && $data['picture'] !== $staff->getPicture()) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Staff::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($staff){$staff->setPicture($filename);} ])); } /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get('doctrine')->getManager($this->connection); $em->flush(); return $this->handleView(FormatUtil::formatView($request, $staff)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Delete("/staffs/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("staff", class="PuzzleApiExpertiseBundle:Staff") */ public function deleteExpertiseStaffAction(Request $request, Staff $staff) { if ($staff->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } $em = $this->get('doctrine')->getManager($this->connection); $em->remove($staff); $em->flush(); return $this->handleView(FormatUtil::formatView($request, null, 204)); } }<file_sep>/Entity/Faq.php <?php namespace Puzzle\Api\ExpertiseBundle\Entity; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as JMS; use Hateoas\Configuration\Annotation as Hateoas; use Puzzle\OAuthServerBundle\Traits\PrimaryKeyable; use Puzzle\OAuthServerBundle\Traits\Nameable; use Knp\DoctrineBehaviors\Model\Blameable\Blameable; use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable; /** * Expertise Faq * * @ORM\Table(name="expertise_faq") * @ORM\Entity() * @JMS\ExclusionPolicy("all") * @JMS\XmlRoot("expertise_faq") * @Hateoas\Relation( * name = "self", * href = @Hateoas\Route( * "get_expertise_faq", * parameters = {"id" = "expr(object.getId())"}, * absolute = true, * )) */ class Faq { use PrimaryKeyable, Timestampable, Blameable; /** * @var string * @ORM\Column(name="question", type="string", length=255) * @JMS\Expose * @JMS\Type("string") */ private $question; /** * @var string * @ORM\Column(name="answer", type="text") * @JMS\Expose * @JMS\Type("string") */ private $answer; public function setQuestion($question) : self { $this->question = $question; return $this; } public function getQuestion() :? string { return $this->question; } public function setAnswer($answer) : self { $this->answer = $answer; return $this; } public function getAnswer() :? string { return $this->answer; } } <file_sep>/Entity/Service.php <?php namespace Puzzle\Api\ExpertiseBundle\Entity; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as JMS; use Hateoas\Configuration\Annotation as Hateoas; use Puzzle\OAuthServerBundle\Traits\PrimaryKeyable; use Knp\DoctrineBehaviors\Model\Blameable\Blameable; use Knp\DoctrineBehaviors\Model\Sluggable\Sluggable; use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable; use Doctrine\Common\Collections\Collection; use Puzzle\OAuthServerBundle\Traits\ExprTrait; use Puzzle\OAuthServerBundle\Traits\Pictureable; use Puzzle\OAuthServerBundle\Traits\Describable; use Puzzle\OAuthServerBundle\Traits\Nameable; /** * Expertise Service * * @ORM\Table(name="expertise_service") * @ORM\Entity() * @JMS\ExclusionPolicy("all") * @JMS\XmlRoot("expertise_service") * @Hateoas\Relation( * name = "self", * href = @Hateoas\Route( * "get_expertise_service", * parameters = {"id" = "expr(object.getId())"}, * absolute = true, * )) * @Hateoas\Relation( * name = "parent", * embedded = "expr(object.getParent())", * exclusion = @Hateoas\Exclusion(excludeIf = "expr(object.getParent() === null)"), * href = @Hateoas\Route( * "get_expertise_service", * parameters = {"id" = "expr(object.getParent().getId())"}, * absolute = true, * )) * @Hateoas\Relation( * name = "childs", * href = @Hateoas\Route( * "get_expertise_services", * parameters = {"filter" = "parent==expr(object.getId())"}, * absolute = true * )) * * @Hateoas\Relation( * name = "count_childs", * embedded = "expr(object.count(object.getChilds()))" * )) */ class Service { use PrimaryKeyable, Sluggable, Timestampable, ExprTrait, Blameable, Nameable, Pictureable, Describable ; /** * @ORM\Column(name="slug", type="string", length=255) * @var string * @JMS\Expose * @JMS\Type("string") */ protected $slug; /** * @ORM\Column(type="string", length=255, nullable=true) * @JMS\Expose * @JMS\Type("string") */ private $picture; /** * @var string * @ORM\Column(name="class_icon", type="string", length=255, nullable=true) * @JMS\Expose * @JMS\Type("string") */ private $classIcon; /** * @var integer * @ORM\Column(name="ranking", type="integer", nullable=true) * @JMS\Expose * @JMS\Type("integer") */ private $ranking; /** * @ORM\OneToMany(targetEntity="Service", mappedBy="parent") */ private $childs; /** * @ORM\ManyToOne(targetEntity="Service", inversedBy="childs") * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") */ private $parent; /** * @ORM\OneToMany(targetEntity="Project", mappedBy="service", fetch="EXTRA_LAZY", cascade={"persist","remove"}) * @var Collection $projects */ private $projects; /** * @ORM\OneToMany(targetEntity="Staff", mappedBy="service", fetch="EXTRA_LAZY", cascade={"persist","remove"}) * @var Collection $staffs */ private $staffs; public function __construct() { $this->projects = new \Doctrine\Common\Collections\ArrayCollection(); } public function getSluggableFields() { return [ 'name' ]; } public function addProject(Project $project) : self { if ($this->projects === null ||$this->projects->contains($project) === false) { $this->projects->add($project); } return $this; } public function removeProject(Project $project) : self { $this->projects->removeElement($project); } public function getProjects() :? Collection { return $this->projects; } public function setClassIcon($classIcon) : self { $this->classIcon = $classIcon; return $this; } public function getClassIcon() :? string { return $this->classIcon; } public function setRanking($ranking) : self { $this->ranking = $ranking; return $this; } public function getRanking():? int { return $this->ranking; } public function setParent(Service $parent = null) { $this->parent = $parent; return $this; } public function getParent() :?self { return $this->parent; } public function addChild(Service $child) :self { $this->childs[] = $child; return $this; } public function removeChild(Service $child) :self { $this->childs->removeElement($child); return $this; } public function getChilds() :?Collection { return $this->childs; } public function setStaffs(Collection $staffs = null) : self { $this->staffs = $staffs; return $this; } public function addStaff(Staff $staff) : self { if ($this->staffs === null || $this->staffs->contains($staff) === false) { $this->staffs->add($staff); } return $this; } public function removeStaff(Staff $staff) : self { $this->staffs->removeElement($staff); return $this; } public function getStaffs() :? Collection { return $this->staffs; } } <file_sep>/Controller/ServiceController.php <?php namespace Puzzle\Api\ExpertiseBundle\Controller; use Puzzle\Api\ExpertiseBundle\Entity\Service; use Puzzle\Api\MediaBundle\PuzzleApiMediaEvents; use Puzzle\Api\MediaBundle\Event\FileEvent; use Puzzle\Api\MediaBundle\Util\MediaUtil; use Puzzle\OAuthServerBundle\Controller\BaseFOSRestController; use Puzzle\OAuthServerBundle\Service\Utils; use Puzzle\OAuthServerBundle\Util\FormatUtil; use Symfony\Component\HttpFoundation\Request; /** * * @author <NAME> <<EMAIL>> * */ class ServiceController extends BaseFOSRestController { public function __construct() { parent::__construct(); $this->fields = ['name', 'description', 'ranking', 'classIcon', 'parent']; } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/services") */ public function getExpertiseServicesAction(Request $request) { $query = Utils::blameRequestQuery($request->query, $this->getUser()); /** @var Puzzle\OAuthServerBundle\Service\Repository $repository */ $repository = $this->get('papis.repository'); $response = $repository->filter($query, Service::class, $this->connection); return $this->handleView(FormatUtil::formatView($request, $response)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/services/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("service", class="PuzzleApiExpertiseBundle:Service") */ public function getExpertiseServiceAction(Request $request, Service $service) { if ($service->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->accessDenied($request)); } return $this->handleView(FormatUtil::formatView($request, $service)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Post("/services") */ public function postExpertiseServiceAction(Request $request) { /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get()->getManager($this->connection); $data = $request->request->all(); $data['parent'] = isset($data['parent']) && $data['parent'] ? $em->getRepository(Service::class)->find($data['parent']) : null; /** @var Puzzle\Api\ExpertiseBundle\Entity\Service $service */ $service = Utils::setter(new Service(), $this->fields, $data); $em->persist($service); /* Service picture listener */ if (isset($data['picture']) && $data['picture']) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Service::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($service){$service->setPicture($filename);} ])); } $em->flush(); return $this->handleView(FormatUtil::formatView($request, $service)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Put("/services/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("service", class="PuzzleApiExpertiseBundle:Service") */ public function putExpertiseServiceAction(Request $request, Service $service) { $user = $this->getUser(); if ($service->getCreatedBy()->getId() !== $user->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } $data = $request->request->all(); /** @var Doctrine\ORM\EntityManager $em */ $em = $this->doctrine->getManager($this->connection); if (isset($data['parent']) && $data['parent'] !== null) { $data['parent'] = $em->getRepository(Service::class)->find($data['parent']); } /** @var Puzzle\Api\ExpertiseBundle\Entity\Service $service */ $service = Utils::setter($service, $this->fields, $data); /* Article picture listener */ if (isset($data['picture']) && $data['picture'] !== $service->getPicture()) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Service::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($service){$service->setPicture($filename);} ])); } $em->flush(); return $this->handleView(FormatUtil::formatView($request, $service)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/services/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("service", class="PuzzleApiExpertiseBundle:Service") */ public function deleteExpertiseServiceAction(Request $request, Service $service) { if ($service->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } $em = $this->get('doctrine')->getManager($this->connection); $em->remove($service); $em->flush(); return $this->handleView(FormatUtil::formatView($request, null, 204)); } }<file_sep>/Controller/TestimonialController.php <?php namespace Puzzle\Api\ExpertiseBundle\Controller; use Puzzle\Api\ExpertiseBundle\Entity\Testimonial; use Puzzle\Api\MediaBundle\PuzzleApiMediaEvents; use Puzzle\Api\MediaBundle\Event\FileEvent; use Puzzle\Api\MediaBundle\Util\MediaUtil; use Puzzle\OAuthServerBundle\Controller\BaseFOSRestController; use Puzzle\OAuthServerBundle\Service\Utils; use Puzzle\OAuthServerBundle\Util\FormatUtil; use Symfony\Component\HttpFoundation\Request; /** * * @author <NAME> <<EMAIL>> * */ class TestimonialController extends BaseFOSRestController { public function __construct(){ parent::__construct(); $this->fields = ['author', 'company', 'position', 'message']; } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/testimonials") */ public function getExpertiseTestimonialsAction(Request $request) { $query = Utils::blameRequestQuery($request->query, $this->getUser()); /** @var Puzzle\OAuthServerBundle\Service\Repository $repository */ $repository = $this->get('papis.repository'); $response = $repository->filter($query, Testimonial::class, $this->connection); return $this->handleView(FormatUtil::formatView($request, $response)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Get("/testimonials/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("testimonial", class="PuzzleApiExpertiseBundle:Testimonial") */ public function getExpertiseTestimonialAction(Request $request, Testimonial $testimonial) { if ($testimonial->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->accessDenied($request)); } return $this->handleView(FormatUtil::formatView($request, $testimonial)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Post("/testimonials") */ public function postExpertiseTestimonialAction(Request $request) { $data = $request->request->all(); /** @var Puzzle\Api\ExpertiseBundle\Entity\Testimonial $testimonial */ $testimonial = Utils::setter(new Testimonial(), $this->fields, $data); /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get('doctrine')->getManager($this->connection); $em->persist($testimonial); if (isset($data['picture']) && $data['picture']) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Testimonial::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($testimonial){$testimonial->setPicture($filename);} ])); } $em->flush(); return $this->handleView(FormatUtil::formatView($request, $testimonial)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Put("/testimonials/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("testimonial", class="PuzzleApiExpertiseBundle:Testimonial") */ public function putExpertiseTestimonialAction(Request $request, Testimonial $testimonial) { $user = $this->getUser(); if ($testimonial->getCreatedBy()->getId() !== $user->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } $data = $request->request->all(); /** @var Puzzle\Api\ExpertiseBundle\Entity\Testimonial $testimonial */ $testimonial = Utils::setter($testimonial, $this->fields, $data); if (isset($data['picture']) && $data['picture'] !== $testimonial->getPicture()) { /** @var Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(PuzzleApiMediaEvents::MEDIA_COPY_FILE, new FileEvent([ 'path' => $data['picture'], 'folder' => $data['uploadDir'] ?? MediaUtil::extractFolderNameFromClass(Testimonial::class), 'user' => $this->getUser(), 'closure' => function($filename) use ($testimonial){$testimonial->setPicture($filename);} ])); } /** @var Doctrine\ORM\EntityManager $em */ $em = $this->get('doctrine')->getManager($this->connection); $em->flush(); return $this->handleView(FormatUtil::formatView($request, $testimonial)); } /** * @FOS\RestBundle\Controller\Annotations\View() * @FOS\RestBundle\Controller\Annotations\Delete("/testimonials/{id}") * @Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter("testimonial", class="PuzzleApiExpertiseBundle:Testimonial") */ public function deleteExpertiseTestimonialAction(Request $request, Testimonial $testimonial) { if ($testimonial->getCreatedBy()->getId() !== $this->getUser()->getId()) { /** @var Puzzle\OAuthServerBundle\Service\ErrorFactory $errorFactory */ $errorFactory = $this->get('papis.error_factory'); return $this->handleView($errorFactory->badRequest($request)); } $em = $this->get('doctrine')->getManager($this->connection); $em->remove($testimonial); $em->flush(); return $this->handleView(FormatUtil::formatView($request, null, 204)); } }<file_sep>/Entity/Partner.php <?php namespace Puzzle\Api\ExpertiseBundle\Entity; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as JMS; use Hateoas\Configuration\Annotation as Hateoas; use Puzzle\OAuthServerBundle\Traits\PrimaryKeyable; use Knp\DoctrineBehaviors\Model\Blameable\Blameable; use Puzzle\OAuthServerBundle\Traits\Nameable; use Puzzle\OAuthServerBundle\Traits\Pictureable; use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable; /** * Expertise Partner * * @ORM\Table(name="expertise_partner") * @ORM\Entity() * @JMS\ExclusionPolicy("all") * @JMS\XmlRoot("expertise_partner") * @Hateoas\Relation( * name = "self", * href = @Hateoas\Route( * "get_expertise_partner", * parameters = {"id" = "expr(object.getId())"}, * absolute = true, * )) */ class Partner { use PrimaryKeyable, Timestampable, Nameable, Pictureable, Blameable; /** * @var string * @ORM\Column(name="location", type="string", length=255, nullable=true) * @JMS\Expose * @JMS\Type("string") */ private $location; public function setLocation($location) : self { $this->location = $location; return $this; } public function getLocation() :? string { return $this->location; } }
cf362c44ac905f63471a30265a98802649526d40
[ "PHP" ]
11
PHP
Webundle/PuzzleApiExpertise
35934f70b6d1aeeb816b85e89f9c4400acd46a13
1d2df38ec1c7e990a3f9bbd6f0a4b536e0b403f7
refs/heads/master
<repo_name>fredo-/MosbyBareBonesRecyclerView<file_sep>/README.md # MosbyBareBonesRecyclerView Simple implementation of a recycler view with Mosby #Step 1: Gradle dependency * add to build.gradle for the app: `compile 'com.hannesdorfmann.mosby:mvp:2.0.1'` #Step 2: Make 3 packages * model * has all the data/api calls/network info providers * view * activity/adapters/view interfaces * presenter * Presenter implementations and interfaces #Step 3: Change activity's extensions * Make the main activity * `extend MvpActivity<ActivityViewInterface, Presenter> implements AvtivityViewInterface` * implement `createPresenter()` * return a new instance of the presenter you want for the instance of the activity/fragment/view * this method allows you to check what instance you have of the class and return the right presenter * for example if you have two tabs both of which use the same fragment code, but two different instances because they do slightly different things, you can check which type of instance the object is and return two different presenters * this is useful if you want to use the same view for slightly different data (two lists but with different headers/different displays of similar data) #Step 4: Write View Interface and Presenter class * a) `public interface ActivityViewInterface.java extends MvpView` * Outlines what the view can do for the presenter * for example * `showError()` * `showList()` * `hideError()` * `displayData()` * b) `public class Presenter extends MvpBasePresenter<ActivityViewInterface>` * Connects the model to the views * holds refs to data/network sources called by callbacks on views and model to get data where it needs to go #Step 5: Move data providing objects/code to model package and access data through presenter * refactor code to display data in MainActivity to `displayData()` * refactor adapter to take in the data array later with a `setData()` method * move the data array to its own class and hold a reference to it in the presenter <file_sep>/app/src/main/java/com/fredo/barebonesrecyclerview/view/RecyclerAdapter.java package com.fredo.barebonesrecyclerview.view; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.fredo.barebonesrecyclerview.R; /** * Created by alfredovelasco on 12/10/16. */ public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.CustomHolder> { private int[] data; @Override public CustomHolder onCreateViewHolder(ViewGroup parent, int viewType) { View layoutInflater = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_layout, parent, false); return new CustomHolder(layoutInflater); } @Override public void onBindViewHolder(CustomHolder holder, int position) { holder.bindData(position); } @Override public int getItemCount() { return data.length; } public void setData(int[] data) { this.data = data; } public class CustomHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView textDisplay; public CustomHolder(View itemView) { super(itemView); textDisplay = (TextView) itemView.findViewById(R.id.text_display); itemView.setOnClickListener(this); } public void bindData(int position){ textDisplay.setText(Integer.toString(data[position])); } @Override public void onClick(View view) { } } } <file_sep>/app/src/main/java/com/fredo/barebonesrecyclerview/view/ActivityViewInterface.java package com.fredo.barebonesrecyclerview.view; import com.hannesdorfmann.mosby.mvp.MvpView; /** * Created by alfredovelasco on 12/19/16. */ public interface ActivityViewInterface extends MvpView { void displayData(int[] data); void setUpRecyclerView(); }<file_sep>/app/src/main/java/com/fredo/barebonesrecyclerview/view/MainActivity.java package com.fredo.barebonesrecyclerview.view; import android.support.annotation.NonNull; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.fredo.barebonesrecyclerview.R; import com.fredo.barebonesrecyclerview.presenter.Presenter; import com.hannesdorfmann.mosby.mvp.MvpActivity; public class MainActivity extends MvpActivity<ActivityViewInterface, Presenter> implements ActivityViewInterface { private RecyclerView recyclerView; private RecyclerAdapter recAdapter; private LinearLayoutManager layoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setUpRecyclerView(); showNumList(); } private void showNumList() { presenter.loadData(); } @Override public void setUpRecyclerView() { recyclerView = (RecyclerView) findViewById(R.id.list); recAdapter = new RecyclerAdapter(); layoutManager = new LinearLayoutManager(this); recyclerView.setAdapter(recAdapter); recyclerView.setLayoutManager(layoutManager); } @NonNull @Override public Presenter createPresenter() { return new Presenter(); } @Override public void displayData(int[] data) { recAdapter.setData(data); recAdapter.notifyDataSetChanged(); } }
45662625f2cdea7f202e25e48c9831267f1ff148
[ "Markdown", "Java" ]
4
Markdown
fredo-/MosbyBareBonesRecyclerView
b3fdf6a3a3b227510e65e19d6c3de0f58bb32e22
32c514bf9b9319ec6fd8f89e6900ecb97c130a9e
refs/heads/master
<file_sep>#include<stdio.h> int mnoz(int a, int b) { printf("Wynik mnozenia: %i\n", a * b); return a * b ;} int dodaj(int a, int b) { printf("Wynik dodawania: %i\n", a + b); return a + b;} int dziel(int a, int b) { printf("Wynik dzielenia: %i\n", a / b); return a / b;} int odejmij(int a, int b) { printf("Wynik odejmowania: %i\n", a - b); return a - b;} int main() { int a = 2, b = 5; char wybor; printf("Podaj wartosc argumentu a: "); scanf("%i", &a); printf("Podaj wartosc argumentu b: "); scanf("%i", &b); printf("Podaj dzialanie: "); scanf("%c", &wybor); scanf("%c", &wybor); if(wybor =='*') {mnoz(a,b);} else if(wybor =='+') {dodaj(a,b);} else if(wybor =='/') {dziel(a,b);} else if(wybor =='-') {odejmij(a,b);}; return 0; } <file_sep>#include<stdio.h> /*dolaczenie biblioteki standardowej input-output, to jest gotowa bibliotek w programie gcc z ktorej korzystamy podjac polecenia main putchar */ /* y=f(x) */ /* f()=>0 */ int main() /* funkcja głowna programu */ /*int - typ zwracanej wartości (int-wartosc całkowita)*/ { puts("Pierwszy program"); /* puts - funkcja z biblioteki standardowej */ /* puts - put string -*/ /*wyswietlajaca ciag znakow*/ /* automatycznie przechodzi do nowej lini*/ putchar('g'); /* wyświetla pojedynczy znak, w tym przypadku to co w nawiasie */ putchar('\n'); /*znak konca lini*/ putchar('\t'); /*tabulator*/ /*putchar('\r');/*powrót karetki - kursor powraca na początek lini*/ putchar('\\'); /*wypisuje \*/ return 0; } /*klamry oznaczaja blok funkcji, zwykle cialo funkcji */ // tak tez mozna wpisywac komentarze nie trzeba ich wtedy zamykac <file_sep>#include<stdio.h> int mnoz(int a, int b) { return a * b; } int dodaj(int a, int b) { return a + b;} int main() { int a = 2, b = 5; /*deklaracja wraz z inicjalizacja */ char wybor; scanf("%c", &wybor); /* to oznacza czytaj z konsoli i zapisz wartosc pod wybor */ /* if -( wyrazenie){ blok jesli wyrazenie prawdziwe} else {blok jesli wyrazenie fałszywe}; */ if(wybor =='*'){; /* == to operator ktory sprawdza czy rowne badz rozne */ printf("wynik mnozenia: %i\n", mnoz(a,b)); }else{printf("wynik dodawania: %i\n", dodaj(a,b)); }; int wynik; /*deklaracja zmiennej typu całkowitego, kompilator nie wie co oznacza*/ /*wyraz wynik wiec poleceniem int podpowiadasz mu co ma zrobic - wyswietlic wynik*/ /*wynik = mnoz(a,b); /*wskazuje co ma zrobic, pomnozyc argumenty */ /*printf("wynik mnozenia: %i\n", wynik);/* wyswietla wynik dzialania - mnozenia */ return 0; } <file_sep> 1 help 2 ls 3 ls -l 4 ls -l -a 5 ls -la 6 history 7 ls 8 ls -la 9 pwd 10 clear 11 ctrl l 12 clear 13 cd desktop 14 cd Desktop 15 cd Pulpit 16 cd 17 cd .. 18 cd ../.. 19 cd Pulpit 20 cd Pulpti 21 cd <pulpit 22 cd Pulpit 23 pwd 24 ls 25 exit 26 cd Pulpit 27 mkdir test 28 cd test 29 git 30 sudo apt install git 31 git --version 32 git 33 git help 34 git --help 35 touch test.txt 36 edit test.txt 37 cd test 38 cd Pulpit test 39 cd Pulpit 40 cd test 41 nano test.txt 42 ls -la 43 git init 44 ls -la 45 git status 46 git add test.txt 47 git status 48 git commit 49 git commit -m "utworzenie nowego pliku" 50 git config --global user.email "<EMAIL>" 51 git config --global user.name "kumy74" 52 git status 53 git commit 54 git status 55 git commit -m "utworzenie nowego pliku" 56 git log 57 nano test.txt 58 git status 59 git add . 60 git commit -m"pierwsza zmiana w pliku" 61 git log 62 nano text.txt 63 nano test.txt 64 git add . 65 git commit -m"to już druga zmiana" 66 git status 67 git log 68 git remote add origin https://github.com/kumy74/test.gif 69 git push -u origin master 70 git remote add origin https://github.com/kumy74/test.git 71 git remote add origin https://github.com/kumy74/test.txt 72 git remote add origin https://github.com/kumy74/test.git 73 git push -u origin master 74 git remote add origin https://github.com/kumy74/test.git 75 git push -u origin master 76 gif log 77 cd first_depo 78 cd Pulpit 79 gif log 80 cd first_depo 81 gif log 82 git log 83 cd Pulpit 84 cd first_repo 85 git log 86 git status 87 git remote add origin https://github.com/kumy74/first_repo.git 88 git push -u origin master 89 git status 90 git log 91 git add. 92 history > readme.md 93 git status 94 git add. 95 git add . 96 git commit 97 git commit -m "<NAME>" 98 git push 99 git remote add origin https://github.com/kumy74/first_repo.git 100 git push -u origin master 101 git remote add origin https://github.com/kumy74/first_repo.git 102 git push -u origin master 103 cd Pulpit 104 cd first_re 105 cd first_repo 106 git status 107 git log 108 git remote add or 109 git remote add origin https://github.com/kumy74/first_repo.git 110 git push -u origin master 111 git status 112 git init 113 git remote add origin https://github.com/kumy74/first_repo.git 114 git push -u origin master 115 cd Pulpit 116 cd .. 117 mkdir pierwszy_program 118 cd pierwszy_program 119 touch program1.c 120 nano program1.c 121 gcc program1.c -o program1.o 122 nano program1.c 123 gcc program1.c -o program1.o 124 nano program1.c 125 gcc program1.c -o program1.o 126 ./program1.o 127 nano program1.c 128 ./program1.o 129 nano program1.c 130 gcc program1.c -o program1.o 131 ./program1.o 132 nano program1.c 133 gcc program1.c -o program1.o 134 ./program1.o 135 git init 136 ls -la 137 git status 138 touch .gitignore 139 ls -la 140 nano .gitignore 141 ls -la 142 git status 143 git add program1.c 144 git status 145 git commit -m "pierwszy program w jezyku C" 146 git log 147 git remote add origin https://github.com/kumy74/program.git 148 git push -u origin master 149 git status 150 git add . 151 git status 152 git push 153 git push -u origin master 154 git status 155 git commit 156 git status 157 git push -u origin master 158 git add . 159 git status 160 git log 161 nano .gitignore 162 ls -la 163 git status 164 git commit -m "gitignore" 165 git push 166 cd ../first_repo/ 167 ls 168 ls -la 169 git status 170 git remote -v 171 git push -u origin master 172 git remote remove origin 173 git remote add origin https://github.com/kumy74/test.git 174 git remote -v 175 git push -u origin master 176 git remote remove origin 177 git remote add origin https://github.com/kumy74/first_repo.git 178 git push -u origin master 179 touch history readme.md 180 git status 181 git add . 182 git status 183 git commit -m "historia" 184 git status 185 git push 186 cd .. 187 cd pierwszy_program 188 touch program2.c 189 nano program2.c 190 gcc program2.c -o program2.o 191 ./program2.o 192 nano program2.c 193 gcc program2.c -o program2.o 194 ./program2.o 195 nano program2.c 196 gcc program2.c -o program2.o 197 nano program2.c 198 gcc program2.c -o program2.o 199 nano program2.c 200 gcc program2.c -o program2.o 201 ./program2.o 202 nano program2.c 203 gcc program2.c -o program2.o 204 nano program2.c 205 gcc program2.c -o program2.o 206 nano program2.c 207 gcc program2.c -o program2.o 208 nano program2.c 209 gcc program2.c -o program2.o 210 nano program2.c 211 gcc program2.c -o program2.o 212 ./program2.o 213 git status 214 git add program2.c 215 git status 216 git commit -m "zmiana w programie jesli, to" 217 git status 218 git push 219 nano program2.c 220 gcc program2.c -o program2.o 221 ./program2.o 222 git commit -m "<NAME> jest +, to dodaj argumenty ab" 223 git add program2.c 224 git status 225 git commit -m "<NAME> jest +, to dodaj argumenty ab" 226 git push 227 history > readme.md
1422dbda0a7f497c7aec0886ee2fa7d6f38155bc
[ "Markdown", "C" ]
4
C
kumy74/program
a98a2420f39c284a5545339dad91510ec4fd5051
87f0494c1b079a7c42a651f390233b6cf9b45c82
refs/heads/master
<file_sep>## demo > https://youyeke.github.io/javascript/loginFormCheck/ <file_sep><?php $fileID=$_POST["fileID"]; $md5=$_POST["md5"]; $temPath="../tem/"; if(is_uploaded_file($_FILES['file']['tmp_name'])){ move_uploaded_file($_FILES['file']['tmp_name'],$temPath.$md5."/".$fileID); echo "success"; } ?><file_sep>(function(w,undefined){ w.Pagination = function(config){ this.bindDOM = config.el; this.url = config.url; this.limit = config.limit || 10; this.limitKey = config.limitKey || 'limit'; this.page = config.page || 1; this.pageKey = config.pageKey || 'page'; this.lastPage = 0; this.lastPageKey = config.lastPageKey || 'lastPage'; this.data = config.data || {}; this.before = config.before || ''; this.callback = config.callback || ''; //this.Ajax(); this.bindEvent(); } Pagination.prototype.update = function(data){//ajax时添加额外的参数 for(key in data){ this.data[key] = data[key]; } this.Ajax(); } Pagination.prototype.Ajax = function(){ this.data[this.pageKey] = this.page; this.data[this.limitKey] = this.limit; if(typeof(this.before) === 'function'){ this.before(); } $.ajax({ url: this.url, type: 'get', context: this, data: this.data, success: function(d){ this.lastPage = parseInt(d[this.lastPageKey],10); if(d[this.pageKey]){//如果后端有传当前的页码,以后端传的为准 this.page = parseInt(d[this.pageKey],10); } this.draw(); this.callback(d); } }); } Pagination.prototype.draw = function(){ var html = '<ul class="pagination">', page = this.page; html += this.drawPrevious(); html += this.pageBefore(); html += '<li class="active"><a href="javascript:;">'+ this.page +'</a></li>'; html += this.pageAfter(); html += this.drawNext(); html += '</ul>'; this.bindDOM.innerHTML = html; setTimeout(function(){ $('#pagination_lastPage')[0].title = '第 '+ page + ' 页'; },20); } Pagination.prototype.drawPrevious = function(){ var html = '<li><a href="javascript:;"><span aria-hidden="true">&laquo;</span></a></li>'; if(this.page == 1){ html = html.replace(/<li>/,'<li class="disabled">'); } return html; } Pagination.prototype.drawNext = function(){ var html = '<li id="pagination_lastPage"><a href="javascript:;"><span aria-hidden="true">&raquo;</span></a></li>'; console.log(this.page,this.lastPage) if(this.page >= this.lastPage){ html = html.replace(/<li id="pagination_lastPage">/,'<li id="pagination_lastPage" class="disabled">'); } return html; } Pagination.prototype.pageBefore = function(){ var html = ''; if(this.page > 3){ html += '<li class="disabled"><a href="javascript:;">…</a></li>'; } for(var i = 2; i > 0; i--){ if(this.page - i > 0){ html += '<li><a href="javascript:;">'+ (this.page - i) +'</a></li>'; } } return html; } Pagination.prototype.pageAfter = function(){ var html = ''; for(var i = 1; 3 > i; i++){ if(this.page + i <= this.lastPage){ html += '<li><a href="javascript:;">'+ (this.page + i) +'</a></li>'; } } if(this.lastPage - this.page >= 3){ html += '<li class="disabled"><a href="javascript:;">…</a></li>'; } return html; } Pagination.prototype.bindEvent = function(){ var _this = this; this.bindDOM.addEventListener('click',function(e){ var oLi = e.target; while(oLi.tagName !== 'LI'){ if(oLi === _this.bindDOM) return false;//以防意外 oLi = oLi.parentElement; } if(oLi.className !== 'disabled' && oLi.className !== 'active'){ var actionMap = { '«': function(){ return 1; }, '»': function(){ return _this.lastPage; }, 'default': function(type){ return parseInt(type,10); } } var page = (actionMap[oLi.innerText] || actionMap['default'])(oLi.innerText); _this.page = page; _this.Ajax(); } }) } })(window);<file_sep>(function(window,undefined){ var maskOperate = { list : [], clearMask : function(){ if(arguments[0] == undefined){ var body=document.body; var mask=document.getElementById("maskBackground"); if(mask && mask.childNodes.length === 0) body.removeChild(mask); } }, addMask : function(type,className,message,callback,time){ this.list.push({ "tipsType" : type, "className": className, "message": message, "callback":callback, "time" : time }); this.check(); }, tipsTypePopupMap : { 'news' : function(oTips){ this.popupNews(oTips); }, 'tips' : function(oTips){ this.popupTips(oTips); } }, tipsTypeCloseMap : { 'news' : function(oTips,config){ var _this = this; setTimeout(function(){ if(typeof(config.callback) === 'function') config.callback(); _this.closeNews(oTips); },config.time); }, 'tips': function(oTips,config){ var _this = this; this.bandClickEvent(oTips,config.callback,function(){ setTimeout(function(){ _this.closeTips(oTips); },config.time); }); } }, check : function(){ if(this.list.length > 0){ var tipsType = this.list[0].tipsType; var oTips = this.createMask(this.list[0]); (this.tipsTypePopupMap[tipsType]).call(this,oTips); (this.tipsTypeCloseMap[tipsType]).call(this,oTips,this.list[0]); this.list.shift(); }else{ this.clearMask(); } }, createMask : function(config){ var maskDOM = document.getElementById('maskBackground'); var oDiv = document.createElement('div'); oDiv.className = config.className; oDiv.innerHTML = config.message; if(!maskDOM){ var body = document.body; maskDOM = document.createElement("div"); maskDOM.id = "maskBackground"; body.appendChild(maskDOM); } maskDOM.appendChild(oDiv); return oDiv; }, popupNews : function(oTips){ setTimeout(function(){ oTips.style.top = 0; oTips.style.opacity = 1; document.getElementById("maskBackground").style.height = 'auto'; },20); }, closeNews : function(oTips){ var _this = this; setTimeout(function(){ oTips.style.top = '-4em'; oTips.style.opacity = 0; oTips.style.height = 0; document.getElementById("maskBackground").style.height = '100%'; },20); setTimeout(function(){ document.getElementById("maskBackground").removeChild(oTips); document.getElementById("maskBackground").style.height = ''; _this.clearMask(); },500); }, popupTips : function(oTips){ var cancelBut = $('#maskBackground button[value="cancel"]'); if(cancelBut.length === 0){ $('#maskBackground button[value="confirm"]').focus(); }else{ cancelBut.focus(); } setTimeout(function(){ oTips.style.marginLeft = window.innerWidth/2 - oTips.clientWidth/2 +'px'; oTips.style.transform = 'scale(1)'; oTips.style.zoom = 1; document.getElementById("maskBackground").style.background = 'hsla(0,0%,0%,0.5)'; },20); }, closeTips : function(oTips){ var _this = this; setTimeout(function(){ oTips.style.marginLeft = window.innerWidth +'px'; oTips.style.transform = 'scale(0)'; oTips.style.opacity = 0; oTips.style.height = 0; document.getElementById("maskBackground").style.background = 'transparent'; },20); setTimeout(function(){ document.getElementById("maskBackground").removeChild(oTips); _this.clearMask(); },500); }, bandClickEvent : function(DOM,callback,close){ DOM.addEventListener("click",function(e){ if(typeof(callback) == 'function'){ if(e.target.value === "confirm"){ callback(); } } if(e.target.type == "button"){ this.removeEventListener("click",arguments.callee); close(); } },false); } }; var maskLayer = { clearMask : function(){ maskOperate.clearMask(); }, news : function(config,callback){ if(typeof(config) ==='string'){ config = {message: config}; } config.className = config.className || 'alert alert-'+(config.type || "info"); config.message = config.message || ''; config.time = config.time || 1500; maskOperate.addMask('news',config.className,config.message,callback, config.time || 1500); }, tips : function(config,callback){ if(typeof(config) ==='string'){ config = {message: config}; } config.title = config.title || '提示'; config.type = config.type || 'primary'; config.confirm = config.confirm || '确定'; var className = 'modal-dialog modal-sm tips'; var message = [ '<div class="modal-dialog modal-sm">', '<div class="modal-content">', '<div class="modal-header">', '<h4 class="modal-title">'+ config.title +'</h4>', '</div>', '<div class="modal-body">'+ config.message +'</div>', '<div class="modal-footer">', '<button type="button" value="confirm" class="btn btn-'+ config.type +'">'+ config.confirm +'</button>', '</div>', '</div>', '</div>' ].join(''); maskOperate.addMask('tips',className,message,callback); }, warn : function(config,callback){ if(typeof(config) ==='string'){ config = {message: config}; } config.title = config.title || '警告'; config.type = config.type || 'danger'; config.cancel = config.cancel || '取消'; config.confirm = config.confirm || '确定'; var className = 'modal-dialog modal-sm tips'; var message = [ '<div class="modal-dialog modal-sm">', '<div class="modal-content">', '<div class="modal-header">', '<h4 class="modal-title">'+ config.title +'</h4>', '</div>', '<div class="modal-body">'+ config.message +'</div>', '<div class="modal-footer">', '<button type="button" value="cancel" class="btn btn-default">'+ config.cancel +'</button>', '<button type="button" value="confirm" class="btn btn-'+ config.type +'">'+ config.confirm +'</button>', '</div>', '</div>', '</div>' ].join(''); maskOperate.addMask('tips',className,message,callback); } } window.maskLayer = maskLayer; })(window); <file_sep># 这个库是干嘛用的? > 这里放着我学习时碰到的,并经过整理后可供复用的代码 ## 断点续传 > 原生javascript + PHP ,需要用到 js-spark-md5 来计算文件MD5 > 点击前往该组件 :https://github.com/youyeke/javascript/tree/master/HTML5-fileUpload > js-spark-md5 的 GitHub :https://github.com/satazor/js-spark-md5 ## 登陆表单验证 > 点击前往该组件 :https://github.com/youyeke/javascript/tree/master/loginFormCheck ## 遮罩型弹出提示 > 点击前往该组件 :https://github.com/youyeke/javascript/tree/master/maskTips ## 日期输入 > 点击前往该组件 :https://github.com/youyeke/javascript/tree/master/inputTime <file_sep><?php $fileName=$_POST["fileName"]; $fileEndID=$_POST["fileEndID"]; $md5=$_POST["md5"]; $temPath="../tem/"; $fullFilePath="../work/"; if(!file_exists($fullFilePath)){ mkdir($fullFilePath,0777); }; unlink($fullFilePath.$fileName); fopen($fullFilePath.$fileName,"w+"); for($i = 0;$i <= $fileEndID;$i++){ file_put_contents($fullFilePath.$fileName,file_get_contents($temPath.$md5."/".$i),FILE_APPEND); } if($md5==md5_file($fullFilePath.$fileName)){ echo "校验成功"; }else{ echo "校验失败\n"; echo "文件名:".$fileName."\n"; echo $md5."\n"; echo "不等于\n"; echo md5_file($fullFilePath.$fileName); }; for($i=0;$i<=$fileEndID;$i++){ unlink($temPath.$md5."/".$i); }; rmdir($temPath.$md5);<file_sep># Demo > https://youyeke.github.io/javascript/maskTips/ bootstrap 版 > https://youyeke.github.io/javascript/maskTips/index-bootstrap.html # 使用方法 ## bootstrap 版 引入 bootstrap-maskTips.js 和 css/bootstrap-maskTips.css ### 弹出提示 ```javascript //简洁调用 maskLayer.tips('提示的内容'); //完整参数调用,message 必须,其它可选 maskLayer.tips({ title : '提示框标题', message : '提示框内容', type : 'primary', // 提示框的主题颜色,支持 Bootstrap 的全部主题颜色。 confirm : '确定' // ‘确定’ 按钮的文字 }); ``` PS. 无论是简洁调用还是全参数调用,第二个参数可传入一个回调函数。该回调函数将会在点击 ‘确定’ 后调用。 ### 弹出确认提示 ```javascript //简洁调用 maskLayer.warn('提示的内容'); //完整参数调用,message 必须,其它可选 maskLayer.warn({ title : '提示框标题', message : '提示框内容', type : 'danger', // 提示框的主题颜色,支持 Bootstrap 的全部主题颜色。 cancel : '取消', // ‘取消’ 按钮的文字 confirm : '确定' // ‘确定’ 按钮的文字 }); ``` PS. 无论是简洁调用还是全参数调用,第二个参数可传入一个回调函数。该回调函数将会在点击 ‘确定’ 后调用。 ### 广播提示 广播提示会出现在屏幕正上方,不拥堵用户操作。默认 1.5 秒后自动消失。 ```javascript //简洁调用 maskLayer.news('提示的内容'); //完整参数调用,message 必须,其它可选 maskLayer.news({ title : '提示框标题', message : '提示框内容', type : 'info', // 广播提示的主题颜色,支持 Bootstrap 的全部主题颜色。 time : 3000 // 多少毫秒后自动消失 }); ``` PS. 无论是简洁调用还是全参数调用,第二个参数可传入一个回调函数。该回调函数将会在广播提示消失后调用。 ## 无依赖版 在引入 js 后,会暴露一个全局对象:maskLayer ### maskLayer.tips 该方法用于弹出一个带有确认按钮的提示,点击‘确定’后关闭 ```javascript maskLayer.tips("提示的内容"); ``` 你也可以使用第二个参数来改变提示的主题颜色 ```javascript maskLayer.tips("警告型提示","failed"); ``` ### maskLayer.warn 该方法用于弹出一个带有‘确定’和‘取消’两个按钮的警告提示 点击‘确定’才会执行回调函数,点‘取消’则会关闭提示 该方法接受两个参数,第一个参数是提示的内容,第二个参数是回调函数 maskLayer.warn(String,callback) Demo: ```javascript maskLayer.warn("警告框,按确认才能执行回调函数",function(){ maskLayer.tips("这是回调函数"); }); ``` ### maskLayer.news 该方法用于弹出一个等待提示,在一定时间后会自动关闭提示 该方法接受四个参数,第一个参数是提示的内容,第二个参数是主题颜色 第三个参数是等待时间(毫秒),第四个是回调函数 maskLayer.news(String,className,time,callback) Demo: ```javascript maskLayer.news("等待2秒","failed",2000,function(){ maskLayer.tips("2秒后才显示"); }); ``` ### maskLayer.wait 该方法用于弹出一个用户无法关闭自行的提示框 Demo: ```javascript maskLayer.wait("只能一直等待下去"); ``` ### maskLayer.clearMask 该方法用于关闭任何提示框,包括由 maskLayer.wait 产生的 Demo: ```javascript maskLayer.clearMask(); ``` <file_sep>(function(window,undefined){ window.FormCheck = function FormCheck(obj){ this.obj = obj.formObj; this.callback = obj.callback; this.bindList = []; } FormCheck.prototype.bind = function(index,regexp,requiredMessage,failedMessage){ //未来需求:当文本框失去焦点后触发ajax var obj = this.obj, bindList = this.bindList; obj[index].index=index;//该元素于form中的位置,用于下面的委托事件 bindList.push({ bindObj : obj[index], Regexp : regexp, requiredMessage : requiredMessage, failedMessage : failedMessage }); }; FormCheck.prototype.check = function(input){ var data =input.bindObj.value; var statu ={}; if(data==""){ statu.result=false; statu.message=input.requiredMessage; console.log(input.requiredMessage); return statu; }else{ var regexpselect = { "" : function(){ statu.result=true; return statu; }, "mail" : function(){ var Reg = new RegExp(/^\w+[@]\w+[\.]\w+$/); console.log(Reg) return check(Reg); }, "default" : function(){ var Reg = new RegExp(input.Regexp); return check(Reg); } }; var check = function(Reg){ if(Reg.test(data)){ statu.result=true; return statu; }else{ console.log(input.failedMessage); statu.result=false; statu.message=input.failedMessage; return statu; }; }; return (regexpselect[input.Regexp] || regexpselect["default"])(); }; }; FormCheck.prototype.addClass = function(input,meaObj){ input.bindObj.classList="input-error"; var parent = input.bindObj.parentNode, child =document.createElement("label"); var repeat=false; Array.prototype.forEach.call(parent.childNodes,function(item,index){//避免重复添加 if(item["localName"]=="label"){ repeat=true; } }); if(!repeat){ child.innerHTML = meaObj.message; child.classList = "input-error-Message"; parent.appendChild(child); } }; FormCheck.prototype.removeClass = function(input){ var parent = input.bindObj.parentNode; input.bindObj.classList=""; Array.prototype.forEach.call(parent.childNodes,function(item,index){ if(item["localName"]=="label"){ parent.removeChild(parent.childNodes[index]); } }); } FormCheck.prototype.ready = function(e){ var obj = this.obj, bindList = this.bindList, instantiation = this; obj.addEventListener("submit",function(e){ e.preventDefault(); var result=bindList.every(function(item,index){ var checkresult = instantiation.check(bindList[index]); if(!checkresult.result){ instantiation.addClass(bindList[index],checkresult); }; return checkresult.result; }); if(result){ var callback=instantiation.callback; callback(); } }); obj.addEventListener("focusin",function(e){ var input=bindList[e.target.index]; if(input!=undefined){ instantiation.removeClass(input); }; }); obj.addEventListener("focusout",function(e){ var input=bindList[e.target.index]; if(input!=undefined){ instantiation.removeClass(input); var result = instantiation.check(input); if(!result.result){ instantiation.addClass(input,result); }; }; },false); }; })(window); <file_sep><?php $md5=$_POST["md5"]; $fileEndID=$_POST["fileEndID"]; $temPath="../tem/"; $fileChunkList=[]; $notUpload=[]; if(!file_exists($temPath)){ mkdir($temPath,0777); } if(!file_exists($temPath.$md5)){ mkdir($temPath.$md5,0777); } $fileChunkList = range(0,$fileEndID); header("Content-Type: text/html;charset=utf-8"); for($i=0;$i<=$fileEndID;$i++){ if(!file_exists($temPath.$md5."/".$i)){ array_push($notUpload,$i); } }; asort($notUpload); //排序 echo json_encode($notUpload,JSON_UNESCAPED_UNICODE); <file_sep>//(c) Copyright 2017 youye. All Rights Reserved. (function(window,undefined){ console.log("HTML5-fileUpload version is v1.0.1") var $ = function(id){ return document.getElementById(id); }; var Ajax = function(obj){ this.type = obj.type || ""; this.url = obj.url || ""; this.data = obj.data || ""; this.success = obj.success || ""; this.failed = obj.failed || ""; this.progress = obj.progress || ""; }; Ajax.prototype.send = function(){ var type=this.type, url=this.url, data=this.data, success=this.success, failed=this.failed, progress=this.progress; var xhr = new XMLHttpRequest; if(progress){ xhr.upload.addEventListener("progress",function(obj){ progress(obj); },false); } xhr.onreadystatechange = function(e){ if(xhr.readyState==4){ if(xhr.status>=200 && xhr.status<300 || xhr.status==304){ success(xhr.responseText); }else{ failed(xhr.status); } } } if(type=="GET"||type=="get"){ xhr.open(type,url,true); xhr.send(null); }else if(type=="POST"||type=="post"){ xhr.open(type,url,true); xhr.send(data); }else{ console.log("不支持的Ajax方法"); return; } } var fileListCommand = { create : function(index,fileInfo){ var fileListHTML=[ "<tr id=\"FL"+index+"\">", "<td>"+fileInfo.name+"</td>", "<td>"+this.getTypeStype(fileInfo.type)+"</td>", "<td>"+this.getSize(fileInfo.size,"auto")+"</td>", "<td>等待上传</td>", "<td><a href=\"javascript:;\" data-type=\"delete\" data-id=\"FL"+index+"\">"+"取消"+"</a></td>", "</tr>" ].join(""); return fileListHTML; }, getTypeStype : function(mimeType){ var stypeMap = { "application/msword" : "doc", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "doc", "application/vnd.ms-powerpoint" : "ppt", "application/vnd.openxmlformats-officedocument.presentationml.presentation" : "ppt", "application/vnd.ms-excel" : "xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "xls", "image/jpeg" : "img", "image/gif" : "img", "image/png" : "img", "video/mp4" : "video", "video/x-msvideo" : "video", "video/mpeg" : "video", "video/quicktime" : "video", "audio/x-ms-wmv" : "video", "text/plain" : "txt", "application/zip" : "zip", "application/x-gzip" : "zip", "application/x-zip-compressed" : "zip", "application/octet-stream" : "rar", "default" : "file" }; return "<span class=\"icon-file-30px icon-file-30px-"+(stypeMap[mimeType] || stypeMap["default"])+"\"></span>"; }, getSize : function(fileSize,type,isUnits){ //接收三个参数,第一个:字节数(B),第二个:数据转换的依据(例如输入KB则永远依照KB进行转换).第三个:返回值是否带单位(number or string) var result=0;//缓存复杂运算的结果 var typeMap = { "B" : function(size,isUnits){ return isUnits?(fileSize+"B"):fileSize; }, "KB" : function(size,isUnits){ result=Math.round(fileSize*100/1024)/100; return isUnits?(result+"KB"):result; }, "MB" : function(size,isUnits){ result=Math.round(size*100/(1024*1024))/100; return isUnits?(result+"MB"):result; }, "auto" : function(size){ switch(true){ case size<1000: return size+" B"; break; case size<1000000: return Math.round(size*100/1024)/100+" KB"; break; case size<1000000000: return Math.round(size*100/(1024*1024))/100+" MB"; break; default: return "文件过大"; } }, "default" : function(){ return "第二个参数错误"; } }; return typeMap[type](fileSize,isUnits) || typeMap["default"](fileSize,isUnits); }, getFielMD5 : function(fileInfo,callback){ var fileReader = new FileReader, spark = new SparkMD5(); var md5 = null; fileReader.readAsBinaryString(fileInfo); fileReader.onload = function(e){ spark.appendBinary(e.target.result); md5=spark.end(); if (typeof(callback) === "function"){ callback(md5); } }; } }; window.UploadJS = function(obj){ this.upWorkFileBox = obj.upWorkFileBox; this.fileMD5Qurey = obj.fileMD5Qurey; this.formAction = obj.formAction; this.mergeFilesAction = obj.mergeFilesAction; this.fileChunk = obj.fileChunk; }; UploadJS.prototype.ready = function(){ var upWorkFileBox = this.upWorkFileBox; var self = this; var fileArray = this.fileArray = [],//用户选择上传的文件列,会转换为dom供用户操作 uploading = this.uploading = [];//确切要上传的文件,请确保由fileArray转化成 upWorkFileBox.innerHTML = [ "<form id=\"upWorkFileForm\"><input type=\"file\" class=\"file\" id=\"selectFile\" multiple />", "<span class=\"file-select-info\">选择需要上传的文件</span><input type=\"submit\" value=\"上传文件\" /></form>", "<table id=\"toBeUploaded\"></table>" ].join(""); var toBeUploadedOL="<tr><td>文件名</td><td>类型</td><td>大小</td><td>状态</td><td>操作</td></tr>"; setTimeout(function(){ var toBeUploaded = $("toBeUploaded"); /*选择文件时的操作*/ $("selectFile").addEventListener("change",function(){ Array.prototype.push.apply(fileArray,this.files); if(fileArray.length>0){ toBeUploaded.style.display = "block"; updataList(); }else{ toBeUploaded.style = ""; } }); /*移除上传列表的文件*/ toBeUploaded.addEventListener("click",function(e){ if(e.target.getAttribute("data-type") == "delete"){ var dataID = e.target.getAttribute("data-id"); var index = dataID.match(/\d/g); fileArray.splice(index[0],1); if(!fileArray.length>0){ toBeUploaded.style = ""; } updataList(); } }) /*提交事件*/ $("upWorkFileForm").addEventListener("submit",function(e){ e.preventDefault(); self.uploading = uploading; self.queryUploadedMD5(); }) function updataList(){//没想好怎么把它封装好,就暂时丢这里用着先 uploading = []; toBeUploaded.innerHTML = toBeUploadedOL; fileArray.forEach(function(fileInfo,index){ toBeUploaded.innerHTML += fileListCommand.create(index,fileInfo); fileListCommand.getFielMD5(fileInfo,function(md5){ uploading.push({ "fileInfo" : fileInfo, "md5" : md5, "DOM" : $("FL"+index) }); }); }); } },0); }; UploadJS.prototype.queryUploadedMD5 = function(){ console.log(this); var self = this, uploading = this.uploading, fileChunk = this.fileChunk, fileMD5Qurey = this.fileMD5Qurey; if(uploading.length>0){ uploading.forEach(function(info,index){ (function(info,index){ var queryData = new FormData(), size = info.fileInfo.size, fileEndID=Math.ceil(size/fileChunk)-1;//最后一个文件片段的ID,从0开始计数 self.uploading[index].fileEndID = fileEndID; queryData.append("md5",info.md5); queryData.append("fileEndID",fileEndID); var queryUploaded = new Ajax({ type : "post", url : fileMD5Qurey, data : queryData, success : function(data){ self.uploadFile(data,index); } }); queryUploaded.send(); })(info,index); }); }; }; UploadJS.prototype.uploadFile = function(data,index){ (function(data,index){ var notUpload = data.match(/\d+/g);//取回未上传的片段ID作为数组 if(notUpload != undefined){ notUpload=notUpload.map(function(item){ return parseInt(item); }); var self = this; var dom = this.uploading[index].DOM, tips = dom.childNodes[3]; var fileChunk = this.fileChunk, fileEndID = this.uploading[index].fileEndID, size = this.uploading[index].fileInfo.size, formAction = this.formAction; var upload = 0, needUpload = notUpload.length; var uploadedSize=needUpload>1?(fileEndID-needUpload+1)*fileChunk:0, concurrentList = [];//存储并发上传时各自的进度 console.log(this.uploading); while(notUpload[0] !== undefined){ var fileID = notUpload[0]; (function(fileID,tips){ var endSize=(notUpload[0]==fileEndID)?size:((notUpload[0]+1)*fileChunk), fileData= new FormData(); fileData.append("file", self.uploading[index].fileInfo.slice((notUpload[0]*fileChunk),endSize)); fileData.append("fileID",notUpload[0]); fileData.append("md5",self.uploading[index].md5); notUpload.shift(); var uploadFile = new Ajax({ type : "post", url : formAction, data : fileData, success : function(data){ upload++; if(upload == needUpload){ uploadFile.progress = null; self.mergeFiles(index); } }, failed : function(status){ console.log(status); }, progress : function(e){ var nowLoadSize = 0; concurrentList[fileID] = e.loaded; concurrentList.forEach(function(uploadedSize){ nowLoadSize+=uploadedSize; }); var tem=Math.round((uploadedSize+nowLoadSize)/size*10000)/100; console.log(tips) console.log(index) console.log(tem) tips.innerHTML=tem>=100?"<font color='#00f'>正在处理</font>":tem+"%"; } }); uploadFile.send(); })(fileID,tips) }; }else{ this.mergeFiles(index); } }).call(this,data,index); }; UploadJS.prototype.mergeFiles = function(index){ var self = this; console.log(this.uploading[index]) var dom = this.uploading[index].DOM; tips = dom.childNodes[3]; var command= new FormData(), mergeFilesAction = this.mergeFilesAction; command.append("fileName",this.uploading[index].fileInfo.name); command.append("fileEndID",this.uploading[index].fileEndID); command.append("md5",this.uploading[index].md5); var mergeFilesCommand = new Ajax({ type : "post", url : mergeFilesAction, data : command, success : function(data){ tips.innerHTML = "<font color='#0f0'>上传成功</font>"; console.log(self.uploading[index].fileInfo.name) console.log(tips) console.log(data); } }); mergeFilesCommand.send(); }; })(window);
e137e8a4ab03e1e6c4c6abfc7c40b3f86cabd3d2
[ "Markdown", "JavaScript", "PHP" ]
10
Markdown
youyeke/javascript
24d39acb456492821501ddda75d4e5ae0ea9f960
7e5866583c7971f95486ad67670fb2f526ba4776
refs/heads/master
<file_sep>require 'rails_helper' RSpec.describe User, type: :model do describe 'Validation' do it 'is invalid without a Name' do user = User.new(name: nil) user.valid? expect(user.errors[:name]).to include("can't be blank") end it 'can be valid' do expect(create(:user)).to be_valid end end describe 'Associations' do it 'has a post' do user = create(:user, :post) expect(user.posts.count).to eq 1 end end end <file_sep>require 'rails_helper' RSpec.describe Post, type: :model do describe 'Validation' do it 'is invalid without a Title' do post = Post.new(title: nil) post.valid? expect(post.errors[:title]).to include("can't be blank") end it 'is invalid without a Body' do post = Post.new(body: nil) post.valid? expect(post.errors[:body]).to include("can't be blank") end it 'can be valid' do expect(create(:post)).to be_valid end end describe 'Associations' do it 'belongs to a user' do user = create(:user, :post) expect(Post.last.user).to eq user end end end <file_sep>FactoryGirl.define do factory :post do title { Faker::Book.title } body { Faker::Lorem.paragraphs } association :user end end <file_sep>FactoryGirl.define do factory :user do name { Faker::Name.name } email { Faker::Internet.email } password '<PASSWORD>' password_confirmation '<PASSWORD>' trait :post do after(:create) do |user| user.posts << create(:post) end end end end <file_sep>require 'rails_helper' RSpec.describe PostsController, type: :controller do before do create_list(:post, 2) end describe '#index' do it 'assigns @posts' do get :index expect(assigns(:posts)).to eq Post.all end end describe '#show' do before do get :show, id: Post.first end it 'assigns the correct @post' do expect(assigns(:post)).to eq Post.first end end end <file_sep># app/controllers/post_controller.rb class PostsController < ApplicationController load_and_authorize_resource def index end def show end end
df24210ac34fe1a0e5c30f9db6500a6902b6f2cc
[ "Ruby" ]
6
Ruby
Reinkaos/crblog
60cf3b10f67370bdb1a2fe827129e99b00650a75
531987788a5d310c562af64058b18f6e565e8235
refs/heads/master
<repo_name>mattc41190/MovingRome<file_sep>/README.md # MovingRome A PoC for a dynamic history website written in javascript using jquery, jquery mobile and the google maps API. The app is currently split into two major sections, the main application which is the meat of the project (index.html) and the coordinate tool (coordinateTool.html). The coordinate tool is segregated in all areas except CSS. All pages respond to changes made in the main CSS sheet (mainstyle.css) <file_sep>/MainApp/JS/mainscript.js var map, mapOptions; var destinations3 = new google.maps.MVCArray(); var destinations4 = new google.maps.MVCArray(); var polyLine3, polyLineOptions3; var polyLine4, polyLineOption4; var augustus = []; var tiberius = []; var circleNum = 0; var menuShown = true; $(document).ready(function() { document.getElementById("dateShower").setAttribute("value", dates[0]); for(emperor in emperorArray) { var currentEmperor = emperorArray[emperor] currentEmperor.destinations.push(currentEmperor.locations[0]); } }); $('input[type="range"]').rangeslider({ polyfill: false, }); $(document).on('input', 'input[type="range"]', function(e){ value = e.target.value; circleNum = value; document.getElementById("dateShower").setAttribute("value", dates[value]); slideChanged(value); }); function slideChanged(value) { if(value >= destinations1.length) { while(value >= destinations1.length) { var lengthVal = destinations1.length; destinations1.push(pompey.locations[lengthVal]) destinations2.push(ceasar.locations[lengthVal]) destinations3.push(augustus[lengthVal]) destinations4.push(tiberius[lengthVal]) } } else if (value < destinations1.length) { while(value < destinations1.length -1) { destinations1.pop() destinations2.pop() destinations3.pop() destinations4.pop() } } } function initialize() { mapOptions = { mapTypeId: google.maps.MapTypeId.SATELLITE, center: new google.maps.LatLng(41.902277040963696, 12.5244140625), zoom: 6, maxZoom: 10, minZoom: 4, streetViewControl: false, zoomControl: false, panControl: false, mapTypeControl: false, }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); for (emperor in emperorArray) { emperorArray[emperor].Polyline = new google.maps.Polyline(emperorArray[emperor].polylineOptions); emperorArray[emperor].Polyline.setMap(map); } polyLineOptions3 = { path: destinations3, strokeColor: '#4D70B8', strokeOpacity: .1 }; polyLineOptions4 = { path: destinations4, strokeColor: ' #FFAD33', strokeOpacity: .1 }; polyLine3 = new google.maps.Polyline(polyLineOptions3); polyLine3.setMap(map); polyLine4 = new google.maps.Polyline(polyLineOptions4); polyLine4.setMap(map); } google.maps.event.addDomListener(window, 'load', initialize); //Function to actively liten to window resizing google.maps.event.addDomListener(window, "resize", function() { var center = map.getCenter(); google.maps.event.trigger(map, "resize"); map.setCenter(center); }); function showMenu() { console.log("clickedMenu"); if (menuShown == true) { document.getElementById("fMenu").style.opacity = "0"; document.getElementById("fMenu").style.height = "0px"; document.getElementById("fMenu").style.width = "0px"; menuShown = false; } else { document.getElementById("fMenu").style.opacity = "1"; document.getElementById("fMenu").style.height = "600px"; document.getElementById("fMenu").style.width = "250px"; menuShown = true; } } function showModal(circleElement, number) { console.log(number); var emperorName = circleElement.getAttribute("name"); document.getElementById("modalTitle").innerHTML = emperorName; document.getElementById("dynamicText").innerHTML = chooseSentence(emperorName, number); } function cellClicked(element, circleID) { var emperorName = element.getAttribute("name"); var circle = document.getElementById(circleID); console.log(emperorName); var colorActive = emperorArray[emperorName].active; if(colorActive == false) { element.className = emperorArray[emperorName].color; emperorArray[emperorName].active = true; emperorArray[emperorName].Polyline.setOptions({strokeOpacity:1.0}); circle.disabled = false; } else if (colorActive == true) { element.className = 'active' emperorArray[emperorName].color emperorArray[emperorName].active = false; emperorArray[emperorName].Polyline.setOptions({strokeOpacity:0}); circle.disabled = true; } } <file_sep>/CoordinateTool/CoordinateToolJS/mainscript.js // Create all vars current needed in global scope var poly, map; var markers = []; var rowButtons = []; var dateLocationsOutput = []; var destinations = new google.maps.MVCArray(); var placingIntermediateMarker = false; var entryPoint = destinations.getLength(); // Create the map and initalize the options for the map function initialize() { var mapOptions = { zoom: 5, disableDoubleClickZoom : true, center: new google.maps.LatLng(40.622291783092706, 17.91046142578125) }; map = new google.maps.Map(document.getElementById('map-canvas-tool'), mapOptions); var polyOptions = { path: destinations, strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 3 }; poly = new google.maps.Polyline(polyOptions); poly.setMap(map); // Add a listener for the click event google.maps.event.addListener(map, 'click', addLatLng); } // Bulk of this application belongs on the addLatLng function as all individual listners are declared upon creation function addLatLng(event) { // Create local variables var stringLatLng = event.latLng.toString(); var currentRowButtonId; // Log current index at which new points will be placed console.log("The current entry point is: " + entryPoint); // Change the point of entry for a new index allowing the user to place a point inbetween two previously existing points function changeEntry(element) { // Log the name of the button we click console.log(element.id) // Loop through all existing rowButtons, disable all other buttons, redefine entryPoint to be the index we want to insert at for(i in rowButtons) { if (rowButtons[i] != element.id) { document.getElementById(rowButtons[i]).setAttribute("disabled", "true"); } else { entryPoint = i; console.log("The value of the entry point is now set to : " + entryPoint) console.log("I am about to create a button not in order at index: "+ entryPoint); } } } // Loop through all table rows and assign currentButtonRowId to be current entryPoint for (var i = 0; i <= dateLocationsOutput.length; i++ ) { if(i == entryPoint) { currentRowButtonId = "rowBtn" + i; // Add button to the entryPoint index of the rowButtons array rowButtons.splice(i, 0, currentRowButtonId); } } // Add new table row and give each button it's own listener dateLocationsOutput.splice(entryPoint, 0,"<tr><td class='danger'> <button id='"+currentRowButtonId+ "'class='btn btn-primary'><span class='caret'></span></button></td><td class='active' >DateArea: "+stringLatLng+ "</td></tr>"); document.getElementById('latLongList').innerHTML = ""; document.getElementById('latLongList').innerHTML = dateLocationsOutput.join(""); for(i in dateLocationsOutput) { document.getElementById(rowButtons[i]).addEventListener('click', function(){changeEntry(this)}); } // Add new polyline point at point of 'click' event destinations.insertAt(entryPoint, event.latLng); // Add a new marker at the new plotted point on the polyline. var marker = new google.maps.Marker({ position: event.latLng, title: '#' + event.latLng, map: map, draggable: true }); markers.splice(entryPoint, 0, marker); // Delete Marker function // Add a 'click' listener to this newly placed marker (every marker gets its own click listener) google.maps.event.addListener(marker, 'click', function() { marker.setMap(null); var i = markers.indexOf(marker); if(i >= 0) { markers.splice(i,1); destinations.removeAt(i); dateLocationsOutput.splice(i,1); document.getElementById('latLongList').innerHTML = dateLocationsOutput.join(""); for(i in dateLocationsOutput) { document.getElementById(rowButtons[i]).addEventListener('click', function(){changeEntry(this)}); } } }); // Move Marker function // Add a 'dragend' listener to this newly placed marker (every marker gets its own dragend listener) google.maps.event.addListener(marker, 'dragend', function() { var i = markers.indexOf(marker); destinations.setAt(i, marker.getPosition()); newLocation = marker.getPosition().toString(); marker.setTitle(newLocation); dateLocationsOutput[i] = "<tr><td class='danger'> <button id='"+currentRowButtonId+ "'class='btn btn-primary'><span class='caret'></span></button></td><td class='active' >DateArea: "+newLocation+ "</td></tr>"; document.getElementById('latLongList').innerHTML = dateLocationsOutput.join(""); for(i in dateLocationsOutput) { document.getElementById(rowButtons[i]).addEventListener('click', function(){changeEntry(this)}); } } ); // Set entry point to destinations.getLength() so that we have a clean slate to start with. entryPoint = destinations.getLength(); } // addLatLng function ends here, it's a monster I know. // Create a method of clearing map of markers function setAllMap(map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } } // Use setAllMap function and set all array to empty to clear map. function clearAll() { setAllMap(null); markers = []; rowButtons = []; dateLocationsOutput = []; destinations.clear(); entryPoint = destinations.getLength(); document.getElementById('latLongList').innerHTML = dateLocationsOutput; } google.maps.event.addDomListener(window, 'load', initialize); <file_sep>/MainApp/JS/plots3.js augustus.push(new google.maps.LatLng(46.800059446787316, -135.87890625)) augustus.push(new google.maps.LatLng(46.92025531537451, -131.1328125)) augustus.push(new google.maps.LatLng(46.55886030311719, -127.79296875)) augustus.push(new google.maps.LatLng(46.6795944656402, -123.3984375)) augustus.push(new google.maps.LatLng(46.31658418182218, -119.70703125)) augustus.push(new google.maps.LatLng(46.195042108660154, -127.96875)) augustus.push(new google.maps.LatLng(44.715513732021336, -127.6171875)) augustus.push(new google.maps.LatLng(42.94033923363183, -127.265625)) augustus.push(new google.maps.LatLng(40.84706035607122, -127.44140625)) augustus.push(new google.maps.LatLng(38.548165423046584, -127.6171875)) augustus.push(new google.maps.LatLng(36.03133177633187, -127.79296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -128.14453125)) augustus.push(new google.maps.LatLng(33.7243396617476, -131.1328125)) augustus.push(new google.maps.LatLng(33.7243396617476, -134.296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -137.4609375)) augustus.push(new google.maps.LatLng(33.87041555094183, -126.38671875)) augustus.push(new google.maps.LatLng(33.7243396617476, -123.486328125)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(46.800059446787316, -135.87890625)) augustus.push(new google.maps.LatLng(46.92025531537451, -131.1328125)) augustus.push(new google.maps.LatLng(46.55886030311719, -127.79296875)) augustus.push(new google.maps.LatLng(46.6795944656402, -123.3984375)) augustus.push(new google.maps.LatLng(46.31658418182218, -119.70703125)) augustus.push(new google.maps.LatLng(46.195042108660154, -127.96875)) augustus.push(new google.maps.LatLng(44.715513732021336, -127.6171875)) augustus.push(new google.maps.LatLng(42.94033923363183, -127.265625)) augustus.push(new google.maps.LatLng(40.84706035607122, -127.44140625)) augustus.push(new google.maps.LatLng(38.548165423046584, -127.6171875)) augustus.push(new google.maps.LatLng(36.03133177633187, -127.79296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -128.14453125)) augustus.push(new google.maps.LatLng(33.7243396617476, -131.1328125)) augustus.push(new google.maps.LatLng(33.7243396617476, -134.296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -137.4609375)) augustus.push(new google.maps.LatLng(33.87041555094183, -126.38671875)) augustus.push(new google.maps.LatLng(33.7243396617476, -123.486328125)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(46.800059446787316, -135.87890625)) augustus.push(new google.maps.LatLng(46.92025531537451, -131.1328125)) augustus.push(new google.maps.LatLng(46.55886030311719, -127.79296875)) augustus.push(new google.maps.LatLng(46.6795944656402, -123.3984375)) augustus.push(new google.maps.LatLng(46.31658418182218, -119.70703125)) augustus.push(new google.maps.LatLng(46.195042108660154, -127.96875)) augustus.push(new google.maps.LatLng(44.715513732021336, -127.6171875)) augustus.push(new google.maps.LatLng(42.94033923363183, -127.265625)) augustus.push(new google.maps.LatLng(40.84706035607122, -127.44140625)) augustus.push(new google.maps.LatLng(38.548165423046584, -127.6171875)) augustus.push(new google.maps.LatLng(36.03133177633187, -127.79296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -128.14453125)) augustus.push(new google.maps.LatLng(33.7243396617476, -131.1328125)) augustus.push(new google.maps.LatLng(33.7243396617476, -134.296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -137.4609375)) augustus.push(new google.maps.LatLng(33.87041555094183, -126.38671875)) augustus.push(new google.maps.LatLng(33.7243396617476, -123.486328125)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(33.284619968887704, -121.025390625)) augustus.push(new google.maps.LatLng(46.800059446787316, -135.87890625)) augustus.push(new google.maps.LatLng(46.92025531537451, -131.1328125)) augustus.push(new google.maps.LatLng(46.55886030311719, -127.79296875)) augustus.push(new google.maps.LatLng(46.6795944656402, -123.3984375)) augustus.push(new google.maps.LatLng(46.31658418182218, -119.70703125)) augustus.push(new google.maps.LatLng(46.195042108660154, -127.96875)) augustus.push(new google.maps.LatLng(44.715513732021336, -127.6171875)) augustus.push(new google.maps.LatLng(42.94033923363183, -127.265625)) augustus.push(new google.maps.LatLng(40.84706035607122, -127.44140625)) augustus.push(new google.maps.LatLng(38.548165423046584, -127.6171875)) augustus.push(new google.maps.LatLng(36.03133177633187, -127.79296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -128.14453125)) augustus.push(new google.maps.LatLng(33.7243396617476, -131.1328125)) augustus.push(new google.maps.LatLng(46.92025531537451, -131.1328125)) augustus.push(new google.maps.LatLng(46.55886030311719, -127.79296875)) augustus.push(new google.maps.LatLng(46.6795944656402, -123.3984375)) augustus.push(new google.maps.LatLng(46.31658418182218, -119.70703125)) augustus.push(new google.maps.LatLng(46.195042108660154, -127.96875)) augustus.push(new google.maps.LatLng(44.715513732021336, -127.6171875)) augustus.push(new google.maps.LatLng(42.94033923363183, -127.265625)) augustus.push(new google.maps.LatLng(40.84706035607122, -127.44140625)) augustus.push(new google.maps.LatLng(38.548165423046584, -127.6171875)) augustus.push(new google.maps.LatLng(36.03133177633187, -127.79296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -128.14453125)) augustus.push(new google.maps.LatLng(33.7243396617476, -131.1328125)) augustus.push(new google.maps.LatLng(36.03133177633187, -127.79296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -128.14453125)) augustus.push(new google.maps.LatLng(33.7243396617476, -131.1328125)) augustus.push(new google.maps.LatLng(36.03133177633187, -127.79296875)) augustus.push(new google.maps.LatLng(33.7243396617476, -128.14453125)) augustus.push(new google.maps.LatLng(33.7243396617476, -131.1328125))<file_sep>/MainApp/JS/ceasarLocations.js function getCeasarLocations(ceasarLocations) { ceasarLocations.push(new google.maps.LatLng(43.97898113341921, 12.376785278320312)) ceasarLocations.push(new google.maps.LatLng(43.971074904863265, 12.380905151367188)) ceasarLocations.push(new google.maps.LatLng(43.95476498408514, 12.387771606445312)) ceasarLocations.push(new google.maps.LatLng(43.944878004396664, 12.3870849609375)) ceasarLocations.push(new google.maps.LatLng(43.93350594453702, 12.38433837890625)) ceasarLocations.push(new google.maps.LatLng(43.90778718292443, 12.388458251953125)) ceasarLocations.push(new google.maps.LatLng(43.85631630786513, 12.40081787109375)) ceasarLocations.push(new google.maps.LatLng(43.83254552160589, 12.407684326171875)) ceasarLocations.push(new google.maps.LatLng(43.80777421387378, 12.413177490234375)) ceasarLocations.push(new google.maps.LatLng(43.781009658142914, 12.41729736328125)) ceasarLocations.push(new google.maps.LatLng(43.74728909225905, 12.42279052734375)) ceasarLocations.push(new google.maps.LatLng(43.715534726205114, 12.4310302734375)) ceasarLocations.push(new google.maps.LatLng(43.66985832954972, 12.43377685546875)) ceasarLocations.push(new google.maps.LatLng(43.632099415557754, 12.432403564453125)) ceasarLocations.push(new google.maps.LatLng(43.598295002627175, 12.426910400390625)) ceasarLocations.push(new google.maps.LatLng(43.51868025160499, 12.418670654296875)) ceasarLocations.push(new google.maps.LatLng(43.46886761482925, 12.415924072265625)) ceasarLocations.push(new google.maps.LatLng(43.39107786275974, 12.415924072265625)) ceasarLocations.push(new google.maps.LatLng(43.30719248161192, 12.432403564453125)) ceasarLocations.push(new google.maps.LatLng(43.27720532212024, 12.451629638671875)) ceasarLocations.push(new google.maps.LatLng(43.24920396697784, 12.462615966796875)) ceasarLocations.push(new google.maps.LatLng(43.22118973298753, 12.468109130859375)) ceasarLocations.push(new google.maps.LatLng(43.1911601915877, 12.465362548828125)) ceasarLocations.push(new google.maps.LatLng(43.03276068583203, 12.46673583984375)) ceasarLocations.push(new google.maps.LatLng(42.98053954751642, 12.46673583984375)) ceasarLocations.push(new google.maps.LatLng(42.932296019030574, 12.47772216796875)) ceasarLocations.push(new google.maps.LatLng(42.896088552971065, 12.48870849609375)) ceasarLocations.push(new google.maps.LatLng(42.84375132629021, 12.49420166015625)) ceasarLocations.push(new google.maps.LatLng(42.79943131987838, 12.51617431640625)) ceasarLocations.push(new google.maps.LatLng(42.75507954507213, 12.52166748046875)) ceasarLocations.push(new google.maps.LatLng(42.69858589169842, 12.52716064453125)) ceasarLocations.push(new google.maps.LatLng(42.65820178455666, 12.54364013671875)) ceasarLocations.push(new google.maps.LatLng(42.512601715736665, 12.58209228515625)) ceasarLocations.push(new google.maps.LatLng(42.4639928001706, 12.60406494140625)) ceasarLocations.push(new google.maps.LatLng(42.4112905190282, 12.62054443359375)) ceasarLocations.push(new google.maps.LatLng(42.382894009614056, 12.63153076171875)) ceasarLocations.push(new google.maps.LatLng(42.26511445833756, 12.64801025390625)) ceasarLocations.push(new google.maps.LatLng(42.21224516288584, 12.64801025390625)) ceasarLocations.push(new google.maps.LatLng(42.114523952464246, 12.64251708984375)) ceasarLocations.push(new google.maps.LatLng(42.06560675405716, 12.62603759765625)) ceasarLocations.push(new google.maps.LatLng(42.032974332441405, 12.61505126953125)) ceasarLocations.push(new google.maps.LatLng(41.983994270935625, 12.61505126953125)) ceasarLocations.push(new google.maps.LatLng(41.96357478222518, 12.61505126953125)) ceasarLocations.push(new google.maps.LatLng(41.94314874732696, 12.60955810546875)) ceasarLocations.push(new google.maps.LatLng(41.84910468610387, 12.58209228515625)) ceasarLocations.push(new google.maps.LatLng(41.81636125072054, 12.60406494140625)) ceasarLocations.push(new google.maps.LatLng(41.78360106648078, 12.64251708984375)) ceasarLocations.push(new google.maps.LatLng(41.759019938155404, 12.63153076171875)) ceasarLocations.push(new google.maps.LatLng(41.74672584176937, 12.55462646484375)) ceasarLocations.push(new google.maps.LatLng(41.77131167976406, 12.49420166015625)) ceasarLocations.push(new google.maps.LatLng(41.77131167976406, 12.49420166015625)) ceasarLocations.push(new google.maps.LatLng(41.77131167976406, 12.49420166015625)) ceasarLocations.push(new google.maps.LatLng(41.77131167976406, 12.49420166015625))//Rome ceasarLocations.push(new google.maps.LatLng(41.77131167976406, 12.49420166015625))//Rome ceasarLocations.push(new google.maps.LatLng(41.77131167976406, 12.49420166015625))// Rome ceasarLocations.push(new google.maps.LatLng(41.88387623204764, 12.47772216796875)) ceasarLocations.push(new google.maps.LatLng(41.86547012230939, 12.63427734375)) ceasarLocations.push(new google.maps.LatLng(41.83682786072714, 12.755126953125)) ceasarLocations.push(new google.maps.LatLng(41.81636125072054, 12.843017578125)) ceasarLocations.push(new google.maps.LatLng(41.74262728637672, 13.1781005859375)) ceasarLocations.push(new google.maps.LatLng(41.70162734378918, 13.3428955078125)) ceasarLocations.push(new google.maps.LatLng(41.672911819602085, 13.4088134765625)) ceasarLocations.push(new google.maps.LatLng(41.63597302844412, 13.4912109375)) ceasarLocations.push(new google.maps.LatLng(41.60722821271716, 13.5791015625)) ceasarLocations.push(new google.maps.LatLng(41.59490508367679, 13.6669921875)) ceasarLocations.push(new google.maps.LatLng(41.57436130598913, 13.7603759765625)) ceasarLocations.push(new google.maps.LatLng(41.55381099217959, 13.853759765625)) ceasarLocations.push(new google.maps.LatLng(41.51680395810117, 13.9910888671875)) ceasarLocations.push(new google.maps.LatLng(41.475660200278234, 14.16961669921875)) ceasarLocations.push(new google.maps.LatLng(41.422134246213616, 14.27947998046875)) ceasarLocations.push(new google.maps.LatLng(41.3850519497068, 14.37835693359375)) ceasarLocations.push(new google.maps.LatLng(41.364441530542244, 14.46624755859375)) ceasarLocations.push(new google.maps.LatLng(41.32320110223851, 14.57061767578125)) ceasarLocations.push(new google.maps.LatLng(41.3108238809182, 14.61456298828125)) ceasarLocations.push(new google.maps.LatLng(41.281934557995356, 14.69696044921875)) ceasarLocations.push(new google.maps.LatLng(41.23238023874142, 14.83978271484375)) ceasarLocations.push(new google.maps.LatLng(41.166249339091976, 15.03753662109375)) ceasarLocations.push(new google.maps.LatLng(41.15797827873605, 15.11993408203125)) ceasarLocations.push(new google.maps.LatLng(41.13315883477399, 15.26824951171875)) ceasarLocations.push(new google.maps.LatLng(41.104190944576466, 15.49896240234375)) ceasarLocations.push(new google.maps.LatLng(41.091772220976644, 15.61981201171875)) ceasarLocations.push(new google.maps.LatLng(41.07106913080641, 15.78460693359375)) ceasarLocations.push(new google.maps.LatLng(41.0545019632905, 15.86700439453125)) ceasarLocations.push(new google.maps.LatLng(41.02964338716638, 15.93292236328125)) ceasarLocations.push(new google.maps.LatLng(41.01721057822846, 15.99334716796875)) ceasarLocations.push(new google.maps.LatLng(41.00477542222949, 16.14166259765625)) ceasarLocations.push(new google.maps.LatLng(40.97575093157534, 16.28448486328125)) ceasarLocations.push(new google.maps.LatLng(40.95501133048621, 16.36138916015625)) ceasarLocations.push(new google.maps.LatLng(40.9218144123785, 16.47125244140625)) ceasarLocations.push(new google.maps.LatLng(40.9052096972736, 16.60308837890625)) ceasarLocations.push(new google.maps.LatLng(40.88860081193033, 16.70745849609375)) ceasarLocations.push(new google.maps.LatLng(40.87614141141369, 16.79534912109375)) ceasarLocations.push(new google.maps.LatLng(40.85537053192496, 16.88323974609375)) ceasarLocations.push(new google.maps.LatLng(40.82212357516945, 16.98760986328125)) ceasarLocations.push(new google.maps.LatLng(40.75974059207392, 17.22930908203125)) ceasarLocations.push(new google.maps.LatLng(40.73893324113603, 17.30072021484375)) ceasarLocations.push(new google.maps.LatLng(40.72228267283148, 17.37762451171875)) ceasarLocations.push(new google.maps.LatLng(40.70562793820589, 17.52593994140625)) ceasarLocations.push(new google.maps.LatLng(40.6723059714534, 17.59735107421875)) ceasarLocations.push(new google.maps.LatLng(40.65563874006118, 17.69622802734375)) ceasarLocations.push(new google.maps.LatLng(40.64730356252251, 17.82806396484375)) ceasarLocations.push(new google.maps.LatLng(40.622291783092706, 17.91046142578125)) } <file_sep>/OtherPages/creatorInfo.html <!DOCTYPE HTML> <html> <head> <link href="css/simple-slider.css" rel="stylesheet" type="text/css" /> <link href="css/simple-slider-volume.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="../CSS/slatetheme.css"> <link rel="stylesheet" type="text/css" href="../css/bootstrap-switch.css"> <link rel="stylesheet" type="text/css" href="../CSS/mainstyle.css"> </head> <body> <div class='jumbotron'> <h1>Welcome to Roman Maps Alpha!</h1> </div> <div class='container'> <h4>My name is <NAME> and I am building this site to bring an interesting and dynamic feel to the things you've probably read about in history books. The site is still very much under construction and I am looking for anyone who is willing to contribute to the project by simply creating historical routes. To contribute simply click the contibute link below. Send any routes you create to <EMAIL>, along with the name of the person you were making the route for and the source material used to find the routes.</h4> <br> <h5><a href="../index.html">Map</a></h5> <h5><a href="../CoordinateTool/coordinateTool.html">Contribute</a></h5> </div> </body> </html> <file_sep>/MainApp/JS/plots.js plots1.push(new google.maps.LatLng(36.77, -75.417)); plots1.push(new google.maps.LatLng(36.71, -74.005)); plots1.push(new google.maps.LatLng(23.63, -102.552)); plots1.push(new google.maps.LatLng(25.63, -102.552)); plots1.push(new google.maps.LatLng(24.63, -108.552)); plots1.push(new google.maps.LatLng(29.63, -110.552)); plots1.push(new google.maps.LatLng(26.77, -129.417)); plots1.push(new google.maps.LatLng(41.71, -84.005)); plots1.push(new google.maps.LatLng(26.63, -112.552)); plots1.push(new google.maps.LatLng(22.63, -102.552)); plots1.push(new google.maps.LatLng(29.23, -107.552)); plots1.push(new google.maps.LatLng(33.63, -100.552)); plots2.push(new google.maps.LatLng(35.77, -118.417)); plots2.push(new google.maps.LatLng(44.71, -73.005)); plots2.push(new google.maps.LatLng(27.63, -101.552)); plots2.push(new google.maps.LatLng(28.63, -101.552)); plots2.push(new google.maps.LatLng(20.63, -101.552)); plots2.push(new google.maps.LatLng(20.63, -101.552)); plots2.push(new google.maps.LatLng(35.77, -118.417)); plots2.push(new google.maps.LatLng(42.71, -73.005)); plots2.push(new google.maps.LatLng(27.63, -103.552)); plots2.push(new google.maps.LatLng(21.63, -104.552)); plots2.push(new google.maps.LatLng(27.63, -105.552)); plots2.push(new google.maps.LatLng(29.63, -109.552)); plots3.push(new google.maps.LatLng(36.77, -75.417)); plots3.push(new google.maps.LatLng(36.71, -44.005)); plots3.push(new google.maps.LatLng(23.63, -102.552)); plots3.push(new google.maps.LatLng(25.63, -102.552)); plots3.push(new google.maps.LatLng(24.63, -108.552)); plots3.push(new google.maps.LatLng(26.63, -110.552)); plots3.push(new google.maps.LatLng(26.77, -129.417)); plots3.push(new google.maps.LatLng(41.71, -84.005)); plots3.push(new google.maps.LatLng(26.63, -112.552)); plots3.push(new google.maps.LatLng(22.63, -102.552)); plots3.push(new google.maps.LatLng(29.23, -107.552)); plots3.push(new google.maps.LatLng(34.63, -120.552)); plots4.push(new google.maps.LatLng(35.77, -118.447)); plots4.push(new google.maps.LatLng(44.71, -73.004)); plots4.push(new google.maps.LatLng(27.63, -134.542)); plots4.push(new google.maps.LatLng(28.63, -101.542)); plots4.push(new google.maps.LatLng(20.63, -101.542)); plots4.push(new google.maps.LatLng(22.63, -101.542)); plots4.push(new google.maps.LatLng(35.77, -118.447)); plots4.push(new google.maps.LatLng(42.71, -73.004)); plots4.push(new google.maps.LatLng(27.63, -103.542)); plots4.push(new google.maps.LatLng(21.63, -104.542)); plots4.push(new google.maps.LatLng(27.63, -105.552)); plots4.push(new google.maps.LatLng(29.63, -110.552)); plots5.push(new google.maps.LatLng(36.77, -75.417)); plots5.push(new google.maps.LatLng(36.71, -74.005)); plots5.push(new google.maps.LatLng(23.63, -102.552)); plots5.push(new google.maps.LatLng(25.63, -102.552)); plots5.push(new google.maps.LatLng(24.63, -106.552)); plots5.push(new google.maps.LatLng(29.63, -116.552)); plots5.push(new google.maps.LatLng(26.77, -126.417)); plots5.push(new google.maps.LatLng(41.71, -84.005)); plots5.push(new google.maps.LatLng(26.63, -119.552)); plots5.push(new google.maps.LatLng(22.63, -109.552)); plots5.push(new google.maps.LatLng(29.23, -109.552)); plots5.push(new google.maps.LatLng(33.63, -100.552)); plots6.push(new google.maps.LatLng(35.77, -118.417)); plots6.push(new google.maps.LatLng(44.71, -73.005)); plots6.push(new google.maps.LatLng(27.63, -101.552)); plots6.push(new google.maps.LatLng(28.63, -109.5342)); plots6.push(new google.maps.LatLng(20.63, -109.5342)); plots6.push(new google.maps.LatLng(20.63, -109.5342)); plots6.push(new google.maps.LatLng(35.77, -118.417)); plots6.push(new google.maps.LatLng(42.71, -73.005)); plots6.push(new google.maps.LatLng(27.63, -103.552)); plots6.push(new google.maps.LatLng(21.63, -104.552)); plots6.push(new google.maps.LatLng(27.63, -105.552)); plots6.push(new google.maps.LatLng(29.63, -109.552)); plots7.push(new google.maps.LatLng(36.77, -75.417)); plots7.push(new google.maps.LatLng(36.71, -74.005)); plots7.push(new google.maps.LatLng(23.63, -102.552)); plots7.push(new google.maps.LatLng(28.63, -102.552)); plots7.push(new google.maps.LatLng(28.63, -108.552)); plots7.push(new google.maps.LatLng(28.63, -110.552)); plots7.push(new google.maps.LatLng(21.77, -129.417)); plots7.push(new google.maps.LatLng(45.71, -84.005)); plots7.push(new google.maps.LatLng(25.63, -112.552)); plots7.push(new google.maps.LatLng(25.63, -102.552)); plots7.push(new google.maps.LatLng(25.23, -107.552)); plots7.push(new google.maps.LatLng(35.63, -100.552)); plots8.push(new google.maps.LatLng(35.77, -118.417)); plots8.push(new google.maps.LatLng(44.71, -73.005)); plots8.push(new google.maps.LatLng(27.63, -101.552)); plots8.push(new google.maps.LatLng(38.63, -101.552)); plots8.push(new google.maps.LatLng(20.63, -101.552)); plots8.push(new google.maps.LatLng(20.63, -101.552)); plots8.push(new google.maps.LatLng(35.77, -118.417)); plots8.push(new google.maps.LatLng(42.71, -73.005)); plots8.push(new google.maps.LatLng(25.63, -103.552)); plots8.push(new google.maps.LatLng(21.63, -144.552)); plots8.push(new google.maps.LatLng(27.63, -105.552)); plots8.push(new google.maps.LatLng(29.63, -129.552));<file_sep>/MainApp/JS/dateStrings.js var dates =[]; dates.push("01/08/49 BC") dates.push("01/09/49 BC") dates.push("01/10/49 BC") // Rubicon dates.push("01/11/49 BC") dates.push("01/12/49 BC") dates.push("01/13/49 BC") dates.push("01/14/49 BC") dates.push("01/15/49 BC") dates.push("01/16/49 BC") dates.push("01/17/49 BC") dates.push("01/18/49 BC") dates.push("01/19/49 BC") dates.push("01/20/49 BC") dates.push("01/21/49 BC") dates.push("01/22/49 BC") dates.push("01/23/49 BC") dates.push("01/24/49 BC") dates.push("01/25/49 BC") dates.push("01/26/49 BC") dates.push("01/27/49 BC") dates.push("01/28/49 BC") dates.push("01/29/49 BC") dates.push("01/31/49 BC") dates.push("02/01/49 BC") dates.push("02/02/49 BC") dates.push("02/03/49 BC") dates.push("02/04/49 BC") dates.push("02/05/49 BC") dates.push("02/05/49 BC") dates.push("02/07/49 BC") dates.push("02/08/49 BC") dates.push("02/09/49 BC") dates.push("02/10/49 BC") dates.push("02/11/49 BC") dates.push("02/12/49 BC") dates.push("02/13/49 BC") dates.push("02/14/49 BC") dates.push("02/15/49 BC") dates.push("02/16/49 BC") dates.push("02/17/49 BC") dates.push("02/18/49 BC") dates.push("02/19/49 BC") dates.push("02/20/49 BC") dates.push("02/21/49 BC") dates.push("02/22/49 BC") dates.push("02/23/49 BC") dates.push("02/24/49 BC") dates.push("02/25/49 BC") dates.push("02/25/49 BC") dates.push("02/26/49 BC") dates.push("02/27/49 BC") dates.push("02/28/49 BC") dates.push("03/01/49 BC") dates.push("03/02/49 BC") dates.push("03/03/49 BC") dates.push("03/04/49 BC") dates.push("03/05/49 BC") dates.push("03/05/49 BC") dates.push("03/07/49 BC") dates.push("03/08/49 BC") dates.push("03/09/49 BC") dates.push("03/10/49 BC") dates.push("03/11/49 BC") dates.push("03/12/49 BC") dates.push("03/13/49 BC") dates.push("03/14/49 BC") dates.push("03/15/49 BC") dates.push("03/16/49 BC") dates.push("03/17/49 BC") dates.push("03/18/49 BC") dates.push("03/19/49 BC") dates.push("03/20/49 BC") dates.push("03/21/49 BC") dates.push("03/22/49 BC") dates.push("03/23/49 BC") dates.push("03/24/49 BC") dates.push("03/25/49 BC") dates.push("03/25/49 BC") dates.push("03/26/49 BC") dates.push("03/27/49 BC") dates.push("03/28/49 BC") dates.push("03/29/49 BC") dates.push("03/30/49 BC") dates.push("03/31/49 BC") dates.push("04/01/49 BC") dates.push("04/02/49 BC") dates.push("04/03/49 BC") dates.push("04/04/49 BC") dates.push("04/05/49 BC") dates.push("04/05/49 BC") dates.push("04/07/49 BC") dates.push("04/08/49 BC") dates.push("04/09/49 BC") dates.push("04/10/49 BC") dates.push("04/11/49 BC") dates.push("04/12/49 BC") dates.push("04/13/49 BC") dates.push("04/14/49 BC") dates.push("04/15/49 BC") dates.push("04/16/49 BC") dates.push("04/17/49 BC") dates.push("04/18/49 BC") dates.push("04/19/49 BC") dates.push("04/20/49 BC") dates.push("04/21/49 BC") dates.push("04/22/49 BC") dates.push("04/23/49 BC") dates.push("04/24/49 BC") dates.push("04/25/49 BC") dates.push("04/25/49 BC") dates.push("04/26/49 BC") dates.push("04/27/49 BC") dates.push("04/28/49 BC") dates.push("04/29/49 BC") dates.push("04/30/49 BC") <file_sep>/MainApp/JS/plots4.js tiberius.push(new google.maps.LatLng(40.713955826286046, -68.90625)); tiberius.push(new google.maps.LatLng(38.8225909761771, -68.90625)); tiberius.push(new google.maps.LatLng(35.460669951495305, -68.73046875)); tiberius.push(new google.maps.LatLng(34.016241889667015, -68.73046875)); tiberius.push(new google.maps.LatLng(32.694865977875075, -68.73046875)); tiberius.push(new google.maps.LatLng(30.44867367928756, -68.5546875)); tiberius.push(new google.maps.LatLng(28.613459424004414, -68.02734375)); tiberius.push(new google.maps.LatLng(27.683528083787756, -66.796875)); tiberius.push(new google.maps.LatLng(27.683528083787756, -64.51171875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -62.05078125)); tiberius.push(new google.maps.LatLng(27.527758206861883, -60.46875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -58.53515625)); tiberius.push(new google.maps.LatLng(27.994401411046173, -56.77734375)); tiberius.push(new google.maps.LatLng(29.84064389983441, -56.25)); tiberius.push(new google.maps.LatLng(31.203404950917395, -56.09619140625)); tiberius.push(new google.maps.LatLng(32.26855544621479, -56.18408203125)); tiberius.push(new google.maps.LatLng(33.17434155100208, -56.085205078125)); tiberius.push(new google.maps.LatLng(34.27083595165, -55.953369140625)); tiberius.push(new google.maps.LatLng(35.42486791930558, -56.063232421875)); tiberius.push(new google.maps.LatLng(36.2354121683998, -56.0577392578125)); tiberius.push(new google.maps.LatLng(36.82687474287727, -56.1126708984375)); tiberius.push(new google.maps.LatLng(38.51378825951165, -56.27197265625)); tiberius.push(new google.maps.LatLng(40.17887331434696, -56.62353515625)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(40.713955826286046, -68.90625)); tiberius.push(new google.maps.LatLng(38.8225909761771, -68.90625)); tiberius.push(new google.maps.LatLng(35.460669951495305, -68.73046875)); tiberius.push(new google.maps.LatLng(34.016241889667015, -68.73046875)); tiberius.push(new google.maps.LatLng(32.694865977875075, -68.73046875)); tiberius.push(new google.maps.LatLng(30.44867367928756, -68.5546875)); tiberius.push(new google.maps.LatLng(28.613459424004414, -68.02734375)); tiberius.push(new google.maps.LatLng(27.683528083787756, -66.796875)); tiberius.push(new google.maps.LatLng(27.683528083787756, -64.51171875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -62.05078125)); tiberius.push(new google.maps.LatLng(27.527758206861883, -60.46875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -58.53515625)); tiberius.push(new google.maps.LatLng(27.994401411046173, -56.77734375)); tiberius.push(new google.maps.LatLng(29.84064389983441, -56.25)); tiberius.push(new google.maps.LatLng(31.203404950917395, -56.09619140625)); tiberius.push(new google.maps.LatLng(32.26855544621479, -56.18408203125)); tiberius.push(new google.maps.LatLng(33.17434155100208, -56.085205078125)); tiberius.push(new google.maps.LatLng(34.27083595165, -55.953369140625)); tiberius.push(new google.maps.LatLng(35.42486791930558, -56.063232421875)); tiberius.push(new google.maps.LatLng(36.2354121683998, -56.0577392578125)); tiberius.push(new google.maps.LatLng(36.82687474287727, -56.1126708984375)); tiberius.push(new google.maps.LatLng(38.51378825951165, -56.27197265625)); tiberius.push(new google.maps.LatLng(40.17887331434696, -56.62353515625)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(40.713955826286046, -68.90625)); tiberius.push(new google.maps.LatLng(38.8225909761771, -68.90625)); tiberius.push(new google.maps.LatLng(35.460669951495305, -68.73046875)); tiberius.push(new google.maps.LatLng(34.016241889667015, -68.73046875)); tiberius.push(new google.maps.LatLng(32.694865977875075, -68.73046875)); tiberius.push(new google.maps.LatLng(30.44867367928756, -68.5546875)); tiberius.push(new google.maps.LatLng(28.613459424004414, -68.02734375)); tiberius.push(new google.maps.LatLng(27.683528083787756, -66.796875)); tiberius.push(new google.maps.LatLng(27.683528083787756, -64.51171875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -62.05078125)); tiberius.push(new google.maps.LatLng(27.527758206861883, -60.46875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -58.53515625)); tiberius.push(new google.maps.LatLng(27.994401411046173, -56.77734375)); tiberius.push(new google.maps.LatLng(29.84064389983441, -56.25)); tiberius.push(new google.maps.LatLng(31.203404950917395, -56.09619140625)); tiberius.push(new google.maps.LatLng(32.26855544621479, -56.18408203125)); tiberius.push(new google.maps.LatLng(33.17434155100208, -56.085205078125)); tiberius.push(new google.maps.LatLng(34.27083595165, -55.953369140625)); tiberius.push(new google.maps.LatLng(35.42486791930558, -56.063232421875)); tiberius.push(new google.maps.LatLng(36.2354121683998, -56.0577392578125)); tiberius.push(new google.maps.LatLng(36.82687474287727, -56.1126708984375)); tiberius.push(new google.maps.LatLng(38.51378825951165, -56.27197265625)); tiberius.push(new google.maps.LatLng(40.17887331434696, -56.62353515625)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(40.713955826286046, -68.90625)); tiberius.push(new google.maps.LatLng(38.8225909761771, -68.90625)); tiberius.push(new google.maps.LatLng(35.460669951495305, -68.73046875)); tiberius.push(new google.maps.LatLng(34.016241889667015, -68.73046875)); tiberius.push(new google.maps.LatLng(32.694865977875075, -68.73046875)); tiberius.push(new google.maps.LatLng(30.44867367928756, -68.5546875)); tiberius.push(new google.maps.LatLng(28.613459424004414, -68.02734375)); tiberius.push(new google.maps.LatLng(27.683528083787756, -66.796875)); tiberius.push(new google.maps.LatLng(27.683528083787756, -64.51171875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -62.05078125)); tiberius.push(new google.maps.LatLng(27.527758206861883, -60.46875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -58.53515625)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(36.82687474287727, -56.1126708984375)); tiberius.push(new google.maps.LatLng(38.51378825951165, -56.27197265625)); tiberius.push(new google.maps.LatLng(40.17887331434696, -56.62353515625)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875)); tiberius.push(new google.maps.LatLng(40.713955826286046, -68.90625)); tiberius.push(new google.maps.LatLng(38.8225909761771, -68.90625)); tiberius.push(new google.maps.LatLng(35.460669951495305, -68.73046875)); tiberius.push(new google.maps.LatLng(34.016241889667015, -68.73046875)); tiberius.push(new google.maps.LatLng(32.694865977875075, -68.73046875)); tiberius.push(new google.maps.LatLng(30.44867367928756, -68.5546875)); tiberius.push(new google.maps.LatLng(28.613459424004414, -68.02734375)); tiberius.push(new google.maps.LatLng(27.683528083787756, -66.796875)); tiberius.push(new google.maps.LatLng(27.683528083787756, -64.51171875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -62.05078125)); tiberius.push(new google.maps.LatLng(27.527758206861883, -60.46875)); tiberius.push(new google.maps.LatLng(27.527758206861883, -58.53515625)); tiberius.push(new google.maps.LatLng(41.046216814520626, -56.942138671875));<file_sep>/MainApp/JS/infoData1.js function getPompeyData(pompeyData) { pompeyData.push("Pompey has not yet been introduced")// 01/08 pompeyData.push(null) pompeyData.push(null) // 01/10 Rubicon pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null)// pompeyData.push(null) pompeyData.push(null) // pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null)// pompeyData.push("Pompey and the senate flea from Rome. Leaving it entirely at the mercy of Ceasar.") pompeyData.push("Pompey and the senate flea from Rome. Leaving it entirely at the mercy of Ceasar.") // pompeyData.push("Pompey and the senate flea from Rome. Leaving it entirely at the mercy of Ceasar.") pompeyData.push("Pompey and the senate flea from Rome. Leaving it entirely at the mercy of Ceasar.") pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null)// pompeyData.push(null) pompeyData.push(null) // pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null)// pompeyData.push(null) pompeyData.push(null) // pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null)// pompeyData.push(null) pompeyData.push(null) // pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push("In March Pompey and the senate arrive in Brindisi") pompeyData.push("In March Pompey and the senate arrive in Brindisi") pompeyData.push("In March Pompey and the senate arrive in Brindisi") pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null)// pompeyData.push(null) pompeyData.push(null) // pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null) pompeyData.push(null)// pompeyData.push(null) pompeyData.push(null) // pompeyData.push(null) pompeyData.push(null) pompeyData.push( "Pompey arrives safely in Greece.") } function getCeasarData(ceasarData) { ceasarData.push("Ceasar has not yet been introduced") ceasarData.push(null) ceasarData.push("On January 10th Ceasar and his legions cors the Rubicon headed for Rome.")// ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push("Ceasar arrives in Rome to find it abandoned by Pompey and the senate.*") ceasarData.push("Ceasar arrives in Rome to find it abandoned by Pompey and the senate.*") ceasarData.push("Ceasar arrives in Rome to find it abandoned by Pompey and the senate.*") ceasarData.push("Ceasar arrives in Rome to find it abandoned by Pompey and the senate.*") ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push("Ceasar pursues Pompey and the fleaing senate.*") ceasarData.push("Ceasar pursues Pompey and the fleaing senate.*") ceasarData.push("Ceasar pursues Pompey and the fleaing senate.*") ceasarData.push("Ceasar pursues Pompey and the fleaing senate.*") ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push(null) ceasarData.push("Ceasar misses Pompey ar Brindisi") } var data3 = [ null ,"data 3 index2 " ,"data 3 index3 " ,"data 3 index4 " ,"data 3 index5 " ,"data 3 index6 " ,"data 3 index7 " ,"data 3 index8 " ,"data 3 index9 " ,"data 3 index10" ,"data 3 index11" ,null ,"data 3 index13" ,"data 3 index14" ,"data 3 index15" ,"data 3 index16" ,"data 3 index17" ,"data 3 index18" ,"data 3 index19" ,"data 3 index20" ,"data 3 index21" ,"data 3 index21" ] var data4 = [ null ,"data 4 index2 " ,"data 4 index3 " ,"data 4 index4 " ,"data 4 index5 " ,null ,"data 4 index7 " ,"data 4 index8 " ,"data 4 index9 " ,"data 4 index10" ,"data 4 index11" ,"data 4 index12" ,"data 4 index13" ,"data 4 index14" ,"data 4 index15" ,"data 4 index16" ,"data 4 index17" ,"data 4 index18" ,"data 4 index19" ,"data 4 index20" ,"data 4 index21" ,"data 4 index21" ] function chooseSentence(emperor, num) { var sentence = emperorArray[emperor].data[num]; if (sentence == null) { for (i = num; i >= 0; i--) { if( emperorArray[emperor].data[i] != null) { sentence = emperorArray[emperor].data[i]; return sentence } } } else { return sentence } } <file_sep>/MainApp/JS/pompeyLocations.js function getPompeyLocations(pompeyLocations) { pompeyLocations.push(new google.maps.LatLng(41.881831370505594, 12.50518798828125)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.880808915193874, 12.523040771484375)) pompeyLocations.push(new google.maps.LatLng(41.87365126992505, 12.547760009765625)) pompeyLocations.push(new google.maps.LatLng(41.86649282301993, 12.566986083984375)) pompeyLocations.push(new google.maps.LatLng(41.84194349089866, 12.605438232421875)) pompeyLocations.push(new google.maps.LatLng(41.81943165932006, 12.652130126953125)) pompeyLocations.push(new google.maps.LatLng(41.801006999656636, 12.709808349609375)) pompeyLocations.push(new google.maps.LatLng(41.790768787851285, 12.745513916015625)) pompeyLocations.push(new google.maps.LatLng(41.78667304519471, 12.775726318359375)) pompeyLocations.push(new google.maps.LatLng(41.77950486590359, 12.827911376953125)) pompeyLocations.push(new google.maps.LatLng(41.775408403663285, 12.871856689453125)) pompeyLocations.push(new google.maps.LatLng(41.76926321969369, 12.904815673828125)) pompeyLocations.push(new google.maps.LatLng(41.76106872528615, 12.93365478515625)) pompeyLocations.push(new google.maps.LatLng(41.75184866809371, 12.959747314453125)) pompeyLocations.push(new google.maps.LatLng(41.74262728637672, 12.998886108398438)) pompeyLocations.push(new google.maps.LatLng(41.70982942509964, 13.15887451171875)) pompeyLocations.push(new google.maps.LatLng(41.68522004222073, 13.24127197265625)) pompeyLocations.push(new google.maps.LatLng(41.66470503009207, 13.34014892578125)) pompeyLocations.push(new google.maps.LatLng(41.63597302844412, 13.46099853515625)) pompeyLocations.push(new google.maps.LatLng(41.611335399441735, 13.57086181640625)) pompeyLocations.push(new google.maps.LatLng(41.582579601430346, 13.65325927734375)) pompeyLocations.push(new google.maps.LatLng(41.56614196476838, 13.69171142578125)) pompeyLocations.push(new google.maps.LatLng(41.52502957323801, 13.84002685546875)) pompeyLocations.push(new google.maps.LatLng(41.49623534616764, 13.95538330078125)) pompeyLocations.push(new google.maps.LatLng(41.47154438707647, 14.05426025390625)) pompeyLocations.push(new google.maps.LatLng(41.45919537950706, 14.24652099609375)) pompeyLocations.push(new google.maps.LatLng(41.45919537950706, 14.29595947265625)) pompeyLocations.push(new google.maps.LatLng(41.44272637767212, 14.37286376953125)) pompeyLocations.push(new google.maps.LatLng(41.38917324986403, 14.48822021484375)) pompeyLocations.push(new google.maps.LatLng(41.32320110223851, 14.65850830078125)) pompeyLocations.push(new google.maps.LatLng(41.24890252240322, 14.92218017578125)) pompeyLocations.push(new google.maps.LatLng(41.21172151054787, 15.03204345703125)) pompeyLocations.push(new google.maps.LatLng(41.15797827873605, 15.24078369140625)) pompeyLocations.push(new google.maps.LatLng(41.1290213474951, 15.33966064453125)) pompeyLocations.push(new google.maps.LatLng(41.08763212467915, 15.51544189453125)) pompeyLocations.push(new google.maps.LatLng(41.075210270566636, 15.63079833984375)) pompeyLocations.push(new google.maps.LatLng(41.06278606873302, 15.72967529296875)) pompeyLocations.push(new google.maps.LatLng(41.00477542222949, 16.05926513671875)) pompeyLocations.push(new google.maps.LatLng(40.9964840143779, 16.13067626953125)) pompeyLocations.push(new google.maps.LatLng(40.967455873296714, 16.41082763671875)) pompeyLocations.push(new google.maps.LatLng(40.94671366508002, 16.50421142578125)) pompeyLocations.push(new google.maps.LatLng(40.93011520598304, 16.56463623046875)) pompeyLocations.push(new google.maps.LatLng(40.91766362458114, 16.63055419921875)) pompeyLocations.push(new google.maps.LatLng(40.901057866884024, 16.70745849609375)) pompeyLocations.push(new google.maps.LatLng(40.88029480552824, 16.82830810546875)) pompeyLocations.push(new google.maps.LatLng(40.8595252289932, 16.91070556640625)) pompeyLocations.push(new google.maps.LatLng(40.834593138080244, 16.97662353515625)) pompeyLocations.push(new google.maps.LatLng(40.79717741518769, 17.02056884765625)) pompeyLocations.push(new google.maps.LatLng(40.76390128094589, 17.16339111328125)) pompeyLocations.push(new google.maps.LatLng(40.734770989672406, 17.29522705078125)) pompeyLocations.push(new google.maps.LatLng(40.70979201243498, 17.37213134765625)) pompeyLocations.push(new google.maps.LatLng(40.70562793820589, 17.46002197265625)) pompeyLocations.push(new google.maps.LatLng(40.693134153308094, 17.54791259765625)) pompeyLocations.push(new google.maps.LatLng(40.65980593837855, 17.61932373046875)) pompeyLocations.push(new google.maps.LatLng(40.61812224225511, 17.73468017578125)) pompeyLocations.push(new google.maps.LatLng(40.62646106367355, 17.82257080078125)) pompeyLocations.push(new google.maps.LatLng(40.61812224225511, 17.91046142578125)) pompeyLocations.push(new google.maps.LatLng(40.61812224225511, 17.93243408203125)) pompeyLocations.push(new google.maps.LatLng(40.6306300839918, 17.98736572265625)) pompeyLocations.push(new google.maps.LatLng(40.65147128144057, 18.08624267578125)) pompeyLocations.push(new google.maps.LatLng(40.65147128144057, 18.16864013671875)) pompeyLocations.push(new google.maps.LatLng(40.65563874006118, 18.25653076171875)) pompeyLocations.push(new google.maps.LatLng(40.6639728763869, 18.39385986328125)) pompeyLocations.push(new google.maps.LatLng(40.730608477796636, 18.502349853515625)) pompeyLocations.push(new google.maps.LatLng(40.77638178482896, 18.598480224609375)) pompeyLocations.push(new google.maps.LatLng(40.80965166748856, 18.686370849609375)) pompeyLocations.push(new google.maps.LatLng(40.86991083161536, 18.793487548828125)) pompeyLocations.push(new google.maps.LatLng(40.93841495689795, 18.848419189453125)) pompeyLocations.push(new google.maps.LatLng(40.9861182878041, 18.911590576171875)) pompeyLocations.push(new google.maps.LatLng(41.03793062246529, 19.004974365234375)) pompeyLocations.push(new google.maps.LatLng(41.11039942586733, 19.043426513671875)) pompeyLocations.push(new google.maps.LatLng(41.191056256696875, 19.150543212890625)) pompeyLocations.push(new google.maps.LatLng(41.24064190269477, 19.213714599609375)) pompeyLocations.push(new google.maps.LatLng(41.27161384188987, 19.274139404296875)) pompeyLocations.push(new google.maps.LatLng(41.28606238749825, 19.342803955078125)) pompeyLocations.push(new google.maps.LatLng(41.32938883149375, 19.427947998046875)) }
eb02ea0eee52310113dc7c4de3a8413b167a6e7b
[ "Markdown", "JavaScript", "HTML" ]
11
Markdown
mattc41190/MovingRome
2b37bf7fca5382a5664d5036d9cfe110667935cd
8dfb1f5fc73064b892aa2fb35c813777bcc604eb
refs/heads/master
<file_sep>package main import "log" func main() { log.Println("Scaffold!") } <file_sep># scaffold-gin gin + vue 的前后端分离项目脚手架
c0857d30b468751018abf73381e7d5125ce6a2d1
[ "Markdown", "Go" ]
2
Go
hanzkering/scaffold-gin
bc6dcd90ed09127224634c33a616ee8a09104af2
eab1125d9f76d8be9790abe75168ee6b7264dfec
refs/heads/main
<file_sep># ChessFrontEnd A front-end for the [ChessEngine server](https://github.com/adamore/ChessEngine) <file_sep>var size = 0.75 * Math.min($(window).height(), $(window).width()); $('#board').width(size); var board; var game = new Chess(); var $status = $('#status'); var $fen = $('#fen'); var $pgn = $('#pgn'); var gameId; function onDragStart(source, piece, position, orientation) { if (game.game_over()) return false // do not allow user to move the computer's side if (game.turn() === 'b') return false // only pick up pieces for the side to move if ((game.turn() === 'w' && piece.search(/^b/) !== -1) || (game.turn() === 'b' && piece.search(/^w/) !== -1)) { return false } } function onDrop(source, target) { // see if the move is legal var move = game.move({ from: source, to: target, promotion: 'q' // always promote to a queen for simplicity }); // illegal move if (move === null) return 'snapback'; } function onSnapEnd(source, target) { board.position(game.fen()); updateStatus(`${source}${target}`); } function getComputerMove(moveString) { $('#computerloading').css('visibility', 'visible'); $('#board').css('cursor', 'not-allowed'); $.getJSON(`https://chess-engine-api.herokuapp.com/make-white-move?game_id=${gameId}&move=${moveString}`, function(data) { var fromString = data.move.substring(0, 2); var toString = data.move.substring(2, 4); var move = game.move({ from: fromString, to: toString, promotion: 'q' }); board.position(game.fen()); updateStatus('', true); $('#computerloading').css('visibility', 'hidden'); $('#board').css('cursor', 'default'); }).fail(function() { window.alert("Apologies, there was an error making your move on the server."); location.reload(); }); } function updateStatus(moveString, wasComputer = false) { var status = ''; var moveColor = 'White'; if (game.turn() === 'b') { moveColor = 'Computer'; } if (game.in_checkmate()) { status = 'Game over, ' + moveColor + ' is in checkmate.'; } else if (game.in_draw()) { status = 'Game over, drawn position'; } else { status = moveColor + ' to move'; if (game.in_check()) { status += ', ' + moveColor + ' is in check'; } } $status.html(status); $fen.html(game.fen()); $pgn.html(game.pgn()); if (!wasComputer && !game.in_checkmate() && !game.in_draw()) { getComputerMove(moveString); } if (game.in_checkmate() || game.in_draw()) { $('#message').html(status); $('#modal').modal(); } } var config = { draggable: true, position: 'start', onDragStart: onDragStart, onDrop: onDrop, onSnapEnd: onSnapEnd }; $.getJSON('https://chess-engine-api.herokuapp.com/create-game', function(data) { gameId = data.game_id; board = Chessboard('board', config); $('#loading').hide(); $('#game').show(); }).fail(function(error) { window.alert('Apologies, there was an error starting the game on the server.'); location.reload(); });
32a9d5e8ae07e9e0d63b36ac98897179a1e652b6
[ "Markdown", "JavaScript" ]
2
Markdown
adamore/Chess
9a29e82dd804ed01817b9d27488548ca517485dd
8a6d50374e018afff5b91813394c3f6486a4291a
refs/heads/master
<repo_name>ldakir/School_stuff<file_sep>/Streams/Vote.java /* Author: <NAME> File: Vote.java */ import java.io.*; import java.util.stream.*; import java.util.Arrays; public class Vote{ public static void main(String[] args) throws IOException { Stream<String> lines= new BufferedReader(new FileReader("voterdata.csv")).lines(); Stream<String[]> splitLines= lines.map(line -> line.split(";")); Stream<String[]> Governor= splitLines.filter(x -> x[2].equals("Governor")); Stream<Tuple<Integer,Integer>> votes= Governor.map(x->{ if (x[4].equals("Democratic")){ return new Tuple<>(Integer.valueOf(x[6]), 0); } else if (x[4].equals("Republican")) { return new Tuple<>(0,Integer.valueOf(x[6])); } else{ return new Tuple<>(0,0); } } ); Tuple<Integer,Integer> result= votes.reduce((tuple1, tuple2) -> { return new Tuple<>((tuple1.fst+tuple2.fst),(tuple1.snd+tuple2.snd)); }).get(); System.out.println(result.fst); System.out.println(result.snd); } } <file_sep>/Strings/sort_strings.c // File: sort_strings.c // Purpose: Sort an array of strings using bubblesort // Written by: <NAME> // Date: March 25, 2019 #include <stdio.h> #define MAX_LEN 22 #define NUM_STRINGS 10 int length(char *string); int scompare(char *string1,char *string2); void fixfgetstring(char *str); void bubblesort(char * string); void swap(char string1[], char string2[]); int main(){ char string[NUM_STRINGS][MAX_LEN]; //2D array to store the strings printf("Enter 10 strings, seperated by linefeed:\n"); for(int i =0; i<NUM_STRINGS; i++) fgets(string+i, MAX_LEN, stdin); //prompt user for string bubblesort((char *) string); //Sort the strings printf("\nThe sorted array is:\n"); for(int i =0; i<NUM_STRINGS; i++){ fixfgetstring((char *)string); //fixes the length of the string printf("%s\n",string+i); //prints the sorted strings } return 0; } int length(char *string){ int l = 0; while(*string != '\0'){ l++; string++; } return l; }//length() int scompare(char *string1,char *string2){ while(*string1 != '\0' || *string2 != '\0'){ if(*string1 == *string2){ string1++; string2++; continue; } else if(*string1 > *string2){ return 1; break; } else if (*string1 < *string2){ return -1; break; } return 0; } } //scompare() void fixfgetstring(char *str){ while(*str != '\n'){ str++; } *str = '\0'; }//fixfgetstring() void bubblesort(char * string){ for(int i = 0; i < (NUM_STRINGS - 1); i++) { for(int j = 0; j < (NUM_STRINGS - i - 1); j++) { if(scompare(string + j * MAX_LEN, string + (j + 1) * MAX_LEN)== 1) { swap(string + j * MAX_LEN, string + (j + 1) * MAX_LEN); } // end if } // end for } // end for } //bubblesort() //swap two strings by copying character by character void swap(char string1[], char string2[]) { char temp[MAX_LEN]; for(int i = 0; i < MAX_LEN; i++){ temp[i] = string1[i]; } for(int i = 0; i < MAX_LEN; i++){ string1[i] =string2[i]; } for(int i = 0; i < MAX_LEN; i++){ string2[i]=temp[i]; } } //swap() <file_sep>/Sorting/multi_sort.c // File: multi_sort.c // Purpose: Sorting arrays using different sorting algorithms // Written by: <NAME> // Date: Feb 15, 2019 #include <stdio.h> #include <stdbool.h> #include <time.h> #include <stdlib.h> #define N 20 // From C Programming K. N. KING void quicksort(int a[], int low, int high); int split(int a[], int low, int high); int randint(int a, int b); void swap(int A[], int i, int j); void shuffle(int n, int A[]); void bubblesort(int n, int A[]); void selectionsort(int n, int A[]); void merge(int A[], int B[], int a, int b,int result[]); void merge_sort(int a[], int n); // From C Programming K. N. KING void quicksort(int a[], int low, int high){ int middle; if(low >= high) return; middle = split(a, low ,high); quicksort(a ,low, middle -1); quicksort(a, middle +1, high); } int split(int a[], int low, int high){ int part_element = a [low]; for(;;){ while(low<high && part_element <= a[high]) high--; if (low >= high) break; a[low++] = a[high]; while(low < high && a[low] <= part_element) low++; if(low >= high) break; a[high--] = a[low]; } a[high] = part_element; return high; } //From sort.c //Written by: <NAME> int randint(int a, int b) { // returns [a..b) return (int) (a + (rand() % (b-a))); } // randint() void swap(int A[], int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } // swap() void shuffle(int n, int A[]) { // Shuffle A[] (uses Fisher-Yates algorithm) for (int i=0; i <= n-2; i++) { int j = randint(i, n); swap(A, i, j); } } // shuffle() //Algorithm taken from //https://interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html void bubblesort(int n, int A[]){ if(n ==1){ return; //array is sorted } for(int i =0; i < n-1; i++){ if(A[i]> A[i+1]){ swap(A, i, i+1); //exchange two elements if there are not in order } } bubblesort(n-1,A); //recursion on the rest of the array } //bubblesort() //algorithm taken from data structure Bryn Mawr course slides void selectionsort(int n, int A[]){ for( int fill = 0; fill <= n-2; fill++){ int index_min = fill; for( int next= fill +1; next <= n-1; next++){ if(A[next] < A[index_min]) index_min= next; //find the index of the smallest element } swap(A,index_min, fill); //swap A[fill] with A[posMin] } } //selectionsort() //algorithm taken from data structure Bryn Mawr course slides //Function that merges two ordered arrays void merge(int A[], int B[], int a, int b,int result[]){ // a is size of A int i =0; int j = 0; int k = 0; //Compare the current items and copy the smallest in the resulting array while(j < a && k < b){ if (A[j] < B[k]){ result[i] = A[j]; j++; //increment the index of the array with the smallest current item } else{ result[i] = B[k]; k++;//increment the index of the array with the smallest current item } i++; //increment the index of the resulting array } //end while //Copy remaining items from the first array while(j<a){ result[i] = A[j]; j++; i++; } //end while //Copy remaining items from the second array while(k<b){ result[i] = B[k]; k++; i++; } //end while }// merge() //algorithm taken from data structure Bryn Mawr course slides void merge_sort(int a[], int n){ // if n == 1, the array is sorted if (n >1){ int left[n/2]; int right[n-(n/2)]; int j=0; //diving the array into two halves for(int i =0; i< n/2; i++){ left[i]= a[j]; j++; } for( int i = 0; i< n-(n/2); i++){ right[i]= a[j]; j++; } //sort the left half merge_sort(left, n/2); //sort the right half merge_sort(right, n-(n/2)); //merge the left and the right merge(left, right, n/2,(n-(n/2)),a); } }//merge_sort int main(){ int data[N]; srand(time(NULL)); //Initialize an array of length N with random numbers from 1 to 100 printf("Initial array: \n"); for (int i=0; i < N; i++) { data[i] = randint(1, 101); printf("%2d ", data[i]); } printf("Not Sorted.\n"); //Sort the array using quick sort printf("Sorted with quick sort: \n"); quicksort(data,0, N-1); for (int i=0; i < N; i++) printf("%2d ", data[i]); printf("Sorted.\n"); //Shuffle the array printf("Shuffled array: \n"); shuffle(N, data); for (int i=0; i < N; i++) printf("%2d ", data[i]); printf("Not Sorted. \n"); //Sort the array using bubble sort printf("Sorted with bubble sort: \n"); bubblesort(N,data); for (int i=0; i < N; i++) printf("%2d ", data[i]); printf("Sorted.\n"); //Shuffle the array printf("Shuffled array: \n"); shuffle(N, data); for (int i=0; i < N; i++) printf("%2d ", data[i]); printf("Not Sorted. \n"); //Sort the array using selection sort printf("Sorted with selection sort: \n"); selectionsort(N,data); for (int i=0; i < N; i++) printf("%2d ", data[i]); printf("Sorted.\n"); //Shuffle the array printf("Shuffled array: \n"); shuffle(N, data); for (int i=0; i < N; i++) printf("%2d ", data[i]); printf("Not Sorted. \n"); //Sort the array using merge sort printf("Sorted with merge sort: \n"); merge_sort(data, N); for (int i=0; i < N; i++) printf("%2d ", data[i]); printf("Sorted.\n"); }//end main
4cff4624cd13da51f61a7b83e8df52be0a81dd3b
[ "Java", "C" ]
3
Java
ldakir/School_stuff
9522b7ac8a5e57f4249c3755db31e9689ba2411b
546b6bb60dc6b19e8eadd76e49019648b6e7889d
refs/heads/master
<file_sep>#!/usr/bin/env ruby def lonelyinteger( a) c = Array.new(101) for i in 0...101 c[i] = 0 end for i in 0...a.length c[a[i]] += 1 end for i in 0...c.length if c[i] == 1 return i end end end a = gets.strip.to_i b = gets.strip.split(" ").map! {|i| i.to_i} print lonelyinteger(b) <file_sep>t = gets.to_i t.times{ (n, c, m) = gets.split.map{|i| i.to_i} answer = 0 wrappers = n/c answer = wrappers while m <= wrappers wrappers -= m answer += 1 wrappers += 1 end puts answer } <file_sep>#!/usr/bin/env python3 mothers = [] class Node: def __init__(self, name, daughters=[]): self.name = name self.daughters = daughters self.mothers = [] def print_tree(self): print(self.name) for daughter in self.daughters: daughter.print_tree() def is_mother(self,relative): if self.name == relative: return True else: for daughter in self.daughters: if daughter.is_mother(relative): return True else: continue def find_closest_antecedent(self, relatives): global mothers if self.is_mother(relatives[0]) and self.is_mother(relatives[1]): mothers.append(self.name) for daughter in self.daughters: daughter.find_closest_antecedent(relatives) i = int(input()) nodes = [] for line in range(i): names = input() names = names.strip().split(',') daughters = [] for daughter in names[1:]: daughters.append(Node(daughter)) node = Node(names[0],daughters) nodes.append(node) nodes_to_remove = [] for j in range(len(nodes)): for i in range(len(nodes)): for daughter in range(len(nodes[i].daughters)): if nodes[j].name == nodes[i].daughters[daughter].name: nodes[i].daughters[daughter] = nodes[j] nodes_to_remove.append(nodes[j]) for i in range(len(nodes_to_remove)): nodes.remove(nodes_to_remove[i]) find_antecedent = input() find_antecedent = find_antecedent.strip().split(',') if find_antecedent[0] == find_antecedent[1]: print(find_antecedent[0]) else: nodes[0].find_closest_antecedent(find_antecedent) print(mothers[-1]) <file_sep>num = int(input()) for i in range(num): cuts = int(input()) vert = int(cuts/2) hor = cuts - vert print(vert * hor) <file_sep>#!/usr/bin/env ruby n = gets.chomp.to_i sticks = gets.split(" ") sticks = sticks.map(&:to_i) while !sticks.empty? do min = sticks[0] for i in 0...sticks.length do if min > sticks[i] min = sticks[i] end end sticks_cut = 0 i = 0 while i < sticks.length do sticks[i] -= min sticks_cut += 1 if sticks[i] <= 0 sticks.delete_at(i) i -= 1 end i += 1 end puts sticks_cut end
7df9267b74f38470b21b9f52c9b8a0521e030029
[ "Python", "Ruby" ]
5
Ruby
tafox/hackerrank
f13936e0e3f5735f4b099a63a5e0e598b286acfe
100c42fef9d8b8ca620f38418e99d568a43784e5
refs/heads/master
<file_sep>package pl.coderslab.tdd.creation; import org.junit.Test; import static org.junit.Assert.*; public class FirstTest { @Test public void testConcatString() { First first = new First(); String result = first.concatString("one","two"); assertEquals("onetwo", result); } @Test public void testMultiply() { First first = new First(); int result = first.multiply(2,3); assertEquals(6, result); } }<file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Utwórz klasę `Calculator.java`, która będzie implementowała cztery działania matematyczne * dodawanie * odejmowanie * mnożenie * dzielenie * porównanie 2 wartości (boolean greater(int a, int b)) 2. Utwórz klasę `CalculatorTest.java`, która będzie implementowała testy dla tej klasy. ## Zadanie 2 W pliku `SimpleCalculatorTest.java` 1. Utwórz testy do metod klasy `SimpleCalculator.java`; 2. Utwórz test sprawdzający wystąpienie wyjątku. ## Zadanie 3 1. W klasie `MaxValue.java` znajduje się metoda, która wyszukuje największą wartość w tablicy. 2. Napisz testy do tej funkcji sprawdzając poprawność wskazań. 3. Jeżeli to konieczne popraw implementację metody. ## Zadanie 4 1. W klasie `MaxValue.java` znajduje się metoda, która wyszukuje największą wartość w tablicy. 2. Napisz testy do tej funkcji sprawdzając poprawność wskazań. 3. Jeżeli to konieczne popraw implementację metody. ## Zadanie 5 1. Uzupełnij klasę testującą o poniższy test: ````java @Test public void evaluatesExpression() { Calculator calculator = new Calculator(); int sum = calculator.eval("1+2+3"); assertEquals(6, sum); } ```` 2. Dodaj do klasy `Calculator` implementację metody tak by test zakończył się powodzeniem. <file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Połącz klasę `Publisher` i `Book` relacją jeden do wielu. 2. Zmodyfikuj kontroler do obsługi książek tak, aby by w metodzie dodawania książki: - utworzyć i zapisać obiekt `Publisher`, - połączyć obiekt klasy `Book` z obiektem klasy `Publisher`, - zapisać obiekt klasy `Book`. ## Zadanie 2 1. Połącz klasę autora i książkę relacją wiele do wielu. 2. Zmodyfikuj kontroler do obsługi książek tak, aby by w metodzie dodawania książki: - pobrać dwóch dowolnych autorów po ich `id`. - połączyć obiekt klasy `Book` z pobranymi autorami - zapisać obiekt klasy `Book`. ## Zadanie 3 1. Utwórz klasę `Person` zawierającą pola: - id - login - password - email 2. Utwórz klasę `PersonDetails` zawierającą pola: - id - firstName - lastName - streetNumber - street - city 3. Połącz encje za pomocą relacji `@OneToOne`. 4. Utwórz kontroler, realizujący operacje CRUD (create, read, update, delete). <file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Uzupełnij projekt o walidację formularzy dodawania/edycji książki. 2. Dodaj wyświetlanie błędów w formularzach. ## Zadanie 2 1. Uzupełnij walidację formularzy dla kontrolerów obsługujących encje: - Author - Publisher <file_sep>package pl.coderslab.tdd.assertions; import org.junit.Test; import static org.junit.Assert.*; public class CalculatorTest { @Test public void add() { Calculator calculator = new Calculator(); int expected = 7; int result = calculator.add(2, 5); assertEquals(expected, result); } @Test public void sub() { Calculator calculator = new Calculator(); int expected = 3; int result = calculator.sub(9, 6); assertEquals(expected, result); } @Test public void multi() { Calculator calculator = new Calculator(); int expected = 42; int result = calculator.multi(6, 7); assertEquals(expected, result); } @Test public void div() { Calculator calculator = new Calculator(); int expected = 4; int result = calculator.div(24, 6); assertEquals(expected, result); } @Test public void grater() { Calculator calculator = new Calculator(); boolean expected = true; boolean result = calculator.grater(7, 5); assertTrue(result); } @Test public void evaluatesExpression() { Calculator calculator = new Calculator(); int sum = calculator.evaluatesExpression("1+2+3"); assertEquals(6, sum); } }<file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Uzupełnij projekt `Spring01hibernate` o odpowiednie zależności Mavena. 2. Dodaj adnotacje konfiguracyjne. 3. Utwórz pakiet zawierający repozytoria a w nim repozytorium dla klasy `Book`. 4. Sprawdź działanie programu. ## Zadanie 2 - rozwiązywane z wykładowcą 1. Stwórz encję `Category` i połącz ją relacją z `Book`. Książka ma jedną kategorię. 2. W repozytorium dla klasy `Book` utwórz metody pobierające: - metodę wyszukującą książki dla zadanego tytułu. - metodę wyszukującą książki dla zadanej kategorii - metodę wyszukującą książki dla zadanego id kategorii ## Zadanie 3 1. W repozytorium dla klasy `Book` utwórz metody pobierające: - Listę książek dla zadanego autora. - Listę książek dla zadanego wydawcy - Listę książek dla określonego ratingu - Pierwszą książkę z zadanej kategorii, z sortowaniem po tytule. ## Zadanie 4 1. Utwórz repozytorium dla klasy `Publisher`. 2. Utwórz metody pobierające: - Wydawcę dla zadanego numeru nip, - Wydawcę dla zadanego numeru regon. ## Zadanie 5 1. Utwórz repozytorium dla klasy `Author`. 2. Utwórz metody pobierające: - Autora dla zadanego adresu email, - Autora dla zadanego numeru pesel, - Listę autorów o zadanym nazwisku. <file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Utwórz akcję wyświetlającą formularz w kontrolerze `PersonController`. 2. Dodaj widok formularza zawierający pola `login` oraz `password`, `email`. 3. Wykorzystaj w tym celu encję `Person` z poprzednich zajęć. 4. Dodaj akcję przetwarzająca formularz (akcja ma zakończyć się zapisem danych do bazy)- pobieraj dane za pomocą **@RequestParam**. ## Zadanie 2 - rozwiązywane z wykładowcą 1. Zmodyfikuj formularz oraz akcję kontrolera w taki sposób aby dane bindowały się automatycznie. ## Zadanie 3 1. W projekcie `Spring01hibernate` utwórz kontroler `StudentController`. 2. Utwórz klasę `Student` zawierającą pola (klasa nie ma być **Encją**): - String firstName; - String lastName; - String gender; - String country; - String notes; - boolean mailingList; - List<String> programmingSkills; - List<String> hobbies; 3. Utwórz formularz do tworzenia obiektu klasy `Student` zawierający pola - firstName (pole tekstowe) - lastName (pole tekstowe) - gender (radio button) - country (select z możliwością pojedynczego wyboru) - notes (textarea) - mailingList (checkbox) - programmingSkills (select z możliwością wyboru wielu opcji) - hobbies (grupa checkboxów) 4. Utwórz metody, które przy pomocy adnotacji `@ModelAttribute` utworzą zestaw danych dla opcji: - programmingSkills - hobbies - country Skorzystaj z przykładu: ```` @ModelAttribute("countries") public List<String> countries() { return Arrays.asList("Poland", "Germany", "France", "Russia", "Denmark"); } ```` 5. Wyświetl zestawy danych do wyboru w formularzu. 6. Po zatwierdzeniu formularza wyświetl wszystkie dane zapisane w zbindowanym obiekcie dane. <file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. W projekcie `Spring01hibernate` utwórz kontroler `BookFormController`, umieścimy w nim akcje odpowiedzialne za operacje na obiektach typu `Book` z wykorzystaniem formularzy. 2. Utwórz formularz, który pozwoli dodać obiekt klasy `Book`. 3. Utwórz akcję wyświetlającą formularz. 4. Dodaj akcję obsługującą dane z formularza, 5. Dodaj możliwość wyboru wydawcy z listy rozwijalnej. 6. Zapisz obiekt do bazy danych. ## Zadanie 2 - rozwiązywane z wykładowcą 1. Dodaj akcję wyświetlającą listę wszystkich książek. 2. Skorzystaj z utworzonej wcześniej metody klasy `BookDao` wykorzystującą zapytanie JPQL. 3. Zmodyfikuj akcję zapisu książki dodając przekierowanie do listy książek. ## Zadanie 3 1. Rozbuduj listę dodając linki umożliwiające przejście do edycji danych oraz usuwania danych. 2. Dodaj formularz edycji danych, zwróć uwagę na poprawne wypełnienie danych podczas edycji. 3. Dodaj akcję usuwania książki. 4. Dodaj zabezpieczenie przed przypadkowym usunięciem danych - dodatkową stronę na której wyświetlisz 2 linki: Potwierdź oraz Anuluj. ## Zadanie 4 1. Rozbuduj formularz o możliwość dodania autorów z listy rozwijalnej select. 2. Dodaj konwerter dla encji `Author`. ## Zadanie 5 1. Utwórz kontroler `AuthorController`, utwórz w nim akcje, które pozwolą: - wyświetlić listę wszystkich autorów - dodać autora - usunąć autora - edytować autora 2. Dla akcji dodawania oraz edycji utwórz formularz. 3. Utwórz linki nawigacyjne umożliwiające przechodzenie między akcjami - bez konieczności znania adresów URL. ## Zadanie 6 1. Utwórz kontroler `PublisherController`, utwórz w nim akcje, które pozwolą: - wyświetlić listę wszystkich wydawców - dodać wydawcę - usunąć wydawcę - edytować wydawcę 2. Dla akcji dodawania oraz edycji utwórz formularz. 3. Utwórz linki nawigacyjne umożliwiające przechodzenie między akcjami - bez konieczności znania adresów URL. <file_sep>package pl.coderslab.tdd.assertions; public class Calculator { public int add(int x, int y) { return x + y; } public int sub(int x, int y) { return x - y; } public int multi(int x, int y) { return x * y; } public int div(int x, int y) { return x / y; } public boolean grater(int x, int y) { return (x > y); } public int evaluatesExpression(final String str) { return new Object() { int pos = -1, ch; void nextChar() { ch = (++pos < str.length()) ? str.charAt(pos) : -1; } boolean eat(int charToEat) { while (ch == ' ') nextChar(); if (ch == charToEat) { nextChar(); return true; } return false; } int parse() { nextChar(); int x = parseExpression(); if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char) ch); return x; } // Grammar: // expression = term | expression `+` term | expression `-` term // term = factor | term `*` factor | term `/` factor // factor = `+` factor | `-` factor | `(` expression `)` // | number | functionName factor | factor `^` factor int parseExpression() { int x = parseTerm(); for (; ; ) { if (eat('+')) x += parseTerm(); // addition else if (eat('-')) x -= parseTerm(); // subtraction else return x; } } int parseTerm() { int x = parseFactor(); for (; ; ) { if (eat('*')) x *= parseFactor(); // multiplication else if (eat('/')) x /= parseFactor(); // division else return x; } } int parseFactor() { if (eat('+')) return parseFactor(); // unary plus if (eat('-')) return -parseFactor(); // unary minus int x; int startPos = this.pos; if (eat('(')) { // parentheses x = parseExpression(); eat(')'); } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers while ((ch >= '0' && ch <= '9') || ch == '.') nextChar(); x = Integer.parseInt(str.substring(startPos, this.pos)); } else if (ch >= 'a' && ch <= 'z') { // functions while (ch >= 'a' && ch <= 'z') nextChar(); String func = str.substring(startPos, this.pos); x = parseFactor(); if (func.equals("sqrt")) x = -1; else if (func.equals("sin")) x = -1; else if (func.equals("cos")) x = -1; else if (func.equals("tan")) x = -1; } else { throw new RuntimeException("Unexpected: " + (char) ch); } if (eat('^')) x = -1; // exponentiation return x; } }.parse(); } } <file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Otwórz IDE a następnie utwórz w nim projekt Maven o nazwie `Spring01hibernate`. 2. Uzupełnij zestaw zależności odpowiedzialnych za Spring MVC. 3. Uzupełnij podstawowy zestaw zależności dla korzystania z Hibernate. 4. Skorzystaj z zależności opisanych w prezentacji. ## Zadanie 2 - rozwiązywane z wykładowcą 1. W projekcie `Spring01hibernate` dodaj plik konfiguracyjny dla hibernate - `persistence.xml`. 2. Utwórz pakiet **pl.coderslab.app**. 3. Dodaj klasę konfiguracji. 4. Utwórz inicjalizator aplikacji. 5. Utwórz bazę danych o nazwie test za pomocą Workbench. 6. Utwórz ziarna konfiguracji dla Hibernate - skorzystaj z przykładów zawartych w prezentacji. 5. Uruchom i sprawdź działanie aplikacji. <file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Uzupełnij klasę `BookDao` o metodę do pobierania listy wszystkich obiektów. 2. Wykorzystaj w tym celu JPQL. ## Zadanie 2 - rozwiązywane z wykładowcą 1. W klasie `BookDao` dodaj metodę `getRatingList(int rating)`, która na podstawie otrzymanego parametru pobierze książki o zadanym parametrze. ## Zadanie 3 1. Uzupełnij klasę `PublisherDao` o metodę do pobierania listy wszystkich obiektów. 2. Uzupełnij klasę `AuthorDao` o metodę do pobierania listy wszystkich obiektów. 3. Wykorzystaj w tym celu JPQL. ## Zadanie 4 1. Uzupełnij klasę `BookDao` o metodę do pobierania listy wszystkich książek, które mają jakiegokolwiek wydawcę. 2. Uzupełnij klasę `BookDao` o metodę do pobierania listy wszystkich książek, które mają określonego w parametrze wydawcę. 3. Uzupełnij klasę `BookDao` o metodę do pobierania listy wszystkich książek, które mają określonego w parametrze autora. <file_sep>![Coders-Lab-1920px-no-background](https://user-images.githubusercontent.com/152855/73064373-5ed69780-3ea1-11ea-8a71-3d370a5e7dd8.png) ## Zadanie 1 - rozwiązywane z wykładowcą 1. Zaimportuj projekt typu `Maven`. 2. Utwórz klasę testującą o nazwie `SimpleSampleTest`. 4. Uruchom test a następnie popraw go dowolnie tak, by test przeszedł. ## Zadanie 2 - rozwiązywane z wykładowcą 1. Utwórz 2 dowolne klasy testujące z przynajmniej jednym testem w każdej. 2. Utwórz `Test Suite` dla utworzonych klas. 3. Uruchom i przetestuj działanie.
2b9ac28d847f7fc009f55e097b6034e84df92de7
[ "Markdown", "Java" ]
12
Java
wasniows/ONL_JEE_W_01_JEE_Hibernate-master
58af912f74faab7e136d6802456519695ebceb0b
ba42cc8772dc1c1fe5a1e42bd42e4af9b66dc657
refs/heads/master
<repo_name>ganeshh27/gitfetch<file_sep>/app.js url = 'https://api.github.com/users/' xname = '' x = '' followers = [] inputFieldId = "fname" following = [] tableId1 = document.getElementById("followerstab") tableId2 = document.getElementById("followingtab") name1 = document.getElementById("fname") name1.addEventListener('keyup',function(e){ if (e.keyCode === 13) { handleGit() } }); nf = document.getElementById("notfound") function delet_tab(tabid){ var table = document.getElementById(tabid); var rowCount = table.rows.length; var tempi = 0 for (var i = 1; i < rowCount; i++) { table.deleteRow(i-tempi); tempi = tempi+1 } } function handleGit(gitUserId){ if (gitUserId){ gitId = gitUserId document.getElementById(inputFieldId).value = gitId } else{ gitId = document.getElementById(inputFieldId).value; } gitfetch(gitId) } function notfound(){ tableId1.style.visibility = "hidden" tableId2.style.visibility = "hidden" nf.style.visibility = 'visible' } function gitfetch(gitId) { delet_tab("followerstab") delet_tab("followingtab") tableId1.style.visibility = "visible" tableId2.style.visibility = "visible" nf.style.visibility = 'hidden' fetch(url+gitId) .then(response => response.json()) .then(function(data) { console.log(data); if (data.message == "Not Found"){ notfound() throw new Error('Something went wrong'); } return fetch(url+gitId+"/followers") }).then(r1 => r1.json()) .then(function(followers) { console.log(followers); followersa = followers return fetch(url+gitId+"/following") }).then(r2 => r2.json()) .then(following => { console.log(following); followinga = following function insertTable(tabId,tabName) { for (i=0;i<tabName.length;i++){ var tr1 = document.createElement('tr'); tr1.innerHTML= "<div class='row mt-2 mb-2' onclick=handleGit('"+tabName[i].login+"') >"+ "<div class='col-md-4'>"+ "<img src='"+tabName[i].avatar_url+"' class='img-thumbnail' alt='<NAME>'>"+ "</div>"+ "<div class='col-md-7'>"+tabName[i].login+ "</div>"+ "</div>" // tr1.innerHTML= "<div class='card'>"+ // "<div class='card-horizontal' onclick=handleGit('"+tabName[i].login+"')>"+ // "<div class='img-square-wrapper'>"+ // "<img class='img-thumbnail' src='"+tabName[i].avatar_url+"' alt='Card image cap'>"+ // "</div>"+ // "<div class='card-body'>"+ // "<h4 class='card-title'>'"+(url+"/"+tabName[i].login).name+"'</h4>"+ // "</div>"+ // "</div>"+ // "</div>" //tr1.innerHTML="<td onclick=handleGit('"+tabName[i].login+"')>"+tabName[i].login+"</td>"; document.getElementById(tabId).appendChild(tr1); } } insertTable("followingtab",followinga) insertTable("followerstab",followersa) }) .catch((error) => { console.log(error) }); } <file_sep>/appold.js url = 'https://api.github.com/users/' xname = '' x = '' followers = [] following = [] function gitfetch() { x = document.getElementById("fname").value; fetch(url+x) .then(response => response.json()) .then(function(data) { console.log(data); return fetch(url+x+"/followers") // .then(r=>r.json) // .then(dataf1 => { // console.log(dataf1);followers = dataf1}) // fetch(url+x+"/following") // .then(r2=>r2.json) // .then(dataf2 => {console.log(dataf2);following = dataf2}) }).then(r1 => r1.json()) .then(function(followers) { console.log(followers); followersa = followers return fetch(url+x+"/following") }).then(r2 => r2.json()) .then(following => { console.log(following); followinga = following function insrt(id,res) { for (i=0;i<res.length;i++){ // var elem = '<tr onclick=gitfetch()> res[i].login</tr>' // var table = document.getElementById(id); // var row = table.insertRow(-1); // var cell1 = row.insertCell(0); // cell1.innerHTML = elem $('id tr:last').after('<tr Onclick="gitfetch()">res[i].login</tr>'); } } insrt("followingtab",followinga) insrt("followerstab",followersa) }) }
f72ea4c701438a1ab59f8fd6b2b1eb6abb7dad66
[ "JavaScript" ]
2
JavaScript
ganeshh27/gitfetch
fca3357655afb195b9f6ce8f6feadb53b8c3dff3
08bfd0eb803e08eed81fbcbb49acef0b97c978aa
refs/heads/master
<file_sep>import pygame from pacman_game import pacman_utils black = (0, 0, 0) white = (255, 255, 255) blue = (0, 0, 255) green = (0, 255, 0) red = (255, 0, 0) purple = (255, 0, 255) yellow = (255, 255, 0) # This class represents the bar at the bottom that the player controls class Wall(pygame.sprite.Sprite): # Constructor function def __init__(self, x, y, width, height, color): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Make a blue wall, of the size specified in the parameters self.image = pygame.Surface([width, height]) self.image.fill(color) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x # This class represents the ball # It derives from the "Sprite" class in Pygame class Block(pygame.sprite.Sprite): # Constructor. Pass in the color of the block, # and its x and y position def __init__(self, color, width, height): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) # Create an image of the block, and fill it with a color. # This could also be an image loaded from the disk. self.image = pygame.Surface([width, height]) self.image.fill(white) self.image.set_colorkey(white) pygame.draw.ellipse(self.image, color, [0, 0, width, height]) # Fetch the rectangle object that has the dimensions of the image # image. # Update the position of this object by setting the values # of rect.x and rect.y self.rect = self.image.get_rect() # This class represents the bar at the bottom that the player controls class Player(pygame.sprite.Sprite): # Set speed vector change_x = 0 change_y = 0 # Constructor function def __init__(self, x, y, filename): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Set height, width self.image = pygame.image.load(filename).convert() # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x self.prev_x = x self.prev_y = y # Clear the speed of the player def prevdirection(self): self.prev_x = self.change_x self.prev_y = self.change_y # Change the speed of the player def changespeed(self, x, y): self.change_x += x self.change_y += y # Change the speed of the player def reset_speed(self, x, y): self.change_x = x self.change_y = y # Find a new position for the player def update(self, walls, gate): # Get the old position, in case we need to go back to it old_x = self.rect.left new_x = old_x+self.change_x prev_x = old_x+self.prev_x self.rect.left = new_x old_y = self.rect.top new_y = old_y+self.change_y prev_y = old_y+self.prev_y # Did this update cause us to hit a wall? x_collide = pygame.sprite.spritecollide(self, walls, False) hits = False if x_collide: # Whoops, hit a wall. Go back to the old position self.rect.left = old_x hits = True # self.rect.top=prev_y # y_collide = pygame.sprite.spritecollide(self, walls, False) # if y_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.top=old_y # print('a') else: self.rect.top = new_y # Did this update cause us to hit a wall? y_collide = pygame.sprite.spritecollide(self, walls, False) if y_collide: # Whoops, hit a wall. Go back to the old position self.rect.top = old_y hits = True # self.rect.left=prev_x # x_collide = pygame.sprite.spritecollide(self, walls, False) # if x_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.left=old_x # print('b') if gate is not False: gate_hit = pygame.sprite.spritecollide(self, gate, False) if gate_hit: hits = True self.rect.left = old_x self.rect.top = old_y return hits # inheritime Player klassist class Ghost(Player): def __init__(self, x, y, filename, move_list, ghost): Player.__init__(self, x, y, filename) self.list = move_list self.ghost = ghost self.turn = 0 self.steps = 0 self.l = len(move_list) - 1 # Change the speed of the ghost def change_speed(self, not_update=False): backup_turn = self.turn backup_steps = self.steps try: z = self.list[self.turn][2] if self.steps < z: self.change_x = self.list[self.turn][0] self.change_y = self.list[self.turn][1] self.steps += 1 else: if self.turn < self.l: self.turn += 1 elif self.ghost == "clyde": self.turn = 2 else: self.turn = 0 self.change_x = self.list[self.turn][0] self.change_y = self.list[self.turn][1] self.steps = 0 if not_update: self.turn = backup_turn self.steps = backup_steps except IndexError: print("IndexError!!") self.turn = 0 self.steps = 0 # This creates all the walls in room 1 def setup_room_one(all_sprites_list): # Make the walls. (x_pos, y_pos, width, height) wall_list = pygame.sprite.RenderPlain() # This is a list of walls. Each is in the form [x, y, width, height] walls = pacman_utils.walls # Loop through the list. Create the wall, add it to the list for item in walls: wall = Wall(item[0], item[1], item[2], item[3], blue) wall_list.add(wall) all_sprites_list.add(wall) # return our new list return wall_list def setup_gate(all_sprites_list): gate = pygame.sprite.RenderPlain() gate.add(Wall(282, 242, 42, 2, white)) all_sprites_list.add(gate) return gate class PacMan: def __init__(self): self.trollIcon = pygame.image.load('resources/images/Trollman.png') # Call this function so the Pygame library can initialize itself pygame.init() # Create an 606x606 sized screen self.screen = pygame.display.set_mode([606, 606]) # This is a list of 'sprites.' Each block in the program is # added to this list. The list is managed by a class called 'RenderPlain.' # Set the title of the window pygame.display.set_caption('Pacman') # Create a surface we can draw on background = pygame.Surface(self.screen.get_size()) # Used for converting color maps and such background = background.convert() # Fill the screen with a black background background.fill(black) self.clock = pygame.time.Clock() pygame.font.init() self.font = pygame.font.Font("resources/freesansbold.ttf", 24) # default locations for Pacman and monsters self.w = 303 - 16 # Width self.p_h = (7 * 60) + 19 # Pacman height self.m_h = (4 * 60) + 19 # Monster height self.b_h = (3 * 60) + 19 # Binky height self.i_w = 303 - 16 - 32 # Inky width self.c_w = 303 + (32 - 16) # Clyde width self.all_sprites_list = pygame.sprite.RenderPlain() self.block_list = pygame.sprite.RenderPlain() self.monster_list = pygame.sprite.RenderPlain() self.pacman_collide = pygame.sprite.RenderPlain() self.wall_list = setup_room_one(self.all_sprites_list) self.gate = setup_gate(self.all_sprites_list) # Create the player paddle object self.pacman = Player(self.w, self.p_h, "resources/images/Trollman.png") self.all_sprites_list.add(self.pacman) self.pacman_collide.add(self.pacman) self.blinky = Ghost(self.w, self.b_h, "resources/images/Blinky.png", pacman_utils.blinky_directions, False) self.monster_list.add(self.blinky) self.all_sprites_list.add(self.blinky) self.pinky = Ghost(self.w, self.m_h, "resources/images/Pinky.png", pacman_utils.pinky_directions, False) self.monster_list.add(self.pinky) self.all_sprites_list.add(self.pinky) # # self.inky = Ghost(self.i_w, self.m_h, "resources/images/Inky.png", pacman_utils.inky_directions, False) # self.monster_list.add(self.inky) # self.all_sprites_list.add(self.inky) # # self.clyde = Ghost(self.c_w, self.m_h, "resources/images/Clyde.png", pacman_utils.clyde_directions, "clyde") # self.monster_list.add(self.clyde) # self.all_sprites_list.add(self.clyde) self.bll = 0 self.score = 0 def start_game(self): pygame.display.set_icon(self.trollIcon) pygame.mixer.init() pygame.mixer.music.load('resources/audio/pacman.mp3') pygame.mixer.music.play(-1, 0.0) # Draw the grid for row in range(19): for column in range(19): if (row == 7 or row == 8) and (column == 8 or column == 9 or column == 10): continue else: block = Block(yellow, 4, 4) # Set a random location for the block block.rect.x = (30*column+6)+26 block.rect.y = (30*row+6)+26 b_collide = pygame.sprite.spritecollide(block, self.wall_list, False) p_collide = pygame.sprite.spritecollide(block, self.pacman_collide, False) if b_collide: continue elif p_collide: continue else: # Add the block to the list of objects self.block_list.add(block) self.all_sprites_list.add(block) self.bll = len(self.block_list) def next_step(self, action): # 奖励机制 reward = 0.3 # 游戏结束标识 game_state = False # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT if action == pacman_utils.PacManActions.LEFT: self.pacman.reset_speed(-30, 0) print("move LEFT") if action == pacman_utils.PacManActions.RIGHT: self.pacman.reset_speed(30, 0) print("move RIGHT") if action == pacman_utils.PacManActions.UP: self.pacman.reset_speed(0, -30) print("move UP") if action == pacman_utils.PacManActions.DOWN: self.pacman.reset_speed(0, 30) print("move DOWN") if action == pacman_utils.PacManActions.NOTHING: self.pacman.reset_speed(0, 0) print("move NOTHING") reward = 0 # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT hits = self.pacman.update(self.wall_list, self.gate) if hits: print("OH. hits wall, reward change to -0.2!") reward = -0.2 self.pinky.change_speed() self.pinky.change_speed(True) self.pinky.update(self.wall_list, False) self.blinky.change_speed() self.blinky.change_speed(True) self.blinky.update(self.wall_list, False) # self.inky.change_speed() # self.inky.change_speed(True) # self.inky.update(self.wall_list, False) # # self.clyde.change_speed() # self.clyde.change_speed(True) # self.clyde.update(self.wall_list, False) # See if the Pacman block has collided with anything. blocks_hit_list = pygame.sprite.spritecollide(self.pacman, self.block_list, True) # Check the list of collisions. if len(blocks_hit_list) > 0: get_score = len(blocks_hit_list) self.score += get_score # 吃到豆子reward增加 if get_score > 0: print("Yeah. eat bean, reward change to 1!") reward = 1.2 # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT self.screen.fill(black) self.wall_list.draw(self.screen) self.gate.draw(self.screen) self.all_sprites_list.draw(self.screen) self.monster_list.draw(self.screen) # 隐藏分数板, 影响识别 # text = self.font.render("Score: "+str(self.score)+"/"+str(self.bll), True, red) # self.screen.blit(text, [10, 10]) image_data = pygame.surfarray.array3d(pygame.display.get_surface()) if self.score == self.bll: game_state = True monster_hit_list = pygame.sprite.spritecollide(self.pacman, self.monster_list, False) if monster_hit_list: # 碰到怪物, reward降低, 游戏结束 print("Woo. killed by monster. reward change to -1!") reward = -5 game_state = True self.__init__() self.start_game() # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT pygame.display.flip() self.clock.tick(10) return game_state, image_data, reward <file_sep>import cv2 import numpy as np from pacman_game import pacman_utils as pac_utils from pacman_game import pacman import time import matplotlib.pyplot as plt # pacman_game = pacman.PacMan() # pacman_game.start_game() # # while True: # result, x_t1_colored, reward = pacman_game.next_step(pac_utils.PacManActions.LEFT) # print(result, reward) # # time.sleep(1) # # # 修改图片色值域 # x_t = cv2.cvtColor(cv2.resize(x_t1_colored, (101, 101)), cv2.COLOR_BGR2HLS) # # 像素高于阈值时,给像素赋予新值,否则,赋予另外一种颜色 # ret, x_t = cv2.threshold(x_t, 1, 255, cv2.THRESH_BINARY) # s_t = np.stack((x_t, x_t, x_t, x_t), axis=2) # print(s_t[:, :, :3]) # print(s_t) # plt.imshow(x_t1) # plt.show() # x_t1 = np.reshape(x_t1, (101, 101, 3)) a = np.zeros((101, 101, 3)) print(a.shape) print(np.append(a, a[:, :, :1], axis=2).shape) print(np.stack((a, a, a, a), axis=2).shape) # print(a[:, :, :3, :]) <file_sep>import tensorflow as tf from tensorflow.python import debug as tf_debug import numpy as np from collections import deque from pacman_game import pacman from pacman_game import pacman_utils import cv2 import random IMAGE_SIZE = 101 # 图片的尺寸 IMAGE_CHANNEL = 3 # 深度(色域) INPUT_NODES = 30603 # 输出的元素的大小, IMAGE_SIZE * IMAGE_SIZE * IMAGE_CHANNEL 像素点数 OUTPUT_NODES = 4 # 4分类问题, 对应PacManActions的4个枚举 # 第一层卷积层的尺寸 CONV1_DEEP = 32 CONV1_SIZE = 8 # 第二层卷积层的尺寸 CONV2_DEEP = 64 CONV2_SIZE = 5 # 第三层卷积层的尺寸 CONV3_DEEP = 64 CONV3_SIZE = 3 # 全连接层 FC_SIZE = 512 REPLAY_MEMORY = 50000 # 保存在队列中作为训练素材的长度 REGULARIZATION_RATE = 0.0001 # 描述模型复杂度的正则化项在损失函数中的系数 OBSERVE = 10000. # timeSteps to observe before training BATCH = 32 INITIAL_EPSILON = 0.1 # random moving def create_network(input_tensor, train, regularizer): # 第一层卷积层, 进入图片尺寸101*101*4, 输出 101*101*32 with tf.variable_scope("layer1-conv1"): conv1_weight = tf.get_variable("weight", [CONV1_SIZE, CONV1_SIZE, IMAGE_CHANNEL, CONV1_DEEP], tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1)) conv1_biases = tf.get_variable("biases", [CONV1_DEEP], tf.float32, initializer=tf.constant_initializer(0.0)) conv1 = tf.nn.conv2d(input_tensor, conv1_weight, strides=[1, 1, 1, 1], padding="SAME") relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases)) # 第二层池化层, 101*101*32 输出 51*51*32 with tf.variable_scope("layer2-pool1"): pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") # 声明第三层的卷积层, 进入 51*51*32, 输出 51*51*64 with tf.variable_scope("layer3-conv2"): conv2_weight = tf.get_variable("weight", [CONV2_SIZE, CONV2_SIZE, CONV1_DEEP, CONV2_DEEP], tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1)) conv2_biases = tf.get_variable("biases", [CONV2_DEEP], tf.float32, initializer=tf.constant_initializer(0.0)) conv2 = tf.nn.conv2d(pool1, conv2_weight, strides=[1, 1, 1, 1], padding="SAME") relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases)) # 第四层池化层, 进入 51*51*64 输出 26*26*64 with tf.variable_scope("layer4-pool2"): pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") # 第四层输入26*26*64输出26*26*64 with tf.variable_scope("layer5-conv3"): conv3_weight = tf.get_variable("weight", [CONV3_SIZE, CONV3_SIZE, CONV2_DEEP, CONV3_DEEP], tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1)) conv3_biases = tf.get_variable("biases", [CONV3_DEEP], tf.float32, initializer=tf.constant_initializer(0.0)) conv3 = tf.nn.conv2d(pool2, conv3_weight, [1, 1, 1, 1], padding="SAME") relu3 = tf.nn.relu(tf.nn.bias_add(conv3, conv3_biases)) # 输入26*26*64 输出 13*13*64 with tf.variable_scope("layer6-pool3"): pool3 = tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") # 准备进入全连接层, 13*13*64=10816 # pool_shape = [None, 10816] pool_shape = pool3.get_shape().as_list() nodes = pool_shape[1] * pool_shape[2] * pool_shape[3] # # # 其实就是转换为[图片数量, 10816]*猜测 # reshaped = tf.reshape(pool3, [pool_shape[0], nodes]) reshaped = tf.reshape(pool3, [-1, nodes]) with tf.variable_scope("layer7-fc1"): fc1_weight = tf.get_variable("weight", [nodes, FC_SIZE], initializer=tf.truncated_normal_initializer(stddev=0.1)) # 全连接层增加正则化, 防止过拟合 if regularizer is not None: tf.add_to_collection("losses", regularizer(fc1_weight)) fc1_biases = tf.get_variable("biases", [FC_SIZE], initializer=tf.constant_initializer(0.1)) fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weight) + fc1_biases) # 只有在训练时加入dropout if train: fc1 = tf.nn.dropout(fc1, 0.5) with tf.variable_scope("layer8-fc2"): fc2_weight = tf.get_variable("weight", [FC_SIZE, OUTPUT_NODES], initializer=tf.truncated_normal_initializer(stddev=0.1)) fc2_biases = tf.get_variable("biases", [OUTPUT_NODES], initializer=tf.constant_initializer(0.1)) if regularizer is not None: tf.add_to_collection("losses", regularizer(fc2_weight)) logit = tf.matmul(fc1, fc2_weight) + fc2_biases # writer = tf.train.Su return logit def train_network(): x = tf.placeholder(tf.float32, [None, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNEL], name="x-input") train_queue = deque(maxlen=50000) # 正则化损失函数 regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE) network = create_network(x, False, regularizer) # 交叉熵 # cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y_, 1), logits=network) # cross_entropy_mean = tf.reduce_mean(cross_entropy) # # # 总损失 = 交叉熵损失 + 正则化的权重 # loss = cross_entropy_mean + tf.add_n(tf.get_collection("losses")) # # train_step = tf.train.AdamOptimizer(1e-6).minimize(loss) a = tf.placeholder("float", [None, OUTPUT_NODES]) y = tf.placeholder("float", [None]) readout_action = tf.reduce_sum(tf.multiply(network, a), reduction_indices=1) cost = tf.reduce_mean(tf.square(y - readout_action)) train_step = tf.train.AdamOptimizer(1e-6).minimize(cost) game = pacman.PacMan() game.start_game() result, image_data, reward = game.next_step(pacman_utils.PacManActions.NOTHING) # 修改图片尺寸, 并调整色值域 image_data = cv2.cvtColor(cv2.resize(image_data, (101, 101)), cv2.COLOR_BGR2HLS) # 像素高于阈值时,给像素赋予新值,否则,赋予另外一种颜色 ret, image_data = cv2.threshold(image_data, 1, 255, cv2.THRESH_BINARY) s_t = np.reshape(image_data, (101, 101, 3)) # image_data = np.append(image_data, image_data[:, :, :2], axis=2) # s_t = np.stack((image_data, image_data, image_data, image_data), axis=2) # s_t = np.append(image_data, image_data[:, :, :1], axis=2) sess = tf.InteractiveSession() # sess = tf_debug.LocalCLIDebugWrapperSession(sess) # sess.add_tensor_filter("has_inf_or_nan", tf_debug.has_inf_or_nan) sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() checkpoint = tf.train.get_checkpoint_state("saved_networks") if checkpoint and checkpoint.model_checkpoint_path: saver.restore(sess, checkpoint.model_checkpoint_path) print("Successfully loaded:", checkpoint.model_checkpoint_path) else: print("Could not find old network weights") epsilon = INITIAL_EPSILON step = 0 while True: network_t = network.eval(feed_dict={x: [s_t]})[0] action = np.zeros([OUTPUT_NODES]) if random.random() <= epsilon and step <= OBSERVE: print("----------Random Action----------") action[random.randrange(OUTPUT_NODES)] = 1 else: action[np.argmax(network_t)] = 1 state, image_data, reward = game.next_step(pacman_utils.get_action_from_array(action)) # 修改图片尺寸, 并调整色值域 image_data = cv2.cvtColor(cv2.resize(image_data, (101, 101)), cv2.COLOR_BGR2HLS) # 像素高于阈值时,给像素赋予新值,否则,赋予另外一种颜色 ret, image_data = cv2.threshold(image_data, 1, 255, cv2.THRESH_BINARY) image_data = np.reshape(image_data, (101, 101, 3)) # s_t1 = np.append(image_data, s_t[:, :, :1], axis=2) train_queue.append((s_t, action, reward, image_data, state)) if step > OBSERVE: minibatch = random.sample(train_queue, BATCH) # get the batch variables s_j_batch = [d[0] for d in minibatch] action_batch = [d[1] for d in minibatch] reward_batch = [d[2] for d in minibatch] screen_batch = [d[3] for d in minibatch] readout_j1_batch = network.eval(feed_dict={x: screen_batch}) y_batch = [] for i in range(0, len(minibatch)): terminal = minibatch[i][4] # if terminal, only equals reward if terminal: y_batch.append(reward_batch[i]) else: y_batch.append(reward_batch[i] + 0.99 * np.max(readout_j1_batch[i])) train_step.run(feed_dict={y: y_batch, a: action_batch, x: s_j_batch}) if step % 1000 == 0: saver.save(sess, 'saved_networks/pacman-dqn', global_step=step) s_t = image_data step += 1 print("Finish step : ", step) if __name__ == '__main__': train_network()
eefed9b48e1aefaa4467631da411c1b8ff00c877
[ "Python" ]
3
Python
saselovejulie/machine_learning_game
3a8f66835dd7cdd2e57456786adb70b97f0b6aca
459d2cac2ec9760974c8c2fcd2974dcbaa10d227
refs/heads/master
<repo_name>linxiahaiyang/test<file_sep>/index.js conosle.log('添加了index.js文件')
441661faf4fcd44c935e672a960e7f6ea2dc723c
[ "JavaScript" ]
1
JavaScript
linxiahaiyang/test
e08868d54183a8fcd9899f097171f4e7c46285a7
69ff9d1224a8772e0674a5c7756a58c589125c3b
refs/heads/master
<file_sep><?php /** * @file * template.php */ function restaurant_subtheme_preprocess_image(&$vars) { // http://getbootstrap.com/css/#overview-responsive-images $vars['attributes']['class'][] = 'img-responsive'; return; } function restaurant_css_alter(&$css) { //cambiar el css padre por el hijo //unset($css[drupal_get_path('theme','bootstrap_business').'/bootstrap/css/bootstrap.css']); // return; } /** * Preprocess variables for html.tpl.php */ function restaurant_preprocess_html(&$variables) { /** * Add IE8 Support */ drupal_add_css(drupal_get_path('theme', 'bootstrap_business') . '/css/ie8.css', array( 'group' => CSS_THEME, 'browsers' => array('IE' => '(lt IE 9)', '!IE' => FALSE), 'preprocess' => FALSE )); /** * Add Javascript for enable/disable Bootstrap 3 Javascript */ // if (theme_get_setting('bootstrap_js_include', 'bootstrap_business')) { drupal_add_js(drupal_get_path('theme', 'bootstrap_business') . '/bootstrap/js/bootstrap.min.js'); // } }<file_sep><?php /** * @file * Template for my home page. */ ?> <div class="panel-display homepage clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>> <div class="row"> <div class="col-lg-12"> <?php print $content['carousel']; ?> </div> </div> <div class="row white-color"> <div class="col-sm-8"><?php print $content['reservar']; ?></div> <div class="col-sm-4"> <div class="row"> <?php print $content['location1']; ?> </div> <div class="row"> <div class="col-xs-6"> <?php print $content['location2']; ?> </div> <div class="col-xs-6"> <?php print $content['horary']; ?> </div> </div> </div> </div> </div> <file_sep>(function ($) { Drupal.behaviors.restaurant = { attach: function (context, settings) { $("#slideshow").fadeIn("slow"); $(".carousel").carousel({ interval: '5000', wrap: true }); $(".carousel").bind("slide", function (e) { setTimeout(function () { var next_h = $(e.relatedTarget).outerHeight(); $(".carousel").css("height", next_h); }, 10); }); } }; })(jQuery);<file_sep><?php /** * @file * Template for my home page. */ ?> <div class="panel-display homepage clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>> <div class="row"> <div class="col-sm-6"><?php print $content['cocteles']; ?></div> <div class="col-sm-6"><?php print $content['cerveza']; ?></div> </div> <div class="row"> <div class="col-sm-6"><?php print $content['sinalchol']; ?></div> </div> </div> <file_sep>Tema Restaurant para Drupal. Un subtema de bootstrap-business. ============================================================= La última capa de Drupal la forman los temas ( themes ) y son los principales responsables de la apariencia gráfica o estilo con que se mostrará la información al usuario. Como ya se ha citado en apartados anteriores, el uso de temas posibilita la separación entre información y aspecto gráfico permitiendo cambiar el diseño u apariencia sin necesidad de modificar los contenidos ni el código, lo que es muy práctico si lo único que queremos es renovar la apariencia de una web. Otra ventaja de esta separación es que podemos actualizar el núcleo de Drupal sin perder el diseño del sitio web, algo que no ocurriría si el diseño se encontrará integrado en el propio núcleo o código de Drupal. Así, en el momento que Drupal dispone de la información a de mostrar, se la pasa al motor de temas para que decida la apariencia que debe darle. Para ello, el motor de temas hace uso de la información del tema activo, que se compone de diferentes ficheros CSS, HTML o PHP. Copiando en nueva carpeta y modificando estos ficheros podremos crear nuestros temas, aunque lo más recomendable es descargar alguno de los muchos temas que se encuentran disponibles en Internet ( consultar apartado de instalación de módulos y temas ). Si echamos una ojeada al contenido de la carpeta de un tema veremos diferentes ficheros: - .info: contiene información general sobre el tema, como el nombre del tema, una descripción, la versión de Drupal en que funciona etc. A parte, en este fichero podremos quitar o añadir elementos del tema como son las regiones, css, javascripts, o elementos como los links primarios, la cajita de búsqueda etc. - .tpl.php: son ficheros .php que mezclan código .html y código .php y especifican algunos detalles del modo en que se ha de mostrar el elemento a que se refieren en su nombre. P.ej page.tpl.php define la estructura general del HTML de una page, block.tpl.php define la estructura general del HTML de un bloque etc. - .css: contiene código css que es utilizado por las templates. - .png, .jpg: son las imágenes que se muestran en el tema. - template.php : se considera la piedra angular de los temas, y contiene un conjunto de funciones .php que, al contrario de lo que sucede con los ficheros .tpl.php, permiten controlar hasta el minimo detalle del modo en que se muestra la información en el navegador. Es decir es el fichero que dará mas juego a la hora crear nuestro tema, permitiéndonos omitir las variables y funciones de estilo de Drupal para usar las nuestras. Si queremos que un Rol, que no sea el administrador, pueda cambiar los temas, deberemos darle permisos en las correspondientes opciones de usuario en "Administer>User managment>Permisions" “System module”, y también marcar la casilla Enabled en “Administer>Site building>Themes”. Así, el usuario podrá elegir entre alguno de los Themes marcados como Enabled. Existen temas más bonitos y otros mas feos, algunos mejor programados y otros peor. Los mejor acabados incluirán diferentes opciones de configuración. Un buen ejemplo de tema configurable es el Garland. Este permite configurar la mayor parte de sus parámetros, y para ello solo deberemos ir a “Administer>Site building>Themes” y seleccionar Edit para configurarlo. En las opciones de configuración podemos especificar si queremos que se visualize el domino de la web, el slogan, cambiar el logo etc. La información del Slogan se configura en “Administer>Site configuration>Site information”. Algunos CMS permiten establecer un Theme para el administrador y otro para los demás usuarios con la finalidad de facilitar el trabajo. Por defecto Drupal utiliza el mismo tema para los administradores que para usuarios, pero si lo deseamos, podemos establecer un tema diferente, para ello debemos ir a “Administer > Site configuration > Administration theme”.<file_sep><?php /** * @file homepage.inc * @date * @brief The panels layout plugin for the homepage panels layout. * * */ // Plugin definition $plugin = array( 'title' => t('homepage'), 'icon' => 'homepage.png', 'category' => t('redbull'), 'theme' => 'homepage', 'css' => 'homepage.css', 'regions' => array( 'carousel' => t('Carousel'), 'reservar' => t('Reservar'), 'location1' => t('Location 1'), 'location2' => t('Location 2'), 'horary' => t('Horary'), ), ); <file_sep><?php /** * @file bebidas.inc * @date * @brief The panels layout plugin for the bebidas panels layout. * * */ // Plugin definition $plugin = array( 'title' => t('Bebidas'), 'icon' => 'bebidas.png', 'category' => t('redbull'), 'theme' => 'bebidas', //'css' => 'homepage.css', 'regions' => array( 'cocteles' => t('Cocteles'), 'cerveza' => t('Cerveza'), 'sinalchol' => t('Sin Alchol'), 'vinos' => t('Vinos'), ), ); <file_sep><?php // Put the logo path into JavaScript for the live preview. drupal_add_js(array('color' => array('logo' => theme_get_setting('logo', 'bootstrap_business'))), 'setting'); $info = array( // Available colors and color labels used in theme. 'fields' => array( 'bg' => t('Main background'), 'highlight' => t('Highlight Background'), 'link' => t('Link/Call-to-Action'), ), // Pre-defined color schemes. 'schemes' => array( 'default' => array( 'title' => t('Default'), 'colors' => array( 'bg' => '#f5f5f5', 'highlight' => '#222222', 'link' => '#e74c3c', ), ), 'blue' => array( 'title' => t('Dark Gray/Blue'), 'colors' => array( 'bg' => '#f4f7fb', 'highlight' => '#454e59', 'link' => '#4484c7', ), ), 'green' => array( 'title' => t('Gray/Green'), 'colors' => array( 'bg' => '#f0f0f0', 'highlight' => '#b0bdc9', 'link' => '#5fb336', ), ), ), // CSS files (excluding @import) to rewrite with new color scheme. 'css' => array( 'color/colors.css', ), // Files to copy. 'copy' => array( 'logo.png', ), // Gradient definitions. 'gradients' => array( array( // (x, y, width, height). 'dimension' => array(0, 0, 0, 0), // Direction of gradient ('vertical' or 'horizontal'). 'direction' => 'vertical', // Keys of colors to use for the gradient. 'colors' => array('top', 'bottom'), ), ), // Color areas to fill (x, y, width, height). 'fill' => array(), // Coordinates of all the theme slices (x, y, width, height) // with their filename as used in the stylesheet. 'slices' => array(), // Reference color used for blending. Matches the base.png's colors. 'blend_target' => '#ffffff', // Preview files. 'preview_css' => 'color/preview.css', 'preview_js' => 'color/preview.js', 'preview_html' => 'color/preview.html', // Base file for image generation. 'base_image' => 'color/base.png', );
cc278e8604e940c891e857e2f21e8dfdaf825026
[ "JavaScript", "Markdown", "PHP" ]
8
PHP
rpayanm/restaurant
32841bde489026eae2eed29413a0a07e66a2a801
c3147d5acafebdff489555ca63d77587ccab4824
refs/heads/main
<repo_name>o2o25252/2021-TIL<file_sep>/Swift/Closure.playground/Contents.swift import UIKit // //var multiplyClosure: (Int, Int) -> Int = { (a: Int, b: Int) -> Int in // return a * b //} var multiplyClosure: (Int, Int) -> Int = { $0 * $1 } let result = multiplyClosure(4,2) func operateTwoNum(a: Int, b: Int, opertion: (Int, Int) -> Int) -> Int { let result = opertion(a,b) return result } operateTwoNum(a: 4, b: 2, opertion: multiplyClosure) var addClosure: (Int, Int) -> Int = {a,b in return a+b} operateTwoNum(a: 4, b: 2, opertion: addClosure) operateTwoNum(a:4, b: 2, opertion: {a,b in return a/b}) <file_sep>/IOS/IOS/main.swift // // main.swift // IOS // // Created by 임희찬 on 2021/03/06. // import Foundation // (A+B)%C, 둘째 줄에 ((A%C) + (B%C))%C, 셋째 줄에 (A×B)%C, 넷째 줄에 ((A%C) × (B%C))%C let num1 = Int(readLine()!)! let num2 = Int(readLine()!)! print(num2) print(num1) <file_sep>/MVVM.md # MVVM ♻️ ### 목적 + 기술부채 최소화 + 재사용 및 지속 가능 구첵적으로 코드 구조에 대한 전략 이전에는 MVC 패턴을 사용했는데 "MVC" 는 무엇일까? Model(데이터:Struct) , View(UI요소:UIView) , Controller(중계자:UIViewController) 컨트롤러 가 너무 많이 관여해서 부채가발생 하여ㅑ..? 현재 MVVM 을 많이 사용중이다. <img width="723" alt="스크린샷 2021-03-05 오후 9 51 27" src="https://user-images.githubusercontent.com/61407010/110117942-f1fc3380-7dfc-11eb-81de-1db81b599e0f.png"> + Model(데이터:Struct) + View(UI요소:UIView, UIViewController) + VieModel(중계자: ViewModel) #### 차이점 + 뷰 컨트롤러가 모델에 직접 접근하지 못한다. + 뷰 컨트롤러가 뷰 모델 클레스 를 새로 받았다. + 뷰 컨트롤러가 뷰 레이어에 있다 개선점 : 뷰컨트롤러에 역활을 축소 그래서 할일이 명확 해서 수정이 명확하고 유지보수 가 좋아진다. <img width="782" alt="스크린샷 2021-03-05 오후 9 58 42" src="https://user-images.githubusercontent.com/61407010/110118597-f412c200-7dfd-11eb-9a80-d827b918aabd.png"> <img width="790" alt="스크린샷 2021-03-05 오후 9 58 57" src="https://user-images.githubusercontent.com/61407010/110118626-fd9c2a00-7dfd-11eb-9225-ca4e6ca3d370.png"> <file_sep>/algorithm/이코테/Python.md # 자료형 ## 정수형 - 정수형(Integer)은 *정수를 다루는 자료형*입니다. + 양의 정수, 음의 정수, 0이 포함됩니다. - 코딩 테스트에서 출제되는 많은 문제들은 정수형을 주로 다루게 됩니다. ## 실수형 - 실수형(Real Number)은 *소수점 아래의 데이터를 포함하는 수 자료형*입니다. + 파이썬에서는 변수에 소수점을 붙인 수를 대입하면 실수형 변수로 처리됩니다. + 소수부가 0이거나 , 정수부가 0인 소수는 0을 생략하고 작성할 수 있습니다. - 개발 과정에서 실수 값을 제대로 비교하지 못해서 원하는 결과를 얻지 못할 수 있습니다. - 이럴 떄는 *round() 함수*를 이용할 수 있으면, 이러한 방법이 권장됩니다. ## 지수 표현 방식 - 파이썬에서는 e 나 E를 이요한 *지수 표현 방식을 이용할 수 이씁니다. + e나 E 다음에 오는 수는 10의 지수부를 의미합니다. + 예를 들어 1e9라고 입력하게 되면, 10dml 9제곱(1,000,000,000)이 됩니다. <img width="442" alt="스크린샷 2021-01-25 오후 11 05 25" src="https://user-images.githubusercontent.com/61407010/105716306-fb72c000-5f61-11eb-8945-3478e0b33cb4.png"> - 지수 표현 방식은 임의의 큰 수를 표현하기 위해 자주 사용됩니다. - 최단 경로 알고리즘에서는 도달할 수 없는 노드에 대하여 최단 거리를 *무한(INF)*로 설정하곤 합니다. + 이떄 가능한 최댓값이 10억 미만이라면 무한(INF)의 값으로 1e9를 이용할 수 있습니다. ## 수 자료형의 연산 - 수 자료형에 대하여 *사칙연산*과 나머지 연산자가 많이 사용 - 단 나누기 연산자(/)를 주의 + 파이썬에서 나누기 연산자(/)는 나눠진 결과를 실수형으로 반환 - 다양한 로직을 설계할 때 *나머지 연산자*를 이용해야 할 떄가 많습니다. - 파이썬에서는 몫을 얻기 위해 *몫 연산자(//)를 사용합니다. - 이외에도 거듭 제곱 연산자(**) 를 비롯해 다양한 연산자 들이 존재 ## 리스트 자료형 - 여러 개의 *데이터를 연속적으로 담아 처리하기 위해 사용하는 자료형* + 리스트 대신에 배열 혹은 테이블이라고 부르기도 한다 ## 리스트 초기화 - 리스트는 대괄호안에 원소를 넣어 초기화하며, 쉼표로 원소를 구분 - 비어 있는 리스트를 선언하고자 할 때는 list() 혹은 [] 를 이용 - 리스트의 원소에 접글할 때는 인덱스 값을 괄호에 넣는다. ## 리스트의 인덱싱과 슬라이싱 - 인덱스 값을 입력하여 *리스트의 특정한 원소에 접근하는 것을 인덱싱(Indexing)*이라고 합니다. + 파이썬의 인덱스 값은 양의 정수와 음의 정수를 모두 사용할 수 있습니다. + 음의 정수를 넣으면 원소를 거꾸로 탐색하게 됩니다. - 리스트에서 *연속적인 위치를 갖는 원소들을 가져와야 할 때는 슬라이싱(Slicing)을 이용* + 대괄호 안에 콜론(:)을 넣어서 *시작 인덱스* 와 *끝 인덱스*를 설정할 수 있다. + 끝 인덱스는 실제 인덱스보다 *1을 더 크게* 설정 ## 리스트 컴프리헨션 - 리스트를 초기화하는 방법 중 하나 + *대괄호 안에 조건문과 반복문을 적용하여 리스트를 초기화* 할 수 있다. ``` # 0부터 9 까지의 수를 포함하는 리스트 array = [i for i in range(10)] [0,1,2,3,4,5,6,7,8,9] #조건 도 가능 array = [1 for i in range(20) if i % 2 == 1] # [1,3,5,7,9,11,13,15,17,19] array = [i * i for i in range(1,10)] ``` *좋은 예시* ``` n = 4 m = 3 array = [0] * m for _in range(n)] ``` ## 언더바 - 파이썬에서는 반복을 수행하되 반복을 위한 변술의 값을 무시하고자 할 때 *언더바*를 자주 사용 ## 리스트 관련 기타 메서드 함수명|서용법|설명|시간복잡도 ----|-----|---|------| append()|asd.append()|리스트 원소를 하나 삽일할 떄 사용한다.|O(1)| sort()|asd.sort()/asd.sort(reverse()=True)|오름,내림차순정렬|O(NlogN)| reverse()|asd.reverse()|리스트의 원소의 순서를 모두 뒤집어 놓는다|O(N) insert()|insert(삽입할 위치 인덱스,삽입할 값)|특정한 인덱스 위치에 원소를 삽입할 때 사용한다.|O(N)| count()|asd.count(특정 값)|리스트에서 특정한 값을 가지는 데이터의 개수를 셀 떄 사용한다.| O(N)| remove()|asd.remove(특정 값)|특정한 값을 갖는 원소를 제거하는데,값을 가진 원소가 여러 개면하나만 제거한다.|O(N)| ## 문자열 자료형 - 문자열 변수를 *초기화*할 때는 큰따옴표나 작은 따옴표를 이용 - 문자열 안에 큰따옴표나 작은따옴표가 포함되어야 하는 경우 + 전체 문자열을 큰따옴표로 구성하는 경우, 내부적으로 작은따옴표를 포함할 수 있다. + 전체 문자열을 작은따옴표로 구성하는 경우, 내부적으로 큰따옴표를 포함할 수 있다. + 혹은 백슬래시(\)를 사용하면,큰따옴표나 작은따옴표를 원하는 만큼 포함시킬 수 있다. ``` data = "Don 't you know \"Python"\"?" ``` ## 문자열 연산 - 문자열 변수에 *덧셈*을 이용하면 *문자열이 더해져서 연결*된다. - 문자열 변수를 특정한 양의 정수와 곱하는 경우, 문자열이 그 값만큼 여러 번 더해집니다. - 문자열에 대해서도 마찬가지로 인덱싱과 슬라이싱을 이용할 수 있다. + 다만 문자열은 특정 인덱스의 값을 변경할 수는 없습니다. (immutable) ## 튜플 자료형 - 튜플 자료형은 리스트와 유사하지만 다음과 같은 문법적 차이가 있다. + 튜플은 * 한 번 선언된 값을 변경할 수 없습니다* + 튜플은 소괄호를 이용 - 튜플은 리스트에 비해 상대적으로 *공간 효율적*이다. ## 딕셔너리 - 키와값의 쌍을 데이터로 가지는 자료형 + 앞서 다루었던 리스트나 튜플이 값을 순차적으로 저장하는 것과는 대비된다. - 딕셔너리는 키와 값의 쌍을 데이터로 가지며 원하는 *'Immutable한 자료형'을 키로 사용*할 수 있다. - 해시 테이블을 이용하므로 __데이터의 조회 및 수정에 있어서 O(1)의 시간에 처리__할 수 있다. ## 딕셔너리 관련 메서드 - 키 데이터만 뽑아서 리스트로 이용할 떄는 *keys()* - 값 데이터만을 뽑아서 리스트로 이용할 떄는 *values()* ## 집합 자료형 - 특징 + 중복을 허용하지 않는다. + 순서가 없다, - 집합은 *리스트 혹은 문자열을 이용해서 초기화*할 수 있다. + 이때 set()함수를이용 - 혹은 중괄호 안에 각 원소를 콤마를 기준으로 구분하여 삽입함으로 초기화 - 데이터의 조회 및 수정에 있어서 O(1)의 시간에 처리할 수 있다. ``` # 합 a | b # 교 a & b # 차 a - b ``` ------ # 입력 ## 자주 사용되는 표준 입력 방법 - input() 함수는 한 줄의 문자열을 입력 받는 함수 - map() 함수는 리스트의 모든 원소에 각각 특정한 함수를 적용할 때 사용 ## 빠르게 입력 받기 - 사용자로부터 *입력을 최대한 바르게 받아야 하는 경우*가 있습니다. - 파이썬의 경우 sys 라이브러리에 정의 되어 이는 sys.stdin.readline() 메서드를 이용 + 단 , 입력 후 엔터가 줄 바꿈 기호로 입력되므로 rstrinp() 메서드를 함께 사용 ``` import sys # 문자열 입력 받기 data =sys.stdin.readline().rstrip() ``` ## f-string - 문자열 앞에 접두사 'f'를 붙여 사용 - 중괄호 안에 변수명을 기입하여 간단히 문자열과 정수를 함께 넣을 수 있다. ``` answer = 7 print(f"정답은 {answer}입니다.") ``` --- ## global 키워드 ``` a = 0 def fuc(): global a a += 1 for i in range(10): fuc() ``` ## 패킹 언 패킹(여러 개의 반환 값) - 파이썬에서 함수는 여러 갸의 반환 값을 가질 수 이싿. ``` def operator(a,b): add_var = a + b sibtract_var = a- b multiply_var = a * b ddivide_var = a / b retirm add_var, subtract_var, multiply_var, divide_var a,b,c,d = operator(7,3) ``` # 람다 표현식 - 람다 표현식을 이용하면 함수를 간단하게 작성 + 특정한 기능을 수행하는 함수를 한 줄에 작성할 수 있다는 점이 특징 ``` print((lamda a, b: a+b)(3,7)) array = [('hong', 50), ('lee, 32),('unknown',74)] def my_key(x): return x[1] sorted(array, key=my_key) # 람다는 sorted(array, key=lamda x: x[1])) ``` --- # 실전 유용 라이브러리 - itertools: 파이썬에서 반복되는 형태의 데이터를 처리하기 위한 유용한 기능 + 특히 순열과 조합 라이브러리는 코테에서 자주 사용 - heapq: 힙 자료구조를 제공 + 일반적으로 우선순위 큐 기능을 구현하기 우해 사용 - bisect: 이진 탐색 기능 제공 - collection: deque, counter등의 유용한 자료 구조 - math: 필수적인 수학적 기능을 제공 + 팩토리얼, 제곱근, 최대공약수,삼각함수 관련 함수부터 파이와 가은 상수를 포함 <file_sep>/todayReadLink.md # 그날 읽은 모든 링크 기록소 ## 2021-03-08 - [IBAction과 IBOutlet이 뭘까](https://etst.tistory.com/74) - [IBOutlet의 Strong vs Weak](http://monibu1548.github.io/2018/05/03/iboutlet-strong-weak/) - [Type Casting](https://zeddios.tistory.com/265) - [Any와 AnyObject의 차이](https://zeddios.tistory.com/213) - [인스턴스 생성과 소멸](https://seoyoung612.tistory.com/entry/swift%EC%8A%A4%EC%9C%84%ED%94%84%ED%8A%B8%EA%B8%B0%EB%B3%B8%EB%AC%B8%EB%B2%9508-%EC%9D%B8%EC%8A%A4%ED%84%B4%EC%8A%A4-%EC%83%9D%EC%84%B1%EA%B3%BC-%EC%86%8C%EB%A9%B8) - [MVVM](https://www.youtube.com/watch?v=bjVAVm3t5cQ&t=286s) - [구조체 와 클레스 차이](https://shark-sea.kr/entry/Swift-%EA%B5%AC%EC%A1%B0%EC%B2%B4%EC%99%80-%ED%81%B4%EB%9E%98%EC%8A%A4-%EC%B0%A8%EC%9D%B4-struct-vs-class) ## 2021-03-09 - [Swift underbar는 모야?](https://medium.com/@codenamehong/swift-underscore-90dcbec5072f) ## 2021-03-10 - [String 반복](https://developer.apple.com/documentation/swift/string/2427723-init) - [print terminator](https://developer.apple.com/documentation/swift/1541053-print) ## 2021-03-11 - [알고리즘에 필요한 스위프트 베이직](https://twih1203.medium.com/swift-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98%EC%97%90-%ED%95%84%EC%9A%94%ED%95%9C-swift-basic-%EC%B4%9D%EC%A0%95%EB%A6%AC-d86453bbeaa5) <file_sep>/Swift/swiftnote.md # 스위프트 로 코테 풀면서 새로 알게된 문법 기록 공간 ### readLine() [REF](https://0urtrees.tistory.com/94) - 공백단위의 문자열 입력을 받아 [Int] 배열로 변환하기 ``` // input : 1 2 3 4 5 let intArr = readLine()!.split(separator: " ").map { Int($0)! } print(intArr) // [1,2,3,4,5] ``` 먼저 *readLine() * 함수는 ```String?``` 값으로 입력값을 주는데, 이를 강제언래핑```!```해서 * String * 값으로 변환 이후 공백단위로 문자열을 쪼개기 위해서 *split*를 사용 , 그 후 해당 값을 원하는 타입으로 변환하는데 이때 map 을 사용한다. map 연산자의 클로저 내에는 앞서 split으로 공백단위로 쪼개진 Character 타입의 값들이 차례대로 맵핑이 되도록 설정합니다. 이제 변수에 할당해주면 intArr 은 [Int] 타입의 배열이 되며, 그 값은 [1.2.3.4.5] 이다. - 공백단위의 문자열을 입력을 받아 [String] 배열로 변환하기 ``` let stringArr = readLine()!.split { $0 == " " } print(stringArr) // ["1","2","3","4","5"] ``` - 붙어이는 readLine() 입력값을 [Int] 배열로 변환하기 Array() 생성자로 입력값을 전달해준다. 입력값을 먼저 배열화 해서 처리하는 방법 ``` // input: 12345 let stringArr2 = Array(readLine()!).map { Int(String($0)! } print(stringArr2) // [1, 2, 3, 4, 5] ``` readLine() 으로 받은 입력값을 강재 언래핑 후, String 타입으로 만든 뒤, Array로 감싸고 있다. 이렇게 하면 문자열은 [Character] 타입의 배열로 변환된다. 이를 map 을 통해 [String] -> [Character] -> [Int] 형으로 변환 작업을 거쳐서 Int 타입의 배열을 얻어낼 수 있다. - 하나의 값 ``` // input: 100 var n = Int(readLine()!)! ``` ## Count ``` let stringAttay=["add","bd","cccc","ddd","e"] var threeCountArray = [String]() for st in stringAttay{ if st.count == 3 { threeCountArray.append(st) } } print(threeCountArray) ``` st.count 일때 st sms add , bd ... 등 으로 하나씩찍히는 데 이때 count 는 그 글자의 글자수 를 나타낸다. ## 고차함수 - map ``` let t = readLine()!.split(separator: " ").map{ Double($0)! } ``` - filter - reduce <file_sep>/Swift/Swift_Flow_Control.playground/Contents.swift import UIKit import Foundation let closeRange = 0...10 let halfCloseRange = 0..10 for i in closeRange{ if i % 2 == 0{ print("짝수: \(i)") } } for i in closeRange where i % 2 == 0 { print("짝수: \(i)") } for i in closeRange{ if i == 3 { continue } print("짝수\(i)") } <file_sep>/Swift/TestApp/BountyList2/BountyList2/DetailViewController.swift // // DetailViewController.swift // BountyList2 // // Created by 임희찬 on 2021/03/08. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var bountyLabel: UILabel! //이름과 현상금 정보로 3개의 값을 뽑을 수 있다. // var name: String? // var bounty: Int? //🧑🏻‍💻 MODEL //var bountyInfo : BountyInfo? // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. 그래서 주석처리 //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. let viewModel = DetailViewModel() // 아니 근데 클레스 인데 왜 뒤에 () 이걸 사용하는 걸까?? //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 override func viewDidLoad() {//컨트롤러의 뷰가 메모리에로드 된 후 호출 super.viewDidLoad() //이 메서드를 재정의 super하는 경우 슈퍼 클래스도이 메서드를 재정의하는 경우 구현의 특정 지점 에서이 메서드를 호출합니다 . UpdateUI() //그래서 이게 실행된후 UpdateUI 를 부르면 이미 데이터를 받은 상태 이겠구나! } //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 func UpdateUI() { //🧑🏻‍💻 MODEL // if let bountyInfo = self.bountyInfo { // imgView.image = bountyInfo.image // nameLabel.text = bountyInfo.name // bountyLabel.text = "\(bountyInfo.bounty)" // } // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. if let bountyInfo = viewModel.bountyInfo { imgView.image = bountyInfo.image nameLabel.text = bountyInfo.name bountyLabel.text = "\(bountyInfo.bounty)" } // if let name = self.name , let bounty = self.bounty { // //아마도 여기에 온다는 것은 앞에서 이미 하나의 셀을 선택하여 그 셀의정보를 보낸거 일 꺼다. // let img = UIImage(named: "\(name).jpg") // imgView.image = img // nameLabel.text = name // bountyLabel.text = "\(bounty)" // } } //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 @IBAction func close(_ sender: Any) { //사라지기 dissmise //completion 은 얘가 사라진 후 에 동작될 것 dismiss(animated: true, completion: nil) } } // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. class DetailViewModel { var bountyInfo : BountyInfo? func update(model: BountyInfo?) { bountyInfo = model } } <file_sep>/Swift/Structure.playground/Contents.swift import UIKit struct Lecture { let name: String let instructor : String let numOfStudent : Int } func printLectureName(from instrutor: String, lectures: [Lecture]) { let lectureName = lectures.first{ (lec) -> Bool in return lec.instructor == instrutor}?.name ?? "없습니다." print("그 강사님 강의는요: \(lectureName)") } // lec 는 돌고있는 현재 Lecture 이다 그래서 입력된강의와 현 lec 의 강의 와 비교해서 같을때 lec.name 을 출력 let lec1 = Lecture(name: "IOS Basic", instructor: "Jason", numOfStudent: 5) let lec2 = Lecture(name: "IOS Advanced", instructor: "Jack", numOfStudent: 5) let lec3 = Lecture(name: "IOS Pro", instructor: "Nick", numOfStudent: 5) let lectures = [lec1,lec2,lec3] printLectureName(from: "no", lectures: lectures) <file_sep>/Swift/one/BountyList/BountyList/DetailViewController.swift // // DetailViewController.swift // BountyList // // Created by 임희찬 on 2021/03/04. // import UIKit class DetailViewController: UIViewController { // MVVM // Model // BountyInfo // > BountyInfo Make! // View // - ListCell // > ListCell  이 필요한 정보를 ViewModel 한테서 받아야 겠다 // > ListCell 은 ViewModel 로 부터 받은 정보로 뷰 업데이트 하기 // ViewModel // - BountyViewModel // > BountyViewModel 만들고 , 뷰 레이어 에서 필요한 메서드 만들기 // > 모델 가지고 있기 , BountyInfo들 @IBOutlet weak var imagView : UIImageView! @IBOutlet weak var nameLabel : UILabel! @IBOutlet weak var bountyLabel : UILabel! var bountyInfo: BountyInfo? override func viewDidLoad() { super.viewDidLoad() updateUI() } func updateUI() { if let bountyInfo = self.bountyInfo{ imagView.image = bountyInfo.image nameLabel.text = bountyInfo.name bountyLabel.text = "\(bountyInfo.bounty)" } // if let name = self.name, let bounty = self.bounty { // let img = UIImage(named: "\(name).jpg") //// imagView.image = img //// nameLabel.text = name //// bountyLabel.text = "\(bounty)" // } } @IBAction func close(_ sender: Any) { //이 클로즈 누룰시 뷰컨트롤러가 사라진다. dismiss(animated: true, completion: nil) } } <file_sep>/Swift/Collection.playground/Contents.swift import UIKit var evenNumbers: [int] = [2,4,6,8] //let evenNumbers2: Array<Int> = [2,4,6,8] //let 은 변경하지 않는다 ?! == const // null 로 처음에 넣어두는 것은 괜찮 evenNumbers.append(10) evenNumbers += [12,14,16] evenNumbers.append(contentOf: [18,20]) //let isEmpty = evenNumbers.isEmpty evenNumbers.count // el 몇개인지 print(evenNumbers.first) //evenNumbers = [] let firstItem = evenNumbers.first // optinal(2) 로 나오는데 이는 값이 있을 수 도없을 수도 있기에 그렇다. //옵셔널 바인딩 if let firstEl = evenNumbers.first{ print("fitst item is : \(fitstEl)") } evenNumbers.min() evenNumbers.max() let firstThree = evenNumbers[0..2] evenNumbers.contains(3) //특정 인덱스에 값 삽입 evenNumbers.insert(0, at: 0) evenNumbers.removeAll() evenNumbers.remove(at:0) evenNumbers[0] = -2 evenNumbers.swapAt(0,9) for (index, num) in evenNumbers.enumerated(){ print("idx: \(index), value: \(num)") } evenNumbers.dropFirst(3)//실제로 영향을 주지는 않고 앞에 3개를 제거후 보여주기만 한다.. dropLast() let firstThree = evenNumbers.prefix(3) // 앞에 3개 만보기 let lastThree = evenNumbers.suffix(3) <file_sep>/Swift/MyPlayground.playground/Contents.swift import UIKit var str = "Hello, playground" let value = arc4random_uniform(100) print("==> \(value)") // 튜플 let coordinates = (4,6) let x = coordinates.0 // coordinates의 0 번쨰 let y = coordinates.1 // coordinates의 1 번쨰 //명시적으로 표현해보기 let coordinatesNamed = (x:2, y:3) let x2 = coordinatesNamed.x let y2 = coordinatesNamed.y let (x3,y3) = coordinatesNamed x3 y3 // Boolean let yes = true let no = false let a = 5 let b = 10 if a > b { print("--> a가 크다") } else{ print("--> b가 크다") } //논리연산자 let name = "Jason" let isJson = name == "Jason" let isMale = false let isJsonAndMale = isJson && isMale let isJsonOrMail = isJson || isMale //삼항연산자 let greetingMessage: String = isJson ? "Hellow Jason" : "Hello somebody" <file_sep>/Swift/Dictionary.playground/Contents.swift import UIKit var str = "Hello, playground" var scoreDic: [String: Int] = ["Jason":80, "Jay":95,"Jake":90] //var scoreDic: Dictinary<String, Int> = ["Jason":80, "Jay":95,"Jake":90] if let score = scoreDic["Jason"]{ score }else { //.score 없음 } scoreDic.isEmpty //scoreDic = [:] scoreDic.count //기존 업데이트 scoreDic["Jason"] = 99 scoreDic //추가 scoreDic["Jack"] = 100 scoreDic //제거 scoreDic["Jack"] = nil scoreDic //For loop for (name,score) in scoreDic{ print("\(name), \(score)") } for key in scoreDic.keys{ print(key) } /* Jason, 99 Jake, 90 Jay, 95 Jason Jake Jay */ var myInfo: [String:String] = ["name":"lim","job":"ios engineer","city":"seoul"] myInfo["city"] = "Busan" func printNameAndCity(dic: [String: String]){ if let name = dic["name"], let city = dic["city"]{ print(name,city) } else{ print("cannot find") } } printNameAndCity(dic: myInfo) <file_sep>/Swift/TestApp/MusicApp/music.md ![musicApp](https://user-images.githubusercontent.com/61407010/110658038-aedaff80-8204-11eb-9ea1-82751ad9a8c0.gif) <file_sep>/react/react.md # 리액트 다루는 기술 + [비구조화 할당 문법](https://github.com/o2o25252/2021-TIL/blob/main/react/react.md#%EB%B9%84%EA%B5%AC%EC%A1%B0%ED%99%94-%ED%95%A0%EB%8B%B9-%EB%AC%B8%EB%B2%95) + [useState](https://github.com/o2o25252/2021-TIL/blob/main/react/react.md#usestate) + [State 주의사항](https://github.com/o2o25252/2021-TIL/blob/main/react/react.md#state-%EC%82%AC%EC%9A%A9%EC%8B%9C-%EC%A3%BC%EC%9D%98-%EC%82%AC%ED%95%AD) --- ## 비구조화 할당 문법 비구조화 할당 문법을 통해 props 내부 값 추출하기 ``` const MyComponent = props => { const { name, children } = props; return ( <div> 내 이름은 { name } 탐정이죠. <br/> 이건 { children } 입니다. </div> ); }; ``` 이렇게 하면 더 짧은 코드로 사용 가능 원래는 ```this.props.name``` 이런 식 으로 하나 하나 해야 했다. 이렇게 객체에서 값을 추출하는 문법은 비구조화 할당 이라고 한다. (구조 분해 문법) 함수의 파라미터 부분에서도 사용 가능 하다 . ``` const MyComponent = ({ name, children}) => { . . . }; ``` 배열 또한 비구조화 할당 이가능하다 . ``` const array = [1,2] const one = array[0] const two = array[1] ``` 이걸 비구조화 할당 을통해 ``` const array = [1,2] const [ one , two ] = array // 비구조화 할당 ``` 이렇게 사용 가능하다 --- ## useState useState 의 함수의 인자에는 상태의 초깃값을 넣어 준다. 값의 형태는 자유 이며 , 함수를 호출하면 배열이 반환된다. 배열의 첫 번쨰 원소는 ```현재상태``` , 두 번째 원소는 상태를 바꾸어 주는 ```함수```이다. useState 는 여러번 사용 도 가능하다 . ``` const Say = () => { const[message, setMessage] =useState(''); const onClickEnter = () => setMessage('안녕히가세요!'); const onClickLeave = () => setMessage('잘가요!'); const [color, setColor] = useState('black'); return( <div> <button onClick={onClickEnter}>입장</button> <button onClick={onClickLeave}>퇴장</button> <h1 style={{ color }}>{message}</h1> <button style={{ color: 'red'}} onClick={() => setColor('red')> 빨강색 </button> <button style={{ color: 'grenn'}} onClick={() => setColor('grenn')> 초록 </button> <button style={{ color: 'blue'}} onClick={() => setColor('blue')> 파랑 </button> </div> ); }; ``` ## State 사용시 주의 사항! useState 를 통해 전달받은 세터 함수를 사용해야 합니다. ``` const [object, setObject] = useState({a: 1, b: 1}); object.b = 2 ; ``` #### 그럼 배열이나 객체를 업데이트해야 할 때는 어떻게 해야 할까요..?! 이떄는 배열이나 객체 사본을 만들고 그 사본에 값을 업데이트한 후, 그 사본의 상태를 setState 혹은 세터 함수를 통해 업데이트해준다. 객체에 대한 사본을 만들 떄는 *spread* 연산자를 사용하여 처리하고 , 배열에 대한 사본을 만들 떄는 배열의 *내장 함수* 들을 활용합니다. <file_sep>/algorithm/leetCode.md ## [TWo Sum](https://leetcode.com/problems/two-sum/submissions/) ``` >>> nums = [1,3,4,5] >>> target = 9 >>> for i in range(len(nums)): print(i) 0 1 2 3 >>> for i in range(len(nums)): for j in range(i+1, len(nums)): temp = nums[i] +nums[j] print(temp) 4 5 6 7 8 9 >>> for i in range(len(nums)): for j in range(i+1, len(nums)): temp = nums[i] +nums[j] print(i,j) 0 1 0 2 0 3 1 2 1 3 2 3 ``` #### 1 Sol ``` class Solution: def twoSum(self, nums, target): for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): temp = nums[i] + nums[j] if temp == target: return [i, j] ``` #### 2 Sol ``` def twoSum(self,nums,target) : vals = {} for i in range(len(nums)): if nums[i] in vals: return [vals[nums[i]],i] vals[target-nums[i]] = i ``` <file_sep>/algorithm/Sort.md # 알고리즘 --- [k번쨰수](https://programmers.co.kr/learn/courses/30/lessons/42748) k번째수 배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다. 예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면 array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다. 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다. 2에서 나온 배열의 3번째 숫자는 5입니다. 배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요. 1. 배열을 커맨드의 1 과 2 번째의 값만큼 slice 한다. 2. 배열을 올므찬순으로 정렬 한다 sort( (a,b) => a-b ) 3. 커맨드의 3번째 값이 k 번째 의 수를 반환 해준다. ``` function solution(array, commads){ return commands.map( v => { array.slice(v[0]-1,v[1]) 첫번째 1 과 2 의 값 만큼 slice 한다. } ) } ``` ``` array.slice(v[0]-1,v[1]).sort( (a,b) => a-b ) 두번째 배열을 오름차순 으로 정렬한다. ``` ``` array.slice(v[0]-1,v[1]).sort( (a,b) => a-b ).slice(v[2]-1, v[2])[0] 세번쨰 K번째 의 수를 반환 해준다. ``` 왜 ? -1 을 해주었는가? 커맨드는 항상 3개를 지닌 배열 이다 . 그러기에 딱 3번째를 반환 해주어야 한다. slice 함수를 통해 마지막 만을 반환 하기 위함이다. slice( 3-1 , 3) 2번째 인덱스 와 3번째 자리 이런 식 이다. --- 0또 는 양의 정수가 주어졌을때, 정수를 이어 붙여 만들 수 있는 가장 큰수 [가장큰수](https://programmers.co.kr/learn/courses/30/lessons/42746?language=javascript) 문자열 로 바꾸어 반환 1. 1의 자리의 수를 먼저 모으고 비교 2. 2의 자리의 수를 비교 배열 안의 원소들의 값의 길이를 비교 하여 볼려 했으나 Undefined 가 나온다 . 그래서 숫자 형을 문자형으로 바꾸어 찾는다. ``` let c = n.map( v => String(v)) 길이를 비겨를 위해서 원소를 문자로 반꾼다. ``` ``` let o = c.filter( v => v.length <= 1 ); 1 의 자리의 수만 모았다 ``` ``` o.sort( (a,b) => b-a); 내림 차순 정렬 ``` 이런 순으로 1 , 2 의 찾고 한배열에 넣고 문자열로 반환 해준다. ``` function solution(numbers) { let n = numbers ; let c = n.map ( v => String(v)); let o = c.filter(v=> v.length <=1); o.sort( (a,b) => b-a); let k = c.filter(v=> v.length > 1); k.sort( (a,b) => b-a); let a = o.concat(k).join(""); return a } ``` 하지만 ... 1 차 시도 실패 첫번째 예시는 맞았지만 두번쨰 예시에 [3, 30, 34, 5, 9] 9534330 처럼 나오지 않는다. 9533430 이렇게 나온다. ``` function solution(numbers) { const arr = numbers .map( num => num.toString() ) .sort( (a,b) => (b+a) - (a+b) ); return arr[0] === '0' ? '0' : arr.join(''); } ``` ``` (b+a) - (a+b) ``` 이 부분이 어떻게 해서 정렬 되는지 모르겠다 ... b+a - a+b 는 a 은 다음 값 b은 현재 값 이다 0 1 -1 로 값을 변경 한다 30 40 34 22 50 일때 (40 + 30) - (30 + 40) 일떄 70 - 70 = 0 이므로 그대로 30 40 다음은 (34 + 40) - ( 40 + 34) 74 - 74 = 0 이므로 그대로 이런 식으로 쭉 하면 전부다 0 인데 ? 어떻게 정렬 되는 걸까?? [SORT 참고 ](https://velog.io/@jakeseo_me/Javascript-Sort%ED%95%A8%EC%88%98%EC%97%90-%EB%8C%80%ED%95%9C-%EC%9E%A1%EC%A7%80%EC%8B%9D) # 자바 스크립트 의 SORT 자바 스클비트의 `sort` 함수는 기본적으로 원소들을 문자열로 만든 뒤에, `UTF-16` 코드 유닛 값을 기준으로 순서을 정렬합니다. 고로 숫자 정렬에 적합하지 않습니다. ## 기본 값은 문자열로 변경 후에 UTF-16 코드 유닛 값을 기준으로 정렬 이로 인해서 내가 궁금해 했던 0 인데 어떻게 정렬 되는 걸까? 를 알게된다. UTF-16 코드 유닛 값으로 값을 정렬하게 되면 , 숫자에 대해 올바른 정렬이 되지 않고 `[1,30,4,21,1000000]` 을 정렬한 결과가 `[1,1000000,21,30,4] ` 와같이 나온다. 이떄문에 우리는 `비교함수` 를 만든다. ## Compare Function 작성하기 `sort` 함수의 기본 문법은 `arr.sort([compareFunction])` 입니다. 여기서 우리가 정의해줘야 하는 것은 `[compareFunction]` 부분입니다. `[compareFunction]`은 sort 함수의 콜백함수로 firstEl과 secondEl이란 인자가 자동으로 들어갑니다. 이 콜백함수의 작성을 생략하면 이전에 설명했듯 문자열로 바뀐 뒤 UTF-16의 코드 유닛 값을 기준으로 정렬이 수행됩니다. ## 1 , 0 , -1 / 단 ,변경은 -1 에서만 일어난다 `[compareFuction]` 을 작성할 떄는 *어떤 값을 반환하는지가 중요* 합니다. 숫자 값을 반환해야 하는데 총 3가지 경우로 나눌 수 있다. * 0 보다크다 * 0 이다 * 0 보다 작다 0을 기준으로 3가지 케이스로 나뉩니다. - 매개변수로 a, b를 받았고 반환 값이 0보다 큰 경우에는 만일 [a, b]의 값이 들어왔다면, 그대로 [a, b]가 됩니다. a가 먼저옵니다. - 매개변수로 a, b를 받았고 반환 값이 0인 경우에는 만일 [a, b]의 값이 들어왔다면, 그대로 [a, b]가 됩니다. a와 b의 위치를 그대로 둡니다. - 매개변수로 a, b를 받았고 반환 값이 0보다 작은 경우에 [a, b]의 값이 들어왔다면, b가 먼저 오게 됩니다. [b, a]가 되는 겁니다. 근데 이렇게 하면 무조건 0 이 나오는데그러면 정렬이 안된 상태 인거 아닌가?? ## H-Index [H-Index](https://programmers.co.kr/learn/courses/30/lessons/42747) ``` 공식적으로 f 가 각 출판물에 대한 인용 횟수에 해당하는 함수 인 경우 다음과 같이 h 인덱스를 계산합니다 . 먼저 f 값을 가장 큰 값에서 가장 낮은 값으로 정렬합니다 . 그런 다음 f 가 위치 보다 크거나 같은 마지막 위치를 찾습니다 ( 이 위치를 h 라고 부릅니다 ). 예를 들어 5 개의 간행물 A, B, C, D, E를 각각 10, 8, 5, 4, 3 번 인용 한 연구원이 있다면 h-index는 4 번째 출판물에 4 개의 인용이 있고 5 번째에는 3 개의 인용이 있기 때문에 4와 같습니다. 반대로 동일한 출판물에 25, 8, 5, 3, 3 개의 인용이있는 경우 색인은 3입니다 (즉, 3 번째 위치 ) 네 번째 논문에는 인용 횟수가 3 회 밖에 없기 때문입니다. f (A) = 10, f (B) = 8, f (C) = 5, f (D) = 4, f (E) = 3 → h -index = 4 f (A) = 25, f (B) = 8, f (C) = 5, f (D) = 3, f (E) = 3 → h -index = 3 함수 f 가 가장 큰 값에서 가장 낮은 값으로 내림차순으로 정렬 된 경우 다음과 같이 h 인덱스를 계산할 수 있습니다 ``` 말이 너무 어렵지만 어떤 과학자의 논문 h 편 이 배열로 들어온다 [5,3,2,1,0] 총 5개 이다 이때 n 개의 인용된 논문 의 최대 값이 h 인덱스이다 ``` function solution(citations) { citations = citations.sort(sorting); var i = 0; while(i + 1 <= citations[i]){ i++; } return i; function sorting(a, b){ return b - a; } } ``` [3, 0, 6, 1, 5] 의 예가 있다 이때 는 총 5 편 의 논문이다 . 이떄 n번의 인용 된 논문을 리턴해야 하니 먼저 내림 차순으로 정렬 후에 1 보다 크거나 같다면 으로 부터 시작해서 점점 늘려간다. 먼저 정렬된 배열 [6,5,3,1,0] 부터 6이 1 보다 크거나 같냐? 맞다 그렇다면 1번 인용됬다. 5가 2 보다 크거나 같은가 ? 맞다 2번 인용 됬다. 3이 3 보다 크거나 같은가 ? 맞다 3번 인용 됬다. 이제 1 을 비교 해야 하지만 이미 비교조차 안된다 조건이 맞지 않아 이렇게 최대 의 값인 3번 을 리턴하게 된다. <file_sep>/algorithm/이코테/README.md # [이것이코딩테스트다](https://www.youtube.com/watch?v=m-9pAwq1o3w&list=PLRx0vPvlEmdAghTr5mXQxGpHjWqSz0dgC) - [복잡도](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#%EB%B3%B5%EC%9E%A1%EB%8F%84) - [그리드](https://github.com/o2o25252/2021-TIL/tree/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C#%EA%B7%B8%EB%A6%AC%EB%93%9C-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98) + [거스름돈](https://github.com/o2o25252/2021-TIL/tree/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C#%EA%B1%B0%EC%8A%A4%EB%A6%84%EB%8F%88) + [1이될떄까지](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#1%EC%9D%B4-%EB%90%A0-%EB%95%8C%EA%B9%8C%EC%A7%80) + [곱하기 혹은 더하기](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#%EA%B3%B1%ED%95%98%EA%B8%B0-%ED%98%B9%EC%9D%80-%EB%8D%94%ED%95%98%EA%B8%B0) + [모험가의 길드](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#%EB%AA%A8%ED%97%98%EA%B0%80-%EA%B8%B8%EB%93%9C) - [구현](https://github.com/o2o25252/2021-TIL/tree/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C#%EA%B5%AC%ED%98%84) + [상하좌우](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#%EC%83%81%ED%95%98%EC%A2%8C%EC%9A%B0) + [시각](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#%EC%8B%9C%EA%B0%81) + [왕실의 나이트](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#%EC%99%95%EC%8B%A4%EC%9D%98-%EB%82%98%EC%9D%B4%ED%8A%B8) + [문자열 재정렬](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#%EB%AC%B8%EC%9E%90%EC%97%B4-%EC%9E%AC%EC%A0%95%EB%A0%AC) - [DFS](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#dfs) - [BFS](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C/README.md#bfs) ------ ## 복잡도 - 복잡도는 알고리즘의 성능을 나타내는 척도 + 시간 복잡도: 특정한 크기의 입력에 대하여 알고리즘의 수행 시간 분석 + 공간 복잡도: 특정한 크기의 입력에대하여 알고리즘의 메모리 사용량 분석 - 동일한 기능을 수행하는 알고리즘이 있다면, 일반적으로 복잡도가 낮을수록 좋은 알고리즘이다. *빅오 표기범* - 가장 빠르게 증가하는 항만을 고려하는 표기법 + 함수의 상한만을 나타내게 됩니다. - ## 그리드 알고리즘 - 그리디 알고리즘은 *현재 상황에서 지금당장 좋은 것만 고르는 방법*을 의미합니다. - 일반적인 그리디 알고리즘은 문제를 풀기 위한 최소한의 아이디어를 떠올릴 수 있는 능력을 요구합니다. - 그리디 해법은 그 정당성 분석이 중요합니다. + 단순히 가장 좋아 보이는 것을 반복적으로 선택해도 최적의 해를 구할 수 있는지 검토합니다. ### 거스름돈 *문제 설명* ``` 당신은 음식점의 계산을 도와주는 점원입니다. 카운터에는 거스름돈으로 사용할 500원, 100원, 50원, 10원짜리 동전이 무한히 존재한다고 가정합니다. 손님에게 거슬러 주어야 할 돈이 N원일 때 거슬러 주어야 할 동전의 최소 개수를 구하세요. 단, 거슬러줘야 할 돈 N은 항상 10의 배수입니다. ``` *해결 아이디어* - 최적의 해를 빠르게 구하기 위해서는 가장 큰 화폐 단위부터 돈을 거슬러 주면 됩니다. - N원을 거슬러 줘야 할 때, 가장 먼저 500원으로 거슬러 줄 수 있을 만큼 거슬러 줍니다. + 이후에 100원, 50원, 10원짜리 동전을 차례대로 거슬러 줄 수 있을 만큼 거슬러 주면 됩니다. - N= 1,260일 때의 예시를 확인해 봅시다. *정당성 분석* - 가장 큰 화폐 단위부터 돈을 거슬러 주는 것이 최적의 해를 보장하는 이유는 무엇일까요??? + 가지고 있는 동전 중에서 큰 단위가 항상 작은 단위의 배수이므로 작은 단위의 동전들을 종합해 다른 해가 나올 수 없기 때문입니다. - 만약에 800원을 거슬러 주어야 하는데 화폐 단위가 500원,400원,100원이라면 어떻게 될까요?? + 우리의 알고리즘에 따르면 500원짜리 하나 100원짜리 3 개 총 4개를 줘야 하지만 사실 최적의 해는 400원짜리를 2개를거슬러 주는게 최적의 해이다 + 다시 말해 큰 단위가 작은 단위의 배수가 아니면 이와 같은 알고리즘을 이용해서 최적의 해를 보장해 줄 수 없다. - 그리디 알고리즘 문제에서는 이처럼 문제 풀이를 위한 최소한의 아이디어를 떠올리고 이것이 정당한지 검토할 수 있어야 한다. *코드* ``` n = 1260 # 거스름 돈 count = 0 # 동전의 갯수 # 큰단위의 화폐부터 차례대로 확인하기 for coin in array: count == n // coin # 해당 화폐로 거슬로 줄 수있는 동전의 개수 세기 ( // 몫 ) n %= coin # 나눈 나머지 값을 n 에 넣어서 남은 돈을 바까준다. print(count) ``` *시간 복잡도 분석* - 화폐의 종류가 K라고 할 때, 소스코드의 시간 복잡도는 O(K)입니다. + 즉, 화폐의 종류만큼만 수행하면 답을 도출 할 수 있다. - 이 알고리즘의 시간 복잡도는 거슬러줘야 하는 금액과는 무관하며, 동전의 총 종류에만 영향을 받습니다. ### 1이 될 때까지 *문제 설명* - 어떠한 수 N이 1이 될 때까지 다음의 두 과정 중 하나를 반복적으로 선택하여 수행할려고 합니다. 단, 두 번째 연산은 N이 K로 나누어 떨어질 때만 선택할 수 있습니다. 1. N에서 1을 뺍니다. 2. N을 K로 나눕니다. (N이 K로 나누어 질때만) - 예를 들어 N이 17 , K가 4라고 가정합시다. 이때 1번의 과정을 한 번 수행하면 N은 16이 됩니다. 이후에 2번의 과정을 + 두 번 수행하면 N은 1이 됩니다. 결과적으로 이 경우 전체 과정을 실행한 횟수는 3이 됩니다. 이는 N을 1로 만드는 최소 횟수입니다. - N과 K가 주어질 떄 N이 1 이 될 때까지 1번 혹은 2번의 과정을 수행해야 하는 최소 횟수를 구하는 프로그램을 작성하시오 *문제 조건* - 시간제한 2초 - 메모리 제한 128MB - 입력조건 : 첫째 줄에 N(1 <=N <= 100,000)과 K(2 <=K <= 100,000) 가 공백을 기준으로 하여 각각 자연수로 주어집니다. - 출력조건: 첫째 줄에 N이 1 이 될 때까지 1번 혹은 2번의 과정을 수행해야 하는 횟수의 쵯솟값을 출력합니다. *정당성 분석* - 가능하면 최대한 많이 나누는 작업이 최적의 해를 항상 보장할 수 있을까요?? - N이 아무리 큰 수여도, K로 계속 나눈다면 기하급수적으로 빠르게 줄일 수 있습니다. - 다시 말해 K가 2이상이기만 하면, K로 나누는 것이 1을 빼는 것보다 항상 빠르게 N을 줄일 수 있습니다. + 또한 N은 항상 1에 도달하게 됩니다. *코드* ``` # 두 개의 변수 가 공백을 기준으로 바로 입력이 가능하기에 #입력받은 문자열을 map 함수를 이용하여 각각 int 형으로 바꾼뒤에 # 각 변수에 넣어준다, n, k = map(int, input().split()) result = 0 #우리가 총 연산을 하는 횟수 while True: # 만약에 n 이 k 로 나누어 떨어지지 않는다면은 가장 가까운 n을 k로 나눈어 떨어진 수가 # 어떤 건지를 찾고자 할 때 즉, 우리는 n 에서 1을 빼는 과정을 몇번 반복 해서 이 target 이라는 값 까지 # 만들 수 가있고 이 target 은 k 로 나누어 떨어지는 수 이다. target = (n // k) * k result += (n - target) # 1을 빼는 연산을 몇번 수행하는지 # 1 # 3 # 5 n = target # 위에서 1로 빼기 작업의 횟수를구했으닌 이제 남은 값만 나무녀 된다. if n < k: break result += 1 n //=k # 나누기 # n 이 일보다 크다면 1이 되도록 만들기 위한 작업 result += ( n - 1)# 마지막 남은 수에 대하여 1씩 뺴기 print(result) ``` 이런 식 으로 한 이유는 ```로그 시간 복잡도``` 가 나오게 하기 위해서 이다 + [map 함수를 알아보자 ](https://dojang.io/mod/page/view.php?id=2286) 하지만 왜 이렇게 코드를 작성햇는지 이해는 잘안된다 ### 곱하기 혹은 더하기 - 각 자리가 숫자(0부터9)로만 이루어진 문자열 S가 주어졌을 때, 왼쪽부터 오른쪽으로 하나씩 모든 숫자를 확인 하며 숫자 사이에 'x' 혹은 '+' 연산자를 넣어 결과적으로 만들어질 수 있는 가장 큰 수를 구하는 프로그램을 작성하세요. 단, +보다 x를 먼저 계산하는 일반적인 방식과는 달리, 모든 연산은 왼쪽에서부터 순서대로 이루진다고 가정합니다. - 예를 들어 02984라는 문자열로 만들 수 있는 가장 큰 수는 (((0+20 x 9) x 8) x 4) = 576입니다. 또한 만들어질 수 있는 가장 큰 수는 항상 20억 이하의 정수가 되도록 입력이 주어집니다. *문제 조건* - 시간 제한: 1초 - 메모리 제한:128MB - 입력조건: 첫째 줄에 여러 개의 숫자로 구성된 하나의 문자열 S가 주어집니다.(1 <= S의 길이 <= 20) - 출력조건: 첫째 줄에 만들어질 수 있는 가장 큰 수를 출력합니다. *아이디어* - 대부분의 경우 '+' 보다는 '*'가 더 값을 크게 만듭니다. + 예를 들어 5+6 = 11 이고. 5 * 6 =30입니다. - 다만 두 수 중에서 하나라도 '0' 혹은 '1'인 경우, 곱하기보다는 더하기를 수행하는 것이 효율적입니다. - 따라서 두 수에 대하여 연산을 수행할 때, 두 수 중에서 하나라도 1 이하인 경우에는 더하며, 두 수가 모두 2 이상인 경우에는 곱하면 정답이다. ``` data = input() #첫 번째 문자를 숫자로 변경하여 대입 result = int(data[0]) for i in range(1, len(data)): #두 수 중에서 하나라도 '0' 혹은 '1'인 경우, 곱하기보다는 더하기 수행 num = int(data[i]) if num <= 1 or result <= 1: result += num else: result *= num print(result) ``` ### 모험가 길드 *문제* - 한 마을에 모험가가 N명 있습니다. 모험가 길드에서는 N명의 모험가를 대상으로 '공포도'를 측정했는데, '공포도'가 높은 모험가는 쉽게 공포를 느껴 위험 상황에서 제대로 대처할 능력이 떨어집니다. - 모험가 길드장인 희찬이는 모험가 그룹을 안전하게 구성하고자 공포도가 X인 모험가는 반드시 X명 이상으로 구성한 모험가 그룹에 참여해야 여행을 떠날 수있도록 규정했습니다. - 희찬이는 최대 몇 개의 모험가 그룹을 만들 수 있는지 궁금합니다. N명의 모험가에 대한 정보가 주어졌을떄, 여행을 떠날 수 있는 그룹 수의 최댓값을 구하는 프로그램을 작성하세요 *문제 해결 아이디어* - 앞에서부터 공포도를 하나씩 확인하며 '현재 그룹에 포함된 모험가의 수'가 현재 확인하고 있는 공포도' 보다 크거나 같다면 이를 그룹으로 설정하면 됩니다. - 이러한 방법을 이용하면 공포도가 오름차순으로 정렬되어 있다는 점에서, 항상 최소한의 모험가의 수만 포함하여 그룹을 결성하게 됩니다. *코드* ``` >>> n = int(input()) # 모험가의 수 >>> data = list(map(int, input().split())) # 공포도 2 2 2 1 3 >>> data.sort() # 오름차순 정렬 >>> data [1, 2, 2, 2, 3] >>> result = 0 # 총 그룹의 수 >>> count = 0 # 현재 그룹에 포함된 모험가의 수 >>> for i in data: #공포도를 낮은 것부터 하나씩 확인 (i) count += 1 # 현재 그룹에 해당 모험가를 포함시키기 if count >= i: # 현재 그룹에 포함된 모험가의 수가 현재의 공포도, 이상이라면 그룹 결성 result += 1 # 총 그룹의 수 증가시키기 count = 0 # 현재 그룹에 포함된모험가의 수 초기화 >>> print(result) 2 ``` ----- ## 구현 - 구현이란, 머릿속에 있는 알고리즘을 소스코드로 바꾸는 과정입니다. - 일반적으로 알고리즘 문제에서의 2차원 공간은 *행렬(Matrix)*의 의미로 사용됩니다. - 시뮬레이션 및 완전 탐색 문제에서는 2차원 공간에서의 *방향 벡터*가 자주 활용됩니다. ### 상하좌우 - 여행가 A는 N x N 크기의 정사각형 공간 위에 서 있습니다. 이 공간은 1 x 1 크기의 정사각형으로 나누어져 있습니다. 가장 위 좌표는 (1,1) 이며 가장 오른쪽 좌표는 (N,N)에 해당합니다. 여행가 A는 상, 하 ,좌 ,우 방향으로 이동할 수 있으며, 시작 좌표는 (1,1)입니다. 우리 앞에는 여행가 A가 이동할 계획이 적힌 계획서가 놓여 있습니다. - 계획서에는 하나의 줄에 띄어쓰기를 기준으로 하여 L, R, U, D중 하나의 문자가 반복적으로 적혀 있습니다. 각 문자의 의미는 다음과 같습니다. + L: 왼쪽으로 한 칸 이동 + R: 오른쪽으로 한 칸 이동 + U: 위로 한 칸 이동 + D: 아래로 한 칸 이동 - 이떼 여행가 A가 N x N 크기의 정사각형 공간을 벗어나는 움직임은 무시됩니다. 예를 들어 (1,1)의 위치에서 L 혹은 U를 만나면 무시됩니다. 다음은 N = 5 인 지도와 계획서입니다. *문제 조건* - 입력조건 + 첫쨰 줄에 공간의 크기를 나타내는 N이 주어집니다. (1 <=N <= 100) + 둘쨰 줄에 여행가 A가 이동할 계획서 내용이 주어집니다. (1 <= 이동 횟수 <= 100) - 출력조건 + 첫째 줄에 여행가 A가 최종적으로 도착할 지점의 좌표 (X, Y)를 공백을 기준으로 구분하여 출력합니다. ``` 입력예시 5 R R R U D D ``` ``` 출력 예시 3 4 ``` *문제 해결 아이디어* - 일련서로 의 명령에 따라서 개체를 차례대로 이동시킨다는 점에서 시뮬레이션 유형으로도 분류되며 구현이 중요한 대표적인 문제 유형입니다. - 다만, 알고리즘 교재나 문제 풀이 사이트에 따라서 다르게 일컬을 수 있으므로, 코딩 테스트에서의 시뮬레이션 유형, 구현 유형, 완전 탐색 유형은 서로 유사한 점이 많다는 정도로만 기억합시다. *코드* ``` >>> n = int(input()) 4 >>> x,y =1,1 >>> plans = input().split() D D R R D # L R U D에 따른 이동 방향 >>> dx = [0,0,-1,1] >>> dy = [-1,1,0,0] >>> move_types = ['L','R','U','D'] >>> for plan in plans: for i in range(len(move_types)): if plan == move_types[i]: nx = x + dx[i] ny = y + dy[i] # 공간을 벗어나는 경우 무시 if nx < 1 or ny < 1 or nx > n or ny > n: continue x,y = nx, ny >>> print(x,y) 4 3 # x : 2->3->3->4 # y : 1->1->2->3 ``` ### 시각 *문제* - 정수 N이 입력되면 00시 00분 00초부터 N시 59분초까지의 *모든 시각 중에서 3이 하나라도 포함되는 모든 경우의 수를 구하는 프로그램을 작성*하세요 예를 들어 1을 입력했을 때 다음은 3이 하나라도 포함되어 있으므로 세어야 하는 시각입니다. + 00시 00분 03초 + 00시 13분 30초 - 반명에 음은 3이 하나도 포함되어 있지 않으므로 세면 안 되는 시각입니다. + 00시 02분 55초 + 01시 27분 45초 *문제 조건* - 풀이시간 : 15분 - 시간제한 : 2초 - 메모리 제한: 128MB - 입력조건 : 첫째 줄에 정수 N이 입력됩니다. (O <= N <= 23) - 출력조건 : 00시 00분 00초부터 N시 59분 59초까지의 모든 시각 중에서 3이 하나라도 포함되는 모든 경우의 수를 출력합니다. *아이디어* - 이 문제는 *가능한 모든 시각의 경우를 하나씩 모두 세서 풀 수 있는 문제*입니다. - 하루는 86,400초이므로, 00시 00분 00초부터 23시 59분 59초까지의 모든 경우는 86,400가지 입니다.(컴퓨터는 약 1초에 2천만번) + 24 * 60 * 60 = 86,400 - 따라서 단순히 시각을 1씩 증가시키면서 3이 하나라도 포함되어 있는지를 확인하면 됩니다. - 이러한 유형은 *완전 탐색(Brute Forcing)* 문제 유형 - 가능한 경우의 수를 모두 검사해보는 탐색 방법을 의미 *코드* 1. 시간 분 초 는 0부터 시작이다 . 하지만 시간 같은 경우 입력 값이 0 이라면 1시간 까지 가기 전까지 59분 59초까지가면서 나오는 3을 무시하게 된다 그래서 입력받은 시간에 +1 을 해주어서 포함된 시간을 붙여준다. ``` h = int(input()) >>> count = 0 >>> for i in range(h): for j in range(60): for k in range(60): if '3' in str(i) + str(j) + str(k): count += 1 >>> count ``` ### 왕실의 나이트 *문제설명* - 행복 왕국의 왕실 정원은 체스판과 같은 *8 X 8 좌표 평면*입니다. 왕실 정원의 특정한 한 칸에 나이트가 서있습니다. 나이트는 매우 충성스러운 신하로서 매일 무슬을 연마합니다. - 나이트는 말을 타고 있기 때문에 이동을 할 때는 L자 형태로만 이동할 수 있으며 정원 밖으로는 나갈 수 없습니다. - 나이트는 특정 위치에서 다음과 같은 2가지 경우로 이동할 수 있습니다. 1. 수평적으로 두칸 이동한 뒤에 수직으로 한 칸 이동하기 2. 수직으로 두칸 이동한 뒤에 수평으로 한 칸 이동하기 - 이처럼 8 X 8 좌표 평면상에서 나이트의 위치가 주어졌을 떄 나이트가 이동할 수 있는 경우의 수를 출력하는 프로그램을 작성하세요. 왕실의 정원에서 행 위치를 표현할 떄는 1부터 8로 표현하며 1부터 8로 표현하며, 열 위치를 표현할 떄는 a부터 h로 표현합니다. - c2에 있을 때 이동할 수 있는 경우의 수는 *6가지*입니다. <img width="268" alt="스크린샷 2021-01-28 오후 7 22 04" src="https://user-images.githubusercontent.com/61407010/106124159-1f224a00-619e-11eb-90b4-221010d3bd41.png"> *문제 조건* - 시간제한 : 1초 - 메모리 제한 : 128MB - 입력조건 : 첫째 줄에 8 X 8 좌표 평면상에서 현재 나이트가 위치한 곳의 좌표를 나타내는 두 문자로 구성된 문자열이 입력된다. 입력 문자는 a1처럼 열과 행으로 이뤄진다. - 출력조건 : 첫째 줄에 나이트가 이동할 수 있는 경우의 수를 출력하시오. *아이디어* - 요구사항대로 충실히 구현면된다. - 나이트의 8가지 경로를 하나씩 확인하며 각 위치로 이동이 가능한지 확인합니다. + 리스트를 이용하여 8가지 방향에 대한 백터를 정의합니다. *코드* ``` >>> input_data = input() c2 >>> row = int(input_data[1]) >>> column = int(ord(input_data[0])) - int(ord('a')) + 1 # 나이트가 이동할 수 이쓴ㄴ 8가지 방향 >>> steps = [(-2, -1) , (-1, -2), (1, -2) , (2, -1), (2,1),(1,2),(-1,2),(-2,1)] >>> result = 0 >>> for step in steps: next_row = row + step[0] next_column = column + step[1] if next_row >= 1 and next_row <= 8 and next_column >= 1 and next_column <= 8: result += 1 >>> result 6 ``` ### 문자열 재정렬 *문제* - 알파벳 문자와 숫자(0~9)로만 구성된 문자열이 입력으로 주어집니다. 이떄 모든 알파벳을 오름차순으로 정렬하여 이어서 출력한 뒤에, 그 뒤에 모든 숫자를 더한 값을 이어서 출력합니다. - 예를 들어 K1KA5CB7이라는 값이 들어오면 ABCKK13을 출력합니다. *문제 조건* - 시간 제한 : 1초 - 메모리 제한 : 128MB - 입력 조건 : 첫째 줄에 하나의 문자열 S까 주어집니다. (1 <= S의 길이 <= 10,000) - 출력 조건 : 첫째 줄에 문제에서 요구하는 정답을 출력합니다. *아이디어* - 요구사항대로 실히 구현 - 문자열이 입력되었을 때 문자를 하나씩 확인합니다. + 숫자인 경우 따로 합계를 계산합니다. + 알파벳은 경우 별도의 리스트에 저장합니다. - 결과적으로 *리스트에 저장된 알파벳을 정렬해 출력하고, 합계를 뒤에 붙여 출력하면 정답* *코드* ``` data 'B9AK1K4TE' >>> result = [] >>> value = 0 >>> for x in data: if x.isalpha(): result.append(x) else: value += int(x) >>> result.sort() >>> result ['A', 'B', 'E', 'K', 'K', 'T'] >>> if value != 0: result.append(str(value)) >>> value 14 >>> print(''.join(result)) ABEKKT14 ``` ## DFS ## BFS <file_sep>/Swift/one/BountyList/BountyList/BountyViewController.swift // // BountyViewController.swift // BountyList // // Created by 임희찬 on 2021/03/04. // import UIKit class BountyViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { // MVVM // Model // BountyInfo // > BountyInfo Make! // View // - ListCell // > imgView , nameLabel, BountyLabel // > View 들은 viewModel을 통해서 구성되기 // ViewModel // - DetailViewModel // > 뷰 레이어 에서 필요한 메서드 만들기 // > 모델 가지고 있기 , BountyInfo들 let BountyList : [BountyInfo] = [ BountyInfo(name: "brook", bounty: 100), BountyInfo(name: "chopper", bounty: 50), BountyInfo(name: "franky", bounty: 2200), BountyInfo(name: "luffy", bounty: 33333333), BountyInfo(name: "nami", bounty: 2500), BountyInfo(name: "robin", bounty: 120), BountyInfo(name: "sanji", bounty: 5000), BountyInfo(name: "zoro", bounty: 8900) ] // let nameList = ["brook","chopper","franky","luffy","nami","robin","sanji","zoro"] // let bountyList = [100,200,300,400,500,3000,120,1900] override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //세그웨이 하기 직전에 DetailViewController -> 데이터 주기 //showDetail  세그웨이 수행시에 if segue.identifier == "showDetail" { let vc = segue.destination as? DetailViewController //sender 가 모였더라??? 아 그거였나? 세규 서준비 작업시 if let index = sender as? Int{ // vc?.name = nameList[index] // vc?.bounty = bountyList[index] let bountyinfo = BountyList[index] vc?.bountyInfo = bountyinfo // vc?.name = bountyinfo.name // vc?.bounty = bountyinfo.bounty } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //UITableViewDataSource //몇개니? func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return bountyList.count return BountyList.count } //어떻게 표현할꺼니? func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ListCell else { return UITableViewCell() } // let img = UIImage(named: "\(nameList[indexPath.row]).jpg") // cell.imagView.image = img // cell.nameLabel.text = nameList[indexPath.row] // cell.bountyLabel.text = "\(bountyList[indexPath.row])" let bountyinfo = BountyList[indexPath.row] cell.imagView.image = bountyinfo.image cell.nameLabel.text = bountyinfo.name cell.bountyLabel.text = "\(bountyinfo.bounty)" return cell } // 클릭시 어떻게 할거야? func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("--> \(indexPath.row) 째") //수행 해라 performSegue(withIdentifier: "showDetail", sender: indexPath.row) // sender 에다가 셀에대한 정보를 준다. } } //커스텀 셀 제작 //?  ! 차이???? class ListCell : UITableViewCell { @IBOutlet weak var imagView : UIImageView! @IBOutlet weak var nameLabel : UILabel! @IBOutlet weak var bountyLabel : UILabel! } struct BountyInfo { let name : String let bounty : Int var image: UIImage? { return UIImage(named: "\(name).jpg") } init(name:String, bounty:Int) { self.name = name self.bounty = bounty } } <file_sep>/algorithm/CodeStates.md # 코트스테이츠 코딩테스트 --- ## transformFirstAndLast ### 문제 배열을 입력받아 차례대로 배열의 첫 요소와 마지막 요소를 키와 값으로 하는 객체를 리런해야 합니다. ### 입력 인자 1: arr `string` 타입을 요소로 갖는 배열 ### 출력 객채를 리턴해야 합니다. ### 주의 사힝 - 빈 배열을 입력받은 경우, 빈 객체를 리턴해야 합니다. - 입력으로 받는 배열을 수정하지 않아야 합니다. ### 입출력 예시 ``` let arr = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce']; let output = transformFirstAndLast(arr); console.log(output); // --> { Queen : 'Beyonce' } arr = ['Kevin', 'Bacon', 'Love', 'Hart', 'Costner', 'Spacey']; output = transformFirstAndLast(arr); console.log(output); // --> { Kevin : 'Spacey' } ``` 1. 들어오는 배열에 0번쨰 인덱스 와 마지막 인덱스 를 뽑아서 2. 0번쨰를 키 마지막 를 값 으로 넣어서 반환 해준다. ``` function transformFirstAndLast(arr){ let key = arr[0]; let value = arr[arr.length-1]; let a = {} a = { key : value } } ``` 첫 번쨰 시도 에 실패 요인은 저 key 부분이 변수 key 가아닌 그저 스트링 "key" 를 글로써 들어간다 ``` function transformFirstAndLast(arr){ let result = {} if(arr.length > 0 ) { result[arr[0]] = arr[arr.length-1]; } return result } } ``` 두번째 시도 객체 를 미리 선언해두고 그곳에 직접 넣어주었다 ## powerOfTwo ### 문제 수를 입력받아 2의 거듭제곱인지 여부를 리턴해야 합니다. ### 입력 인자 1: num `number` 타입의 정수( `num` >=1) ### 출력 `boolean` 타입을 리턴해야 합니다 ### 주의 사힝 - 반복문(while)문을 사용해야 합니다 - 2의 0승은 1입니다. - Number.isInteger, Math.log2, Math.log 사용은 금지됩니다. ### 입출력 예시 ``` let output1 = powerOfTwo(16); console.log(output1); // true let output2 = powerOfTwo(22); console.log(output2); // false ``` 1. 입력받은 수 n 을 n/2 를 했을때 1 이라면 그건 2의 제곱 일 것이다. 2. 또한 2의 제곱이라면 2 와 같거나 커야 하므로 반복의 조건은 `n >=2` 이어야 한다. ``` function powerOfTwo(num) { // TODO: 여기에 코드를 작성합니다. let n = num; // 어떤수 while( n >= 2){ // 어떤 수 가 2보다 크거나 같을떄까지 반복 n = n/2; // 어떤수 n에다가 나누기 2 를 한다. // 이렇게 해서 n 이 위의 조건이 충족에 안될떄 까지 나누어 지면 //while 문을 바빠져나온다. } if( n === 1){ //그떄의 수 n 이 1 과 같다면 return true; // n 은 2의 거듭제곱 이므로 true } else{ return false; } } ``` [REF] 코트스테이츠 ``` function powerOfTwo(num) { if (num === 1) { return true; } if (num % 2) { return false; } let powered = 2; while (powered < num) { powered = powered * 2; } return powered === num; } ``` --- ## powerOfTwo ### 문제 수를 입력받아 2의 거듭제곱인지 여부를 리턴해야 합니다. ### 입력 인자 1: num `number` 타입의 정수( `num` >=1) ### 출력 `boolean` 타입을 리턴해야 합니다 ### 주의 사힝 - 반복문(while)문을 사용해야 합니다 - 2의 0승은 1입니다. - Number.isInteger, Math.log2, Math.log 사용은 금지됩니다. ### 입출력 예시 ``` let output1 = powerOfTwo(16); console.log(output1); // true let output2 = powerOfTwo(22); console.log(output2); // false ``` 1. 입력받은 수 n 을 n/2 를 했을때 1 이라면 그건 2의 제곱 일 것이다. 2. 또한 2의 제곱이라면 2 와 같거나 커야 하므로 반복의 조건은 `n >=2` 이어야 한다. ``` function powerOfTwo(num) { // TODO: 여기에 코드를 작성합니다. let n = num; // 어떤수 while( n >= 2){ // 어떤 수 가 2보다 크거나 같을떄까지 반복 n = n/2; // 어떤수 n에다가 나누기 2 를 한다. // 이렇게 해서 n 이 위의 조건이 충족에 안될떄 까지 나누어 지면 //while 문을 바빠져나온다. } if( n === 1){ //그떄의 수 n 이 1 과 같다면 return true; // n 은 2의 거듭제곱 이므로 true } else{ return false; } } ``` [REF] ``` function powerOfTwo(num) { if (num === 1) { return true; } if (num % 2) { return false; } let powered = 2; while (powered < num) { powered = powered * 2; } return powered === num; } ``` <file_sep>/Swift/set.playground/Contents.swift import UIKit //순서가 없다. //유일하다 //중복이 없는 유니크한 것들을 관리 //어레이와 유사 var someSet : Set<Int> = [1,2,3,4,1,2] someSet.isEmpty someSet.count someSet.contains(4) someSet.insert(5) someSet someSet.remove(1) someSet <file_sep>/Swift/README.md # 스위프트 ✍🏻 문법 기록 ## Comment ``` // 코멘트 import UIKit // var str = "Hello, playground" // let value = arc4random_uniform(100) // print("==> \(value)") /* 여 러 줄 */ ``` ## Tuple ``` let coordinates = (4,6) //(.0 4, .1 6) let x = coordinates.0 // coordinates의 0 번쨰 //4 let y = coordinates.1 // coordinates의 1 번쨰 //6 //명시적으로 표현해보기 let coordinatesNamed = (x:2, y:3)// (x 2 ,y 3) let x2 = coordinatesNamed.x// 2 let y2 = coordinatesNamed.y// 3 let (x3,y3) = coordinatesNamed x3//2 y3//3 ``` ## Boolean ``` let yes = true let no = false let a = 5 let b = 10 if a > b { print("--> a가 크다") } else{ print("--> b가 크다")// "--> b가 크다" } ``` *논리연산자* ``` let name = "Jason" let isJson = name == "Jason" let isMale = false let isJsonAndMale = isJson && isMale // false let isJsonOrMail = isJson || isMale // true ``` *삼항연산자* ``` let greetingMessage: String = isJson ? "<NAME>" : "Hello somebody" //Hellow Jason ``` ## Flow Control ``` var i = 0 while i <10 { print(i) if i == 5 { break } i += 1 } ``` ``` i = 10 repeat{ print(i) i += 1 }while i < 10 ``` ``` let coordinate = (x:10, y:10) switch coordinate { case ( 0,0 ): print("원점 이에여") case (let x, 0): print("x축 이에요 , x: \(x)") case (let x, let y ) where x == y: print("x 랑 y랑 같은 x,y = \(x) . \(y)") case (let x, let y) print("좌표 어딘가 x,y \(x),\(y)") } ``` ## Fuction and Optional ### Function ``` //물건값과 갯수를 받아서 전체 금액을 출력하는 함수 //func printTotalPrice(price: Int, count: Int) { // print("Total price : \(price * count)") //} //printTotalPrice(price:1500, count: 5) func printTotalPrice(가격 price: Int, 갯수 count: Int) { print("Total Price" \(price * count)") } printTotalPrice(가격:1500, 갯수: 5) ``` //In-out paramter ['value' is a 'let' constant] 라고 우리에게 알려준다. 처음에 Swift에서 파라미터는 기본적으로 상수(constant)이다. 상수는 변경할 수 없는데 value 값을 증가시키려고 시도했기 때문에 오류가 발생한 것이다. 자, 이제 이러한 문제를 inout 키워드로 해결해보자. ``` var value = 3 func incrementAndPrint(_ value: inout Int){ value +=1 print(value) } incrementAndPrint(&value) ``` 함수를 호출할 때 변수 명 앞에 앰퍼샌드(&) 기호를 붙여서 사용 ### Optinal - Forced unwrapping - Optinal binding (if let) - Optinal binding (guard) - Nil colescing ``` nil: 무 ``` ``` //carName = nil //print(carName!) //err if let unwrappedCarName = carName { print(unwrappedCarName) } else { pirnt("Car Name 없다") } ``` ``` func printParsedInt(from: String){ if let parsedInt = Int(from){ print(parsedInt) } else{ print("Int로 컨버팅 안된다.") } } //printParsedInt(from: "10") // 10 //printParsedInt(from: "hellow) // Int로 컨버팅 안된다. ``` ``` func printPasedInt(from : Stirng){ guard let parsedInt = Int(from) else { print("Int로 컨버팅 안된다.") return } print(parsedInt) } ``` ``` let MyCarName: String = carName ?? "모델" // carName 이 Nil 이라면 '모델' 이라는 디폴트 값 ``` ## Collection ### Array ``` var evenNumbers: [int] = [2,4,6,8] //let evenNumbers2: Array<Int> = [2,4,6,8] //let 은 변경하지 않는다 ?! == const // null 로 처음에 넣어두는 것은 괜찮 evenNumbers.append(10) evenNumbers += [12,14,16] evenNumbers.append(contentOf: [18,20]) //let isEmpty = evenNumbers.isEmpty evenNumbers.count // el 몇개인지 print(evenNumbers.first) //evenNumbers = [] let firstItem = evenNumbers.first // optinal(2) 로 나오는데 이는 값이 있을 수 도없을 수도 있기에 그렇다. //옵셔널 바인딩 if let firstEl = evenNumbers.first{ print("fitst item is : \(fitstEl)") } evenNumbers.min() evenNumbers.max() let firstThree = evenNumbers[0..2] evenNumbers.contains(3) //특정 인덱스에 값 삽입 evenNumbers.insert(0, at: 0) evenNumbers.removeAll() evenNumbers.remove(at:0) evenNumbers[0] = -2 evenNumbers.swapAt(0,9) for (index, num) in evenNumbers.enumerated(){ print("idx: \(index), value: \(num)") } evenNumbers.dropFirst(3)//실제로 영향을 주지는 않고 앞에 3개를 제거후 보여주기만 한다.. dropLast() let firstThree = evenNumbers.prefix(3) // 앞에 3개 만보기 let lastThree = evenNumbers.suffix(3) ``` ## Dictionary ``` var str = "Hello, playground" var scoreDic: [String: Int] = ["Jason":80, "Jay":95,"Jake":90] //var scoreDic: Dictinary<String, Int> = ["Jason":80, "Jay":95,"Jake":90] if let score = scoreDic["Jason"]{ score }else { //.score 없음 } scoreDic.isEmpty //scoreDic = [:] scoreDic.count //기존 업데이트 scoreDic["Jason"] = 99 scoreDic //추가 scoreDic["Jack"] = 100 scoreDic //제거 scoreDic["Jack"] = nil scoreDic //For loop for (name,score) in scoreDic{ print("\(name), \(score)") } for key in scoreDic.keys{ print(key) } /* Jason, 99 Jake, 90 Jay, 95 Jason Jake Jay */ var myInfo: [String:String] = ["name":"lim","job":"ios engineer","city":"seoul"] myInfo["city"] = "Busan" func printNameAndCity(dic: [String: String]){ if let name = dic["name"], let city = dic["city"]{ print(name,city) } else{ print("cannot find") } } printNameAndCity(dic: myInfo) ``` ## set ``` //순서가 없다. //유일하다 //중복이 없는 유니크한 것들을 관리 //어레이와 유사 var someSet : Set<Int> = [1,2,3,4,1,2] someSet.isEmpty someSet.count someSet.contains(4) someSet.insert(5) someSet (" gk someSet.remove(1) someSet ``` ## Closure 이름 없는 함수 ``` : 2개의 파라미터 받기 Int 로 반환 var multiplyClosure: (Int,Int) -> Int = { (a: Int , b: Int) -> Int in return a * b } 축약 가능 var multiplyClosure: (Int, Int) -> Int = { $0 * $1 } let result = multiplyClosure(4,2) func operateTwoNum(a: Int, b: Int, opertion: (Int, Int) -> Int) -> Int { let result = opertion(a,b) return result } operateTwoNum(a: 4, b: 2, opertion: multiplyClosure) var addClosure: (Int, Int) -> Int = {a,b in return a+b} operateTwoNum(a: 4, b: 2, opertion: addClosure) operateTwoNum(a:4, b: 2, opertion: {a,b in return a/b}) ``` ``` // Trailing Closure func someSimpleFuncion(message: String, choSimpleClosure: () -> void) { print("함수에서 호출이 되었어요, 메세지는 \(message)") choSimpleClosure() } someSimpleFunction(message: "메로나", choSimpleClosure: { print("헬로") }) someSimpleFunction(message: "로나"){ print("하이이") } // 어떻게 이렇게 해도 둘이 같을까...? ``` ## Structure - 스트럭쳐 타입은 복사 되고 - 클레스는 참조 된다 ``` //거리구하는 함수 func distance(current: (x: Int, y: Int), target: (x: Int, y: Int)) -> Double { // 피타고라스 let distanceX = Double(target.x - current.x) let distanceY = Double(target.y - current.y) let distance = sqrt(distanceX * distanceX + distanceY * DistanceY) return distance } // 가장 가까운 스토어 구해서 프린트 하는 함수 func printClosesStore(currentLocation:(x: Int, y: Int), stores:[(x: Int, y: Int, name: String)]) { var closestStroeName = "" var closestStroeDistance = Double.infinity for stroe in stores { let distanceToStore = distance(current: currentLocation, target: (x :store.x y: store.y))) closesStoreDistance = min(distanceTostroe, closestStoreDistance) if closestStoreDistance == distanceToStore { closestStoreName = store.name } } print("Closest store: \(closestStoreName)") } 스트럭쳐로 줄여보자 (미구현) ``` ``` import UIKit struct Lecture { let name: String let instructor : String let numOfStudent : Int } func printLectureName(from instrutor: String, lectures: [Lecture]) { let lectureName = lectures.first{ (lec) -> Bool in return lec.instructor == instrutor}?.name ?? "없습니다." print("그 강사님 강의는요: \(lectureName)") } // lec 는 돌고있는 현재 Lecture 이다 그래서 입력된강의와 현 lec 의 강의 와 비교해서 같을때 lec.name 을 출력 let lec1 = Lecture(name: "IOS Basic", instructor: "Jason", numOfStudent: 5) let lec2 = Lecture(name: "IOS Advanced", instructor: "Jack", numOfStudent: 5) let lec3 = Lecture(name: "IOS Pro", instructor: "Nick", numOfStudent: 5) let lectures = [lec1,lec2,lec3] printLectureName(from: "no", lectures: lectures) ``` ### Protocol 준수 ``` import UIKit // CustomStringConvertible 프로토콜 struct Lecture: CustomStringConvertible{ var descriptionL String { return "Title: \(name), Instuctor: \(instructor)" } let name: String let instructor : String let numOfStudent : Int } func printLectureName(from instrutor: String, lectures: [Lecture]) { let lectureName = lectures.first{ (lec) -> Bool in return lec.instructor == instrutor}?.name ?? "없습니다." print("그 강사님 강의는요: \(lectureName)") } // lec 는 돌고있는 현재 Lecture 이다 그래서 입력된강의와 현 lec 의 강의 와 비교해서 같을때 lec.name 을 출력 let lec1 = Lecture(name: "IOS Basic", instructor: "Jason", numOfStudent: 5) let lec2 = Lecture(name: "IOS Advanced", instructor: "Jack", numOfStudent: 5) let lec3 = Lecture(name: "IOS Pro", instructor: "Nick", numOfStudent: 5) let lectures = [lec1,lec2,lec3] printLectureName(from: "no", lectures: lectures) print(lec1) // Title: IOS Basic, Instructor: Jason ``` ### Property ### Method ``` import UIKit struct Lecture{ var title:String var maxStudent: Int = 30 var numOfRegistered:Int = 0 // 메서드 func remainSeats() -> Int { let remainSeats = maxStudent - numOfRegistered return remainSeats } //  Struct 관련 메서드를 썻는데 그 메서드가 스트럭트에 프로퍼티를 변경 시키면 // mutating 키워드 을 써주어야 한다. mutating func register(){ //등록된 학생수 증가시키기 numOfRegistered += 1 } //타입 프로퍼티 static let target: String = "Anybody !" //타입 메서드 static func 소속() -> String { return "무직" } } var lec = Lecture(title: "IOS Basic") lec.remainSeats() lec.register() lec.register() lec.register() lec.register() lec.register() lec.register() lec.remainSeats() Lecture.target Lecture.소속() struct Math { static func abs(value: Int) -> Int{ if value > 0 { return value }else { return -value } } } // 메서드 추가 extension extension Math { static func squre(value: Int) -> Int{ return value * value } static func half(value: Int) -> Int{ return value/2 } } Math.squre(value: 5) Math.half(value: 20) ``` ## Class 스트럭트 클레스 차이 ``` import UIKit struct PersonStruct { var firstName:String var lastName:String init(firstName: String, lastName:String) { self.firstName = firstName self.lastName = lastName } var fullName: String { return "\(firstName) \(lastName)" } mutating func uppercaseName() { firstName = firstName.uppercased() lastName = lastName.uppercased() } } class PersonClass { var firstName:String var lastName:String init(firstName: String, lastName:String) { self.firstName = firstName self.lastName = lastName } var fullName: String { return "\(firstName) \(lastName)" } func uppercaseName() { firstName = firstName.uppercased() lastName = lastName.uppercased() } } ``` ## 상속 ``` struct Grade { var letter: Character var points: Double var credits: Double } class Person { var firstName: String var lastName: String init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } func printMyName() { print("My name is \(firstName) \(lastName)") } } class Student: Person { var grades: [Grade] = [] } let jay = Person(firstName: "Jay", lastName: "Lee") let jason = Student(firstName: "Jasson", lastName: "Lee") jay.firstName jason.firstName jay.printMyName() jason.printMyName() let math = Grade(letter: "B", points: 8.5, credits: 3) let history = Grade(letter: "A", points: 10.0, credits: 3) jason.grades.append(math) jason.grades.append(history) //jay.grades jason.grades.count ``` phase 1 이 끝나기 전에는 어떤 프로퍼티나 메서드를 사용할 수없다 phase 2 는 일단 프로퍼티가 다 세팅이 되어야 할 수있다. designated vs convenience Initialization ``` class Student: Person { var grades: [Grade] = [] // designated override init(firstName: String, lastName: String) { super.init(firstName: firstName, lastName: lastName) } // convenience convenience init(student: Student) { self.init(firstName: student.firstName, lastName: student.lastName) } } // 학생인데 운동선수 class StudentAthlete: Student { var minimumTrainingTime: Int = 2 var trainedTime: Int = 0 var sports: [String] init(firstName: String, lastName: String, sports: [String]) { // Phase 1 self.sports = sports // 자식 클래스 즉, 자기 자신부터 먼저 init해주어야 한다. 이걸 2phase 이니셜 라이즈네이션 이라한다. // Person 클래스에 상속되어 기에 사용할수 있다. super 사용 super.init(firstName: firstName, lastName: lastName) // Phase 2 self.train() } convenience init(name: String) { self.init(firstName: name, lastName: "", sports: []) } func train() { trainedTime += 1 } } // 운동선인데 축구선수 class FootballPlayer: StudentAthlete { var footballTeam = "FC Swift" override func train() { trainedTime += 2 } } let student1 = Student(firstName: "Jason", lastName: "Lee") let student1_1 = Student(student: student1) let student2 = StudentAthlete(firstName: "Jay", lastName: "Lee", sports: ["Football"]) let student3 = StudentAthlete(name: "Mike") ``` - DI 는 자신의 부모의 Di 를 호출해야한다. - CI 는 같은클래스의 이니셜라이저를 꼭 하나 호출해야한다, - CI는 궁극적으로 DI 를 호출해야함 <file_sep>/Python/README.md # Python ------ ## 자료형 ### 자료에 대한 타입 + [숫자](https://github.com/o2o25252/2021-TIL/blob/main/Python/README.md#%EC%88%AB%EC%9E%90) + [문자열](https://github.com/o2o25252/2021-TIL/blob/main/Python/README.md#%EB%AC%B8%EC%9E%90%EC%97%B4) + [불](https://github.com/o2o25252/2021-TIL/blob/main/Python/README.md#%EB%B6%88) ### 어떤 값을 담는 자료구조 + [변수](https://github.com/o2o25252/2021-TIL/blob/main/Python/README.md#%EB%B3%80%EC%88%98) + [리스트](https://github.com/o2o25252/2021-TIL/blob/main/Python/README.md#list) + [튜플](https://github.com/o2o25252/2021-TIL/blob/main/Python/README.md#%ED%8A%9C%ED%94%8C) + [딕셔너리](https://github.com/o2o25252/2021-TIL/tree/main/Python#%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC) + [집합](https://github.com/o2o25252/2021-TIL/blob/main/Python/README.md#%EC%A7%91%ED%95%A9) ### 제어문 + [조건문]( ### 숫자 ``` a = 3 b = 4 print(a+b) print(a-b) print(a*b) print(a/b) print(a//b) print(a%b) print(a**b) ``` 나누기 / 몫 // 나머지 % ### 문자열 다른언어와 같다 ``` """ 따옴표 3 개는 이런식 으로 해도 이걸 알아 먹는다 """ \ 이걸로도 구분 가능 a = "2021" print(a[:2]) //이상: 미만: 간격 즉 처음부터 시작해서 인덱스 2 미만 인 20 이나온다 print(a[::2]) 처음부터 끝까지 2간격 으로 def is_palindrome(s): """Check whether a string is a palindrome""" return s == s[::-1] 뒤로 읽는 값과 일반값과 같냐? ``` *문자열 포메팅* ``` a = "I eat %d apples." % 3 print(a) // i eat 3 apples. ``` 이걸 왜 쓰냐..? ``` b = "I eat " + str(3) + " apples" 이렇게 쓰기 귀찮으닌깐🤷🏼‍♂️ 그러면 이걸 이렇게 여러개 로 도 사용할 수 있다. number = 10 day = "three" a = "I ate %d apples. so i was sick for %s days." % (number, day) print(a)//I ate 10 apples. so i was sick for three days. ``` *문자열 포맷 코드* 코드 | 설명 -------- | -------- %s | 문자열 %c | 문자1개 %d | 정수 %f | 부동 소수 %o | 8진수 3.6 번전 이후 부터는 이것도 가능 ``` a = "{ age }qwer 1234 { name } qwer".format( name ="임희찬" , age = 27) print(a) ``` ``` name ="int" a = f"나의 이름은 {name}입니다." print(a) //나의 이름은 int입니다. ``` ``` a = "%10s" % "hi" print(a)// hi b = "%-10sjane." % 'hi' //'hi jane.' 뒤로 ``` *실수형* ``` a ="0.4f" % 3.42134234 //간격.소수점 남기는 자리 수 print(a) //3.4213 ``` *문자열 개수 세기* ``` a = "hobby" a.count('b') //2 ``` *위치 알려주기* ``` a = "hobby" a.find('b') //2 처음 찾은 인덱스의 번호만 알려준다 뒤에 나오는 건 알려주지 않는다. //없다면 -1 을 반환한다. ``` ``` a = "Life is too short" a.index('t') //8 //없으면 에러 ``` *문자열 삽입* ``` a= "," a.join('abcd') //'a,b,c,d' 요거는 리스트랑 많이 사용된다. ``` *소문자를 대문자로 바꾸기 ``` a = "hi" a.upper() //'HI' a = "HI" a.lower() //'hi' a=" HI " //양쪽 공백 지우기 print(a.strip()) //HI ``` *교체하기* ``` a ="Life is too short" print(a.replace("Life", "Your leg")) //Your leg is too short ``` *잘라서 리스트 만들기* ``` a ="Life is too short" print(a.split()) //['Life','is','too','shrt'] ``` ## List 하나의 변수에 여러개 의 값을 넣고 싶을떄 ``` a = [1,2,3] b = [4,5,6] print(a+b) //[1,2,3,4,5,6] * 기도 가능 ``` *연속 교체* ``` a =["qwer","asdf","zxcv"] a[0:2] =["1234","4567"] // [이상:미만:간격] print(a) // ["1234","4567","zxcv"] 삭제도 가능 a =["qwer","asdf","zxcv"] a[0:2] =[] // [이상:미만:간격] //["zxcv"] a =["qwer","asdf","zxcv"] del a[0] print(a)//["asdf","zxcv"] ``` *리스트 맨뒤에 요소 추가* ``` a = [1,2,3] a.append(4) //[1,2,3,4] ``` *리스트 정렬* ``` a = [1,4,3,2] a.sort() //[1,2,3,4] ``` *리스트 뒤집기* ``` a = ['a','c','b'] a.reverse() //['b','c','a'] ``` *insert* ``` a =[1,5,3] a.insert(0,4)// 0번쨰 인덱스에 4를 추가 print(a.index(a))//[4,1,5,3] ``` *요소 제거* ``` a = [1,2,3,1,2,3] a.remove(3)//값을 제거 //[1,2,1,2] ``` *리스트 요소 끄집어내기* ``` a = [1,2,3] a.pop() //3 print(a)//[1,2] 마지막 요소를 빼낸다 ``` *count* ``` a =[1,5,3,1,1] print(a.count(1)) // 3 ``` *리스트 확장* ``` a = [1,2,3] a.extent([4,5]) //[1,2,3,4,5] ``` ## 튜플 리스트와 튜플 의 차이점은 ```a=[1,2,3] // 리스트 추가 삭제 변경가능``` ```b=(1,2,3) // 튜플 고정되어있다. 보기만 가능 (read only)``` ``` t1 =(1,2,'a','b') >>> del t1[0] Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> del t1[0] TypeError: 'tuple' object doesn't support item deletion ``` ``` >>> t1[0] ='c' Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> t1[0] ='c' TypeError: 'tuple' object does not support item assignment ``` 보는 것만 가능 인덱싱 , 슬라이싱 된다 . 더하기 곱하기 다 가능하다 그런데 t1,t2 가 변하는게 아니고 단지 t1 ,t2 를 더한 새로운 튜플을 만든 것이다. t1,t2 는 변하지 않는다. ``` t2 =(3,4) >>> t1+t2 (1, 2, 'a', 'b', 3, 4) ``` ## 딕셔너리 자바스크립트 에서는 *object* 라고 생각 하면 된다. ``` >>> dic = {'name':'Eric','age':15} >>> dic['name'] 'Eric' ``` *딕셔너리 자료형* *딕셔너리 쌍 추가하기* ``` >>> a ={1:'a'} >>> a['name'] ="익명" >>> a {1: 'a', 'name': '익명'} //어떤 Key 와 Value ``` *딕셔너리 요소 삭제* ``` del a[1] >>> a {'name': '익명'} ``` *딕셔너리 주의 사항* ``` d ={1:'aa',1:'bb'} >>> d {1: 'bb'} // 보면 키는 같으면 안된다. 같을 시에는 뒤에 값만 남아있는다. ``` *keys 로 키 만 가져오기* ``` dict = {1:'날토',2:'이치',3:'dl'} >>> dict.keys() dict_keys([1, 2, 3]) ``` *values 로 벨류 만 가져오기* ``` >>> dict.values() dict_values(['날토', '이치', 'dl']) ``` *배열 안 튜플 형태 items* ``` >>> dict.items() dict_items([(1, '날토'), (2, '이치'), (3, 'dl')]) # 언제 쓰이냐 >>> for k,v in dict.items(): print("키는:" + str(k)) print("벨루는" + v) 키는:1 벨루는날토 키는:2 벨루는이치 키는:3 벨루는dl ``` *딕셔널 비우기* ``` >>> dict.clear() >>> dict {} ``` *get()* ``` #만약에 딕셔너리 안에 어떤 요소를 찾는다고 하면은 a={1:'a',2:'b',3:'c'} >>> print(a[4]) Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> print(a[4]) KeyError: 4 # 에러가 나온다 하지만 get()  을 사용하면 print(a.get(4)) None print(a.get(4,'없음')) 없음 이렇게 사용 할 수있다. 또한 딕셔너리의 핵심은 키를이용해서 빠르게 찾는 것이다. 그래서 print(4 in a) # False print(1 in a) # True 이렇게 해서찾는 것 또한 가능하다. ``` ## 집합 + 집합에 관련된 것들을 쉽게 처리하기 위해 만들어진 자료형 + 집합은 원속 각각 고유 하면 중복 될 수 없다. + 순서가 없다 *집합 만들기* ``` >>> s1 = set([1,2,3]) >>> s1 {1, 2, 3} >>> s2 ={1,2,3} >>> s2 {1, 2, 3} >>> print(type(s1)) <class 'set'> >>> print(type(s2)) <class 'set'> ``` 어떨때 사용하는가..? *중복 제거* ``` l = [1,2,2,2,3,3] newList = list(set(l)) # 이렇게 하면 중복이 제거 되면서 다시 list 로 바꾼다. ``` *문자열 중복 제거* ``` >>> s1 = set("hello") >>> print(s1) {'o', 'l', 'h', 'e'} #쪼개 진다 # 하지만 순서는 뒤준박죽이다. ``` *교집합* ``` >>> s1 = set([1,2,3,4,5,6]) >>> s2 = set([4,5,6,7,8,9]) >>> s1 & s2 {4, 5, 6} s1.intersection(s2)# 이것도 교집합 {4, 5, 6} ``` *합집합* ``` >>> s1 | s2 {1, 2, 3, 4, 5, 6, 7, 8, 9} s1.union(s2) # 이것도 합집합 ``` *차집합* ``` # s1 에서 s2 를 뺀 값 출력 s1-s2 {1, 2, 3} # 반대 s2.difference(s1) {8, 9, 7} ``` *값 1개 추가하기* ``` >>> s1.add(7) >>> s1 {1, 2, 3, 4, 5, 6, 7} ``` *값 여러 개 추가하기* ``` >>> s1.update([7,8,9,1]) >>> s1 {1, 2, 3, 4, 5, 6, 7, 8, 9} # 1은 중복 되므로 추가 되지 않는다. ``` ## 불 ``` >>> a = True >>> type(a) <class 'bool'> ``` *자료형의 참과 거짓* 값 | 참 or 거짓 -------- | -------- "python" | True "" | False [1,2,3] | True [] | False () | False {} | False 1 | True 0 | False None | False ## 변수 [시각적 변수 보기](http://pythontutor.com/live.html#mode=edit) *주소* ``` a =[1,2,3] b = a # a 의 주소를 b 에 주었다. a[1] = 4 print(b) # [1,4,3] 1 번째 가 4 로 바뀐 이유는 a의 주소를 가지고 있으므로 같이 변동된다. #id 주소 확인 print(id(a)) # 4371000016 print(id(b)) # 4371000016 >>> print(a is b) True ``` a 의 값을 그대로 b 에게 주고 싶을땐? 슬라이싱을 사용 ``` >>> a = [1,2,3] >>> b = a[:] >>> b [1, 2, 3] # 이제는 다르다. >>> a[1] = 4 >>> a [1, 4, 3] >>> b [1, 2, 3] # 이제는 주소가 다른다 >>> id(a) 140221406474880 >>> id(b) 140221406476032 ``` *copy* ```모듈``` 를 사용 ``` >>> from copy import copy >>> a = [1,2,3] >>> b = copy(a) >>> a[1] = 4 >>> id(a) 140221412654272 >>> id(b) 140221406386304 ``` *변수를 만드는 여러가지 방법* ``` >>> a,b =('python','life') >>> a 'python' >>> >>> b 'life' ``` ``` (a,b) = ('python','life') ``` ``` (a,b) = 'python','life' ``` ``` [a,b] = ['python','life'] ``` ``` a = b = 'life' ``` *temp 하기* ``` >>> a = 3 >>> b = 5 >>> a,b =b,a >>> a 5 >>> b 3 ``` <file_sep>/Swift/TestApp/BountyList2/BountyList2/BountyViewController.swift // // BountyViewController.swift // BountyList2 // // Created by 임희찬 on 2021/03/08. // import UIKit class BountyViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate{ //🧑🏻‍💻 MODEL //⁉️VIEWMODEL 이 모델을 가지고 있어야 하므로 주석 처리 한거다. // let bountyInfoList : [BountyInfo] = [ // BountyInfo(name: "brook" , bounty: 33000000), // BountyInfo(name: "chopper" , bounty: 50), // BountyInfo(name: "franky" , bounty: 44000000), // BountyInfo(name: "luffy" , bounty: 300000000), // BountyInfo(name: "nami" , bounty: 16000000), // BountyInfo(name: "robin" , bounty: 80000000), // BountyInfo(name: "sanji" , bounty: 77000000), // BountyInfo(name: "zoro" , bounty: 120000000) // ] //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. let viewModel = BountyViewModel() //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 // let nameList = ["brook", "chopper", "franky", "luffy", "nami", "robin", "sanji", "zoro"] // let bountyList = [33000000, 50, 44000000, 300000000, 16000000, 80000000, 77000000, 120000000] //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 //원래 뷰컨트롤러에 있는 함수인데 우리가 상속받았고 그걸 다시 재정의? 할려고 하닌깐 오버라이드 되었다. // 세그웨이 수행직전에 수행되는 준비하는 함수 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //print(sender!) // ⁉️ Swift는 특정하지 않은 타입에 대해 동작하도록 특별한 타입 두가지를 제공합니다. // ● Any // // Any는 함수타입을 포함하여 모든 타입의 인스턴스를 나타낼 수 있습니다. // // ● AnyObject // // AnyObject는 모든 클래스 타입의 인스턴스를 나타낼 수 있습니다. // 출처: https://zeddios.tistory.com/213 [ZeddiOS] //DetailViewController 에게 데이터를 주기 //"showDetaill" 세그웨이 가 지칭하고 있는 데스티네이션 세그웨이 가 DetaillViewController 이다 // 근데 if segue.identifier == "showDetail" { let vc = segue.destination as? DetailViewController // DetailViewController 여기에는 name 과 bounty 가 있다. 그래서 우리는 여기에 정보를 넣어줄려 한다. // 그래서 현재 클릭한 번쨰의 셀이 몇번째 인지를 "sender" 를 통해 정보를 보냈다 if let index = sender as? Int { //🧑🏻‍💻 MODEL //let bountyInfo = bountyInfoList[index] // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. let bountyInfo = viewModel.bountyInfo(at: index) // vc?.name = bountyInfo.name // vc?.bounty = bountyInfo.bounty // vc?.bountyInfo = bountyInfo // ⁉️ 우리가 뷰 컨트롤러 사이에서 데이터를 넘겨줄떄 DetailViewController 에서 bountyInfo 직접 들고있는게 아니라? 먼말이야 // viewModel 한테 있기 때문에 vc?.viewModel.update(model: bountyInfo) // vc?.name = nameList[index] // vc?.bounty = bountyList[index] } // https://seoyoung612.tistory.com/entry/swift%EC%8A%A4%EC%9C%84%ED%94%84%ED%8A%B8%EA%B8%B0%EB%B3%B8%EB%AC%B8%EB%B2%9508-%EC%9D%B8%EC%8A%A4%ED%84%B4%EC%8A%A4-%EC%83%9D%EC%84%B1%EA%B3%BC-%EC%86%8C%EB%A9%B8 // 근데 나는 이 as? 하면서 리턴타입값 정해주고 {} 안에 수행문 하는거 이런 문법 잘모르겠단 말이지? // -> 타입캐스팅 에 다운캐스팅 부분 ! //출처: https://zeddios.tistory.com/265 [ZeddiOS] } } //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 override func viewDidLoad(){//컨트롤러의 뷰가 메모리에로드 된 후 호출 super.viewDidLoad() //이 메서드를 재정의 super하는 경우 슈퍼 클래스도이 메서드를 재정의하는 경우 구현의 특정 지점 에서이 메서드를 호출합니다 . } //UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //🧑🏻‍💻 MODEL //return bountyInfoList.count // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. return viewModel.numberOfBountyInfoList } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ListCell else{ return UITableViewCell() } // let img = UIImage(named: "\(nameList[indexPath.row]).jpg") // cell.imgView.image = img //subclass UITableViewCell 에서 imgView 에 UIImageView 넣어서 사 image 사용 거기에 img 넣기 // cell.nameLabel.text = nameList[indexPath.row] // cell.bountyLabel.text = "\(bountyList[indexPath.row])" //🧑🏻‍💻 MODEL //let bountyInfo = bountyInfoList[indexPath.row] // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. let bountyInfo = viewModel.bountyInfo(at: indexPath.row) //🧑🏻‍💻 VIEW // cell.imageView?.image = bountyInfo.image // cell.nameLabel.text = bountyInfo.name // cell.bountyLabel.text = "\(bountyInfo.bounty)" cell.update(info: bountyInfo) return cell } //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 //UITableViewDelegate 클릭시 수행작업 부분 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("indexpath\(indexPath.row)") //모달로 올라가는 뷰 컨트롤러의 아이덴티파이 는 "showDetail" //세그웨이 연결 할떄 여러개의 세그웨이를 보낼수 있기에 //구분자 👀"withIdentifier" 에 "withIdentifier" 로 지정 // 세그웨이 를 수행시 어떤 특정한 오브젝트를 같이 껴서 보낼수 있다. 👀"sender" performSegue(withIdentifier: "showDetail" , sender: indexPath.row) // sender 에 indexPath.row (cell 에대 한 정보) 를 준다 : ? prepare 작업 } } //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 class ListCell: UITableViewCell { // weak 를 사용하는냐? strong 을 사용하는냐? // http://monibu1548.github.io/2018/05/03/iboutlet-strong-weak/ // @IBOutlet , @IBAction ...?? 이거 모야 // https://etst.tistory.com/74 @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var bountyLabel: UILabel! // ! 는 옵셔널 로 Nil 이 올 일이 없을떄 강제레퍼 하는것?! //🧑🏻‍💻 VIEW func update(info: BountyInfo) { imageView?.image = info.image nameLabel.text = info.name bountyLabel.text = "\(info.bounty)" } } //🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧🚧 // 🧑🏻‍💻 VIEWMODEL : 데이터(MODEL)를 가지고 있어야 한다. //뷰랑 뷰모델에서는 모델에 직접 엑세스 하지않고 뷰모델을 통해서만 엑세스 한다 class BountyViewModel { let bountyInfoList : [BountyInfo] = [ BountyInfo(name: "brook" , bounty: 33000000), BountyInfo(name: "chopper" , bounty: 50), BountyInfo(name: "franky" , bounty: 44000000), BountyInfo(name: "luffy" , bounty: 300000000), BountyInfo(name: "nami" , bounty: 16000000), BountyInfo(name: "robin" , bounty: 80000000), BountyInfo(name: "sanji" , bounty: 77000000), BountyInfo(name: "zoro" , bounty: 120000000) ] var sortedList: [BountyInfo] { let sortedList = bountyInfoList.sorted{ prev , next in return prev.bounty > next.bounty} return sortedList } //bountyInfoList 갯수 구하기 var numberOfBountyInfoList : Int { return bountyInfoList.count } // 이거 도대체 모지 ? 함수 아닌데 ??? 걍 변수인데?? //몇번째의 데이터 인지 구하기 func bountyInfo(at index: Int) -> BountyInfo { return sortedList[index] } } <file_sep>/Swift/Class.playground/Contents.swift import UIKit struct PersonStruct { var firstName:String var lastName:String init(firstName: String, lastName:String) { self.firstName = firstName self.lastName = lastName } var fullName: String { return "\(firstName) \(lastName)" } mutating func uppercaseName() { firstName = firstName.uppercased() lastName = lastName.uppercased() } } class PersonClass { var firstName:String var lastName:String init(firstName: String, lastName:String) { self.firstName = firstName self.lastName = lastName } var fullName: String { return "\(firstName) \(lastName)" } func uppercaseName() { firstName = firstName.uppercased() lastName = lastName.uppercased() } } //학생인데 운동선수 //운동선수인데 축구선수 <file_sep>/README.md # TIL ✍🏻 # 알고리즘 🤖 + [Sort](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/Sort.md) + [Basic](https://github.com/o2o25252/2021-TIL/blob/main/algorithm/CodeStates.md) + [프로그래머스](https://programmers.co.kr/job?utm_source=google&utm_medium=cpc&utm_campaign=job_board&gclid=Cj0KCQiAj9iBBhCJARIsAE9qRtBBaVeh77oEnMxl9wvxAZqGd4kiUBsvjMh5kkoGP7Lfazze1koUZDAaAhi1EALw_wcB) + [백준](https://www.acmicpc.net/step) + [스위프트 알고리즘](///) --- # 리액트를 다루는 기술 ⚛️ + [React](https://github.com/o2o25252/2021-TIL/blob/main/react/react.md) --- # 파이썬 + [Python](https://github.com/o2o25252/2021-TIL/tree/main/Python) --- # 이코테 + [이코테](https://github.com/o2o25252/2021-TIL/tree/main/algorithm/%EC%9D%B4%EC%BD%94%ED%85%8C) # 스위프트 📱 + [MyAlbum](https://github.com/o2o25252/2021-TIL/tree/main/MyAlbum) + [PlayGround](https://github.com/o2o25252/2021-TIL/tree/main/Swift) + [Swift -> 코테 팁 하며 배운 문법 정리 공간](https://github.com/o2o25252/2021-TIL/blob/main/Swift/swiftnote.md) + [오늘읽은거 링크](https://github.com/o2o25252/2021-TIL/blob/main/todayReadLink.md) # IOS Test APP + [BountyList](https://github.com/o2o25252/2021-TIL/tree/main/Swift/TestApp/BountyList2) + [BountyList CollectionView](https://github.com/o2o25252/2021-TIL/tree/main/Swift/TestApp/BountyListCollectionView/BountyList.xcodeproj/project.xcworkspace) + [TODO-List](///) + --- # 아키텍쳐 + [MVVM](https://github.com/o2o25252/2021-TIL/blob/main/MVVM.md) codershigh <file_sep>/algorithm/DFS:BFS.md # 알고리즘 --- ## 타켓 넘버 (타겟넘버)[https://programmers.co.kr/learn/courses/30/lessons/43165] n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타켓 넘버를 만들려고 합니다. 예를 들어[1,1,1,1,1] 로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. ``` -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 ``` 사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 함수를 작성해주세요 ### 제한사항 - 주어지는 숫자의 개수는 2개 이상 20개 이하입니다. - 각 숫자는 1 이상 50 이하인 자연수입니다. - 타겟 넘버는 1 이상 1000 이하인 자연수입니다. <file_sep>/Swift/Method.playground/Contents.swift import UIKit struct Lecture{ var title:String var maxStudent: Int = 30 var numOfRegistered:Int = 0 // 메서드 func remainSeats() -> Int { let remainSeats = maxStudent - numOfRegistered return remainSeats } //  Struct 관련 메서드를 썻는데 그 메서드가 스트럭트에 프로퍼티를 변경 시키면 // mutating 키워드 을 써주어야 한다. mutating func register(){ //등록된 학생수 증가시키기 numOfRegistered += 1 } //타입 프로퍼티 static let target: String = "Anybody !" //타입 메서드 static func 소속() -> String { return "무직" } } var lec = Lecture(title: "IOS Basic") lec.remainSeats() lec.register() lec.register() lec.register() lec.register() lec.register() lec.register() lec.remainSeats() Lecture.target Lecture.소속() struct Math { static func abs(value: Int) -> Int{ if value > 0 { return value }else { return -value } } } // 메서드 추가 extension extension Math { static func squre(value: Int) -> Int{ return value * value } static func half(value: Int) -> Int{ return value/2 } } Math.squre(value: 5) Math.half(value: 20)
6cf4288fe5b21bc93ec8588af7842834979707ef
[ "Swift", "Markdown" ]
28
Swift
o2o25252/2021-TIL
d5931437cbca4ec37f48a36dc5940129ae2601a3
4d9137bb9d7dc135529b8e7df81842e6534b424b
refs/heads/master
<file_sep># golang blog 开发中的golang博客系统<file_sep>package app import ( "strconv" "github.com/gin-gonic/gin" "controller/user" "controller/article" ) type App struct { port int } func(s *App) Run(port int){ s.port = port r := gin.Default(); r.POST("/login", user.Login) r.GET("/articles/:page",article.FindByPage) r.PUT("/article",article.Add) r.GET("/article/:id",article.FindById) r.POST("/article/:id",article.Update) r.DELETE("/article/:id",article.Delete) r.GET("/category/:id",article.FindByCategory) r.Run((":" + strconv.Itoa(s.port))) } <file_sep>package util import ( "strconv" "reflect" "fmt" "github.com/gin-gonic/gin" ) func typeOf(arg interface{}) string{ return reflect.TypeOf(arg).String() } func toString(arg interface{}) string{ ret := "" if typeOf(arg) == "int" { // 类型断言 ret = strconv.Itoa(arg.(int)) } if typeOf(arg) == "string" { // 类型断言 ret = arg.(string) } return ret } func Log(args ...interface{}){ str := "" for _,arg := range args{ str += toString(arg) } fmt.Println(str) } const ( MESSAGE_ERROR = "失败" MESSAGE_SUCCESS = "成功" CODE_SUCCESS = 0 CODE_ERROR = 1 ) func Send(ctx *gin.Context, args ...interface{}) { httpCode := 200 code := CODE_SUCCESS msg := MESSAGE_SUCCESS var data interface{} = nil for index,arg := range args{ if index == 0 { if typeOf(arg) == "int" { httpCode = arg.(int) if httpCode != 200 && httpCode != 304 { msg = MESSAGE_ERROR code = CODE_ERROR } } else { data = arg } } else if index == 1 { data = arg } else if index == 2 && typeOf(arg) == "string" { msg = arg.(string) } } ctx.JSON(httpCode, gin.H{ "code": code, "msg": msg, "data": data, }) } <file_sep>package user import ( "github.com/gin-gonic/gin"; "model" // "time" ) // func Index(ctx *gin.Context){ // user := model.User{ // Account:"lingluo", // Password: "123", // Alias: "零落", // Type: 0, // CreateDate: time.Now(), // LastLoginDate: time.Now(), // CurrLoginDate: time.Now(), // LoginCount: 1, // Email:"<EMAIL>", // State: 1, // } // model.DB.Create(&user) // ctx.JSON(200,gin.H{ // "code":0, // "msg":"成功", // "data":[0]string{}, // }) // } // func List(ctx *gin.Context){ // ctx.JSON(200,gin.H{ // "code":0, // "msg":"成功", // "data":[0]int{}, // }) // } func Login(ctx *gin.Context) { var user model.User if err := ctx.ShouldBindJSON(&user) ; err != nil { } else { FindUser(&user) } } func FindUser(user *model.User) { model.DB.Find(user) } <file_sep>package article import ( "github.com/gin-gonic/gin" "model" "math" // "math/big" "util" "strconv" // "time" ) func Add(ctx *gin.Context){ var article model.Article if err := ctx.ShouldBindJSON(&article) ; err != nil { util.Send(ctx,400) return } if er := model.DB.Create(&article).Error ; er != nil { util.Send(ctx,500) } else { util.Send(ctx) } } func Update(ctx *gin.Context){ var article model.Article if err := ctx.ShouldBindJSON(&article) ; err != nil { util.Send(ctx,400) return } if er := model.DB.Update(&article) ; er != nil { util.Send(ctx,500) } else { util.Send(ctx) } } func Delete(ctx *gin.Context){ id , err := strconv.Atoi(ctx.Param("id")) sendError := func (){ util.Send(ctx,400,nil,"无效的参数:id") } if err != nil || id < 0 { sendError() return } article := model.Article{ ID:uint(id), } if model.DB.Delete(&article).Error != nil { sendError() } else { util.Send(ctx) } } func FindById(ctx *gin.Context){ id , err := strconv.Atoi(ctx.Param("id")) if err != nil || id < 0 { util.Send(ctx,400,nil,"无效的参数:id") return } article := model.Article{ ID:uint(id), } if model.DB.Find(&article).Error != nil { util.Send(ctx,404) } else { util.Send(ctx,article) } } func FindByPage(ctx *gin.Context){ page, err := strconv.Atoi(ctx.Param("page")) var articles []model.Article var dataCount int = 0 var size int = 10 model.DB.Model(&model.Article{}).Count(&dataCount) var pageCount = int(math.Ceil(float64(dataCount) / float64(size))) if err != nil || page < 1 { page = 1 } if page > pageCount { page = pageCount } var offset int = (page - 1) * size model.DB.Offset(offset).Limit(size).Find(&articles) util.Send(ctx, map[string]interface{} { "list":articles, "pageIndex":page, "pageSize":size, "pageCount":pageCount, "dataCount":dataCount, }) } func FindByCategory(ctx *gin.Context){ _,err := strconv.Atoi(ctx.Param("id")) if err != nil { util.Send(ctx,400) } } <file_sep>package model import ( "github.com/jinzhu/gorm" "util" _ "github.com/go-sql-driver/mysql" "time" "fmt" "config" ) var DB *gorm.DB var dbConfig = config.DBConfig var url string = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=false&loc=Local",dbConfig["user"], dbConfig["password"], dbConfig["host"], dbConfig["port"], dbConfig["database"], dbConfig["charset"]) func init() { if DB != nil { return } db,err := gorm.Open(dbConfig["type"].(string), url) if err == nil { util.Log("数据库连接失败") } else { util.Log("数据库连接成功") } // defer db.Close() // 使用表名单数形式 db.SingularTable(true) DB = db } type Article struct { ID uint `json:"id"` Title string `form:"title" binding:"required" json:"title"` Content string `form:"content" binding:"required" json:"content"` CategoryId uint `json:"categoryId"` CreateDate string `gorm:"TYPE:DATETIME" json:"createDate"` UpdateDate string `json:"updateDate"` DeleteDate string `json:"deleteDate"` CreateUser int `json:"createUser"` VisitCount uint `json:"visitCount"` CommentState uint `json:"commentState"` State uint `json:"state"` Permission uint `json:"permission"` Reminder string `json:"reminder"` ReminderKey string `json:"reminderKey"` } type Comment struct { ID uint `json:id` } type User struct { ID uint `json:"id"` Account string `json:"account"` Password string `json:"<PASSWORD>"` Alias string `json:"alias"` Type uint `json:"type"` CreateDate time.Time `json:"createDate"` LastLoginDate time.Time `json:"lastLoginDate"` CurrLoginDate time.Time `json:"currLoginDate"` LoginCount int `json:"loginCount"` Email string `json:"email"` State uint `json:"state"` } type Search struct { ID uint `json:"id"` Name string `json:"name"` Count uint `json:"count"` Type uint `json:"type"` CreateDate time.Time `json:"createDate"` LastSearchDate time.Time `json:"lastSearchDate"` } type Message struct { ID uint `json:"id"` UserName string `json:"userName"` Content string `json:"content"` Ipv4 string `json:"ipv4"` Email string `json:"email"` CreateDate time.Time `json:"createDate"` UserType uint `json:"userType"` State uint `json:"state"` } <file_sep>package main import ( "fmt" "strconv" "time" "reflect" ) func main(){ log("hello go") doSwap(1,2) testFor() testChan() testVar() testIota() testIf() // testSlect() testClass() testScope() testMultipleReturn() testArray() testSlice() testMap() testCon() testNew() testError() } func typeOf(arg interface{}) string{ return reflect.TypeOf(arg).String() } func toString(arg interface{}) string{ ret := "" if typeOf(arg) == "int" { // 类型断言 ret = strconv.Itoa(arg.(int)) } if typeOf(arg) == "string" { // 类型断言 ret = arg.(string) } return ret } func log(args ...interface{}){ str := "" for _,arg := range args{ str += toString(arg) } fmt.Println(str) } func log1(args ...string){ str := "" for _, arg := range args{ str += arg } fmt.Println(str) } func log2(mark string, others ...int){ str := mark for _,other := range others{ //int转string str += strconv.Itoa(other) } fmt.Println(str) } func log3(a int){ fmt.Println(a) } //指针相关 func swap(a *int, b *int){ *a ,*b = *b , *a //交换 } func doSwap(x int, y int){ log("交换前",x,y) swap(&x,&y) log("交换后",x,y) } func testFor(){ for i := 0;i<10;i++{ log(i) } } // channel相关 func worker(c chan int){ var i int = 0; for ; i< 10 ; i++{ c <- i } close(c) //关闭通道 } func testChan(){ // 创建一个通道 var c chan int = make(chan int,100) //第二个参数为缓冲区大小,带缓冲的通道,发送到缓冲区,不用等待接收方,除非缓存满了 //c := make(chan int) // 不带缓冲的通道,发送方会阻塞,直到接收方收到 //开启协程 go worker(c) //从通道接收一条消息 msg := <- c log("来自goroutine的通道消息",msg) //遍历通道的所有消息 for data := range c { log("来自goroutine的通道消息",data) } log("testChan执行完毕") } //定义变量相关 func testVar(){ //定义一个常量 const a = 10 var ( b int = 123 c = 2 ) const ( d = "567" e = 6 ) var f int = 1 var g = 2 var h,i,j int= 10,11,12 k,l,m := 13,14,"15" log(a) log(b) log(c) // len计算字符串常量的长度,不可用于变量 log("d的长度是:",len(d)) log(e) log(f) log(g) log(h) log(i) log(j) log(k) log(l) log(m) } //iota相关 func testIota(){ const ( a = iota //iota = 0 b //1 iota + 1 c = "str" //iota + 1 d //str iota + 1 e = iota //4 ) log(a) log(b) log(c) log(d) log(e) } //条件相关 func testIf(){ if(true){ log("if(ture)就打印这行") } if(false){ }else if(true){ log("else if(ture)就打印这行") } switch "abc"{ //或switch ("abc") case "abc": log("case \"abc\"就打印这行") //自带break效果 case "def": log("case\"def\"就打印这行") default: log("default就打印这行") } flag := "abc" switch{ case flag == "abc": log("case flag == \"abc\"就打印这行") default: log("没有匹配时的默认项") } var s interface{}; //利用 switch进行类型判断 switch s.(type){ case int : log("s是int类型就打印这行") case string: log("s是string类型就打印这行") default: log("s未知类型") } var str string = "123" //获取字符串长度 log(len(str)) var m uint = 1 switch m{ case 2: log("这条不会打印") case 1: log("这条一定会打印,在下一行用fallthrough关键字,下一个case无论是否成立都会执行") fallthrough case 3: log("这条case不匹配也会打印,因为上一个case用了fallthrough关键字") default: log("这条不会打印") } } //select相关 func select_worker(c chan int){ for i := 0; i < 10 ; i++{ c <- i //需要导入time包 time.Sleep(time.Duration(1) * time.Second) } close(c) //关闭通道 } func testSlect(){ ch1,ch2 := make(chan int,10),make(chan int,10) go select_worker(ch1) go select_worker(ch2) finish1, finish2 := false ,false //利用死循环和select的阻塞特性来接收消息 for true{ select { case r1, ok1 := (<- ch1): //(<- ch1) 同 <- ch1 log("收到ch1通道发来的消息",r1) if(!ok1){ finish1 = true if(finish1 && finish2){ goto PRINT } } case r2, ok2 := <- ch2: log("收到ch2通道发来的消息",r2) if(!ok2){ finish2 = true if(finish1 && finish2){ goto PRINT } } // default: //如果开启default则select语句不阻塞,否则阻塞,不开启default语句则不要写死循环这种危险操作 // log("暂无消息") } } PRINT:log("消息接收完毕!") } //结构 类相关 type Person struct { name string age int } func (p *Person) getName() string{ return p.name } func (p *Person) getAge() int{ return p.age } func testClass(){ p := Person{ name:"lingluo", age:18 } // }不能放在下一行,否则报错 log("p.getName() 的值是:",p.getName()) } // 作用域 、提升相关 func testScope(){ //测试块级作用域 log("测试块级作用域和变量提升") var a = 1 { log(a) // 1 var a = 2 log(a) // 2 } log(a) // 1 // go语言具有块级作用域 ,并且不会提升变量 log("测试函数提升") // (1) var myfunc = func (){ log("我是在函数体内定义的函数") } // (2) myfunc() // (1) (2) 不可交换位置,否则报错 // go语言在函数体内定义函数时,只能用变量赋值的形式,不可采用 func funcName(){}的形式 //go语言 全局函数、全局变量 有 ‘提升’的效果,可以写在main函数后面 } // 多个返回值 go语言支持返回多个值 func multipleReturn()(int,string){ return 1,"abc" } func testMultipleReturn(){ log("go函数支持返回多个值") a,b:= multipleReturn() log("返回的第一个值是",a) log("返回的第二个值是",b) } //数组相关 func testArray(){ //定义数组方式,不指定成员个数 var array = [...]int{1,2,3} //指定成员个数 array2 := [4]string{"a","b","c","d"} array3 := [2]Person{ Person{"lingluo",18}, Person{"lingluo2",19} } // 最后一个}不能换行,要报错 array4 := [...]interface{}{ //利用空接口 interface{} 放入任意类型 "str", 123, Person{"lingluo",18}} // 访问数组 log(array3[0].name) // 数组遍历, for i ,len := 0,len(array2);i < len; i ++ { log(array2[i]) } // 数组遍历, range方式 for _,item := range array2 { log(item) } _ = array _ = array2 _ = array3 _ = array4 } //切片相关 切片类似于ArrayList func testSlice(){ var arraylist []int = []int {1,2,3} log("初始切片长度为,",len(arraylist)) arraylist = append(arraylist,1) log("调用append函数后的长度为,",len(arraylist)) arraylist2 := make([]string ,2) //使用make函数创建切片 第二个参数2表示切片初始化长度为2 log("初始化长度,",len(arraylist2)) // 2 arraylist3 := make([]string,4,5) //第三个参数表示切片容量,当调用append超出容量时会自动增加容量大小 log("arraylist3的容量是",cap(arraylist3)) //5 cap(arr)函数计算切片的容量 arraylist3 = append(arraylist3,"str1") //append函往切片增加项 log(len(arraylist3)) arraylist4 := arraylist3[0:1] //[startIndex:endIndex] 包含startIndex,不包含endIndex,startindex或endindex都可省略 log("通过切片获得的新切片的长度是",len(arraylist4)) // 1 arraylist4 = append(arraylist4,"str3") // 切片后的arraylist4也是一个切片,可以用append函数 source := []string{"a","b"} target := make([]string,len(source),len(source) * 2) copy(target,source) //copy(target,source)函数将source的内容拷贝给target log("target的长度是",len(target)) } //map相关 func testMap(){ myMap := map[string]int { "count1":1, "count2":2 } myMap2 := make(map[string]int) myMap2["count3"] = 1 var myMap3 map[string]int //以这种形式先声明map的类型在下一行还得用make函数才能使用 myMap3 = make(map[string]int) myMap3["count4"] = 2 log("myMap2[\"count3\"]的值是",myMap2["count3"]) delete(myMap,"count2") // 使用delete函数删除key _,ok := myMap["count2"] if(ok){ log("myMap[\"count2\"]的值是",myMap["count2"]) }else{ log("myMap[\"count2\"]不存在") } } //类型转换 func testCon(){ var a int = 1 b := string(a) //语法 type(expression) log("int转换后的类型",typeOf(b)) var c = "123" // log("string转换后的类型",typeOf(int(c))) //报错 只能在兼容的类型之间转换 如 int -> float64 int -> string _ = c } //new函数 type People interface{ eat() } type Boy struct{ } func (p *Boy) eat(){ log("I am eating...") } func testNew(){ var p *int = new(int) //new(type)返回一个指针 log("new(int)初始化的值是",*p) // 0 *p = 10 //修改指针指向地址的值 log("p的值是",*p) boy := new(Boy) boy.eat() } //错误处理 func testError(){ defer func(){ log("我在异常抛出后第二执行") err := recover() //使用recover函数来catch异常 log("捕获到错误 ,错误信息是:",err) }() defer func(){ log("我在异常抛出后首先执行") }() panic("使用panic抛出了一个异常,开始向上执行defer函数,defer函数结尾有一对'()'号") } <file_sep>package comment import ( "github.com/gin-gonic/gin"; "model" "util" "strconv" ) // func FindByPage(ctx *gin.Context) { // if articleId ,err := strconv.Atoi(ctx.Param("id")) ; err != nil { // util.Send(ctx,400) // return // } // var comment model.Comment // model.DB.Offset(offset).Limit(size).Find(&comment) // } <file_sep> package config var DBConfig = map[string] interface{} { "type": "mysql", "user": "root", "password": "123", "host": "127.0.0.1", "port": 3306, "database": "test" , "charset":"utf8", } <file_sep>package main import ( "app" ) func main (){ app := new(app.App) app.Run(8001) }
37c5fa3be669acf8d07db1ced68a7c5b58fb9863
[ "Markdown", "Go" ]
10
Markdown
laivv/go-learn
6a1b34ee5207781f3239a82a9b52f865dfe74ac9
3813d64ae2b1a6a3c52073a761007a08c019de0b
refs/heads/master
<repo_name>timomer/Pump_Driver_Example<file_sep>/app/src/main/java/com/hypodiabetic/pumpdriverexample/MainActivity.java package com.hypodiabetic.pumpdriverexample; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.res.Resources; import android.graphics.Color; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.support.design.widget.Snackbar; import android.widget.TextView; import com.hypodiabetic.pumpdriverexample.Objects.Basal; import com.hypodiabetic.pumpdriverexample.Objects.Treatment; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity { SectionsPagerAdapter mSectionsPagerAdapter; //will provide fragments for each of the sections ViewPager mViewPager; Fragment bolusFragmentObject; Fragment basalFragmentObject; BroadcastReceiver happConnected; BroadcastReceiver refreshTreatments; BroadcastReceiver refreshBasal; //Our Service that HAPP will connect to private Messenger myService = null; private ServiceConnection myConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { myService = new Messenger(service); //Broadcast there has been a connection Intent intent = new Intent("HAPP_CONNECTED"); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); } public void onServiceDisconnected(ComponentName className) { myService = null; //FYI, only called if Service crashed or was killed, not on unbind } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create the adapter that will return a fragment for each of the 4 primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) this.findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); bolusFragmentObject = new bolusFragment(); basalFragmentObject = new basalFragment(); } @Override public void onPause() { super.onPause(); if (happConnected != null){ LocalBroadcastManager.getInstance(MainApp.instance()).unregisterReceiver(happConnected); } if (refreshTreatments != null){ unregisterReceiver(refreshTreatments); } if (refreshBasal != null){ unregisterReceiver(refreshBasal); } } @Override protected void onResume(){ super.onResume(); //Refresh the treatments list refreshTreatments = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { bolusFragment.update(); } }; registerReceiver(refreshTreatments, new IntentFilter("UPDATE_TREATMENTS")); bolusFragment.update(); //Refresh the Basal list refreshBasal = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { basalFragment.update(); } }; registerReceiver(refreshBasal, new IntentFilter("UPDATE_BASAL")); basalFragment.update(); } public void sendMessage(final View view) { //listen out for a successful connection happConnected = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Resources appR = view.getContext().getResources(); CharSequence txt = appR.getText(appR.getIdentifier("app_name", "string", view.getContext().getPackageName())); Message msg = Message.obtain(); Bundle bundle = new Bundle(); bundle.putString("ACTION","TEST_MSG"); bundle.putString("UPDATE", txt.toString()); msg.setData(bundle); try { myService.send(msg); } catch (RemoteException e) { e.printStackTrace(); //cannot Bind to service Snackbar snackbar = Snackbar .make(view, "error sending msg: " + e.getMessage(), Snackbar.LENGTH_INDEFINITE); snackbar.show(); } if (happConnected != null) LocalBroadcastManager.getInstance(MainApp.instance()).unregisterReceiver(happConnected); //Stop listening for new connections MainApp.instance().unbindService(myConnection); } }; LocalBroadcastManager.getInstance(MainApp.instance()).registerReceiver(happConnected, new IntentFilter("HAPP_CONNECTED")); connect_to_HAPP(MainApp.instance()); } //Connect to the HAPP Treatments Service private void connect_to_HAPP(Context c){ Intent intent = new Intent("com.hypodiabetic.happ.services.TreatmentService"); intent.setPackage("com.hypodiabetic.happ"); c.bindService(intent, myConnection, Context.BIND_AUTO_CREATE); } public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. switch (position){ case 0: return bolusFragmentObject; case 1: return basalFragmentObject; default: return null; } } @Override public int getCount() { // Show 2 total pages. return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Bolus Requests"; case 1: return "Basal Requests"; } return null; } } public static class bolusFragment extends Fragment { public bolusFragment(){} private static ListView list; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_treatments_list, container, false); list = (ListView) rootView.findViewById(R.id.treatmentsFragmentList); update(); return rootView; } public static void update(){ if (list != null) { ArrayList<HashMap<String, String>> treatmentsList = new ArrayList<>(); List<Treatment> treatments = Treatment.getLatestTreatments(10); Calendar treatmentDate = Calendar.getInstance(); SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd MMM HH:mm", MainApp.instance().getResources().getConfiguration().locale); for (Treatment treatment : treatments) { //Convert from a List<Object> Array to ArrayList HashMap<String, String> treatmentItem = new HashMap<String, String>(); if (treatment.date_requested != null) { treatmentDate.setTime(new Date(treatment.date_requested)); } else { treatmentDate.setTime(new Date(0)); //Bad Treatment } treatmentItem.put("type", treatment.type); treatmentItem.put("value", treatment.value.toString() + "U"); treatmentItem.put("dateTime", sdfDateTime.format(treatmentDate.getTime())); treatmentItem.put("state", "State:" + treatment.state); treatmentItem.put("delivered", "Delivered:" + treatment.delivered); treatmentItem.put("rejected", "Rejected:" + treatment.rejected); treatmentItem.put("happ_id", "HAPP Integration ID:" + treatment.happ_int_id); treatmentItem.put("happ_update", "Update Needed:" + treatment.happ_update); treatmentItem.put("details", treatment.details); treatmentsList.add(treatmentItem); } SimpleAdapter adapter = new SimpleAdapter(MainApp.instance(), treatmentsList, R.layout.treatments_list_layout, new String[]{"type", "value", "dateTime", "state", "delivered", "rejected", "happ_id", "happ_update", "details"}, new int[]{R.id.treatmentTypeLayout, R.id.treatmentValueLayout, R.id.treatmentDateTimeLayout, R.id.treatmentStateLayout, R.id.treatmentDeliveredLayout, R.id.treatmentRejectedLayout, R.id.treatmentHAPPIDLayout, R.id.treatmentHAPPUpdateLayout, R.id.treatmentDetailsLayout}); list.setAdapter(adapter); } } } public static class basalFragment extends Fragment { public basalFragment() { } private static ListView list; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_treatments_list, container, false); list = (ListView) rootView.findViewById(R.id.treatmentsFragmentList); update(); return rootView; } public static void update() { if (list != null) { ArrayList<HashMap<String, String>> basalList = new ArrayList<>(); List<Basal> basals = Basal.getLatest(10); Calendar basalDate = Calendar.getInstance(); SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd MMM HH:mm", MainApp.instance().getResources().getConfiguration().locale); for (Basal basal : basals) { //Convert from a List<Object> Array to ArrayList HashMap<String, String> basalItem = new HashMap<String, String>(); basalDate.setTime(basal.start_time); basalItem.put("type", basal.action); basalItem.put("value", basal.rate + "U/h (" + basal.ratePercent + "%) " + basal.duration + "mins"); basalItem.put("dateTime", sdfDateTime.format(basalDate.getTime())); basalItem.put("state", "State:" + basal.state); basalItem.put("delivered", "Set:" + basal.been_set); basalItem.put("rejected", "Rejected:" + basal.rejected); basalItem.put("happ_id", "HAPP Integration ID:" + basal.happ_int_id); basalItem.put("happ_update", "Update Needed:" + basal.happ_update); basalItem.put("details", basal.details); basalList.add(basalItem); } SimpleAdapter adapter = new SimpleAdapter(MainApp.instance(), basalList, R.layout.treatments_list_layout, new String[]{"type", "value", "dateTime", "state", "delivered", "rejected", "happ_id", "happ_update", "details"}, new int[]{R.id.treatmentTypeLayout, R.id.treatmentValueLayout, R.id.treatmentDateTimeLayout, R.id.treatmentStateLayout, R.id.treatmentDeliveredLayout, R.id.treatmentRejectedLayout, R.id.treatmentHAPPIDLayout, R.id.treatmentHAPPUpdateLayout, R.id.treatmentDetailsLayout}); list.setAdapter(adapter); } } } }
bc6cace8fa36bf47f8177214af0c6f4b498e3531
[ "Java" ]
1
Java
timomer/Pump_Driver_Example
0018e25b7ca6ac2c1c7a70ebcf53d44976f8810a
c659e0c1dbb00fd3978bd13db10a8ae6f8d3de98
refs/heads/master
<file_sep><p align="center"><a href="#" target="_blank"><img src="https://avatars0.githubusercontent.com/u/2921276?s=460&u=cc3289e50e48284ef4370c388e4f4aa29186f466&v=4" width="400"></a></p> ## About me Junior desarrollador, semisenior student and senior asking. [Mi web](http://mabregu.online). - [Node](https://github.com/mabregu/devflix). - [Sails](https://github.com/mabregu/Tienda-de-fotos). - [PHP](https://github.com/mabregu/campus). - JavaScript. - HTML. - CSS. - React. - Vue.js. ## Contact If you want to contact me, send an email via [<EMAIL>](mailto:<EMAIL>). I will answer you immediately. ## License The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). <file_sep><?php //use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // DB::listen(function($query) { // echo "<pre>"; // var_dump($query->sql); // echo "</pre>"; // }); Route::view('/', 'home')->name('home'); Route::view('/' . __('about'), 'about')->name('about'); Route::resource('portafolio', 'ProjectController') ->parameters(['portafolio' => 'project']) ->names('projects'); Route::patch('portfolio/{project}/restore', 'ProjectController@restore') ->name('projects.restore'); Route::delete('portfolio/{project}/force-delete', 'ProjectController@forceDelete') ->name('projects.force-delete'); Route::get('categories/{category}', 'CategoryController@show') ->name('categories.show'); Route::view('/' . __('contact'), 'contact') ->name('contact'); Route::post('contact', 'MessageController@store') ->name('messages.store'); // Auth::routes(['register' => false]); Auth::routes(); <file_sep><?php namespace App\Http\Controllers; use App\Project; use App\Category; use App\Events\ProjectSaved; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use App\Http\Requests\SaveProjectRequest; class ProjectController extends Controller { public function __construct() { $this->middleware('auth')->except('index', 'show'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('projects.index', [ 'newProject' => new Project, 'projects' => Project::with('category')->latest()->paginate(), 'deletedProjects' => Project::onlyTrashed()->get() ]); } public function show(Project $project) { return view('projects.show', [ 'project' => $project ]); } public function create() { $this->authorize('create', $project = new Project); return view('projects.create', [ 'project' => $project, 'categories' => Category::pluck('name', 'id') ]); } public function store(SaveProjectRequest $request) { $project = new Project( $request->validated() ); $this->authorize('create', $project); $project->image = $request->file('image')->store('images'); $project->save(); ProjectSaved::dispatch($project); return redirect()->route('projects.index')->with('status', __('The project was created successfully')); } public function edit(Project $project) { $this->authorize('update', $project); return view('projects.edit', [ 'project' => $project, 'categories' => Category::pluck('name', 'id') ]); } public function update(Project $project, SaveProjectRequest $request) { $this->authorize('update', $project); if ( $request->hasFile('image') ) { Storage::delete($project->image); $project->fill( $request->validated() ); $project->image = $request->file('image')->store('images'); $project->save(); ProjectSaved::dispatch($project); } else { $project->update( array_filter($request->validated()) ); } return redirect()->route('projects.show', $project) ->with('status', __('The project was successfully updated')); } public function destroy(Project $project) { $this->authorize('delete', $project); $project->delete(); return redirect()->route('projects.index') ->with('status', __('The project was successfully removed')); } public function restore($projectUrl) { $project = Project::withTrashed()->whereUrl($projectUrl)->firstOrFail(); $this->authorize('restore', $project); $project->restore(); return redirect()->route('projects.index') ->with('status', __('The project was successfully removed')); } public function forceDelete($projectUrl) { $project = Project::withTrashed()->whereUrl($projectUrl)->firstOrFail(); $this->authorize('force-delete', $project); Storage::delete($project->image); $project->forceDelete(); return redirect()->route('projects.index')->with('status', __('The project was permanently removed successfully')); } } <file_sep><?php namespace Tests\Feature; use App\Project; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class ListProjectsTest extends TestCase { use RefreshDatabase; /** * A basic feature test example. * * @return void */ public function test_can_see_all_projects() { $this->withoutExceptionHandling(); $project = factory(Project::class)->create(); $project2 = factory(Project::class)->create(); $response = $this->get(route('projects.index')); $response->assertStatus(200); $response->assertViewIs('projects.index'); $response->assertViewHas('projects'); $response->assertSee($project->title); $response->assertSee($project2->title); } public function test_can_see_individual_projects() { $project = factory(Project::class)->create(); $project2 = factory(Project::class)->create(); $response = $this->get(route('projects.show', $project)); $response->assertSee($project->title); $response->assertDontSee($project2->title); } }
b5f50b41e6b416ced1b46b2ddbb53a9ee67c73f1
[ "Markdown", "PHP" ]
4
Markdown
mabregu/portfolio
d87ca6c2209890e910ed1ec938e053c62b8f9439
8fd9c6a87ad822566b8451e4199a77816c502932
refs/heads/master
<repo_name>parimalkesan/EMICalculator<file_sep>/app/src/main/java/parimal/examples/emicalculator/MainActivity.java package parimal.examples.emicalculator; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import static java.sql.Types.NULL; public class MainActivity extends AppCompatActivity { Double interestRate; Double interestRatepermonth; public static final String EMIcalculated="emi"; public static final String interestcalculated="interest"; public static final String amountcalculated="amount"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinnerItemSelected(); setListenerOnButton(); } public void spinnerItemSelected() { Spinner loanTypeSpinner=(Spinner)findViewById(R.id.loan_type_spinner); final TextView interestRateTextView=(TextView)findViewById(R.id.interest_rate_textView); loanTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Object selectedItem=parent.getItemAtPosition(position); String loanType=selectedItem.toString(); if(loanType.equals("Home Loan")) { interestRateTextView.setText("10.5"); interestRate=10.5; } else if(loanType.equals("Vehicle Loan")) { interestRateTextView.setText("12.5"); interestRate=12.5; } else if(loanType.equals("Education Loan")) { interestRateTextView.setText("9.5"); interestRate=9.5; } else if(loanType.equals("Personal Loan")) { interestRateTextView.setText("17.5"); interestRate = 17.5; } else if(loanType.equals("Business Loan")) { interestRateTextView.setText("19.5"); interestRate=19.5; } else if(loanType.equals("Gold Loan")){ interestRateTextView.setText("15.5"); interestRate=15.5; } interestRatepermonth=interestRate/1200; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void setListenerOnButton() { Button calculateEMIButton=(Button)findViewById(R.id.calculate_EMI_button); final EditText loanAmountEdt=(EditText)findViewById(R.id.loan_amount_editText); final EditText loanTenureEdt=(EditText)findViewById(R.id.loan_tenure_editText); calculateEMIButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Double amount=Double.parseDouble(loanAmountEdt.getText().toString()); Double tenure=(Double.parseDouble(loanTenureEdt.getText().toString())); Double tenureInMonths=tenure*12; if(amount!=null && tenure!=null) { Double power = Math.pow(1 + interestRatepermonth, tenureInMonths); Double power1 = power - 1; Double calculatedEmi = (amount * interestRatepermonth * power) / power1; calculatedEmi=Math.round(calculatedEmi*100.0)/100.0; Double totalAmount = calculatedEmi*tenureInMonths; totalAmount=Math.round(totalAmount*100.0)/100.0; Double calculatedInterest = totalAmount-amount; calculatedInterest=Math.round(calculatedInterest*100.0)/100.0; Intent intent = new Intent(getApplicationContext(), EMIDisplay.class); Bundle args=new Bundle(); args.putDouble(EMIcalculated,calculatedEmi); args.putDouble(interestcalculated,calculatedInterest); args.putDouble(amountcalculated,totalAmount); intent.putExtras(args); startActivity(intent); } } catch(Exception e) { Toast.makeText(getApplicationContext(),"Please enter required details",Toast.LENGTH_LONG).show(); } } }); } }
9ae13c481a802c06817953f30c1344e53b6c02b9
[ "Java" ]
1
Java
parimalkesan/EMICalculator
b045619557213d24503cd43c64966c39366e1687
1f023125b40dc1b58503471a7290357982a4b068
refs/heads/main
<file_sep>module.exports = function calcSalesTax(price){ console.log((price * 0.07).toFixed(2)) } <file_sep>// Calculate the sum of numbers in an array of numbers let array = [2, 4, 6, 8] let total = 0 for (let i = 0; i < array.length; i++){ total += array[i] } console.log(total)<file_sep>// Create a function that will convert from Celsius to Fahrenheit function celciusToFahrenheit(tempC){ let tempF = (tempC * 1.8 + 32) console.log(tempF) } celciusToFahrenheit(18)
bdabadac5eea5a7fd0326c1ca0a16341d13cc571
[ "JavaScript" ]
3
JavaScript
LSilva30/Day04
614e0be550ac498f93b3715db16af44e1f010ac4
2861c149a68e0567edcd733283735b3a4a81af68
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head w3-include-html="head.xml"> <!--<script src="js/w3data.js "></script>--> <script src="http://www.w3schools.com/lib/w3data.js "></script> <script> w3IncludeHTML(); </script> </head> <body> <title>Our History</title> <!-- NAVBAR ================================================== --> <nav w3-include-html="mainnav.html" class="navbar navbar-inverse navbar-fixed-top" role="navigation"></nav> <div class="jumbotron fill text-center" style="background-image:url('images/Core-Values-Banner.jpg'); background-size: cover; color:white"> <h1>Our History</h1> </div> <div class="container "> <div class="container col-md-4"> <div class="panel panel-info" style="min-height: 368px;"> <div class="panel-heading"> <h3 class="panel-title">Beginnings - 2003-2004</h3> </div> <div class="panel-body"> <!--<h5><strong>Beginnings - 2003-2004</strong></h5>--> <p>Several families, who had been commuting from the south of Johannesburg to Sandton Bible Church in the Fourways area, had the vision to start a new Bible church closer to home. These families asked American missionaries with Biblical Ministries Worldwide, who had been serving at Sandton Bible Church, if they would lead the new church plant in the south.</p> <p>The initial efforts began with a series of Bible studies, and as God worked through relationships, the group expanded, and on 31 October 2004, Sunday morning services began in Glenanda.</p> </div> </div> </div> <div class="container col-md-4"> <div class="panel panel-info" style="min-height: 368px;"> <div class="panel-heading"> <h3 class="panel-title">Expansion - 2005-2009</h3> </div> <div class="panel-body"> <!--<h5><strong>Expansion - 2005-2009</strong></h5>--> <p>MountainView moved to the Sha-Mani Conference Centre in Alberton in 2005 and met there for several years. As children, youth, and ladies' and men's ministries grew, the church to almost 80 believers.</p> </div> </div> </div> <div class="container col-md-4"> <div class="panel panel-info" style="min-height: 368px;"> <div class="panel-heading"> <h3 class="panel-title">Existing Church Home - 2010-Present</h3> </div> <div class="panel-body"> <!--<h5><strong>Existing Church Home - 2010-Present</strong></h5>--> <p>We saved up for years toward the purchase of our own building, and in August of 2010, we purchased a house in Glenanda (four houses away from where MountainView began in 2004!) that had a massive living area that we could renovate into a church hall. The house has become home and is now a very busy place! God has continued to provide leadership for the church through the years from missionaries and local men. As we continue to grow, both in numbers and financially, we look forward to moving into a larger facility in the future.</p> </div> </div> </div> </div> <!-- Footer --> <footer w3-include-html="footer.html" id="footersection"></footer> <!-- jQuery --> <script src="js/jquery.js"></script> <script src="js/mvbc.js"></script> <!--<script src="js/w3data.js"></script> <script> w3IncludeHTML(); </script>--> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> </body> </html><file_sep> function getYear() { $('#copyrightdate').html(new Date().getFullYear()); } $("#navbar").load("mainnav.html"); $("#headersection").load("header.html"); $("#footersection").load("footer.html");
5816b8e0b7e44d947a3ffe3cd07c4a61be804bcc
[ "JavaScript", "HTML" ]
2
HTML
robertbravery/MVBCWeb
9b5ca88685689ea04d20d3ca26af9490ed2a5560
6b861675546bc04d914c5e4b81d72e3d0b2a6468
refs/heads/master
<file_sep>import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import './style.css'; import sedes from './sedes.png'; import contacto from './contacto.png'; import videoinformtaivo from './videoinformtaivo.png'; import { BrowserRouter as Router, Redirect, Link, Route, Switch } from "react-router-dom"; class Appdos extends Component { render() { return ( <div className="App"> <nav class="page__menu page__custom-settings menu"> <ul class="menu__list r-list"> <li class="menu__group"><Link to="/" class="menu__link r-link text-underlined">Página principal</Link></li> <li class="menu__group"><Link to="/PaginaProductos" class="menu__link r-link text-underlined">Información de productos</Link></li> <li class="menu__group"><Link to="/PaginaDeConctacto" class="menu__link r-link text-underlined">Contacto</Link></li> </ul> </nav> <header className="App-header"> <img src={sedes} className="App-logodos" alt="sedes" /> <h1 className="App-title">Sedes</h1> </header> <p className="App-intro"> Ubicaciòn de nuestra sede </p> <br /> <br /> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3859.78728754968!2d-90.45828788531881!3d14.668009579353928!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x858999096fdbd161%3A0x170e7fbdd215149!2sGuatemala!5e0!3m2!1ses!2sgt!4v1634882041863!5m2!1ses!2sgt" width="1000" height="450" allowfullscreen="" loading="lazy"> </iframe> <p className="App-intro"> Nos encontramos en la 6ta avenida 8-60 Zona 1 de la Ciudad de Guatemala. </p> <br /> <br /> <header className="App-header"> <img src={contacto} className="App-logodos" alt="contacto" /> <h1 className="App-title">Datos de contacto</h1> </header> <p className="App-intro"> Datos de contacto </p> <form class='contacto'> <div><label>Tu Nombre:</label><input type='text' value=''/></div> <div><label>Tu Email:</label><input type='text' value=''/></div> <div><label>Asunto:</label><input type='text' value=''/></div> <div><label>Mensaje:</label><textarea rows='6'></textarea></div> <div><input type='submit' value='Envia Mensaje'/></div> </form> <header className="App-header"> <img src={videoinformtaivo} className="App-logodos" alt="videoinformtaivo" /> <h1 className="App-title">Video informativo</h1> </header> <p className="App-intro"> <iframe width="1000" height="600" src="https://www.youtube.com/embed/tN6-KziOBzg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </p> <br /> </div> ); } } export default Appdos; <file_sep>import React, { Component } from 'react'; import logo from './logo.svg'; import img from './1.jpg'; import img2 from './2.jpg'; import img3 from './3.png'; import img4 from './4.jpg'; import img5 from './5.jpg'; import img6 from './6.png'; import img7 from './7.png'; import img8 from './8.png'; import img9 from './9.png'; import img10 from './10.png'; import catalogo from './catalogo.png'; import './App.css'; import './style.css'; import { BrowserRouter as Router, Redirect, Link, Route, Switch } from "react-router-dom"; class Apptres extends Component { render() { return ( <div className="App"> <nav class="page__menu page__custom-settings menu"> <ul class="menu__list r-list"> <li class="menu__group"><Link to="/" class="menu__link r-link text-underlined">Página principal</Link></li> <li class="menu__group"><Link to="/PaginaProductos" class="menu__link r-link text-underlined">Información de productos</Link></li> <li class="menu__group"><Link to="/PaginaDeConctacto" class="menu__link r-link text-underlined">Contacto</Link></li> </ul> </nav> <header className="App-header"> <img src={catalogo} className="App-logodos" alt="catalogo" /> <h1 className="App-title">Informaciòn de productos</h1> </header> <p className="App-intro"> En esta secciòn podremos encontrar los productos relacionados. </p> <section class="NovidadesSection"> <main class="mainDestacados"> <h2>Catalogo de Productos</h2> <section class="containerProdutos"> <div class="produto"> <img src={img} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 1</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> <div class="produto"> <img src={img2} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 2</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> <div class="produto"> <img src={img3} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 3</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> <div class="produto"> <img src={img4} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 4</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> <div class="produto"> <img src={img5} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 5</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> <div class="produto"> <img src={img6} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 6</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> <div class="produto"> <img src={img7} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 7</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> <div class="produto"> <img src={img8} alt="logo" /> <div class="productDescription"> <h3 class="produto__title">Producto 8</h3> <spam class="produto__price">Q90.00</spam> </div> <a href=""><i class="produto__icon fas fa-cart-plus"></i></a> </div> </section> </main> </section> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <div className="Appdos"> <div class="content-carrousel"> <figure><img src={img} alt="logo" /></figure> <figure><img src={img2} alt="logo" /></figure> <figure><img src={img3} alt="logo" /></figure> <figure><img src={img5} alt="logo" /></figure> <figure><img src={img4} alt="logo" /></figure> <figure><img src={img6} alt="logo" /></figure> <figure><img src={img7} alt="logo" /></figure> <figure><img src={img8} alt="logo" /></figure> <figure><img src={img9} alt="logo" /></figure> <figure><img src={img10} alt="logo" /></figure> </div> </div> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <Link to="/PaginaDeConctacto"><button class="btn btn-info"> Siguiente pàgina </button> </Link> </div> ); } } export default Apptres;
15de89528ef9fba86d9a386a21fd81c491b7dab3
[ "JavaScript" ]
2
JavaScript
DiegoMF123/SOPF
5386df4a8ef85c1a54fc7a08b8886afbe1aa5e63
042d0dbe932939aad85cbbabf77afc51d152fc1b
refs/heads/master
<file_sep><?php class CheckOrder { private $login_url; private $check_url; private $cookie_path; private $username; private $password; public function __construct($options) { $this->change($options); } public function change($options) { foreach ($options as $key => $value) { if (property_exists($this, $key)) { $this->$key = $value; } else { throw new Exception(sprintf('The property %s does not exists', $key)); } } } public function check($url = null) { if (!$url) { throw new Exception('You must provide url to check'); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->login_url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6'); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_path); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_path); $html = new DOMDocument(); $html->loadHTML(curl_exec($ch)); $csrf_token = $html->getElementById('csrf_token')->getAttribute('value'); if (curl_error($ch)) { throw new Exception(curl_error($ch)); } curl_setopt($ch, CURLOPT_URL, $this->check_url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array( '_username' => $this->username, '_password' => $this-><PASSWORD>, '_remember_me' => 'on', '_csrf_token' => $csrf_token ))); curl_exec($ch); if (curl_error($ch)) { throw new Exception(curl_error($ch)); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, false); curl_exec($ch); if (curl_error($ch)) { throw new Exception(curl_error($ch)); } $info = curl_getinfo($ch); curl_close($ch); unlink($this->cookie_path); return array( 'url' => $info['url'], 'http_code' => $info['http_code'] ); } } $check = new CheckOrder(array( 'login_url' => 'http://domain/login', 'check_url' => 'http://domain/login_check', 'cookie_path' => 'path/to/cookie.tx', 'username' => 'username', 'password' => '<PASSWORD>' )); echo('<pre>'); print_r($check->check('http://prgcc.salda.lt/lt/crm/order/DXN10000001190')); echo('</pre>'); class CheckOrderStatic { private static $login_url = 'http://domain/login'; private static $check_url = 'http://domain/login_check'; private static $cookie_path = 'path/to/cookie.txt'; private static $username = 'username'; private static $password = '<PASSWORD>'; public static function check($url) { if (!$url) { throw new Exception('You must provide url to check'); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, self::$login_url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6'); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_COOKIEJAR, self::$cookie_path); curl_setopt($ch, CURLOPT_COOKIEFILE, self::$cookie_path); $html = new DOMDocument(); $html->loadHTML(curl_exec($ch)); $csrf_token = $html->getElementById('csrf_token')->getAttribute('value'); if (curl_error($ch)) { throw new Exception(curl_error($ch)); } curl_setopt($ch, CURLOPT_URL, self::$check_url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array( '_username' => self::$username, '_password' => <PASSWORD>, '_remember_me' => 'on', '_csrf_token' => $csrf_token ))); curl_exec($ch); if (curl_error($ch)) { throw new Exception(curl_error($ch)); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, false); curl_exec($ch); if (curl_error($ch)) { throw new Exception(curl_error($ch)); } $info = curl_getinfo($ch); curl_close($ch); unlink(self::$cookie_path); return array( 'url' => $info['url'], 'http_code' => $info['http_code'] ); } } echo('<pre>'); print_r(CheckOrderStatic::check('http://domain/url_to_check')); echo('</pre>');
a70c11ed06e3c4662725c693e2c5e4a8d6bbcd40
[ "PHP" ]
1
PHP
sepikas-antanas/sf2urlcheck
4528a5f2bb6d4d0b9f3d9313fada60a670020457
ffc48245ee1fcb789c3dd13e164f0455009d19b2
refs/heads/master
<file_sep>#include <iostream> #include <string> #include <iomanip> #include <cmath> #include <fstream> using namespace std; const int row = 20; const int col = 20; const int times_to_go = 20; const int Change = 1; const double Threshold = .10; void Initialize_Plate(double table[row][col]) { for (int row = 0; row < times_to_go; row++) { for (int col = 0; col < times_to_go; col++) { table[row][col] = 0; if (row == 0 || row == 19) { table[row][col] = 100; table[row][col] = 100; } if (col == 0 || col == 19) { table[row][col] = 0; table[row][col] = 0; } } } } void Print_Plate(double table[row][col]) { for (int row = 0; row < times_to_go; row++) { for (int col = 0; col < times_to_go; col++) { cout << fixed << setprecision(2) << table[row][col] << "," << "\t"; } cout << endl; } } void Average_Plate(double table[row][col]) { double top_value = 0; double right_value = 0; double bottom_value = 0; double left_value = 0; double average_value = 0; for (int row = 1; row < (times_to_go - Change); row++) { for (int col = 1; col < (times_to_go - Change); col++) { top_value = table[row - Change][col]; right_value = table[row][col + Change]; bottom_value = table[row + Change][col]; left_value = table[row][col - Change]; average_value = ((top_value + right_value + bottom_value + left_value) / 4); table[row][col] = average_value; } } } void Final_Hot_Plate(double table[row][col]) { double top_value = 0; double right_value = 0; double bottom_value = 0; double left_value = 0; double new_average_value = 0; double old_average = 0; double greatest_difference = 0; do { greatest_difference = 0; for (int row = 1; row < (times_to_go - Change); row++) { for (int col = 1; col < (times_to_go - Change); col++) { old_average = table[row][col]; top_value = table[row - Change][col]; right_value = table[row][col + Change]; bottom_value = table[row + Change][col]; left_value = table[row][col - Change]; new_average_value = ((top_value + right_value + bottom_value + left_value) / 4); table[row][col] = new_average_value; if (abs(old_average - new_average_value) > greatest_difference) { greatest_difference = (abs(old_average - new_average_value)); } } } } while (greatest_difference > Threshold); } void Export_Plate(double table[row][col]) { ofstream HotPlateExport; HotPlateExport.open("Final.csv"); for (int row = 0; row < times_to_go; row++) { for (int col = 0; col < times_to_go; col++) { HotPlateExport << table[row][col] << ","; } HotPlateExport << endl; } HotPlateExport.close(); } int main() { cout << "Initialized Hot Plate" << endl; cout << endl; double table[row][col]; Initialize_Plate(table); Print_Plate(table); cout << endl; cout << endl; cout << endl; cout << "Updated Elements Once" << endl; cout << endl; Average_Plate(table); Print_Plate(table); cout << endl; cout << endl; cout << endl; cout << "Stabilized Hot Plate" << endl; cout << endl; Final_Hot_Plate(table); Print_Plate(table); Export_Plate(table); system("pause"); return 0; } <file_sep># Hot-Plate Compute the steady state temperature distribution over a piece of metal.
6166669e6354a626e1524cd4ce2b079b25152337
[ "Markdown", "C++" ]
2
C++
BryceTrueman/Hot-Plate
10ba3486edfe7ae3fadab937c31d2c353c9c34c4
0d1c204ad3db95f450da417090c0036bbc41e07f
refs/heads/master
<repo_name>AaronMuriel/mygit<file_sep>/test.py #!/usr/bin/python # -*- coding:utf-8 -*- import sys import os os.mkdir(sys.argv[1]) os.mkdir(sys.argv[2]) 11111
7cfcb6dc9ef01ed77d8f0c63e9c05b0475be9765
[ "Python" ]
1
Python
AaronMuriel/mygit
e6ec5a277a6ae914b255ffc5874788517359d8b8
d1255237359b975186d64a663c08e76f836dc646
refs/heads/master
<file_sep>class Timer attr_reader :hours, :minutes, :seconds, :frames def initialize @hours = 0 @minutes = 0 @seconds = 0 @frames = 0 @last_time = Gosu::milliseconds() end def update if @frames > 59 @frames = 0 else @frames += 1 end if (Gosu::milliseconds - @last_time) / 1000 == 1 @seconds += 1 @last_time = Gosu::milliseconds() end if (@seconds + 1) % 61 == 0 @seconds = 0 @minutes += 1 end if @minutes > 59 @hours += 1 @minutes = 0 end end end <file_sep>class Bullet attr_accessor :x, :y def initialize(window, player, time, icon) @window = window @which_player = player.x @x = player.x @y = player.y @x_vel = 0.1 @y_vel = 0.1 @x_acc = 100 @y_acc = 10 @weight = 0.5 @angle = player.angle @time = time # binding.pry @bullet_img = Gosu::Image.new(@window, icon, true) end def update move end def move if @which_player > 900 @x -= @x_vel * Math.cos(-@angle * (Math::PI / 180)) * @x / @x_acc if @angle > 0 @y += -(0.5 * @y_acc + @y_vel * Math.sin(-@angle * (Math::PI / 180))) end else @x += @x_vel * Math.cos(@angle * (Math::PI / 180)) * @x / @x_acc if @angle < 0 @y += -(0.5 * @y_acc + @y_vel * Math.sin(@angle * (Math::PI / 180))) end end @x_acc += 5 @y_acc -= 0.25 * @weight @x_vel += 0.1 @y_vel -= 0.1 @weight += 0.0025 end def draw @bullet_img.draw(@x, @y, 2) end def bounds BoundingBox.new(@x, @y, 18, 12) end def fire(time) @x += @x * time # @y -= 1 end def fire_alt @x -= 1 # @y += 1 end end <file_sep>class Player attr_accessor :x, :y, :angle, :health def initialize(window, x, y, icon) @window = window @x = x @y = y @angle = 0 @move_right = false @move_left = false @icon = Gosu::Image.new(@window, icon, true) @health = 100 end def draw # @icon.draw(@x, @y, 0) @icon.draw_rot(@x, @y, 0, @angle, 0.1, 0.2) end def update if @move_right == true @x += 1 end end def bounds BoundingBox.new(@x, @y, 40, 42) end def move_left if @x < 0 @x = 0 else @x = @x - 0.5 end end def move_right if @x == 1035 @x = 1035 else @x = @x + 0.5 end end def rotate_up if @angle < 15 @angle += 0.5 @y -= 0.1 end end def rotate_down if @angle > -45 @angle -= 0.5 @y += 0.1 end end def rotate_up_alt if @angle < 45 @angle += 0.5 @y -= 0.1 @x += 0.1 end end def rotate_down_alt if @angle > -15 @angle -= 0.5 @y += 0.1 @x -= 0.1 end end def hit_by?(bullet) Gosu::distance(@x, @y, bullet.x, bullet.y) < 50 end def minus_health @health -= 1 end end <file_sep>require 'gosu' require 'pry' require 'date' require_relative 'player' require_relative 'bullet' require_relative 'bounding_box' require_relative 'timer' class GameWindow < Gosu::Window SCREEN_WIDTH = 1072 SCREEN_HEIGHT = 720 attr_accessor :player1, :width def initialize super(SCREEN_WIDTH, SCREEN_HEIGHT, false) self.caption = "TankBound" @player1 = Player.new(self, 10, SCREEN_HEIGHT - 50, "img/boy.png") @player2 = Player.new(self, SCREEN_WIDTH - 50, SCREEN_HEIGHT - 50, "img/girl.png") @bg_img = Gosu::Image.new(self, 'img/bg.jpg', true) @bullets = [] @bullets1 = [] @bullets2 = [] end def update @bullets.each do |bullet| bullet.update end if button_down? Gosu::Button::KbA @player1.move_left end if button_down? Gosu::Button::KbD @player1.move_right end if button_down? Gosu::Button::KbLeft @player2.move_left end if button_down? Gosu::Button::KbRight @player2.move_right end if button_down? Gosu::Button::KbW @player1.rotate_up end if button_down? Gosu::Button::KbS @player1.rotate_down end if button_down? Gosu::Button::KbUp @player2.rotate_up_alt end if button_down? Gosu::Button::KbDown @player2.rotate_down_alt end if button_down? Gosu::Button::KbSpace @time = Timer.new @bullet1 = Bullet.new(self, @player1, @time, "img/bullet1.png") @bullets1 << @bullet1 @bullets << @bullet1 end if button_down? Gosu::Button::KbRightShift @time = Timer.new @bullet2 = Bullet.new(self, @player2, @time, "img/bullet2.png") @bullets2 << @bullet2 @bullets << @bullet2 end @bullets2.each do |bullet| if @player1.hit_by?(bullet) @player1.minus_health end end @bullets1.each do |bullet| if @player2.hit_by?(bullet) @player2.minus_health end end end def draw @bg_img.draw(0, 0, 0) @player1.draw @player2.draw @bullets.each do |bullet| bullet.draw end end end GameWindow.new.show
608533138175cbbeb7a91346913e9a7246592501
[ "Ruby" ]
4
Ruby
momentmaker/tank_bound
67abcd625956713070c187880963755b4c6e2169
1089aa30c2271fc77eda1c8623bb3911e5c91dfc
refs/heads/master
<repo_name>jumorean/latex_examples<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.17) project(latex_example) set(CMAKE_CXX_STANDARD 14) add_executable(untitled main.cpp)<file_sep>/script/build.sh xelatex paper.tex
d6f950cc382aa36c20410340e9ae536e04a1bcee
[ "CMake", "Shell" ]
2
CMake
jumorean/latex_examples
c013f7af4320548570cb51a90f0e0f18c80b6b6d
fb5b96e747a72886989eb1fc077d5fa40be36263
refs/heads/master
<file_sep><?php abstract class Figure { protected $_params; abstract public function draw(); public function setParams(array $params) { $this->_params = $params; } } class Square extends Figure{ public function draw() { echo 'Square'; } } class Triangle extends Figure { public function draw() { echo 'Triangle'; } } class Circle extends Figure { public function draw() { echo 'Circle'; } } $figures = [ 'square'=>['params'=>[23,43,54,76]], 'triangle'=>['params'=>[23,43,54,76]], 'circle'=>['params'=>[23,43,54,76]], ]; foreach ($figures as $figure=>$params){ $className = ucfirst($figure); if(class_exists($className)) { $class = new $className(); $class->setParams($params['params']); $class->draw(); } }<file_sep>FROM php:7.3-fpm WORKDIR /var/www CMD ["php-fpm"]
c746971cdff0f9fff0458d7ee6ee2bfebf49ea9f
[ "Dockerfile", "PHP" ]
2
PHP
Kshevchenko94/factory
73eddca2410c23817f8a76f12b6623efa331c836
2416402bd1a7232301fff2ff146c8d101b5940b3
refs/heads/master
<file_sep>// // ViewController.swift // Social Justice // // Created by Girls Who Code on 8/1/18. // Copyright © 2018 Girls Who Code. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } /*override func viewWillAppear(_ animated: Bool) { print("I'm here!") }*/ /*override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.isHidden = true; print("I'm here!") }*/ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep># lai GWC APP <file_sep>// // InputViewController.swift // Social Justice // // Created by Girls Who Code on 8/1/18. // Copyright © 2018 Girls Who Code. All rights reserved. // import UIKit import CoreData class InputViewController: UIViewController { @IBOutlet weak var textArea: UITextField! @IBAction func enter(_ sender: Any) { if(textArea.text != " "){ let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let newTask = Task(context: context) newTask.taskName = textArea?.text (UIApplication.shared.delegate as! AppDelegate).saveContext() } } /*override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.isHidden = false; }*/ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: false) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // ContentViewController.swift // Social Justice // // Created by Girls Who Code on 7/30/18. // Copyright © 2018 Girls Who Code. All rights reserved. // import UIKit class ContentViewController: UIViewController { var topics: String = "" @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentText: UITextView! @IBOutlet weak var image: UIImageView! @IBAction func link1(_ sender: Any) { if(topics == "Human Trafficking"){ UIApplication.shared.open (URL( string: "https://www.dosomething.org/us/facts/11-facts-about-human-trafficking")! as URL, options:[:], completionHandler: nil) } else if(topics == "Police Brutality"){ UIApplication.shared.open (URL( string: "https://vittana.org/42-shocking-police-brutality-statistics")! as URL, options:[:], completionHandler: nil) } else if(topics == "Suicide / Self Harm"){ UIApplication.shared.open (URL( string: "https://afsp.org/about-suicide/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Sexual Assualt"){ UIApplication.shared.open (URL( string: "https://www.equalrights.org/legal-help/know-your-rights/sexual-harassment-at-school/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Cyber Bullying"){ UIApplication.shared.open (URL( string: "https://www.stopbullying.gov/cyberbullying/what-is-it/index.html")! as URL, options:[:], completionHandler: nil) } else{ UIApplication.shared.open (URL( string: "https://www.fairus.org/issue/illegal-immigration/truth-about-zero-tolerance-and-family-separation-what-americans-need-know")! as URL, options:[:], completionHandler: nil) } } @IBOutlet weak var link1Label: UIButton! @IBOutlet weak var link2Label: UIButton! @IBAction func link2(_ sender: Any) { if(topics == "Human Trafficking"){ UIApplication.shared.open (URL( string: "https://www.antislavery.org/slavery-today/human-trafficking/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Police Brutality"){ UIApplication.shared.open (URL( string: "https://copcrisis.com/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Suicide / Self Harm"){ UIApplication.shared.open (URL( string: "https://www.medicinenet.com/suicide/article.htm#what_is_suicide")! as URL, options:[:], completionHandler: nil) } else if(topics == "Sexual Assualt"){ UIApplication.shared.open (URL( string: "https://www.theatlantic.com/education/archive/2017/08/the-younger-victims-of-sexual-violence-in-school/536418/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Cyber Bullying"){ UIApplication.shared.open (URL( string: "https://cyberbullying.org")! as URL, options:[:], completionHandler: nil) } else{ UIApplication.shared.open (URL( string: "https://www.isidewith.com/poll/3493858070")! as URL, options:[:], completionHandler: nil) } } @IBOutlet weak var link3Label: UIButton! @IBAction func link3(_ sender: Any) { if(topics == "Human Trafficking"){ UIApplication.shared.open (URL( string: "http://16days.thepixelproject.net/16-ways-to-take-action-against-human-trafficking/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Police Brutality"){ UIApplication.shared.open (URL( string: "https://www.huffingtonpost.com/ravishly/what-you-can-do-right-now_1_b_7050424.html")! as URL, options:[:], completionHandler: nil) } else if(topics == "Suicide / Self Harm"){ UIApplication.shared.open (URL( string: "https://afsp.org/take-action/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Sexual Assualt"){ UIApplication.shared.open (URL( string: "https://www.aauw.org/resource/campus-sexual-assault-tool-kit/")! as URL, options:[:], completionHandler: nil) } else if(topics == "Cyber Bullying"){ UIApplication.shared.open (URL( string: "https://www.stopbullying.gov")! as URL, options:[:], completionHandler: nil) } else{ UIApplication.shared.open (URL( string: "https://www.mother.ly/news/how-to-help-immigrant-children-separated-from-parentss/")! as URL, options:[:], completionHandler: nil) } } override func viewDidLoad() { super.viewDidLoad() getRec() } var topic: [String] = ["Human Trafficking", "Police Brutality", "Suicide / Self Harm", "Sexual Assualt", "Cyber Bullying", "Immigration"] var content: [String] = ["Human Trafficking is the action or practice of illegally transporting people from one country or area to another, typically for the purposes of forced labor or commercial sexual exploitation.", "Police brutality is the use of excessive and/or unnecessary force by police when dealing with civilians.", "Suicide is the act or instance of taking one’s life voluntarily and intentionally", "Sexual harassment/assault is unwelcome sexual behavior. This is more common in educational institutions such as schools and colleges because students are usually too afraid to speak up", "Cyber bullying/harassment, also known as online bullying, is the form of bullying through electronic means. In this day and age, this is a rapidly growing issue.", "After the Presidential elections in 2016, the issue of legal and illegal immigration has been very prominent. Trump’s “No Tolerance” policy has separated families and sparked many controversial topics."] var links1: [String] = ["www.dosomething.org", "hvittana.org", "afsp.org", "www.equalrights.org", "www.stopbullying.gov", "www.fairus.org"] var links2: [String] = ["www.antislavery.org", "vittana.org", "www.medicinenet.com", "www.theatlantic.com", "cyberbullying.org", "www.isidewith.com"] var links3: [String] = ["16days.thepixelproject.net", "www.huffingtonpost.com", "www.aauw.org", "afsp.org", "stopbullying.gov", "mother.ly"] var index: Int = 0 func getRec() { let size: Int = topic.count let randIndex: Int = Int(arc4random_uniform(UInt32(size))) topics = topic[randIndex] titleLabel.text = topic[randIndex] contentText.text = content[randIndex] link1Label.setTitle (links1[randIndex], for: .normal) link2Label.setTitle (links2[randIndex], for: .normal) link3Label.setTitle (links3[randIndex], for: .normal) image.image = UIImage(named: images[randIndex]) } var images: [String] = ["humanTraffic", "police", "suicide", "sexualAssualt", "cyberbullying", "immigration"] // Do any additional setup after loading the view. override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
2efbe6475dac939432f090b618667656f32fb9d9
[ "Swift", "Markdown" ]
4
Swift
christinasherpa/lai
8f1674fa38cdd79cbe7562995a6f4b9c7306d425
f6610c453fc8939e44d45d0fdbafd1f4d1c94f83
refs/heads/master
<file_sep>package gitHubDemo2; public class GitHubDemo2 { }
90047cb8874a1085bb4131c4c987d4307b9114d5
[ "Java" ]
1
Java
RichBj/GitHubDemo
c62ab305d6c2357eac102814f7ced93befc5162c
e044fda9bc60626ebb70f60675afeecc29cb9e31
refs/heads/master
<repo_name>joselee/UnityTowerDefense<file_sep>/Assets/Scripts/gui/UI.cs using UnityEngine; using System.Collections.Generic; using System.Collections; public class UI : MonoBehaviour { //private static List<GameObject> createdGameObjects // = new List<GameObject>(); private static Dictionary<string,UIObject> instances = new Dictionary<string, UIObject>(); public Camera camera; public static GameObject group; public GameObject GuiGroup; public static GameObject attach(UIObject o) { Vector2 userPosition = o.getPosition(); Vector3 correctedPosition = new Vector3( userPosition.x, userPosition.y, 1); GameObject inst = Instantiate(Resources.Load(o.getResourceName()), correctedPosition, Quaternion.identity) as GameObject; inst.transform.parent = group.transform; inst.transform.localScale = new Vector3(o.getWidth(), o.getHeight(), 1); inst.name = o.getName(); return inst; } // Use this for initialization void Start () { if ( group == null ){ group = GuiGroup; } } // Update is called once per frame void Update () { this.camera.orthographicSize = Screen.height / 2; this.camera.transform.position = new Vector3(Screen.width/2, Screen.height/2, 0); } } <file_sep>/Assets/Scripts/gui/UIObject.cs using UnityEngine; using System.Collections; public class UIObject { private int width; private int height; private string name; private string resourceName; private Vector2 position; public bool needtoCreate = false; public bool needtoUpdate = false; public bool needtoRemove = false; public UIObject(string resourceName, string name) { this.resourceName = resourceName; this.name = name; } public UIObject(string resourceName, string name, int width, int height) { this.resourceName = resourceName; this.name = name; this.width = width; this.height = height; } public void setPosition(Vector2 position) { this.position = position; } public Vector2 getPosition() { return this.position; } public void setWidth(int w){ this.width = w; } public int getWidth(){ return this.width; } public void setHeight(int h) { this.height = h; } public int getHeight(){ return this.height; } public string getName() { return name; } public void setName(string name) { this.name = name; } public string getResourceName() { return resourceName; } public void setResourceName(string resourceName) { this.resourceName = resourceName; } } <file_sep>/Assets/Scripts/AirEnemy.cs using UnityEngine; using System.Collections; public class AirEnemy : MonoBehaviour { public float Health; public float MinAltitude = 4.0f; public float MaxAltitude = 5.5f; public float MinSpeed = 20.0f; public float MaxSpeed = 25.0f; public float healthBarLength = 10.0f; private float maxHealth; private float movementSpeed; // Use this for initialization void Start () { Health = 250; maxHealth = Health; healthBarLength = Screen.width / 10; movementSpeed = Random.Range(MinSpeed, MaxSpeed); Vector3 temp = transform.position; temp.y = Random.Range(MinAltitude, MaxAltitude); transform.position = temp; } // Update is called once per frame void Update () { transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed); } public void TakeDamage (float damageAmount) { Health -= damageAmount; AdjustHealthBar(); if(Health <= 0) { explode (); return; } } private void explode() { Destroy(gameObject); } public void AdjustHealthBar() { healthBarLength = (Screen.width / 10) * (Health /(float)maxHealth); } }<file_sep>/Assets/Scripts/core/User interaction/DragGameObject.cs using UnityEngine; using System.Collections; public class DragGameObject { public static IDraggable GetDraggable(GameObject target) { // Iterate over Selectable components Component[] draggableComponents = target.GetComponents(typeof(IDraggable)); for (int i = 0; i<draggableComponents.Length; i++){ // If the class inherits draggabl inteface if (draggableComponents[i] is IDraggable) return draggableComponents[i] as IDraggable; } return null; } // Return bool that tells camera to stop or procced with moving public static bool DispatchDrag(IDraggable draggableComponent, Vector3 pos) { Ray ray = Camera.main.ScreenPointToRay(pos); Plane hPlane = new Plane(Vector3.up, Vector3.zero); float distance = 0; if (hPlane.Raycast(ray, out distance)){ Vector3 pointerPosition = ray.GetPoint(distance); return draggableComponent.OnDragMove(pointerPosition); } return false; } public static void DispatchDragStop(IDraggable draggableComponent) { draggableComponent.OnDragStop(); } } <file_sep>/Assets/Scripts/gui/UnitBar.cs using UnityEngine; using System.Collections; public class UnitBar : MonoBehaviour { private static GameObject researchButton; private static GameObject buildButton; public static bool inited = false; public Material ReseachMaterial; public Material BuildMaterial; // Movement speed in units/sec. private static float speed = 20.0f; // Time when the movement started. private static float startTime; private static float destinationPosition; private static float destinationSpeed; private static bool move = false; private static bool hideButtons = false; private static float opacity = 0.0f; public static void show() { if ( researchButton != null ){ GameObject.Destroy(researchButton); Debug.Log("removing buttons"); } if ( buildButton != null ){ GameObject.Destroy(buildButton); } int bWidth = 75; UIObject _researchButton = new UIObject("gui/research-button", "research-button", bWidth, bWidth ); _researchButton.setPosition(new Vector2(Screen.width/2 - bWidth/2,-95)); researchButton = UI.attach(_researchButton); UIObject bButton = new UIObject("gui/build-button", "build-button", bWidth, bWidth ); bButton.setPosition(new Vector2(Screen.width / 2 + bWidth/2,-95)); buildButton = UI.attach(bButton); startTime = Time.time; // Calculate the journey length. destinationPosition = 50; destinationSpeed = 10; opacity=0; move = true; hideButtons = false; } public static void hide() { destinationPosition = -95; destinationSpeed = 100; move = true; hideButtons = true; opacity = 1; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (UnitBar.researchButton != null && UnitBar.buildButton != null && move == true) { float distCovered = (Time.time - startTime) * speed; float fracJourney = distCovered/destinationSpeed; Vector3 destinationResearch = new Vector3(researchButton.transform.position.x, destinationPosition, 1); Vector3 destinationBuild = new Vector3(buildButton.transform.position.x, destinationPosition, 1); if ( hideButtons ){ opacity = opacity - 0.2f; if ( opacity < 0){ opacity = 0; } } else { opacity = opacity + 0.04f; if ( opacity > 1){ opacity = 1; } } researchButton.renderer.materials[0].SetFloat("_Alpha",opacity); buildButton.renderer.materials[0].SetFloat("_Alpha",opacity); researchButton.transform.position = Vector3.Lerp(researchButton.transform.position,destinationResearch, fracJourney); buildButton.transform.position = Vector3.Lerp(buildButton.transform.position, destinationBuild, fracJourney); if ( destinationResearch == researchButton.transform.position ){ opacity = 1; move = false; } } } } <file_sep>/README.md UnityTowerDefense ================= Tower defense for learning Unity. <file_sep>/Assets/Scripts/core/Building.cs using UnityEngine; using System.Collections; using System; public abstract class Building : MonoBehaviour, ISelectable, IDraggable { private bool unitSelected = false; private Vector3 lastValidPosition; private bool currentPositionValid = true; private bool upgradeButtonShown = false; private GameObject upgradeButton; private GameObject buildButton; void Start() { lastValidPosition = gameObject.transform.position; } void Update() { if ( upgradeButton) { //UI.animateFromBottom(upgradeButton,0); } } private Vector3 dragStartPosition = Vector3.zero; private Vector3 dragStartUnitPosition = Vector3.zero; // Dragging public bool OnDragMove(Vector3 position) { if (unitSelected) { if ( dragStartPosition == Vector3.zero ){ dragStartPosition = position; } if ( dragStartUnitPosition == Vector3.zero) { dragStartUnitPosition = transform.position; } float xDiff = position.x - dragStartPosition.x; float zDiff = position.z - dragStartPosition.z; transform.position = dragStartUnitPosition + position - dragStartPosition; Debug.Log("SELECTED"); return true; } return false; } // Dragging stopped public void OnDragStop() { dragStartPosition = Vector3.zero; dragStartUnitPosition = Vector3.zero; if(!currentPositionValid) { gameObject.transform.position = lastValidPosition; } else { lastValidPosition = gameObject.transform.position; } } // Selecting unit public void OnSelect() { //showInfoButton.Show(); SelectGameObject.HighlightObject (gameObject); UnitBar.show(); unitSelected = true; } // Deselecting unit public void OnDeselect() { //showInfoButton.Hide(); SelectGameObject.UnHightlightObject (gameObject); unitSelected = false; UnitBar.hide(); } public bool IsSelected { get{return unitSelected;} set{unitSelected = value;} } public bool CurrentPositionValid { get{return currentPositionValid;} set{currentPositionValid = value;} } } <file_sep>/Assets/Scripts/MapBoundary.cs using UnityEngine; using System.Collections; public class MapBoundary : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerExit(Collider collisionObject){ if(collisionObject.gameObject.tag == "Air_Enemy" || collisionObject.gameObject.tag == "Enemy") { print (collisionObject.gameObject.name); Destroy(collisionObject.gameObject); } } } <file_sep>/Assets/Scripts/core/User interaction/SelectGameObject.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class SelectGameObject { // Current list of selected object private static List<ISelectable> selected = new List<ISelectable>(); // Deselect all object public static void DeselectAll() { for (int a = 0; a<selected.Count; a++){ ISelectable cSelected = selected[a]; cSelected.OnDeselect(); selected.Remove(cSelected); } } public static bool SelectionPresent() { return selected.Count > 0; } public static ISelectable GetObjectByIndex(int index) { return index < selected.Count ? selected[index] : null; } public static void Dispatch(GameObject target) { // Iterate over Selectable components Component[] selectableComponents = target.GetComponents(typeof(ISelectable)); for (int i = 0; i<selectableComponents.Length; i++){ // If the class inherits selectable inteface if (selectableComponents[i] is ISelectable){ ISelectable selectableObject = selectableComponents[i] as ISelectable; ISelectable alreadySelected = null; // In future, we may allow groups to be selected // But for now, let's just reset em all for (int a = 0; a<selected.Count; a++){ ISelectable cSelected = selected[a]; if ( alreadySelected != cSelected){ cSelected.OnDeselect(); selected.Remove(cSelected); } } // call OnSelect method // First check if it's there alread // We don't want to select it twice, do we? if ( selected.Contains(selectableObject) == false) { selectableObject.OnSelect(); // Adding it to the list of selected object selected.Add(selectableObject); alreadySelected = selectableObject; } else { alreadySelected = selectableObject; } } } } public static void HighlightObject(GameObject objectToSelect) { // Assigns a material named "Assets/Resources/SelectedIndicator_Material" to the object. Material indicatorMaterial = Resources.Load("SelectedIndicator_Material", typeof(Material)) as Material; GameObject selectedIndicator = objectToSelect.transform.Find ("SelectedIndicator").gameObject; selectedIndicator.renderer.material = indicatorMaterial; } public static void UnHightlightObject(GameObject objectToDeSelect) { Material[] emptyMaterialsList = new Material[0]; GameObject selectedIndicator = objectToDeSelect.transform.Find ("SelectedIndicator").gameObject; selectedIndicator.renderer.materials = emptyMaterialsList; } } <file_sep>/Assets/Scripts/gui/Menu.cs using UnityEngine; using System.Collections; public class Menu : MonoBehaviour { GameObject selectedObject; string cannonButtonCaption = "Cannon"; public GameObject Cannon; public GameObject AirEnemy; public GameObject MissileLauncher; public GUISkin skin; private Texture2D testButton; private Rect niceButtonRect = new Rect (50, Screen.height - 100, 100,100); // Use this for initialization void Start () { } bool cannonButton(string text) { return GUI.Button(new Rect(10,Screen.height - 100,100,100), text); } bool missileButton() { return GUI.Button(new Rect(120,Screen.height - 100,120,100), "MissileLauncher"); } /* void OnGUI(){ //GUI.skin = skin; //testButton = (Texture2D) Resources.Load("people", typeof(Texture2D)); //if ( GUI.Button (niceButtonRect, testButton) ) { // Debug.Log("OLOLO"); //} // Debug.Log("Clicked"); //} GUI.Box (new Rect (0,Screen.height - 100,Screen.width,100), ""); if(cannonButton(cannonButtonCaption)) { // Storing the object selectedObject = Cannon; Debug.Log("Cannong selected"); } if(missileButton()) { selectedObject = MissileLauncher; Debug.Log("MissileLauncher selected"); } if(GUI.Button(new Rect(300,Screen.height - 100,120,100), "Air Enemy")) { selectedObject = AirEnemy; Debug.Log("AirEnemy selected"); } } */ // Update is called once per frame void Update () { Rect a = new Rect (0, 0, 150, 150); if (niceButtonRect.Contains(Input.mousePosition)) { Debug.Log("Clicked"); } if(Input.GetMouseButtonDown(0) && selectedObject){ RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Plane hPlane = new Plane(Vector3.up, Vector3.zero); float distance = 0; if (hPlane.Raycast(ray, out distance)){ Instantiate(selectedObject,ray.GetPoint(distance), transform.rotation); selectedObject = null; //Debug.Log(selectedObject.GetComponent<cannon>()); } } } } <file_sep>/Assets/Scripts/core/Unit.cs using UnityEngine; using System.Collections; public abstract class Unit : MonoBehaviour, ISelectable { private bool unitSelected = false; void Start () { } void Update () { } public void OnSelect() { SelectGameObject.HighlightObject (gameObject); unitSelected = true; } public void OnDeselect() { SelectGameObject.UnHightlightObject (gameObject); unitSelected = false; } public bool IsSelected { get{return unitSelected;} set{unitSelected = value;} } } <file_sep>/Assets/Scripts/core/UserInput.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class UserInput : MonoBehaviour { private bool lockCameraMovement = false; private Vector3 hitPosition = Vector3.zero; private Vector3 cameraStartPosition = Vector3.zero; private Vector3 cameraMovePosition = Vector3.zero; public float defaultCameraY = 100; private Vector3 lastCameraPosition = Vector3.zero; // Used to calculate camera velocity private Vector3 cameraVelocity = Vector3.zero; // Used to smoothly decelerate camera private bool smoothToStop = false; // Flag that tells whether the camera should decelerate or not public float momentum = 9.0f; // Determines how long it takes for the camera to stop private float deadZoneThreshold = 30f; private bool withinDeadZone = true; private Vector3 deadZoneLeavePosition = Vector3.zero; void Awake () { Application.targetFrameRate = 60; } void Start () { Camera.main.transform.position = new Vector3 (Camera.main.transform.position.x, defaultCameraY, Camera.main.transform.position.z); } void Update () { bool userFingerUp = false; bool userFingerDown = false; bool userFingerPressed = false; Vector3 pointerPosition = Vector3.zero; if (Input.touchCount == 0) { userFingerUp = Input.GetMouseButtonUp (0); userFingerDown = Input.GetMouseButtonDown (0); userFingerPressed = Input.GetMouseButton (0); pointerPosition = Input.mousePosition; } else { if (Input.touchCount == 1) { userFingerUp = Input.GetTouch (0).phase == TouchPhase.Ended; userFingerDown = Input.GetTouch (0).phase == TouchPhase.Began; userFingerPressed = Input.GetTouch (0).phase == TouchPhase.Moved; pointerPosition = Input.GetTouch (0).position; } } selectAndDrag (pointerPosition, userFingerUp, userFingerDown, userFingerPressed); if (!lockCameraMovement) { moveCamera (userFingerUp, userFingerDown, userFingerPressed, pointerPosition); } } void moveCamera (bool userFingerUp, bool userFingerDown, bool userFingerPressed, Vector3 pointerPosition) { if (userFingerDown) { hitPosition = pointerPosition; cameraStartPosition = Camera.main.transform.position; cameraVelocity = Vector3.zero; smoothToStop = false; } if (userFingerPressed && !withinDeadZone) { cameraVelocity = Vector3.zero; smoothToStop = false; // Our camera is rotated 90degrees on the X axis.. so Z axis and Y axis are inverted. pointerPosition.z = hitPosition.z = deadZoneLeavePosition.z = cameraStartPosition.y; // Add the offset of the deadZone, so that the camera doesn't suddenly jump 30f when it starts moving. Vector3 deadZoneOffset = deadZoneLeavePosition - hitPosition; hitPosition += deadZoneOffset; // Calculating camera shift Vector3 direction = Camera.main.ScreenToWorldPoint (pointerPosition) - Camera.main.ScreenToWorldPoint (hitPosition); direction *= -1; Vector3 calculatedPosition = cameraStartPosition + direction; cameraMovePosition = new Vector3 (calculatedPosition.x, defaultCameraY, calculatedPosition.z); Camera.main.transform.position = cameraMovePosition; cameraVelocity = (Camera.main.transform.position - lastCameraPosition); lastCameraPosition = cameraMovePosition; } // Finger lifted after dragging camera.. check if we need to decelerate. if (userFingerUp && cameraVelocity != Vector3.zero) { smoothToStop = true; } if(smoothToStop) { Vector3 newVelocity = cameraVelocity - (cameraVelocity / momentum); float newXPosition = Camera.main.transform.position.x + newVelocity.x; float newZPosition = Camera.main.transform.position.z + newVelocity.z; Camera.main.transform.position = new Vector3(newXPosition, defaultCameraY, newZPosition); cameraVelocity = newVelocity; if(cameraVelocity == Vector3.zero) { smoothToStop = false; } } } /*----- Moving a draggable object below ------*/ private IDraggable draggableComponent = null; private Vector3 latestDragCameraPosition; private Vector3 latestFingerDownPosition; private bool draggingOccured = false; private Vector3 terrainPointed; void selectAndDrag (Vector3 pointerPosition, bool userFingerUp, bool userFingerDown, bool userFingerPressed) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay (pointerPosition); if (Physics.Raycast (ray, out hit)) { if (userFingerDown) { latestFingerDownPosition = pointerPosition; withinDeadZone = true; if (hit.transform.gameObject.name == "Terrain") { terrainPointed = pointerPosition; } draggableComponent = DragGameObject.GetDraggable (hit.transform.gameObject); if (draggableComponent != null && SelectGameObject.GetObjectByIndex (0) == draggableComponent) { lockCameraMovement = true; } else { lockCameraMovement = false; } } // Once we leave the deadzone, we don't check this anymore until the next touch/mouse down. if(userFingerPressed && withinDeadZone) { float draggedDistance = Vector3.Distance(latestFingerDownPosition, pointerPosition); if(draggedDistance > deadZoneThreshold) { withinDeadZone = false; deadZoneLeavePosition = pointerPosition; } } if (userFingerUp) { // Deselect all objects if (hit.transform.gameObject.name == "Terrain") { if (withinDeadZone) { SelectGameObject.DeselectAll (); } } // If we have not move a screen if (withinDeadZone) { SelectGameObject.Dispatch (hit.transform.gameObject); } if (draggableComponent != null && draggingOccured) { DragGameObject.DispatchDragStop (draggableComponent); draggingOccured = false; } draggableComponent = null; withinDeadZone = true; } } if (draggableComponent != null) { if (!withinDeadZone) { lockCameraMovement = DragGameObject.DispatchDrag (draggableComponent, pointerPosition); draggingOccured = lockCameraMovement; } } else { lockCameraMovement = false; } latestDragCameraPosition = pointerPosition; } }
d9d8920104dfc65f6db53c656f02795bb0808b05
[ "Markdown", "C#" ]
12
C#
joselee/UnityTowerDefense
ef77e0e2e92900f5e90ccda53da180301f9b3dc3
989403b40a23373b8ce778f4fb38330db8855ad9
refs/heads/main
<file_sep>import Resizer from 'react-image-file-resizer' export const resizeImage = ( image: Blob, width = 700, height = 600 ): Promise<string | Blob | File | ProgressEvent<FileReader>> => new Promise((resolve) => { Resizer.imageFileResizer( image, width, height, 'JPEG', 100, 0, (uri) => { resolve(uri) }, 'base64' ) })
7f4c438d21388f50a2d18a0b67cb1bca0e32522f
[ "TypeScript" ]
1
TypeScript
sayog4/ts-nextjs-ecommerce
dd4e3beed4fbaf14dfdc6b88644ff74c66be7bfc
d899cedab08dc61c98d0fded3645cd70cb69315b
refs/heads/master
<repo_name>BenjaminRojas/Laboratorio1<file_sep>/E6.c /* Definir las variables. Indicar que mientras a uno se le suma uno, al otro se le resta uno. Imprimir el resultado obtenido. Retornar a 0. */ #include <stdio.h> int main () { int kilometro_1 = 190; int kilometro_2 = 250; while (kilometro_1 != kilometro_2){ kilometro_1 ++; kilometro_2 --; } printf ("Los autos se encontrarán en el kilometro: %d", kilometro_1); return 0; } <file_sep>/E1.c /* Definición de variables. Imprimir que si el valor es igual a "f", el ciclo terminará. Ingresar los números 1,2 o 3 para votar por el candidato que tengo asignado dicho número. Si se ingresa un número distinto, se contabilizará el voto como nulo. Cerrar el programa con la letra "f". Imprimir los votos obtenidos por cada candidado y los votos nulos. Imprimir quién fue el ganador. Definir variables para sacar el porcentaje de los votos obtenidos por los candidatos y los votos nulos. Sacar el porcentaje con la fórmula expresada. Imprimir los resultados obtenidos anteriormente. Retornar a 0. */ #include <stdio.h> int main () { float Juanito_Alcachofa = 0, Aquiles_Baeza = 0, Otto_Van_Choton = 0, nulo = 0, Total_de_votos; float porcentaje_Juanito_Alcachofa, porcentaje_Aquiles_Baeza, porcentaje_Otto_Van_Choton, porcentaje_nulo; float porcentaje = 100; char x; printf ("Para salir ingrese f\n"); printf ("Ingrese el número de su candidato: \n"); while (x != 'f'){ scanf ("%c", &x); if (x == '1'){ Juanito_Alcachofa++; } else if (x == '2'){ Aquiles_Baeza++; } else if (x == '3'){ Otto_Van_Choton++; } else if (x != 'f'){ nulo++; } while(getchar()!='\n'); } printf ("Los votos obtenidos por <NAME>cachofa son: %f\n", Juanito_Alcachofa); printf ("Los votos obtenidos por <NAME> son: %f\n", Aquiles_Baeza); printf ("Los votos obtenidos por Otto Van Choton son: %f\n", Otto_Van_Choton); printf ("La cantidad de votos nulos es: %f\n", nulo); if ((Juanito_Alcachofa > Aquiles_Baeza) && (Juanito_Alcachofa > Otto_Van_Choton)){ printf ("El nuevo presidente del centro de Alumno de la carrera de Ingenierı́a Civil en Bioinformática es <NAME>"); } else if ((Aquiles_Baeza > Juanito_Alcachofa) && (Aquiles_Baeza > Otto_Van_Choton)){ printf ("El nuevo presidente del centro de Alumno de la carrera de Ingenierı́a Civil en Bioinformática es <NAME>"); } else if ((Otto_Van_Choton > Aquiles_Baeza) && (Otto_Van_Choton > Juanito_Alcachofa)){ printf ("El nuevo presidente del centro de Alumno de la carrera de Ingenierı́a Civil en Bioinformática es <NAME>"); } else if ((Otto_Van_Choton = Aquiles_Baeza) && (Otto_Van_Choton = Juanito_Alcachofa) && (Otto_Van_Choton = Aquiles_Baeza)){ printf ("Hay un empate entre los 3 candidatos\n"); } Total_de_votos = (Juanito_Alcachofa + Aquiles_Baeza + Otto_Van_Choton + nulo); porcentaje_Juanito_Alcachofa = (Juanito_Alcachofa/Total_de_votos * porcentaje); porcentaje_Aquiles_Baeza = (Aquiles_Baeza/Total_de_votos * porcentaje); porcentaje_Otto_Van_Choton = (Otto_Van_Choton/Total_de_votos * porcentaje); porcentaje_nulo = (nulo/Total_de_votos * porcentaje); printf ("El porcentaje de votos obtenidos por <NAME> es: %f\n", porcentaje_Juanito_Alcachofa); printf ("El porcentaje de votos obtenidos por Aquiles Baeza es: %f\n", porcentaje_Aquiles_Baeza); printf ("El porcentaje de votos obtenidos por Otto Van Choton es: %f\n", porcentaje_Otto_Van_Choton); printf ("El porcentaje de votos nulos es: %f\n", porcentaje_nulo); return 0; } <file_sep>/E3.c /* Definir las variables. Solicitar el precio del traje comprado. Definir si el precio del traje comprado es mayor que 2500, se le aplicará un descuento del 15%. Definir si el precio del traje comprado es menor o igual que 2500, se le aplicará un descuento del 8%. Imprimir el valor con el descuento aplicado. Retornar a 0. */ #include <stdio.h> int main () { int precio_del_traje; float dsc1, dsc2; float d1 = 0.15; float d2 = 0.08; printf ("Ingrese el precio del traje comprado: "); scanf ("%d", &precio_del_traje); dsc1 = (precio_del_traje - (precio_del_traje * d1)); dsc2 = (precio_del_traje - (precio_del_traje * d2)); if (precio_del_traje > 2500){ printf ("El valor del traje será: %f", dsc1); } if (precio_del_traje <= 2500){ printf ("El valor del traje será: %f", dsc2); } return 0; } <file_sep>/E2.c /* Definir las variables. Solicitar la cantidad de amigos de Pedro. Solicitar el monto de la comida sin IVA y sin el porcentaje destinado a la propina. Sacar el total de comensales. Sacar el valor de la cuenta con el IVA. Sacar el valor de la propina. Sacar el valor final de la cuenta. Sacar cuanto pagará cada comensal. Imprimir dicho valor. Retornar a 0. */ #include <stdio.h> int main () { int Total_de_comensales, amigos_de_Pedro, cuenta; int Pedro = 1; float Cuenta_final, Total_a_pagar, Cuenta_con_IVA, Propina; float IVA = 0.19; float propina = 0.1; printf ("Ingrese el número de amigos que comerán con Pedro: "); scanf ("%d", &amigos_de_Pedro); printf ("Ingrese el valor del consumo de los comensales: "); scanf ("%d", &cuenta); Total_de_comensales = (amigos_de_Pedro + Pedro); Cuenta_con_IVA = (cuenta + (cuenta * IVA)); Propina = (Cuenta_con_IVA * propina); Cuenta_final = (Cuenta_con_IVA + Propina); Total_a_pagar = (Cuenta_final/Total_de_comensales); printf ("El monto que deberá cancelar cada comensal será de: %.3f", Total_a_pagar); printf (" pesos"); return 0; }
be403b34c48e018a41cf33083b1b349e0942b360
[ "C" ]
4
C
BenjaminRojas/Laboratorio1
da9ddb4806872552fe15a89f1c299f6f178c0aac
56cdfa40575cbb28e44369d8950fd6c1cc4c16e8
refs/heads/master
<file_sep>import React, { Component} from "react"; import './Navbar.css' import NavItem from '../NavItem/NavItem'; import { render } from "@testing-library/react"; import Routes from './Components/Routes/Routes'; import {Link} from "react-router-dom"; <file_sep>using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using pp1_api.Api.Models; using pp1_api.Api.Services; namespace pp1_api.Api.Controllers { [ApiController] [Route("api/people")] public class PeopleController : ControllerBase { private IPeopleRepository repository; public PeopleController(IPeopleRepository peopleRepository) { repository = peopleRepository ?? throw new ArgumentNullException(nameof(peopleRepository)); } [HttpGet] public IActionResult GetPeople() { var result = repository.GetAllPeople(); if (result == null) { return NotFound(); } return Ok(result); } } }<file_sep>import React from "react"; import ResumePDFViewer from "../Components/PDFViewer/PDFViewer"; import './Resume.css' export default function Resume() { return ( <div className="Resume"> <div id="space"></div> <div className="lander"> <ResumePDFViewer /> </div> </div> ); }<file_sep>using System.Collections.Generic; using pp1_api.Api.Models; namespace pp1_api.Api.Services { public interface IPeopleRepository { IEnumerable<Person> GetAllPeople(); } }<file_sep>using System.Collections.Generic; using pp1_api.Api.Models; namespace pp1_api.Api.Services { public class PeopleRepository : IPeopleRepository { private List<Person> _people = new List<Person>() { new Person{ Id = 1, First_Name = "Brad", Last_Name = "Kaes" } }; public IEnumerable<Person> GetAllPeople() { return _people; } } }
6c260bacf3701f63ac349dc118ca08976183d2da
[ "JavaScript", "C#" ]
5
JavaScript
bkaes/PP1
1a05d2e854cd1ce9f264b4a750c56bd9b489ae2c
ac542a5b55d5e5399db05a9f613d6c69fbbedeaf
refs/heads/master
<repo_name>schmich/wordament-solver<file_sep>/solver.rb require 'set' require 'ffi/aspell' module Wordament class Solver def initialize @speller = FFI::Aspell::Speller.new('en_US') end def words(letters, min_length: nil, max_length: nil) raise if !min_length || !max_length @unmarked = true @min = min_length @max = max_length @matrix = [ letters[0..3], letters[4..7], letters[8..11], letters[12..15] ] suggested = Set.new 0.upto(3) do |y| 0.upto(3) do |x| strings(y, x) do |s| if @speller.correct? s if suggested.add? s yield s end end end end end end private def mark(marks, y, x) bit = 1 << ((y << 2) + x) @unmarked = ((marks & bit) == 0) marks | bit end def strings(y, x, path = '', marks = mark(0, y, x), &block) acc = path + @matrix[y][x] if acc.length >= @min block.call(acc) end return if acc.length >= @max n = y - 1 s = y + 1 w = x - 1 e = x + 1 nok = (n >= 0) sok = (s < 4) wok = (w >= 0) eok = (e < 4) if nok nmarks = mark(marks, n, x) if @unmarked strings(n, x, acc, nmarks, &block) end if wok nwmarks = mark(marks, n, w) if @unmarked strings(n, w, acc, nwmarks, &block) end end if eok nemarks = mark(marks, n, e) if @unmarked strings(n, e, acc, nemarks, &block) end end end if sok smarks = mark(marks, s, x) if @unmarked strings(s, x, acc, smarks, &block) end if wok swmarks = mark(marks, s, w) if @unmarked strings(s, w, acc, swmarks, &block) end end if eok semarks = mark(marks, s, e) if @unmarked strings(s, e, acc, semarks, &block) end end end if wok wmarks = mark(marks, y, w) if @unmarked strings(y, w, acc, wmarks, &block) end end if eok emarks = mark(marks, y, e) if @unmarked strings(y, e, acc, emarks, &block) end end end end end letters = ARGV[0] || 'fyulsaesessartip' puts 'Enumerating...' solver = Wordament::Solver.new solver.words(letters, min_length: 5, max_length: 10) do |word| puts word end
e4fc67e26827a70995d61b24a386f53ce702af07
[ "Ruby" ]
1
Ruby
schmich/wordament-solver
350124262e6500a908796cbbee1d7fc4b05250c1
436430e2301f99c129fc6e5788862c8ca772ad71
refs/heads/master
<file_sep>import numpy as np loaded_arr = np.load('merged_pairs.npy') trainfile = open("merged_pairs_train.txt","w") evalfile = open("merged_pairs_eval.txt","w") len_total = len(loaded_arr) subsample_ratio = 0.4 total_idxs = np.arange(len_total) subsample_idxs = np.random.choice(total_idxs, size=int(len_total * subsample_ratio), replace=False) subsample_arr = loaded_arr[subsample_idxs] len_subsample = len(subsample_arr) idxs = np.arange(len_subsample) trainidxs = np.random.choice(idxs, size=int(len_subsample*0.8),replace=False) evalidxs = np.delete(idxs, trainidxs) # testidxs = np.remove(idxs, trainidxs) # import IPython; IPython.embed() for elem in subsample_arr[trainidxs]: str1 = elem[0].replace('\n', ' ') str2 = "| [RESPONSE] " + elem[1] + '\n' trainfile.writelines(str1+str2) for elem in subsample_arr[evalidxs]: str1 = elem[0].replace('\n', ' ') str2 = "| [RESPONSE] " + elem[1] + '\n' evalfile.writelines(str1+str2) trainfile.close() evalfile.close() <file_sep>import numpy as np A = np.load('merged_pairs.npy') idxs = np.arange(len(A)) train_idxs = np.random.choice(idxs, int(len(A)*0.8), replace=False) np.random.shuffle(train_idxs) #import pdb; pdb.set_trace() test_idxs = np.delete(idxs, train_idxs) np.random.shuffle(test_idxs) print('- num_train : %d, num_eval : %d'%(len(train_idxs), len(test_idxs))) np.save('train_data.npy', A[train_idxs]) np.save('eval_data.npy', A[test_idxs])
0c3a95ef3cf5e3c5d168b545afc29d9e5e07c4ad
[ "Python" ]
2
Python
tzs930/transformers
206c1e0bb5bb0ee5cad394360a2accc8c2295344
af759adb96cf92a98d1692138c79fafd925930ad
refs/heads/master
<repo_name>imaditiagg/IOT<file_sep>/push_button/push_button.ino int LED = D4; // pin number for LED int button = D7; // pin number of button void setup() { pinMode(LED, OUTPUT); //set LED as OUTPUT pinMode(button, INPUT); //set LED as INPUT } void loop() { if(digitalRead(button)==1){ // Checking if button is high digitalWrite(LED, 1); // turn the LED 1 ON } else{ digitalWrite(LED, 0); // turn the LED 1 OFF } } <file_sep>/Blink_1_led/Blink_1_led.ino int LED = D7; int button =16; int buzzer=14; int bulb = 12; void setup() { pinMode(LED, OUTPUT); pinMode(button,INPUT); //pinMode(buzzer, OUTPUT); pinMode(bulb,OUTPUT); } void loop() { if(digitalRead(button)==0) //high brightness when push button is pressed analogWrite(bulb, 1032); else analogWrite(bulb, 255); // wait for a second /* analogWrite(LED, 255); //digitalWrite(buzzer,LOW); analogWrite(buzzer, 255); delay(1000); analogWrite(LED, 150); //digitalWrite(buzzer,HIGH); analogWrite(buzzer, 150); delay(1000);*/ } <file_sep>/MQTT_Client_Publish/MQTT_Client_Publish.ino #include <ESP8266WiFi.h> #include <MQTTClient.h> #include "dht.h" dht DHT; const char* ssid = "Aditi"; const char* password = "<PASSWORD>"; WiFiClient WiFiclient; MQTTClient MQTTclient; void connectMQTTBroker();//connect client with broker void setup() { Serial.begin(9600); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" WiFi Connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); Serial.print("connecting to MQTT broker..."); MQTTclient.begin("broker.shiftr.io", WiFiclient); connectMQTTBroker();//call } void connectMQTTBroker() { //connect to broker while (!MQTTclient.connect("aditi", "try", "try")){//client name,username,password { Serial.print("."); } Serial.println("connected"); } void loop() { MQTTclient.loop();//handle network packets if(!MQTTclient.connected()) {//if not connected connectMQTTBroker();//try to connect } DHT.read11(D7); //data read every second String temp = (String)DHT.temperature; String humidity = (String)DHT.humidity; Serial.println("Temperature is: "); Serial.println(DHT.temperature); Serial.println("Humidity is: "); Serial.println(DHT.humidity); MQTTclient.publish("Topic_Temp_Adi", (String)temp); //topic and value MQTTclient.publish("Topic_Humidity_Adi", (String)humidity); delay(1000); } <file_sep>/OLED_text/OLED_text.ino #include <Wire.h> #include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> #define OLED_ADDR 0x3C // OLED display TWI address Adafruit_SSD1306 OLED(-1); void setup() { OLED.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR); // initialize and clear display OLED.clearDisplay(); OLED.display(); OLED.setTextSize(2); //set text size OLED.setTextColor(WHITE); //set text color OLED.setCursor(10,10); //set start coordinates for printing OLED.print("ETI Labs"); //display text OLED.display(); } void loop() { } <file_sep>/thingspeak-write/thingspeak-write.ino #include "dht.h" #include <ESP8266WiFi.h> #include "ThingSpeak.h" const char* ssid = "Aditi"; const char* password = "<PASSWORD>"; unsigned long myChannelNumber = 662455; const char * myWriteAPIKey = "<KEY>"; WiFiClient WiFiclient; dht DHT; void setup() { Serial.begin(9600); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP());// ip address assigned by router or phone ThingSpeak.begin(WiFiclient); } void loop() { DHT.read11(D7); String temp = (String)DHT.temperature; String humidity = (String)DHT.humidity; Serial.println("Temperature is: "); Serial.println(DHT.temperature); Serial.println("Humidity is: "); Serial.println(DHT.humidity); ThingSpeak.setField(1, temp); //set field values ThingSpeak.setField(2, humidity); ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); delay(17000); } <file_sep>/Serial/Serial.ino void setup() { Serial.begin(9600); } void loop(){ for(int i=1;i<=100;i++) { Serial.println(i); //board to pc delay(500); } } <file_sep>/TempOnOLED/TempOnOLED.ino #include "dht.h" //incude libraries folder #define DHT11_PIN D7 dht DHT11; #include <Wire.h> #include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> #define OLED_ADDR 0x3C // OLED display TWI address Adafruit_SSD1306 OLED(-1); void setup(){ Serial.begin(9600); OLED.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR); // initialize and clear display OLED.clearDisplay(); OLED.display(); OLED.setTextSize(2); //set text size OLED.setTextColor(WHITE); //set text color OLED.setCursor(10,10); //set start coordinates for printing } void loop(){ OLED.clearDisplay(); DHT11.read11(DHT11_PIN); //read DHT11 data OLED.setCursor(10,10); OLED.print(DHT11.temperature); //display text OLED.display(); Serial.print("Temp: "); Serial.print(DHT11.temperature); // Print the temperature Serial.println("*C"); Serial.print("Relative Humidity: "); Serial.print(DHT11.humidity); // Print the humidity Serial.println("%"); delay(2000); } <file_sep>/brightnesschangeAcctoLightSensor/brightnesschangeAcctoLightSensor.ino #include <Wire.h> //to use I2C #include "TSL2561.h" TSL2561 tsl(TSL2561_ADDR_FLOAT); int bulb = 12; void setup() { pinMode(bulb,OUTPUT); Serial.begin(9600); tsl.setGain(TSL2561_GAIN_16X); // set 16x gain (for dim situations) //tsl.setGain(TSL2561_GAIN_0X); // set 16x gain (for bright situations) tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); // shortest integration time (bright light) //tsl.setTiming(TSL2561_INTEGRATIONTIME_101MS); // medium integration time (medium light) //tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS); // longest integration time (dim light) } void loop() { uint16_t x = tsl.getLuminosity(TSL2561_VISIBLE); //16 bit reading of unsigned integer Serial.println("Light intensity: " + String (x)); if( x > 1000) analogWrite(bulb,500); else{ analogWrite(bulb,250); } } <file_sep>/ScrollOLED/ScrollOLED.ino #include <Wire.h> #include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> #define OLED_ADDR 0x3C // OLED display TWI address int x=5; int y=5; Adafruit_SSD1306 OLED(-1); void setup() { OLED.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR); // initialize and clear display OLED.clearDisplay(); OLED.display(); OLED.setTextSize(2); //set text size OLED.setTextColor(WHITE); //set text color OLED.setCursor(x,y); //set start coordinates for printing OLED.print("ETI Labs"); //display text OLED.display(); } void loop() { if(x>80){ x=5; y=5; } OLED.clearDisplay(); OLED.setCursor(x,10); OLED.print("ETI Labs"); //display text OLED.display(); x=x+1; } <file_sep>/MQTT_Client_Publish/MQTT_Client_Publish (2).ino // Both publisher and subscriber are clients #include <ESP8266WiFi.h> #include <MQTTClient.h> #include "dht.h" const char* ssid = "Aditi"; const char* password = "<PASSWORD>"; WiFiClient WiFiclient; MQTTClient MQTTclient; int val=0; void connectMQTTBroker(); //connect client with broker server dht DHT; int x=1; void setup() { Serial.begin(9600); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" WiFi Connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); Serial.print("connecting to MQTT broker..."); MQTTclient.begin("broker.shiftr.io", WiFiclient); connectMQTTBroker(); //call } void connectMQTTBroker() { while (!MQTTclient.connect("aditi", "try", "try")) { // publisher name,username,password Serial.print("."); } Serial.println(" connected"); } void loop() { MQTTclient.loop(); // handle network packets of it if(!MQTTclient.connected()) { //recheck if connnect connectMQTTBroker(); } DHT.read11(D7); String temp = (String)DHT.temperature; String humidity = (String)DHT.humidity; //val++; MQTTclient.publish("Temp_Adi", (String)temp); MQTTclient.publish("Humid_Adi", (String)humidity); /*if(val==10){ val=0; }*/ delay(1000); } <file_sep>/OLED_rect/OLED_rect.ino #include <Wire.h> #include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> int i,j; #define OLED_ADDR 0x3C // OLED display TWI address Adafruit_SSD1306 OLED(-1); void setup() { OLED.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR); // initialize and clear display OLED.clearDisplay(); OLED.display(); for(i=0;i<64;i++){ //make rectangle with single pixels OLED.drawPixel(0, i, WHITE); OLED.drawPixel(127, i, WHITE); } for(j=0;j<128;j++){ OLED.drawPixel(j, 0, WHITE); OLED.drawPixel(j, 63, WHITE); } OLED.display(); OLED.setTextSize(2); //set text size OLED.setTextColor(WHITE); //set text color OLED.setCursor(10,10); OLED.print("Aditi"); OLED.display(); } void loop() { } <file_sep>/MQTT_Client_Subscribe/MQTT_Client_Subscribe.ino #include <ESP8266WiFi.h> #include <MQTTClient.h> const char* ssid = "Aditi"; const char* password = "<PASSWORD>"; WiFiClient WiFiclient; MQTTClient MQTTclient; void connectMQTTBroker(); void setup() { Serial.begin(9600); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" WiFi Connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); Serial.print("connecting to MQTT broker..."); MQTTclient.begin("broker.shiftr.io", WiFiclient); MQTTclient.onMessage(messageReceived); connectMQTTBroker(); } void connectMQTTBroker() { while (!MQTTclient.connect("adi", "try", "try")) {//subscriber name,username,password Serial.print("."); } Serial.println("connected"); MQTTclient.subscribe("Temp_Adi");//Topic ka name } void loop() { MQTTclient.loop(); if(!MQTTclient.connected()) { connectMQTTBroker(); } delay(10); } void messageReceived(String &topic, String &payload) { Serial.println("Topic: " + topic); Serial.println("Data: " + payload); } <file_sep>/DTHThingSpeak/DTHThingSpeak.ino #include "dht.h" #include <ESP8266WiFi.h> #include "ThingSpeak.h" #include <Wire.h> //to use I2C #include "TSL2561.h" TSL2561 tsl(TSL2561_ADDR_FLOAT); const char* ssid = "Aditi"; const char* password = "<PASSWORD>"; unsigned long myChannelNumber = 662455; const char * myWriteAPIKey = "<KEY>"; WiFiClient WiFiclient; dht DHT; uint32_t prevTime=0; void setup() { Serial.begin(9600); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP());// ip address assigned by router or phone ThingSpeak.begin(WiFiclient); tsl.setGain(TSL2561_GAIN_16X); // set 16x gain (for dim situations) tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); } void loop() { DHT.read11(D7); //data read every second String temp = (String)DHT.temperature; String humidity = (String)DHT.humidity; Serial.println("Temperature is: "); Serial.println(DHT.temperature); Serial.println("Humidity is: "); Serial.println(DHT.humidity); uint32_t t = millis(); //write on thingspeak after 15 seconds if((t- prevTime) > 15000){ ThingSpeak.setField(1, temp); //set field values ThingSpeak.setField(2, humidity); ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); prevTime=t; } delay(1000); //delay of 1 seconds } <file_sep>/blink/blink.ino int LED =15; int bulb=2; //executed only once void setup() { // put your setup code here, to run once: pinMode(LED,OUTPUT); pinMode(bulb,OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(LED,HIGH); digitalWrite(bulb,HIGH); delay(1000); digitalWrite(LED,LOW); digitalWrite(bulb,LOW); delay(1000); } <file_sep>/Potentiometer/Potentiometer.ino #define s1=0; #define s0=2; void setup() { // put your setup code here, to run once: pinMode(s0,OUTPUT); pinMode(s1,OUTPUT); // s1 and s0 should be 0 and 0 in case of potentiometer /*digitalWrite(s0,0); digitalWrite(s1,0);*/ Serial.begin(9600); // s1 and s0 should be 1 and 1 in case of gas sensor digitalWrite(s0,1); digitalWrite(s1,1); } void loop() { // put your main code here, to run repeatedly: uint16_t pot = AnalogRead(A0); Serial.println(pot); delay(1000); } <file_sep>/push/push.ino int LED =D8; int button = D0; int buzzer=14; void setup() { // put your setup code here, to run once: pinMode(button,INPUT); pinMode(LED,OUTPUT); pinMode(buzzer,OUTPUT); } void loop() { // put your main code here, to run repeatedly: // turn on buzzer when push button is pressed and glow LED when button is not pressed if(digitalRead(button)==0){ digitalWrite(buzzer,LOW); digitalWrite(LED,LOW); } else{ digitalWrite(LED,HIGH); digitalWrite(buzzer,HIGH); } } <file_sep>/ThingSpeak/ThingSpeak.ino #include "dht.h" #include <ESP8266WiFi.h> #include "ThingSpeak.h" #include <Wire.h> //to use I2C #include "TSL2561.h" TSL2561 tsl(TSL2561_ADDR_FLOAT); #include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> #define OLED_ADDR 0x3C // OLED display TWI address Adafruit_SSD1306 OLED(-1); const char* ssid = "Aditi"; const char* password = "<PASSWORD>"; unsigned long myChannelNumber = 662455; const char * myWriteAPIKey = "<KEY>"; WiFiClient WiFiclient; dht DHT; int count=1; uint32_t prevTime=0; void setup() { Serial.begin(9600); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP());// ip address assigned by router or phone ThingSpeak.begin(WiFiclient); tsl.setGain(TSL2561_GAIN_16X); // set 16x gain (for dim situations) tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); OLED.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR); // initialize and clear display OLED.clearDisplay(); OLED.display(); OLED.setTextSize(1); //set text size OLED.setTextColor(WHITE); //set text color OLED.setCursor(10,10); //set start coordinates for printing OLED.print("ETI Labs"); //display text OLED.display(); } void loop() { DHT.read11(D7); //data read every second OLED.clearDisplay(); String temp = (String)DHT.temperature; String humidity = (String)DHT.humidity; uint16_t x = tsl.getLuminosity(TSL2561_VISIBLE); //16 bit reading of unsigned integer Serial.println("Temperature is: "); Serial.println(DHT.temperature); Serial.println("Humidity is: "); Serial.println(DHT.humidity); Serial.println("Light intensity: " + String (x)); uint32_t t = millis(); //if((count%17)==0){ //write on thingspeak after 17 seconds if((t- prevTime) > 15000){ ThingSpeak.setField(1, temp); //set field values ThingSpeak.setField(2, humidity); ThingSpeak.setField(3, String(x)); ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); prevTime=t; } OLED.setCursor(10,10); //OLED update every second OLED.print(temp+":"+humidity+":"+String(x)); OLED.display(); delay(1000); //delay of 1 seconds count++; }
28dc731cf5497ee0dbeab4a4fe4acdfc60d8e00f
[ "C++" ]
17
C++
imaditiagg/IOT
a05fba5563e979a7e70953b3933c6ebee317b5c8
8b4c9302ed17010b76db3078a4c02644e68203d8
refs/heads/master
<file_sep>import java.util.ArrayList; /** * This class represents a Hand. */ public class GameHand { public ArrayList<Card> hand = new ArrayList<>(); // holds the cards in the hand /** * Adds a card to the hand. * @param newCard */ public void addCard(Card newCard) { hand.add(newCard); } /** * Gets how many cards are in the hand. * @return */ public int size() { return hand.size(); } /** * Gets a specific card in the hand * @param index * @return the card at index of the arraylist */ public Card getCard(int index) { return hand.get(index); } /** * Returns the value of the hand. In the case of there being an Ace added to the hand that would cause the player to Bust, the ace is changed to a 1. * @return */ public int handValue() { int value = 0; for (Card card : hand) { value += card.value(); } if (changeAceValue()) { value += 10; } return value; } private boolean hasAce() { for (Card card : hand) { if (card.value() == 1) { return true; } } return false; } public boolean changeAceValue() { int value = 0; for (Card card : hand) { value += card.value(); } boolean returnValue = false; if(hasAce() && value < 12){ returnValue = true; } return returnValue; } @Override public String toString() { String outputString = "Hand is " + hand.toString(); return outputString; } } <file_sep>import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; public class Server { private static final int DEFAULT_PORT = 8888; private static final int DEFAULT_PLAYERS_PER_TABLE = 2; private static final int DEFAULT_STARTING_MONEY = 12; private static final int DEFAULT_MINIMUM_BET = 1; private static final int DEFAULT_NUMBER_OF_DECKS = 6; private static final int DEFAULT_MINIMUM_CARDS_BEFORE_SHUFFLE = 78; private final int serverPort; private final int playersPerTable; private final int startingStakes; private final int minimumWager; private final int numberOfDecks; /** * * @param serverPort The server port * @param playersPerTable The number of players required at each table. Recommended to lower the number for testing. * @param startingStakes Number of starting stakes. * @param minimumWager Minimum wager. * @param numberOfDecks The number of decks that will be put in the deckHolder. */ public Server(int serverPort, int playersPerTable, int startingStakes, int minimumWager, int numberOfDecks) { this.serverPort = serverPort; this.playersPerTable = playersPerTable; this.startingStakes = startingStakes; this.minimumWager = minimumWager; this.numberOfDecks = numberOfDecks; } public void start() { System.out.println( "Starting server\nServer port: " + serverPort + "\nPlayers per table: " + playersPerTable + "\nStarting money: " + startingStakes + "\nMinimum bet: " + minimumWager + "\nNumber of decks: " + numberOfDecks ); ServerSocket serverSocket = null; try { System.out.println("Creating server socket"); serverSocket = new ServerSocket(serverPort); } catch (IOException e) { System.err.println("Could not start server on port " + serverPort); System.exit(1); } System.out.println("Listening on port " + serverPort); int playerCount = 1; while (true) { //Creates a Game object and adds it to its own thread. Game game = new Game(minimumWager, numberOfDecks, startingStakes, playersPerTable); Thread gameThread = new Thread(game); gameThread.setName("GameThread"); for (int i = 0; i < playersPerTable; i++) { // Allows the specified number of connections. try { Socket socket = serverSocket.accept(); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream, true); printWriter.write(playerCount); System.out.println("Received request from port " + socket.getPort()); Player newPlayer = new Player(socket, game, startingStakes, playerCount); game.addPlayer(newPlayer); Thread newPlayerThread = new Thread(newPlayer); newPlayerThread.start(); playerCount++; } catch (SocketException e) { System.out.println("Player " + playerCount + " disconnected."); game.removePlayerByID(playerCount); } catch (IOException e) { System.out.println("IOException on socket."); } } gameThread.start(); } } public static void main(String[] args) { int serverPort = DEFAULT_PORT; int playersPerTable = DEFAULT_PLAYERS_PER_TABLE; int startingMoney = DEFAULT_STARTING_MONEY; int minimumWager = DEFAULT_MINIMUM_BET; int numberOfDecks = DEFAULT_NUMBER_OF_DECKS; int minimumCardsBeforeShuffle = DEFAULT_MINIMUM_CARDS_BEFORE_SHUFFLE; if (playersPerTable < 2) { System.err.println("Number of players per table must be at least 2"); System.exit(1); } else if (startingMoney < minimumWager) { System.err.println("Amount of starting money cannot be less than minimum bet"); System.exit(1); } else if (numberOfDecks < 1) { System.err.println("Number of decks must be at least 1"); System.exit(1); } else if (minimumCardsBeforeShuffle < 0) { System.err.println("Minimum cards before shuffle cannot be less than 0"); System.exit(1); } Server server = new Server(serverPort, playersPerTable, startingMoney, minimumWager, numberOfDecks); server.start(); } } <file_sep># 21-Game A Threaded Multiplayer 21 Game This project was created for an assessment at the University of Glasgow. It is a multiplayer 21 game which utilises threading and socket programming. In it's default setting, the program requires four players to run though this can be changed at any time by altering the default settings in the Server class. First run Server.java, then run four of Client.java.
94154c7abb0fcbbc2e1b63779ebf01e67d30fb4c
[ "Markdown", "Java" ]
3
Java
mgdarroch/21-Game
0f49e0e158f47fd7301949e0d87cf9d2fb8a8c26
35d598b600fae2522b8aa00ce2c28ab1c661a098
refs/heads/master
<file_sep>import pygame import sys import time from math import fabs WIDTH = 1000 HEIGHT = 750 FPS = 30 # Задаем цвета YELLOW = (255, 215, 0) WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("My Game") all_heroes = pygame.sprite.Group() class Bullet(pygame.sprite.Sprite): def __init__(self, color, x, y, speed, damage=10, unthrough=True,huge =10): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((huge, huge)) self.image.fill(color) self.through = [] self.rect = self.image.get_rect(center=(x, y)) self.color = color self.mouse = pygame.mouse.get_pos() self.end = True self.unthrough = unthrough a = self.mouse[0] - self.rect.x b = self.mouse[1] - self.rect.y c = (a * a + b * b) ** 0.5 sin = a / c cos = b / c self.speedx = sin * speed self.speedy = cos * speed self.damage = damage def update(self): self.rect.x = self.rect.x + self.speedx self.rect.y = self.rect.y + self.speedy if 0 > self.rect.x > 720 or 0 > self.rect.y > 720: self.kill() for hero in all_heroes: if hero.rect.x - hero.rect.width // 2 < self.rect.x < hero.rect.x + hero.rect.width // 2: if hero.rect.y - hero.rect.height // 2 < self.rect.y < hero.rect.y + hero.rect.height // 2: if hero.color != self.color and hero not in self.through: hero.health -= self.damage if self.unthrough: self.kill() else: self.through.append(hero) print(hero.health) global choosing choosing = True player_color = (0, 0, 0) all_bullets = pygame.sprite.Group() class Buttons(pygame.sprite.Sprite): def __init__(self, color, active_color, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((100, 30)) self.color = color self.image.fill(color) self.active_color = active_color self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, y) def update(self): click = pygame.mouse.get_pressed() mouse = pygame.mouse.get_pos() if self.rect.x < mouse[0] < self.rect.x + self.rect.width: if self.rect.y < mouse[1] < self.rect.y + self.rect.height: self.image.fill(self.active_color) if click[0] == 1: if self.color == GREEN: globals()['player_color'] = GREEN elif self.color == RED: globals()['player_color'] = RED elif self.color == YELLOW: globals()['player_color'] = YELLOW globals()['choosing'] = False else: self.image.fill(self.color) all_buttons = pygame.sprite.Group() class Text(pygame.sprite.Sprite): def __init__(self, text, color, width=100, height=70, size=30): # Call th e parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) self.font = pygame.font.SysFont("C:/Users/semen/PycharmProjects/gameabc/19888.ttf", size) self.textSurf = self.font.render(text, True, color) self.image = pygame.Surface((width, height)) W = self.textSurf.get_width() H = self.textSurf.get_height() self.image.blit(self.textSurf, [width / 2 - W / 2, height / 2 - H / 2]) def update(self): pass all_textes = pygame.sprite.Group() def print_text(message, x, y, font_color=(255, 255, 255), font_type="C:/Users/semen/PycharmProjects/gameabc/19888.ttf", font_size=30): font_type = pygame.font.Font(font_type, font_size) text = font_type.render(message, True, font_color) screen.blit(text, (x, y)) class Gr_ability(pygame.sprite.Sprite): def __init__(self,x,y): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((7,7)) self.image.fill(GREEN) self.color = GREEN self.rect = self.image.get_rect() self.rect.center = (x,y) self.speed = 9 self.damage = 9 self.rangehero = [x, y] def search(self): for hero in all_heroes: if (abs(hero.rect.x - self.rangehero[0]) + abs(hero.rect.y - self.rangehero[1])) > 0 and hero.color != GREEN: self.rangehero[0] = hero.rect.x self.rangehero[1] = hero.rect.y def update(self): a = self.rangehero[0] - self.rect.x b = self.rangehero[1] - self.rect.y c = (a * a + b * b) ** 0.5 or 1 sin = a / c cos = b / c self.speedx = sin * self.speed self.speedy = cos * self.speed self.rect.x = self.rect.x + self.speedx self.rect.y = self.rect.y + self.speedy if 0 > self.rect.x > 720 or 0 > self.rect.y > 720: self.kill() for hero in all_heroes: if hero.rect.x - hero.rect.width // 2 < self.rect.x < hero.rect.x + hero.rect.width // 2: if hero.rect.y - hero.rect.height // 2 < self.rect.y < hero.rect.y + hero.rect.height // 2: if hero.color != self.color : hero.health -= self.damage self.kill() all_abil = pygame.sprite.Group() class Green(pygame.sprite.Sprite): def __init__(self, order=2): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 50)) self.image.fill(GREEN) self.color = GREEN self.rect = self.image.get_rect() self.rect.center = (WIDTH / order, HEIGHT / order) self.speed = 5 self.timerbul = 0 self.timerabil = 0 self.damage = 30 self.health = 100 def update(self): if self.health <= 0: all_textes.add(Text(("death"), WHITE)) self.kill() # осуждаю keys = pygame.key.get_pressed() click = pygame.mouse.get_pressed() if keys[pygame.K_a]: self.rect.x = self.rect.x - self.speed if keys[pygame.K_d]: self.rect.x = self.rect.x + self.speed if keys[pygame.K_w]: self.rect.y = self.rect.y - self.speed if keys[pygame.K_s]: self.rect.y = self.rect.y + self.speed if click[1] == 1: if self.timerbul == 0: all_bullets.add(Bullet(GREEN, self.rect.x, self.rect.y, 20, damage=self.damage)) self.timerbul = time.time() else: if time.time() - self.timerbul > 2: self.timerbul = time.time() bullet = Bullet(GREEN, self.rect.x, self.rect.y, 20, damage=self.damage) all_bullets.add(bullet) ability = (Gr_ability(self.rect.x, self.rect.y)) ability.search() if self.timerabil == 0: all_abil.add(ability) self.timerabil = time.time() else: if time.time() -self.timerabil >1.75: self.timerabil = time.time() all_abil.add(ability) class Red(pygame.sprite.Sprite): def __init__(self, order=2, clon_x=0): pygame.sprite.Sprite.__init__(self) self.clon_x= clon_x self.color = RED self.image = pygame.Surface((50, 50)) self.image.fill(RED) self.rect = self.image.get_rect() if self.clon_x == 0: self.rect.center = (WIDTH / order, HEIGHT / order) else: self.rect.center = (clon_x,HEIGHT / order) self.speed = 10 self.i = 0 self.health = 80 def ability(self): clon = Red(clon_x=self.rect.x-10) all_heroes.add(clon) def update(self): if self.health <= 0: print_text("game over", 360, 360) self.kill() # осуждаю keys = pygame.key.get_pressed() click = pygame.mouse.get_pressed() if keys[pygame.K_LEFT]: self.rect.x = self.rect.x - self.speed if keys[pygame.K_RIGHT]: self.rect.x = self.rect.x + self.speed if keys[pygame.K_UP]: self.rect.y = self.rect.y - self.speed if keys[pygame.K_DOWN]: self.rect.y = self.rect.y + self.speed if keys[pygame.K_r]: if self.clon_x ==0: self.ability() if click[0] == 1: if self.i == 0: all_bullets.add(Bullet(RED, self.rect.x, self.rect.y, 10)) self.i = time.time() else: if time.time() - self.i > 1.5: self.i = time.time() all_bullets.add( Bullet(RED, self.rect.x + self.rect.width // 2, self.rect.y + self.rect.height // 2, 10)) class Yellow(pygame.sprite.Sprite): def __init__(self, order=2): pygame.sprite.Sprite.__init__(self) self.color = YELLOW self.image = pygame.Surface((50, 50)) self.image.fill(self.color) self.rect = self.image.get_rect() self.rect.center = (WIDTH // order, HEIGHT / order) self.speed = 8 self.timerbul = 0 self.timerabil = 0 self.health = 120 self.damage = 10 def update(self): if self.health <= 0: print_text("game over", 360, 360) self.kill() # осуждаю keys = pygame.key.get_pressed() click = pygame.mouse.get_pressed() if keys[pygame.K_y]: self.rect.x = self.rect.x - self.speed if keys[pygame.K_i]: self.rect.x = self.rect.x + self.speed if keys[pygame.K_7]: self.rect.y = self.rect.y - self.speed if keys[pygame.K_u]: self.rect.y = self.rect.y + self.speed if keys[pygame.K_SPACE]: if self.timerbul == 0: all_bullets.add(Bullet(YELLOW, self.rect.x, self.rect.y, self.speed, damage=self.damage, unthrough=False)) self.timerbul = time.time() else: if time.time() - self.timerbul > 0.75: self.timerbul = time.time() all_bullets.add( Bullet(YELLOW, self.rect.x + self.rect.width // 2, self.rect.y + self.rect.height // 2, self.speed, damage=self.damage, unthrough=False)) if keys[pygame.K_f]: if self.timerabil == 0: all_bullets.add(Bullet(YELLOW, self.rect.x, self.rect.y, 8, damage=self.damage-7,huge=5)) self.timerabil = time.time() else: if time.time() - self.timerabil > 0.3: self.timerabil=time.time() all_bullets.add(Bullet(YELLOW, self.rect.x, self.rect.y, 8, damage=self.damage - 7, huge=5)) clock = pygame.time.Clock() all_buttons.add(Buttons(RED, pygame.Color(255, 150, 150), 400)) all_buttons.add(Buttons(GREEN, pygame.Color(150, 255, 150), 200)) all_buttons.add(Buttons(YELLOW, pygame.Color(255, 215, 150), 600)) while globals()['choosing']: clock.tick(FPS) screen.fill(WHITE) # Держим цикл на правильной скорости clock.tick(FPS) all_buttons.update() all_buttons.draw(screen) print_text("Choose a hero", 360, 350, font_color=BLACK) # Ввод процесса (события) for event in pygame.event.get(): # check for closing window if event.type == pygame.QUIT: choosing = False pygame.display.flip() if player_color == RED: player = Red() all_heroes.add(player) elif player_color == GREEN: player = Green() all_heroes.add(player) elif player_color == YELLOW: player = Yellow(order=3) all_heroes.add(player) all_heroes.add(Green()) all_heroes.add(Red(1)) # Цикл игры running = True while running: # Держим цикл на правильной скорости clock.tick(FPS) # Ввод процесса (события) for event in pygame.event.get(): # check for closing window if event.type == pygame.QUIT: running = False # Обновление all_heroes.update() all_bullets.update() all_textes.update() all_abil.update() # Рендеринг screen.fill(BLACK) all_heroes.draw(screen) all_bullets.draw(screen) all_abil.draw(screen) print_text(str(all_heroes), 0, 0, font_color=WHITE) # После отрисовки всего, переворачиваем экран pygame.display.flip() pygame.quit() <file_sep>import pygame import sys import random from time import monotonic pygame.init() button_sound = pygame.mixer.Sound("Надёжная ладонь .wav") class Game(): def __init__(self): self.screen_width = 720 self.screen_height = 720 self.red = pygame.Color(255, 0, 0) self.green = pygame.Color(0, 255, 0) self.blue = pygame.Color(0, 0, 255) self.white = pygame.Color(255, 255, 255) self.brown = pygame.Color(162, 42, 42) self.run = True self.score = 0 self.fps_controller = pygame.time.Clock() self.play_surface = pygame.display.set_mode((self.screen_width, self.screen_height)) pygame.display.set_caption("SEGAm") def control(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.run = False def print_text(self, message, x, y, font_color=(255, 255, 255), font_size=30): font_type = pygame.font.Font("C:/Users/semen/PycharmProjects/gameabc/19888.ttf", font_size) text = font_type.render(message, True, font_color) self.play_surface.blit(text, (x, y)) def pause(self): paused = True while paused: self.print_text('Please choose your color', 160, 100) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() button = Button(50, 50, pygame.Color(255, 0, 0), pygame.Color(255, 255, 255)) button2 = Button(50, 50, pygame.Color(0, 255, 0), pygame.Color(255, 255, 255)) if button.choose(200, 200, "red"): hero = Red() return hero elif button2.choose(270, 200, "green"): hero = Green() return hero if button.choosed: paused = False pygame.display.update() pygame.time.delay(100) def refresh_screen(self): pygame.display.flip() self.fps_controller.tick(23) game = Game() class Button: def __init__(self, width, height, inactive_color, active_color): self.width = width self.height = height self.inactive_color = inactive_color self.active_color = active_color self.choosed = False def choose(self, x, y, text): click = pygame.mouse.get_pressed() mouse = pygame.mouse.get_pos() if x < mouse[0] < x + self.width: if y < mouse[1] < y + self.height: pygame.draw.rect(game.play_surface, self.active_color, (x, y, self.width, self.height)) if click[0] == 1: pygame.mixer.Sound.play(button_sound) pygame.time.delay(300) self.choosed = True return True else: pygame.draw.rect(game.play_surface, self.inactive_color, (x, y, self.width, self.height)) bullets = [] class Bullet: def __init__(self, color, pos, speed): self.color = color self.x = pos[0] self.y= pos[1] self.mouse = pygame.mouse.get_pos() self.end = True a = self.mouse[0]-self.x b= self.mouse[1]-self.y c = (a*a+b*b)**0.5 sin = a/c cos = b/c self.speedx = sin*10 self.speedy = cos*10 print(a,b) def shooting(self): pygame.draw.circle(game.play_surface, self.color, (self.x, self.y), 10) self.x = self.x+self.speedx self.y = self.y+self.speedy def waiting(self): if self.x > 720 or self.x < 0: if self.y > 720 or self.y < 0: self.end = False class Red(): def __init__(self): self.color = pygame.Color(255, 0, 0) self.pos = [100, 50] self.speed = 10 self.timing = 0 def moving(self): keys = pygame.key.get_pressed() click = pygame.mouse.get_pressed() if keys[pygame.K_LEFT]: self.pos[0] = self.pos[0] - self.speed if keys[pygame.K_RIGHT]: self.pos[0] = self.pos[0] + self.speed if keys[pygame.K_UP]: self.pos[1] = self.pos[1] - self.speed if keys[pygame.K_DOWN]: self.pos[1] = self.pos[1] + self.speed if click[0] == 1: if len(bullets)<5 and monotonic()-self.timing>10: bullets.append(Bullet(self.color,self.pos,7)) self.timing = monotonic() class Green(): def __init__(self): self.color = pygame.Color(0, 255, 0) self.pos = [100, 50] self.speed = 5 def moving(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.pos[0] = self.pos[0] - self.speed if keys[pygame.K_RIGHT]: self.pos[0] = self.pos[0] + self.speed if keys[pygame.K_UP]: self.pos[1] = self.pos[1] - self.speed if keys[pygame.K_DOWN]: self.pos[1] = self.pos[1] + self.speed def play(hero): while game.run: game.control() hero.moving() game.play_surface.fill((0, 0, 0)) pygame.draw.rect(game.play_surface, hero.color, (hero.pos[0], hero.pos[1], 50, 60)) for bullet in bullets: bullet.waiting() if bullet.end: bullet.shooting() else: bullets.pop(bullets.index(bullet)) game.refresh_screen() hero = game.pause() play(hero)
016d8cfe8b8bd76ab3956cfba3d5d6c9cc87a5ce
[ "Python" ]
2
Python
reet1304/diep_pygame
726491f1e54efe4790c8b8dc6218f80543195db1
f14daa78dafc76879e641172af6f6718334b547a
refs/heads/master
<file_sep>/** * * * * */ export default { auth: { loginBtn: 'Login By LeanCloud' } }; <file_sep>/** * Created by fengxiaoping on 4/15/16. */ const AV = require('leanengine'); AV.Cloud.define('', function (req, res) { })<file_sep>// 所有 API 的路由 'use strict'; const router = require('express').Router(); const AV = require('leanengine'); // 添加一个模块 const hello = require('./hello'); //const order = require('./order'); // 一个 API 路由下的 hello 接口,访问 /api/hello var Ticket = AV.Object.extend('Ticket'); var Store = AV.Object.extend('Store'); function checkSource(req) { return AV.Promise.as().then(function () { return new AV.Query(Store).get(req.headers['store']); }); } router.post('/ticket', function (req, res) { return checkSource(req) .then(function (store) { req.body.store = store; var ticket = new Ticket(req.body); return ticket.save(); }).then(function (ticket) { res.send(ticket); }, function (err) { res.status(400).send(err); }) }); router.post('/ticket/:ticket_id', function (req, res) { return checkSource(req) .then(function (store) { return new AV.Query(Ticket).get(req.params['ticket)id']); }).then(function (ticket) { ticket.set('customer', req.body.customer); return ticket.save(); }).then(function (ticket) { res.send(ticket); }, function (err) { res.status(400).send(err); }) }); router.get('/ticket', function (req, res) { var skip = (req.query['skip']) ? req.query['skip'] : 0, limit = (req.query['limit']) ? req.query['limit'] : 10; return checkSource(req) .then(function (store) { var query = new AV.Query(Ticket); query.skip(skip); query.limit(limit); query.equalTo('store', store); return query.find(); }).then(function (tickets) { res.send(tickets); }, function (err) { res.status(400).send(err); }) }); router.get('/ticket/:ticket_id', function (req, res) { return checkSource(req) .then(function (store) { var query = new AV.Query(Ticket); query.equalTo('store', store); query.equalTo('objectId', req.params['ticket_id']); return query.first(); }).then(function (ticket) { res.send(ticket); }, function (err) { res.status(400).send(err); }) }); router.post('/ticket/:ticket_id/:action', function (req, res) { var ticket_id = req.params['ticket_id'], action = req.params['action']; return checkSource(req) .then(function (store) { var query = new AV.Query(Ticket); query.equalTo('store', store); query.equalTo('objectId', req.params['ticket_id']); return query.first(); }).then(function (ticket) { if ('ready' === action) { ticket.set('status', 'ready'); } else if ('complete' === action) { ticket.set('status', 'completed'); } else if ('fire' === action) { // TODO dispatch deliverman ticket.set('status', 'fetching'); } else if ('deliver' === action) { ticket.set('status', 'delivering'); } else if ('cancel' === action) { ticket.set('status', 'failed'); } return ticket.save(); }).then(function (ticket) { res.send(ticket); }, function (err) { res.status(400).send(err); }) }); var request = require("request"); router.post('/util/distance', function (req, res) { var from = req.body['from'], to = req.body['to']; console.log('from,', from); console.log('to,', to); var options = { method: 'GET', url: 'http://api.map.baidu.com/direction/v1', qs: { mode: 'riding', origin: from, destination: to, region: '北京', output: 'json', ak: '<PASSWORD>' }, headers: { 'postman-token': '<PASSWORD>', 'cache-control': 'no-cache' } }; request(options, function (error, response, body) { if (error) throw new Error(error); var result = JSON.parse(response.body); console.log(response.body); res.json({ distance: result.result.routes[0].distance }) }); }) module.exports = router; <file_sep># buytime.dashboard
248eb28be3aa692caa01bb6598638a6c020e5c6a
[ "JavaScript", "Markdown" ]
4
JavaScript
fxp/buytime.dashboard
7a760c564442f53fe62778a49fce36aa542e04ad
7d285dd12b8eeefda7c6cf6e3a8b69bd0fb7ccea
refs/heads/master
<repo_name>onedebos/Get-hired-Api<file_sep>/app/controllers/sessions_controller.rb # frozen_string_literal: true class SessionsController < ApplicationController include CurrentUserConcern def create error = if User.find_by(email: params['email']) 'Password incorrect' else '' end user = User .find_by(email: params['email']) .try(:authenticate, params['password']) if user session[:user_id] = user.id render json: { status: 'created', logged_in: true, user: user } else render json: { status: 401, error: error } end end def logged_in if @current_user render json: { logged_in: true, user: @current_user } else render json: { logged_in: false } end end def logout reset_session # session[:user_id] = null render json: { logged_out: true } end end <file_sep>/app/controllers/registrations_controller.rb # frozen_string_literal: true class RegistrationsController < ApplicationController def create user = User.new(reg_params) if user.save session[:user_id] = user.id render json: { status: 'created', logged_in: true, user: user } else render json: { status: 500, errors: user.errors } end end def reg_params params.permit(:email, :password, :password_confirmation) end end
a44ba4077963bb3e3a6d12d925293414b46740c1
[ "Ruby" ]
2
Ruby
onedebos/Get-hired-Api
3d1616b012dacb47b16e692ac5b00c9f730637a5
1059230b556c111d5b29f2d8218887846e6d3a25
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com</groupId> <artifactId>jisoooh</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>Spring Training Webapp</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>utf-8</project.reporting.outputEncoding> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <java-version>1.8</java-version> <org.springframework-version>5.2.9.RELEASE</org.springframework-version> <junit.version>4.13.1</junit.version> <log4j.version>2.13.1</log4j.version> </properties> <dependencies> <!-- test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.10.19</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.14.RELEASE</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> </exclusions> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.13</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.8.13</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>3.2.4.RELEASE</version> </dependency> <!-- jsp --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- util --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>9.0.35</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency> <!-- logging --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j.version}</version> </dependency> <!-- DB --> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.0.3.RELEASE</version> </dependency> </dependencies> <profiles> <profile> <id>alpha</id> <properties> <env>alpha</env> </properties> </profile> <profile> <id>real</id> <properties> <env>real</env> </properties> </profile> </profiles> <build> <filters> <filter>src/main/resources/profile/${env}/common.properties</filter> </filters> <resources> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.1</version> <configuration> <warSourceDirectory>webapp</warSourceDirectory> <!--<warSourceExcludes>WEB-INF/web.xml</warSourceExcludes>--> <!--<webXml>webapp\WEB-INF\web.xml</webXml>--> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.11</version> <configuration> <showWeaveInfo>true</showWeaveInfo> <source>1.8</source> <target>1.8</target> <verbose>true</verbose> <complianceLevel>1.8</complianceLevel> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep># LocalCachingModule # AS-IS * ThreadLocal 을 멤버필드로 가지는 ThreadLocalCacheSupport 클래스 정의 ```java public abstract class ThreadLocalCacheSupport<T> { private ThreadLocal<Map<String, T>> threadLocal = new InheritableThreadLocal<Map<String, T>>(); protected T getCacheValue(String key) { ... } protected void putCacheValue(String key, T value) { ... } protected void removeCache(String key) { ... } } ``` * 캐시 토픽별로 ThreadLocalCacheSupport을 상속받는 Repository 클래스 정의 ```java public class UserInfoRepository extends ThreadLocalCacheSupport<Object> { public PublicGroupInfo getUserInfo(String userId) { String key = getUserInfoKey(userId); UserInfo userInfo = (UserInfo)getCacheValue(key); if(userInfo == null) { try { userInfo = userInvoker.getUserInfo(userId); putCacheValue(key, userInfo); } catch (UserInvokeException e) { putCacheValue(key, DEFAULT_USER_INFO); } } return userInfo; } ... } ``` ### AS-IS 의 문제점 * LocalCaching 사용 위해 ThreadLocalCacheSupport 를 상속받는 별도의 Repository 클래스 정의 필요 * putCache, getCache 호출 코드의 중복 * Cache topic 별로 개별적으로 ThreadLocal 객체를 가지게되어 메모리 낭비 * Cache topic 별 정의한 Cache 모듈 객체들을 threadLocalRepositoryList 에 등록하여 ThreadLocalClearInterceptor에서 요청 완료후 clear 하도록 처리 필요, 관리에 어려움 (Human error발생 가능) ```java <beans profile="NCS"> <util:list id="threadLocalRepositoryList"> <ref bean="userInfoRepository"/> </util:list> </beans> <mvc:interceptors> <bean class="ThreadLocalClearInterceptor"> <property name="supportList" ref="threadLocalRepositoryList"/> </bean> </mvc:interceptors> public class ThreadLocalClearInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if (CollectionUtils.isNotEmpty(supportList)) { for (ThreadLocalCacheSupport<?> support : supportList) { support.clearCache(); } } } } ``` # TO-BE * LocalCaching 로직을 횡단관심사 모듈로 분리 ```java @Aspect public class LocalCacheSupport { private final ThreadLocal<EnumMap<LocalCacheTopic, CacheStorage>> threadLocalCache = new InheritableThreadLocal<>(); @SuppressWarnings("unchecked") @Pointcut("@annotation(target) && execution(* *(..))") public void annotion(LocalCacheable target) {} @SuppressWarnings("unchecked") @Around("annotion(target)") public <T> T methodCall(ProceedingJoinPoint invoker, LocalCacheable target) throws Throwable { //caching logic } } ``` * 어노테이션을 통한 AOP 로 캐싱 적용 ```java @LocalCacheable public UserInfo getUserInfo(String userId) { return userInvoker.getUserInfo(userId); } ``` * 하나의 ThreadLocal 객체에서 모든 캐시데이터 관리 > AS-IS ![image](https://user-images.githubusercontent.com/48702893/121021984-e560f000-c7dc-11eb-8446-413d3d43dce0.png) > TO-BE ![image](https://user-images.githubusercontent.com/48702893/121022249-20632380-c7dd-11eb-8fd5-c6b4da840327.png) * 2중 해싱으로 인한 성능 저하를 완화하기위해 Topic 을 Enum 으로 정의 후, Topic 맵을 EnumMap 으로 선언 ```java //getCache EnumMap<LocalCacheTopic, CacheStorage> cacheMapCollection = threadLocalCache.get(); Map<Key, Value> cacheMap = cacheMapCollection.get(topic); return cacheMap.get(key); ``` ### TO-BE 의 문제점 1. AOP 프록시 객체로 전달되는 파라미터 중 cache key 로 사용할 파라미터를 알 수 없음 ```java public class UserInfoRepository extends ThreadLocalCacheSupport<String> { public String getUserDetailedInfo(String userId, String userNo) { String userName; try { userName = getCacheValue(userId); ... } } ... } ``` ```java @LocalCacheable public String getUserDetailedInfo(String userId, String userNo) { ... } ``` * 선택적 CacheKey 적용을 위해 @CacheKey 파라미터 어노테이션 추가 ```java @LocalCacheable public String getUserDetailedInfo(String userId, @CacheKey String userNo) { ... } //LocalCacheSupport private String generateCacheKey(Object[] args, Annotation[][] annotations) { //메서드 파라미터중, @CacheKey 어노테이션이 적용되어있는 파라미터만 키에 포함시킨다. List<Object> keyParamList = IntStream.range(0, args.length) .boxed() .filter(idx -> annotations[idx] != null) .filter(idx -> Stream.of(annotations[idx]).anyMatch(annotation -> annotation.annotationType() == CacheKey.class)) .map(idx -> args[idx]) .collect(Collectors.toList()); ... } ``` 2.public 메서드에 대해서만 캐싱 적용 가능하여 여전히 별도의 Repository 클래스 필요 ```java //UserInfoRepository.class @LocalCacheable public UserInfo getUserInfo(String userId) { return userInvoker.getUserInfo(userId); } //UserInfoBo.class @Autowired private UserInfoRepository userInfoRepository; private String getUserInfo(String userId) { ... UserInfo userInfo = userInfoRepository.getUserInfo(userId); String userName = userInfo.getUserName(); int userAge = userInfo.getUserAge(); ... } ``` * Proxy 객체를 사용하는 Srping AOP 대신, AspectJ AOP 를 사용하여, Compile time weaving 을 통해 private method 에 localcahing 적용 ```java //UserInfoBo.class @Autowired private String getUserInfo(String ownerId) { ... UserInfo userInfo = getUserInfo(userId); String userName = userInfo.getUserName(); int userAge = userInfo.getUserAge(); ... } @LocalCacheable private UserInfo getUserInfo(String userId) { return userInvoker.getUserInfo(userId); } ``` 3. 캐시데이터에 캐시 만료 시간 적용 불가능 ```java public List<String> get(final int userId) { // local cache 조회 Map<String, Object> cacheValue = getCacheValue(String.valueOf(userId)); if (MapUtils.isNotEmpty(cacheValue)) { Date curDate = new Date(); Date createDate = (Date)cacheValue.get(KEY_CREATETIME); if (expireSeconds <= 0 || curDate.before(DateUtils.addSeconds(createDate, expireSeconds))) { return (List<String>)cacheValue.get(KEY_EXTENSIONS); } } ... } ``` * 어노테이션 파라미터로 만료시간 설정할 수 있는 기능 제공 ```java @LocalCacheable(expireTime = 15000L) private UserInfo getUserInfo(String userId) { return userInvoker.getUserInfo(userId); } ``` <br> # 성능 테스트 ### 테스트 표본 * Caching 클래스를 이용한 캐싱 * AspectJ AOP 를 이용한 캐싱 ### 테스트 설계 * max cache size : 100 * case 1 : Cache Hit 만 발생 * getCache 만 수행했을때의 성능 비교 * case 2 : Cache Miss 만 발생 * getCache + setCache 수행했을때의 성능 비교 ### 테스트 결과 - 1 | 시나리오 | 캐시 적중률(%) | 캐싱 종류 | 평균 수행 시간(ms) | 비고 | |:----------:|:------------:|:-----------------:|:--------------:|:-----:| |1|100|aop|10.08|| | | |direct|1.98|| |2|0|aop|11.04|| | | |direct|2.69|| ### 테스트 결과 분석 - 1 * Aop 를 이용한 캐시가 Direct 캐시에 비해 약 5배 정도 성능이 떨어짐 * Aop 캐시 로직의 각 단계별로 시간 측정 결과 * key 생성 : 0.0785 * threadLocal에서 cache 조회 : 0.0142 * threadLocal 에 cache 설정 : 0.0181 * key 생성 로직에서 많은 부하 발생 * 메서드의 전체 파라미터 탐색 * stream 을 이용한 loop * reflection 을 통한 Method signature 및 파라미터 조회 ```java //메서드 파라미터중, @CacheKey 어노테이션이 적용되어있는 파라미터만 키에 포함시킨다. List<Object> keyParamList = IntStream.range(0, args.length) .boxed() .filter(idx -> annotations[idx] != null) .filter(idx -> Stream.of(annotations[idx]).anyMatch(annotation -> annotation.annotationType() == CacheKey.class)) .map(idx -> args[idx]) .collect(Collectors.toList()); //@CacheKey 어노테이션이 적용된 파라미터가 없다면, 전체 파라미터를 키에 포함시킨다. return StringUtil.format(keyForamt, keyParamList.isEmpty() ? args : keyParamList.toArray()); ``` * key 생성 로직에서 stream 이 아닌, for-each 문으로 loop 하도록 수정 ```java for(int idx = 0; idx < args.length; idx++) { if(annotations[idx] != null) { for(Annotation annotation : annotations[idx]) { if(annotation.annotationType() == CacheKey.class) { keyParamList.add(args[idx]); break; } } } } ``` ### 테스트 결과 - 2 | 시나리오 | 캐시 적중률(%) | 캐싱 종류 | 평균 수행 시간(ms) | 비고 | |:----------:|:------------:|:-----------------:|:--------------:|:-----:| |1|100|aop|3.75|| | | |direct|1.95|| |2|0|aop|5.28|| | | |direct|2.49|| ### 테스트 결과 분석 - 2 * 성능 측정결과 Aop 캐시의 성능이 2배 이상 향상 * Aop 캐시 로직의 각 단계별로 시간 측정 결과 key 생성 로직의 소요시간이 2배 이상 줄어듬 * key 생성 : 0.0316 * threadLocal에서 cache 조회 : 0.0162 * threadLocal 에 cache 설정 : 0.0226 ### 테스트 결과 정리 * Aop Cache 는 Direct Cache 에 비해 약 2배정도의 시간 소모 * 컴파일 타임 위빙으로 프록시 객체로 인한 성능저하는 없음 * 1번의 해싱만 하면 되는 Direct Cache 에 비해 Aop Cache 는 2번의 Hashing 이 필요하여 약간의 성능 저하 발생 > Topic 구분용 Map 을 EnumMap 으로 사용하여 2번의 Hashing 으로 인한 성능저하는 거의 없을것으로 예상 * Cache Key 생성 과정에서 메서드 전체 파라미터 탐색이 수행되어 결정적인 성능 저하 발생 * Cache Key 생성 로직을 수정하여 추가적은 성능 개선 가능 * Aop Cache 를 통해 얻는 이득(중복코드 제거, 사용의 편리, 개발 시간 절약) 과 손실(성능 저하) 을 따져본뒤 적용 필요<file_sep>INSERT INTO user_info(user_id, user_age, user_name) VALUES ('foo', 20, '푸'), ('bar', 20, '바');<file_sep>package controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; /** * @author jisoooh */ @Controller @RequestMapping("/test") public class TestController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final JdbcTemplate jdbcTemplate; private final String env; @Autowired public TestController(JdbcTemplate jdbcTemplate, @Value("${env}") String env) { this.jdbcTemplate = jdbcTemplate; this.env = env; } @GetMapping("/helloWorld") public String helloWorld() { return "index"; } @GetMapping("/property/injection") public String propertyInjection() { System.out.println(env); return "index"; } @GetMapping("/log4j2") public String loggingModule() { logger.debug("Test logging"); return "index"; } @GetMapping("/log4j2/logLevel") public void runtimeLogLevelChangeTest() { logger.error("error log"); logger.warn("warn log"); logger.info("info log"); logger.debug("debug log"); } @GetMapping("/embeddeddb") public void embeddedDbTest() { List<Map<String, Object>> userInfoList = jdbcTemplate.query("SELECT * FROM user_info", (row, rowIdx) -> { Map<String, Object> result = new HashMap<>(); result.put("userId", row.getString("user_id")); result.put("userNo", row.getInt("user_no")); return result; }); logger.info(userInfoList.toString()); } } <file_sep>package view; public enum ViewNameSpace { USER_INFO("userInfo") ; private String viewName; ViewNameSpace(String viewName) { this.viewName = viewName; } public String getViewName() { return viewName; } } <file_sep>package controller; import static view.ViewNameSpace.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import bo.UserInfoBo; import model.UserInfo; @Controller @RequestMapping("/user") public class UserController { private final UserInfoBo userInfoBo; @Autowired public UserController(UserInfoBo userInfoBo) { this.userInfoBo = userInfoBo; } @GetMapping("/info") public String getUserInfo(@RequestParam String userId, ModelMap model) { String userName = userInfoBo.getUserName(userId); int userAge = userInfoBo.getUserAge(userId); int userNo = userInfoBo.getUserNo(userId); UserInfo userInfo = new UserInfo(userNo, userId, userAge, userName); model.addAttribute("key", "UserInfo"); model.addAttribute("value", userInfo); return USER_INFO.getViewName(); } @GetMapping("/name") public String getUserName(@RequestParam String userId, ModelMap model) { String userName = userInfoBo.getUserName(userId); model.addAttribute("key", "UserName"); model.addAttribute("value", userName); return USER_INFO.getViewName(); } @GetMapping("/age") public String getUserAge(@RequestParam String userId, ModelMap model) { int userAge = userInfoBo.getUserAge(userId); model.addAttribute("key", "UserAge"); model.addAttribute("value", userAge); return USER_INFO.getViewName(); } @GetMapping("/no") public String getUserNo(@RequestParam String userId, ModelMap model) { int userNo = userInfoBo.getUserNo(userId); model.addAttribute("key", "UserNo"); model.addAttribute("value", userNo); return USER_INFO.getViewName(); } }<file_sep>package cache; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; import java.util.EnumMap; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; import cache.impl.MapCacheStorage; import cache.type.LocalCacheTopic; @RunWith(MockitoJUnitRunner.class) public class LocalCacheSupportTest { private LocalCacheSupport localCacheSupport = new LocalCacheSupport(); @Mock private ThreadLocal threadLocal; private int size = 100; private String sampleKey = "sampleKey"; private String sampleValue = "sampleValue"; private LocalCacheTopic cacheTopic = LocalCacheTopic.USER_INFO_CACHE; private int cacheSize = 100; private EnumMap<LocalCacheTopic, CacheStorage> cacheStorageCollection = new EnumMap<>(LocalCacheTopic.class); @Before public void init() { ReflectionTestUtils.setField(localCacheSupport, "threadLocalCache", threadLocal); } @Test public void getCache() { CacheStorage<String, String> cacheStorage = new MapCacheStorage<>(size); cacheStorage.setCache(sampleKey, sampleValue); cacheStorageCollection.put(cacheTopic, cacheStorage); given(threadLocal.get()).willReturn(cacheStorageCollection); String result = localCacheSupport.getCache(cacheTopic, sampleKey); assertEquals(sampleValue, result); } @Test public void getCache_cacheStorageCollection_null() { given(threadLocal.get()).willReturn(null); String result = localCacheSupport.getCache(cacheTopic, sampleKey); assertNull(result); } @Test public void getCache_cacheStorage_null() { given(threadLocal.get()).willReturn(cacheStorageCollection); String result = localCacheSupport.getCache(cacheTopic, sampleKey); assertNull(result); } @Test public void setCache() { CacheStorage<String, String> cacheStorage = new MapCacheStorage<>(cacheSize); cacheStorageCollection.put(cacheTopic, cacheStorage); given(threadLocal.get()).willReturn(cacheStorageCollection); localCacheSupport.setCache(cacheTopic, cacheSize, sampleKey, sampleValue); assertEquals(sampleValue, cacheStorage.getCache(sampleKey)); } @Test public void setCache_cacheStorage_null() { given(threadLocal.get()).willReturn(cacheStorageCollection); localCacheSupport.setCache(cacheTopic, cacheSize, sampleKey, sampleValue); CacheStorage<String, String> cacheStorage = cacheStorageCollection.get(cacheTopic); assertEquals(sampleValue, cacheStorage.getCache(sampleKey)); assertEquals(cacheStorage.getMaxSize(), cacheSize); } @Test public void setCache_cacheStorage_full() { String sampleKey_2 = "sampleKey_2"; CacheStorage<String, String> cacheStorage = new MapCacheStorage<>(1); cacheStorage.setCache(sampleKey, sampleValue); cacheStorageCollection.put(cacheTopic, cacheStorage); given(threadLocal.get()).willReturn(cacheStorageCollection); localCacheSupport.setCache(cacheTopic, cacheSize, sampleKey_2, sampleValue); assertEquals(sampleValue, cacheStorage.getCache(sampleKey_2)); assertNull(cacheStorage.getCache(sampleKey)); } } <file_sep>package repository.impl; import java.util.List; import java.util.Map; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import repository.Repository; public class NamedParameterRepository implements Repository { private final NamedParameterJdbcTemplate jdbcTemplate; public NamedParameterRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate); } @Override public <T> List<T> selectList(String query, Map<String, Object> param, RowMapper<T> rowMapper) { return jdbcTemplate.query(query, param, rowMapper); } @Override public <T> T selectOne(String query, Map<String, Object> param, RowMapper<T> rowMapper) { return jdbcTemplate.queryForObject(query, param, rowMapper); } @Override public <T> T selectOne(String query, Map<String, Object> param, Class type) { return (T)jdbcTemplate.queryForObject(query, param, type); } } <file_sep>env=${env} view.prefix=/WEB-INF/jsp/ view.suffix=.jsp<file_sep>package util.constants; public class CommonConstants { private CommonConstants() { throw new AssertionError(); } public static final String UTF_8 = "UTF-8"; public static final String ROOT = "/"; } <file_sep>### 요구사항 ### Features - [ ] feature ### See also <file_sep>CREATE TABLE user_info ( user_no INTEGER IDENTITY PRIMARY KEY, user_id VARCHAR(10) NOT NULL UNIQUE, user_age INTEGER NOT NULL, user_name VARCHAR(4) NOT NULL );<file_sep>package cache; import static cache.CacheStorage.*; import static cache.type.LocalCacheTopic.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.commons.lang3.StringUtils; import cache.type.LocalCacheTopic; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface LocalCacheable { LocalCacheTopic topic() default COMMON_CACHE; String keyFormat() default "{}"; int maxSize() default 0; long expireTime() default 0; }<file_sep># Description Fixes # (issue) ## Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) ## Proposed Changes * * * ## Checklist: - [ ] self review - [ ] self comment - [ ] code style - [ ] test code - [ ] test pass - [ ] no warnings
8d57a66a15193dbf32e0f892c68614117f18936f
[ "SQL", "Markdown", "Maven POM", "INI", "Java" ]
14
Maven POM
JisooOh94/AopLocalCaching
2d8e889c9bae822d24c19a26411be9220d0dd147
b0240aa539dde2f67d9bb86608785c6a35b5892f
refs/heads/master
<file_sep><p align="center"><img src="https://www.evokewebs.com/wp-content/uploads/2016/01/logo.png"></p> ## About Evokewebhosting API (EWHAPI) EWHAPI is a headless web application developed using Laravel as PHP development framework. To connect server database to the frontend of the evokewebhosting.com using RESTful API as mode of data exchange between Web/Mobile application and Backend database. Using the EWHAPI & Angular the Web Interface is designed & developed, and with that NativeScript is used to develop Android/IOS app for (https://evokewebhosting.com). ## Security Vulnerabilities If you discover a security vulnerability within EWHAPI, please send an e-mail to <NAME> via [<EMAIL>](mailto:<EMAIL>). All security vulnerabilities will be promptly addressed.<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\User; use App\Http\Resources\User as UserResource; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // Get Users $users = User::paginate(10); // Return collection of users as a resource return UserResource::collection($users); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Create/ Update User data $user = $request->isMethod('put') ? User::findOrFail($request->id) : new User; $user->id = $request->input('id'); $user->UserGroupID = $request->input('UserGroupID'); $user->EmailID = $request->input('EmailID'); $user->PhoneNo = $request->input('PhoneNo'); $user->UName = $request->input('UName'); $user->Password = md5($request->input('<PASSWORD>')); $user->FName = $request->input('FName'); $user->LName = $request->input('LName'); $user->Address = $request->input('Address'); $user->City = $request->input('City'); $user->State = $request->input('State'); $user->Country = $request->input('Country'); $user->ZipCode = $request->input('ZipCode'); $user->Status = $request->input('Status'); if($user->save()){ return new UserResource($user); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // Get User $user = User::findOrFail($id); // Return single User as a resource return new UserResource($user); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // Get User $user = User::findOrFail($id); if($user->delete()){ return new UserResource($user); } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Country; use App\Http\Resources\Country as CountryResource; class CountryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // Get Countries $countries = Country::paginate(10); // Return collection of countries as a resource return CountryResource::collection($countries); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // Get country $country = Country::findOrFail($id); // Return single country as a resource return new CountryResource($country); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Database\Seeder; class UserGroupTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('user_groups')->delete(); $group = array( array('group' => 'Super Administrator'), array('group' => 'Administrator'), array('group' => 'Manager'), array('group' => 'Staff'), array('group' => 'Customer'), ); DB::table('user_groups')->insert($group); } } <file_sep><?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->delete(); // $time = date("Y-m-d H:i:s"); // $users = array( // array('user_group_ID' => '1', 'email' => '<EMAIL>', 'phone' => '9853412445', 'uname' => 'EWHAdmin', 'password' => md5('<PASSWORD>'), 'fname' => '<NAME>', 'lname' => 'Sahoo', 'address' => '280, Nayapalli', 'city' => 'Bhubaneswar', 'state' => 'Odisha', 'country' => '100', 'zipcode' => '751012', 'status' => '1', 'created_at' => $time, 'updated_at' => $time), // ); // DB::table('users')->insert($users); DB::table('users')->insert([ 'name' => '<NAME>', 'email' => '<EMAIL>', 'password' => <PASSWORD>('<PASSWORD>'), 'utype' => 2, 'status' => 1, 'remember_token' => str_random(10), ]); DB::table('users')->insert([ 'name' => '<NAME>', 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>'), 'utype' => 1, 'status' => 1, 'remember_token' => str_random(10), ]); DB::table('users')->insert([ 'name' => '<NAME>', 'email' => '<EMAIL>', 'password' => <PASSWORD>('<PASSWORD>'), 'remember_token' => str_random(10), ]); } } <file_sep><?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! | */ // Auth::routes(); //404 Page Not Found. Route::fallback(function(){ return response()->json(['error' => "NotFoundError: This route don't exist!"], 404); })->name('api.fallback.404'); //Authorization api Route::group([ 'middleware' => 'auth.apikey' ], function () { Route::post('login', 'AuthController@login')->name('api.login'); Route::post('signup', 'AuthController@signup')->name('api.signup'); Route::group([ 'middleware' => 'auth:api' ], function() { Route::get('logout', 'AuthController@logout')->name('api.logout'); }); Route::resource('user_groups', 'UserGroupController'); Route::resource('users', 'UserController')->except([ 'create', 'edit' ]); Route::resource('countries', 'CountryController')->only([ 'index', 'show' ]); }); <file_sep># Compile PHP 7.1.0RC5 with static linked dependencies # to create a single running binary FROM ubuntu ARG PHP_VERSION RUN apt-get update && apt-get install -y \ git \ autoconf \ wget \ libcurl4-openssl-dev \ libjpeg-dev \ libpng-dev \ libxpm-dev \ libmysqlclient-dev \ libpq-dev \ libicu-dev \ libfreetype6-dev \ libldap2-dev \ libxslt-dev \ build-essential \ libssl-dev \ libgmp-dev \ libpspell-dev \ librecode-dev \ php-mysql RUN git clone -b $PHP_VERSION https://github.com/php/php-src.git /php-src/ WORKDIR /php-src RUN ln -s /usr/include/x86_64-linux-gnu/gmp.h /usr/include/gmp.h RUN wget http://launchpadlibrarian.net/140087283/libbison-dev_2.7.1.dfsg-1_amd64.deb RUN wget http://launchpadlibrarian.net/140087282/bison_2.7.1.dfsg-1_amd64.deb RUN dpkg -i libbison-dev_2.7.1.dfsg-1_amd64.deb RUN dpkg -i bison_2.7.1.dfsg-1_amd64.deb RUN ./buildconf --force RUN ./configure \ --prefix=$HOME/php7/usr \ --with-config-file-path=$HOME/php7/usr/etc \ --without-pear \ --enable-shared=no \ --enable-static=yes \ --enable-mbstring \ --enable-zip \ --enable-bcmath \ --enable-pcntl \ --enable-exif \ --enable-calendar \ --enable-sysvmsg \ --enable-sysvsem \ --enable-sysvshm \ --enable-json \ --with-curl \ --with-iconv \ --with-gmp \ --with-gd \ --enable-ctype \ --enable-pdo \ --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd \ --enable-gd-native-ttf \ --enable-gd-jis-conv \ --libdir=/usr/lib64 \ --disable-opcache \ --disable-cgi RUN make RUN make install RUN strip /root/php7/usr/bin/php
9b575681982527a517f21af21d0fb14a2e851065
[ "Markdown", "Dockerfile", "PHP" ]
7
Markdown
arunsahoo/ewhapi
ebd62fc36ed04287a532c068a6ed4b83dd79734a
3ea9c04fdcbb0d3dd1f14d9573593a80e8bdd786
refs/heads/master
<file_sep>Page({ data:{ cost:0, count:0, lists:[1,2] }, onLoad:function(options){ // 生命周期函数--监听页面加载 }, })<file_sep># 微信小程序 * babel编译 * gulp构建 ---- ## 首次使用 1. npm install 安装依赖 2. npm run dev 生成dist,用微信开发工具打开 --- *建议vscode安装插件vscode-wechat* <file_sep>var gulp = require("gulp"); var babel = require("gulp-babel"); var through = require('through2'); var path = require('path'); var sourcemaps = require('gulp-sourcemaps'); var watch = require('gulp-watch'); var clean = require('gulp-clean'); function prefixStream(prefixText) { var stream = through(); stream.write(prefixText); return stream; } function gulpAddRequireRuntime() { // 创建一个让每个文件通过的 stream 通道 return through.obj(function (file, enc, cb) { var prefixText = ``; var rel = path.relative(path.dirname(file.path), path.join(file.base, 'lib/runtime.js')); rel = rel.replace(/\\/g, '/'); if (rel === 'runtime.js') { prefixText = new Buffer(prefixText); // 预先分配 } else { prefixText = `var regeneratorRuntime = require("${rel}");`; prefixText = new Buffer(prefixText); // 预先分配 } if (file.isNull()) { // 返回空文件 cb(null, file); } if (file.isBuffer()) { file.contents = Buffer.concat([prefixText, file.contents]); } if (file.isStream()) { file.contents = file.contents.pipe(prefixStream(prefixText)); } cb(null, file); }); } gulp.task('compile', () => { return watch(['./src/**/*.js'], { ignoreInitial: false }) // .pipe(sourcemaps.init()) .pipe(babel()) .pipe(gulpAddRequireRuntime()) // .pipe(sourcemaps.write()) .pipe(gulp.dest('./dist')); }); gulp.task('scripts', () => { return gulp.src(['./src/**/*.js']) .pipe(babel()) .pipe(gulpAddRequireRuntime()) .pipe(gulp.dest('./dist')); }); gulp.task('css', () => { return gulp.src('./src/**/*.wxss') .pipe(gulp.dest('./dist')); }); gulp.task('xml', () => { return gulp.src('./src/**/*.wxml') .pipe(gulp.dest('./dist')); }); gulp.task('json', () => { return gulp.src('./src/**/*.json') .pipe(gulp.dest('./dist')); }); gulp.task('jpg', () => { return gulp.src('./src/**/*.jpg') .pipe(gulp.dest('./dist')); }); gulp.task('png', () => { return gulp.src('./src/**/*.png') .pipe(gulp.dest('./dist')); }); gulp.task('watch-css', () => { return watch('./src/**/*.wxss') .pipe(gulp.dest('./dist')); }); gulp.task('watch-xml', () => { return watch('./src/**/*.wxml') .pipe(gulp.dest('./dist')); }); gulp.task('watch-json', () => { return watch('./src/**/*.json') .pipe(gulp.dest('./dist')); }); gulp.task('watch-jpg', () => { return watch('./src/**/*.jpg') .pipe(gulp.dest('./dist')); }); gulp.task('watch-png', () => { return watch('./src/**/*.png') .pipe(gulp.dest('./dist')); }); gulp.task("clean", function () { return gulp.src('./dist') .pipe(clean()); }); gulp.task('res', ['css', 'xml', 'json', 'jpg', 'png']); gulp.task('build', ['clean'], function () { gulp.start('scripts', 'res'); }); gulp.task('watch', [ 'watch-css', 'watch-css', 'watch-xml', 'watch-json', 'watch-jpg', 'watch-png', 'compile', ]); <file_sep>var regeneratorRuntime = require("../../lib/runtime.js");//index.js var app = getApp(); Page({ /** * 页面的初始数据 */ data: { orderDetail:{ orderType:'新订单1', getOrderNo:'C088', expectGetTime:'2018-08-08 20:30:00', goodsNameSize:'珍珠奶茶/中杯', goodsSpec:['常规','半塘','少冰'], goodsPrice:'¥10.0', goodsNum:'x1', goodsTotalPrice:'¥10.0', orderTotalPrice:'¥10.0', orderNo:'WD10731193321240577', orderTime:'2018-07-31 19:32:02', storeAddress:'四川省成都市青羊区日月大道一段978号1栋附4015号' } } });<file_sep>import util from '../utils/util.js'; import config from '../config/index.js'; // 请求用户信息接口 const getUserInfo = (data) => { return util.promise(wx.request, { header: { 'content-type': 'application/json'//小程序默认为json }, url: `${config.api}/userInfo`, method: 'POST',//必须大写 data: data }).then(res => { let data = res.data if (data.code === 0) { wx.setStorageSync('userInfo', data.data) return data.data } }).catch(e => { }) } //商品菜单 const getMenu = (data) => { return util.promise(wx.request, { header: { 'content-type': 'application/json'//小程序默认为json }, url: `${config.api}/getMenu`, method: 'GET',//必须大写 data: data }).then(res => { let data = res.data; return data; }).catch(e => { }) } //优惠信息 const aitivity = (data) => { return util.promise(wx.request, { header: { 'content-type': 'application/json'//小程序默认为json }, url: `${config.api}/aitivity`, method: 'GET',//必须大写 data: data }).then(res => { let data = res.data; return data; }).catch(e => { }) } module.exports = { getUserInfo, getMenu, aitivity }<file_sep>Mock.mock(/userInfo/,{ status:200, data:{ userName:'卡布达lala' } }), Mock.mock(/storeInfo/,{ status:200, storeInfo:{ name:'卡布达的奶茶店', distance:'1.2', address:'四川省成都市卡卡', phone:'15278907890', longitude:'', latitude:'' }, }) Mock.mock(/getMenu/,{ data:[ { "typeName": "快餐类", "menuContent": [{ "name": "炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡炸鸡", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534311601157&di=4bb480a6aee42d0191ff63976337dbbf&imgtype=0&src=http%3A%2F%2Fcy.89178.com%2Fupload%2Farticle%2F20160825%2F87214375981472114735.jpg", "sales": 22, "rating": 3, "price": 15, "numb": 0 }, { "name": "汉堡", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534311630643&di=e8605ec3b56c9b36130c94d5fce474a6&imgtype=0&src=http%3A%2F%2Ftop.shang360.com%2Fupload%2Farticle%2F20151010%2F94320056731444459546.jpg", "sales": 22, "rating": 3, "price": 10, "numb": 0 }, { "name": "鸡翅", "src": "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2605376543,2660171472&fm=27&gp=0.jpg", "sales": 22, "rating": 3, "price": 11, "numb": 0 }, { "name": "薯条", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534311675352&di=4f90cc6f2b72e225ac8ad5c398449c60&imgtype=0&src=http%3A%2F%2Fwww.cnfoodnet.com%2Fuploadfile%2F2017%2F0925%2F20170925064910414.jpg", "sales": 22, "rating": 3, "price": 32, "numb": 0 }, { "name": "汉堡", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534311630643&di=e8605ec3b56c9b36130c94d5fce474a6&imgtype=0&src=http%3A%2F%2Ftop.shang360.com%2Fupload%2Farticle%2F20151010%2F94320056731444459546.jpg", "sales": 22, "rating": 3, "price": 10, "numb": 0 }] }, { "typeName": "盖浇饭类", "menuContent": [{ "name": "土豆牛肉盖浇饭", "src": "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=453984443,3335605648&fm=27&gp=0.jpg", "sales": 22, "rating": 3, "price": 9, "numb": 0 }, { "name": "肉末茄子盖浇饭", "src": "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2233585827,3571560627&fm=27&gp=0.jpg", "sales": 22, "rating": 3, "price": 21, "numb": 0 }, { "name": "番茄炒蛋盖浇饭", "src": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3007961664,1748996109&fm=27&gp=0.jpg", "sales": 22, "rating": 3, "price": 50, "numb": 0 }] }, { "typeName": "养生粥类", "menuContent": [{ "name": "桂圆莲子粥", "src": "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4185962345,377564467&fm=27&gp=0.jpg", "sales": 22, "rating": 3, "price": 15, "numb": 0 }, { "name": "皮蛋瘦肉粥", "src": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3820026741,30884540&fm=27&gp=0.jpg", "sales": 22, "rating": 3, "price": 12, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] }, { "typeName": "小吃类", "menuContent": [{ "name": "肉夹馍", "src": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534312673780&di=aa880aaec11729f14f9acb80670e3421&imgtype=0&src=http%3A%2F%2Fs14.sinaimg.cn%2Fmw690%2F003n3ghzzy7gpGbUhZP2d%26690", "sales": 22, "rating": 3, "price": 4, "numb": 0 }] } ] }) Mock.mock(/aitivity/,{ code:200, data:[{ text:'只是优惠信息1只是优惠信息1只是优惠信息1只是优惠信息1只是优惠信息1只是优惠信息1只是优惠信息1只是优惠信息1' },{ text:'只是优惠信息2' },{ text:'只是优惠信息3' },{ text:'只是优惠信息4' }] })<file_sep>const app = getApp() Page({ data: { orders: [ { orderTime: '2018-8-5 16:57:15', storeName: 'CoCo都可(成都市高新店)', getOrderTime: '2018-8-5 16:59:38', orderType: '预约订单', state: '已退款', orderNum: 'C088', price: '¥10.0' }, { orderTime: '2018-8-7 16:57:15', storeName: 'CoCo都可(成都市高新店)', getOrderTime: '2018-8-5 16:59:38', orderType: '预约订单', state: '已确定', orderNum: 'C089', price: '¥15.0' }, { orderTime: '2018-8-6 16:57:15', storeName: 'CoCo都可(成都市高新店)', getOrderTime: '2018-8-5 16:59:38', orderType: '预约订单', state: '已退款', orderNum: 'C099', price: '¥17.0' } ] }, //事件处理函数 bindViewTap() { }, onLoad() { // getCourseList() }, goDetail(){ wx.navigateTo({ url: "/pages/orderDetail/orderDetail" }); } }) <file_sep>//index.js //获取用户信息 import { getUserInfo } from '../../api/index' //引用腾讯地图API var QQMapWX = require('../../lib/qqmap-wx-jssdk.js'); var qqmapsdk; const app = getApp() Page({ data: { address: '', movies: [{ url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533273890882&di=ade7b6950e519d7fd7bb5c917903cda6&imgtype=0&src=http%3A%2F%2Fimg17.3lian.com%2Fd%2Ffile%2F201703%2F10%2F4927d1387af50334baff7de26a9da07e.jpg' }, { url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533868695&di=db62948974e268b25fb6ee313395a55c&imgtype=jpg&er=1&src=http%3A%2F%2Fimg4q.duitang.com%2Fuploads%2Fblog%2F201404%2F27%2F20140427225623_Gck4c.thumb.700_0.jpeg' }, { url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533273936332&di=16606d497b212ae1ff5076ef1615b27d&imgtype=0&src=http%3A%2F%2Fscimg.jb51.net%2Fallimg%2F161201%2F106-161201101A5946.jpg' }, { url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533274291381&di=ed091a0c5769f09e229f37d0093a5ccc&imgtype=0&src=http%3A%2F%2Fimg06.tooopen.com%2Fimages%2F20170221%2Ftooopen_sy_199240913125.jpg' }], currentTab: 1, currentStore: 0, storeList: [{ storeId:11, name: '卡布达的奶茶店', distance: 0.1, address: '四川省成都市三江镇啦啦啦啦', isSelect: false }, { storeId:22, name: '卡布达的奶茶店', distance: 0.2, address: '四川省成都市三江镇啦啦啦啦', isSelect: true }, { storeId:33, name: '卡布达的奶茶店', distance: 0.3, address: '四川省成都市三江镇啦啦啦啦', isSelect: false }, { storeId:44, name: '卡布达的奶茶店', distance: 0.4, address: '四川省成都市三江镇啦啦啦啦', isSelect: true }, { storeId:55, name: '卡布达的奶茶店', distance: 0.5, address: '四川省成都市三江镇啦啦啦啦', isSelect: false }] }, onLoad: function (options) { //获取用户信息 getUserInfo().then(res=>{ console.log(res) }) /*判断是第一次加载还是从position页面返回 如果从position页面返回,会传递用户选择的地点*/ if (options.address != null && options.address != '') { //设置变量 address 的值 this.setData({ address: options.address }); } else { var that = this; // 调用接口 wx.getLocation({ type: "wgs84", success: function (t) { that.getAddress(); }, fail: function () { wx.showModal({ title: "警告", content: "您点击了拒绝授权,无法正常使用功能,点击确定重新获取授权。", showCancel: !1, success: function (t) { wx.openSetting({ success: function(t) { that.getAddress(); }, fail: function(t) {} }) } }); }, complete: function (t) { } }); } }, //获取当前地址 getAddress:function(){ var that = this; // 实例化API核心类 qqmapsdk = new QQMapWX({ //此key需要用户自己申请 key: '<KEY>' }); qqmapsdk.reverseGeocoder({ success: function (res) { that.setData({ address: res.result.address }); }, fail: function (res) { }, complete: function (res) { //console.log(res); } }); }, //选择地址 onChangeAddress: function () { wx.navigateTo({ url: "/pages/position/position" }); }, changeTab: function (event) { var type = event.currentTarget.dataset['type']; if (type !== this.data.currentTab) { this.setData({ currentTab: type }) //列表数据处理 if (type == 1) { //请求所有数据 } else if (type == 2) { //请求收藏数据 } } }, chooseStore: function (event) { var index = event.currentTarget.dataset['index']; this.setData({ currentStore: index }) }, goDetail:function(event){ var id = event.currentTarget.dataset['id']; console.log(id); wx.navigateTo({ url: "/pages/menu/menu?id="+id }) } }) <file_sep>var regeneratorRuntime = require("../../lib/runtime.js");//index.js var app = getApp(); Page({ /** * 页面的初始数据 */ data: { userInfo: {}, menuitems: [ { text: '我的优惠', url: '../coupons/coupon', icon: '../../imgs/mine/coupons.png', iconEnd: '../../imgs/mine/next.png' }, { text: '', url: '../getPhone/getPhone', icon: '../../imgs/mine/phone.png', iconEnd: '../../imgs/mine/next.png' }, { text: '平台须知', url: '../notice/notice', icon: '../../imgs/mine/notice.png', iconEnd: '../../imgs/mine/next.png' } ] }, onLoad: function () { console.log('onLoad') var that = this; // 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId console.log(res.userInfo); that.setData({ userInfo : res.userInfo }) // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () {}, /** * 生命周期函数--监听页面显示 * onShow: function () { let that = this; _app.getUserInfo(function (userinfo) { console.log(userinfo); console.log(getApp().globalData.userSign); that.setData({ userinfo: userinfo, userSign: getApp().globalData.userSign }); }); }, */ /** * 生命周期函数--监听页面隐藏 */ onHide: function () {}, /** * 生命周期函数--监听页面卸载 */ onUnload: function () {}, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () {}, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () {}, /** * 用户点击右上角分享 */ onShareAppMessage: function () {} });
6dd5c0be9dd45905859e505b5ec6700f89bb11f1
[ "JavaScript", "Markdown" ]
9
JavaScript
Nameda/xcx_order
6cf4052297eb38d41e9e446772e22c71bae88992
1b233567766228fa550640eef1ad24366617154b
refs/heads/master
<file_sep>''' ''' import os, sys import time sys.path.insert(0, './python-package/') isMORT = len(sys.argv)>1 and sys.argv[1] == "mort" if isMORT: sys.path.insert(1, 'E:/LiteMORT/python-package/') import litemort from litemort import * print(f"litemort={litemort.__version__}") import numpy as np import matplotlib.pyplot as plt import node_lib import quantum_forest import pandas as pd import pickle import torch, torch.nn as nn import torch.nn.functional as F import lightgbm as lgb from sklearn.model_selection import KFold from qhoptim.pyt import QHAdam #You should set the path of each dataset!!! data_root = "F:/Datasets/" #dataset = "MICROSOFT" #dataset = "YAHOO" #dataset = "YEAR" dataset = "CLICK" #dataset = "HIGGS" def InitExperiment(config,fold_n): config.experiment = f'{config.data_set}_{config.model_info()}_{fold_n}' #'year_node_shallow' #experiment = '{}_{}.{:0>2d}.{:0>2d}_{:0>2d}_{:0>2d}'.format(experiment, *time.gmtime()[:5]) #visual = quantum_forest.Visdom_Visualizer(env_title=config.experiment) visual = quantum_forest.Visualize(env_title=config.experiment) visual.img_dir = "./results/images/" print("experiment:", config.experiment) log_path=f"logs/{config.experiment}" if os.path.exists(log_path): #so strange!!! import shutil print(f'experiment {config.experiment} already exists, DELETE it!!!') shutil.rmtree(log_path) return config,visual def GBDT_test(data,fold_n,num_rounds = 100000,bf=1,ff=1): model_type = "mort" if isMORT else "lgb" nFeatures = data.X_train.shape[1] early_stop = 100; verbose_eval = 20 #lr = 0.01; bf = bf; ff = ff if data.problem()=="classification": metric = 'auc' #"rmse" params = {"objective": "binary", "metric": metric,'n_estimators': num_rounds, "bagging_fraction": bf, "feature_fraction": ff,'verbose_eval': verbose_eval, "early_stopping_rounds": early_stop, 'n_jobs': -1, } else: metric = 'l2' #"rmse" params = {"objective": "regression", "metric": metric,'n_estimators': num_rounds, "bagging_fraction": bf, "feature_fraction": ff, 'verbose_eval': verbose_eval, "early_stopping_rounds": early_stop, 'n_jobs': -1, } print(f"====== GBDT_test\tparams={params}") X_train, y_train = data.X_train, data.y_train X_valid, y_valid = data.X_valid, data.y_valid X_test, y_test = data.X_test, data.y_test if not np.isfortran(X_train): #Very important!!! mort need COLUMN-MAJOR format X_train = np.asfortranarray(X_train) X_valid = np.asfortranarray(X_valid) #X_train, X_valid = pd.DataFrame(X_train), pd.DataFrame(X_valid) print(f"GBDT_test\ttrain={X_train.shape} valid={X_valid.shape}") #print(f"X_train=\n{X_train.head()}\n{X_train.tail()}") if model_type == 'mort': params['verbose'] = 667 model = LiteMORT(params).fit(X_train, y_train, eval_set=[(X_valid, y_valid)]) #y_pred_valid = model.predict(X_valid) #y_pred = model.predict(X_test) if model_type == 'lgb': if data.problem()=="classification": model = lgb.LGBMClassifier(**params) else: model = lgb.LGBMRegressor(**params) model.fit(X_train, y_train,eval_set=[(X_train, y_train), (X_valid, y_valid)],verbose=min(num_rounds//10,1000)) pred_val = model.predict(data.X_test) #plot_importance(model) lgb.plot_importance(model, max_num_features=32) plt.title("Featurertances") plt.savefig(f"./results/{dataset}_feat_importance_.jpg") #plt.show(block=False) plt.close() fold_importance = pd.DataFrame() fold_importance["importance"] = model.feature_importances_ fold_importance["feature"] = [i for i in range(nFeatures)] fold_importance["fold"] = fold_n #fold_importance.to_pickle(f"./results/{dataset}_feat_{fold_n}.pickle") print('best_score', model.best_score_) acc_train,acc_=model.best_score_['training'][metric], model.best_score_['valid_1'][metric] if data.X_test is not None: pred_val = model.predict(data.X_test) if False:#config.err_relative: #nrm_Y = ((YY_) ** 2).mean() #mse = ((YY_ - prediction) ** 2).mean()/nrm_Y lenY = np.linalg.norm(data.y_test) acc_ = np.linalg.norm(data.y_test - pred_val)/lenY else: acc_ = ((data.y_test - pred_val) ** 2).mean() print(f'====== Best step: test={data.X_test.shape} ACCU@Test={acc_:.5f}') return acc_,fold_importance def get_feature_info(data,fold_n): pkl_path = f"./results/{dataset}_feat_info_.pickle" nSamp,nFeat = data.X_train.shape[0],data.X_train.shape[1] if os.path.isfile(pkl_path): feat_info = pd.read_pickle(pkl_path) else: #fast GBDT to get feature importance nMostSamp,nMostFeat=100000.0,100.0 bf = 1.0 if nSamp<=nMostSamp else nMostSamp/nSamp ff = 1.0 if nFeat<=nMostFeat else nMostFeat/nFeat accu,feat_info = GBDT_test(data,fold_n,num_rounds=2000,bf = bf,ff = ff) with open(pkl_path, "wb") as fp: pickle.dump(feat_info, fp) importance = torch.from_numpy(feat_info['importance'].values).float() fmax, fmin = torch.max(importance), torch.min(importance) weight = importance / fmax feat_info = data.OnFeatInfo(feat_info,weight) return feat_info def cascade_LR(): #意义不大 if config.cascade_LR: LinearRgressor = quantum_forest.Linear_Regressor({'cascade':"ridge"}) y_New = LinearRgressor.BeforeFit((data.X_train, data.y_train),[(data.X_valid, data.y_valid),(data.X_test, data.y_test)]) YY_train = y_New[0] YY_valid,YY_test = y_New[1],y_New[2] else: YY_train,YY_valid,YY_test = data.y_train, data.y_valid, data.y_test return YY_train,YY_valid,YY_test def VisualAfterEpoch(epoch,visual,config,mse): if visual is None: if config.plot_train: clear_output(True) plt.figure(figsize=[18, 6]) plt.subplot(1, 2, 1) plt.plot(loss_history) plt.title('Loss') plt.grid() plt.subplot(1, 2, 2) plt.plot(mse_history) plt.title('MSE') plt.grid() plt.show() else: visual.UpdateLoss(title=f"Accuracy on \"{dataset}\"",legend=f"{config.experiment}", loss=mse,yLabel="Accuracy") def NODE_test(data,fold_n,config,visual=None,feat_info=None): YY_train,YY_valid,YY_test = data.y_train, data.y_valid, data.y_test data.Y_mean,data.Y_std = YY_train.mean(), YY_train.std() #config.mean,config.std = mean,std print(f"====== NODE_test \ttrain={data.X_train.shape} valid={data.X_valid.shape} YY_train_mean={data.Y_mean:.3f} YY_train_std={data.Y_std:.3f}\n") in_features = data.X_train.shape[1] #config.tree_module = node_lib.ODST config.tree_module = quantum_forest.DeTree Learners,last_train_prediction=[],0 qForest = quantum_forest.QForest_Net(in_features,config, feat_info=feat_info,visual=visual).to(config.device) Learners.append(qForest) if False: # trigger data-aware init,作用不明显 with torch.no_grad(): res = qForest(torch.as_tensor(data.X_train[:1000], device=config.device)) #if torch.cuda.device_count() > 1: model = nn.DataParallel(model) #weight_decay的值需要反复适配 如取1.0e-6 还可以 0.61142-0.58948 optimizer=QHAdam; optimizer_params = { 'nus':(0.7, 1.0), 'betas':(0.95, 0.998),'lr':config.lr_base,'weight_decay':1.0e-8 } #一开始收敛快,后面要慢一些 #optimizer = torch.optim.Adam; optimizer_params = {'lr':config.lr_base } from IPython.display import clear_output loss_history, mse_history = [], [] best_mse = float('inf') best_step_mse = 0 early_stopping_rounds = 3000 report_frequency = 1000 config.eval_batch_size = 512 if config.leaf_output=="distri2CNN" else \ 512 if config.path_way=="TREE_map" else 1024 wLearner=Learners[-1] trainer = quantum_forest.Experiment( config,data, model=wLearner, loss_function=F.mse_loss, experiment_name=config.experiment, warm_start=False, Optimizer=optimizer, optimizer_params=optimizer_params, verbose=True, #True n_last_checkpoints=5 ) config.trainer = trainer trainer.SetLearner(wLearner) print(f"====== trainer.learner={trainer.model}\ntrainer.opt={trainer.opt}"\ f"\n====== config={config.__dict__}") print(f"====== X_train={data.X_train.shape},YY_train={YY_train.shape}") print(f"====== |YY_train|={np.linalg.norm(YY_train):.3f},mean={data.Y_mean:.3f} std={data.Y_std:.3f}") wLearner.AfterEpoch(isBetter=True, epoch=0) epoch,t0=0,time.time() for batch in node_lib.iterate_minibatches(data.X_train, YY_train, batch_size=config.batch_size,shuffle=True, epochs=float('inf')): metrics = trainer.train_on_batch(*batch, device=config.device) loss_history.append(metrics['loss']) if trainer.step%10==0: symbol = "^" if config.cascade_LR else "" print(f"\r============ {trainer.step}{symbol}\t{metrics['loss']:.5f}\tL1=[{wLearner.reg_L1:.4g}*{config.reg_L1}]" f"\tL2=[{wLearner.L_gate:.4g}*{config.reg_Gate}]\ttime={time.time()-t0:.2f}\t" ,end="") if trainer.step % report_frequency == 0: epoch=epoch+1 if torch.cuda.is_available(): torch.cuda.empty_cache() mse = trainer.AfterEpoch(epoch,data.X_valid,YY_valid,best_mse) if mse < best_mse: best_mse = mse best_step_mse = trainer.step trainer.save_checkpoint(tag='best_mse') mse_history.append(mse) if config.average_training: trainer.load_checkpoint() # last trainer.remove_old_temp_checkpoints() VisualAfterEpoch(epoch,visual,config,mse) if False and epoch%10==9: #有bug啊 #YY_valid = YY_valid- prediction dict_info,train_pred = trainer.evaluate_mse(data.X_train, YY_train, device=config.device, batch_size=config.eval_batch_size) #last_train_prediction = last_train_prediction+train_pred mse_train = dict_info["mse"] YY_train = YY_train-train_pred mean,std = YY_train.mean(), YY_train.std() qForest = quantum_forest.QForest_Net(in_features,config, feat_info=feat_info,visual=visual).to(config.device) #Learners.append(qForest) wLearner=qForest#Learners[-1] print(f"NODE_test::Expand@{epoch} eval_train={mse_train:.2f} YY_train={np.linalg.norm(YY_train)}") trainer.SetModel(wLearner) if trainer.step>50000: break if trainer.step > best_step_mse + early_stopping_rounds: print('BREAK. There is no improvment for {} steps'.format(early_stopping_rounds)) print("Best step: ", best_step_mse) print(f"Best Val MSE: {best_mse:.5f}") break if data.X_test is not None: mse = trainer.AfterEpoch(epoch,data.X_test, YY_test,best_mse,isTest=True) if False: if torch.cuda.is_available(): torch.cuda.empty_cache() trainer.load_checkpoint(tag='best_mse') t0=time.time() dict_info,prediction = trainer.evaluate_mse(data.X_test, YY_test, device=config.device, batch_size=config.eval_batch_size) if config.cascade_LR: prediction=LinearRgressor.AfterPredict(data.X_test,prediction) #prediction = prediction*data.accu_scale+data.Y_mu_0 prediction = data.Y_trans(prediction) mse = ((data.y_test - prediction) ** 2).mean() #mse = dict_info["mse"] reg_Gate = dict_info["reg_Gate"] print(f'====== Best step: {trainer.step} test={data.X_test.shape} ACCU@Test={mse:.5f} \treg_Gate:{reg_Gate:.4g}time={time.time()-t0:.2f}' ) best_mse = mse trainer.save_checkpoint(tag=f'last_{mse:.6f}') return best_mse,mse def Fold_learning(fold_n,data,config,visual): t0 = time.time() if config.model=="QForest": if config.feat_info == "importance": feat_info = get_feature_info(data,fold_n) else: feat_info = None accu,_ = NODE_test(data,fold_n,config,visual,feat_info) elif config.model=="GBDT": accu,_ = GBDT_test(data,fold_n) else: #"LinearRegressor" model = quantum_forest.Linear_Regressor({'cascade':"ridge"}) accu,_ = model.fit((data.X_train, data.y_train),[(data.X_test, data.y_test)]) print(f"\n======\n====== Fold_{fold_n}\tACCURACY={accu:.5f},time={time.time() - t0:.2f} ====== \n======\n") return if __name__ == "__main__": data = quantum_forest.TabularDataset(dataset,data_path=data_root, random_state=1337, quantile_transform=True, quantile_noise=1e-3) #data = quantum_forest.TabularDataset(dataset,data_path=data_root, random_state=1337, quantile_transform=True) config = quantum_forest.QForest_config(data,0.002,feat_info="importance") #,feat_info="importance" random_state = 42 config.device = quantum_forest.OnInitInstance(random_state) config.model="QForest" #"QForest" "GBDT" "LinearRegressor" if dataset=="YAHOO" or dataset=="MICROSOFT" or dataset=="CLICK" or dataset=="HIGGS": config,visual = InitExperiment(config, 0) data.onFold(0,config,pkl_path=f"{data_root}{dataset}/FOLD_Quantile_.pickle") Fold_learning(0,data, config,visual) else: nFold = 5 if dataset != "HIGGS" else 20 folds = KFold(n_splits=nFold, shuffle=True) index_sets=[] for fold_n, (train_index, valid_index) in enumerate(folds.split(data.X)): index_sets.append(valid_index) for fold_n in range(len(index_sets)): config, visual = InitExperiment(config, fold_n) train_list=[] for i in range(nFold): if i==fold_n: #test continue elif i==fold_n+1: #valid valid_index=index_sets[i] else: train_list.append(index_sets[i]) train_index=np.concatenate(train_list) print(f"train={len(train_index)} valid={len(valid_index)} test={len(index_sets[fold_n])}") data.onFold(fold_n,config,train_index=train_index, valid_index=valid_index,test_index=index_sets[fold_n],pkl_path=f"{data_root}{dataset}/FOLD_{fold_n}.pickle") Fold_learning(fold_n,data,config,visual) break <file_sep># QuantumForest QuantumForest is a new lib on the model of differentiable decision trees. It has the advantages of both trees and neural networks. Experiments on large datasets show that QuantumForest has higher accuracy than both deep networks and best GBDT libs(XGBoost, Catboost, mGBDT,...). - Keeping **simple tree structure**,easy to use and explain the decision process - **Full differentiability** like neural networks. So we could train it with many powerful optimization algorithms (SGD, Adam, …), just like the training of deep CNN. - Support **batch training** to reduce the memory usage greatly. - Support the **end-to-end learning** mode. Reduce a lot of work on data preprocessing and feature engineering. ![](Differentiable tree_1.png) ## Performance To verify our model and algorithm, we test its performance on **five large datasets**. | | Higgs | Click | YearPrediction | Microsoft | Yahoo | | ----------- | -------------- | -------------- | -------------------- | ------------ | ------------------- | | Train | 10.5M | 800K | 463K | 723K | 544K | | Test | 500K | 200K | 51.6K | 241K | 165K | | Features | 28 | 11 | 90 | 136 | 699 | | Problem | Classification | Classification | Regression | Regression | Regression | | Description | UCI ML Higgs | 2012 KDD Cup | Million Song Dataset | MSLR-WEB 10k | Yahoo LETOR dataset | The following table listed the accuracy of some libraries | | Higgs | Click | YearPrediction | Microsoft | Yahoo | | ------------- | --------- | ---------- | -------------- | ---------- | ---------- | | CatBoost [7] | 0.2434 | 0.3438 | 80.68 | 0.5587 | 0.5781 | | XGBoost [5] | 0.2600 | 0.3461 | 81.11 | 0.5637 | 0.5756 | | NODE [2] | 0.2412 | **0.3309** | 77.43 | 0.5584 | 0.5666 | | mGBDT [21] | OOM | OOM | 80.67 | OOM | OOM | | QuantumForest | **0.237** | 0.3318 | **74.02** | **0.5568** | **0.5656** | *Some results are copied form the testing results of NODE All libraries use default parameters. It’s clear that mGBDT needs much more memory than other libs. mGBDT always failed because out or memory for most large datasets. Both NODE and QuantumForest have higher accuracy than CatBoost and XGBoost. It is a clear sign that differentiable forest model has more potential than classical GBDT models. ## Demo python main_tabular_data.py ## Citation If you find this code useful, please consider citing: ``` [1] <NAME>. "Deep differentiable forest with sparse attention for the tabular data." arXiv preprint arXiv:2003.00223 (2020). [2] <NAME>. "LiteMORT: A memory efficient gradient boosting tree system on adaptive compact distributions." arXiv preprint arXiv:2001.09419 (2020). ``` ## Future work - More huge testing datasets. ​ If anyone has larger dataset, please send to us for testing - More models. - More papers. ## Author <NAME> (<EMAIL>) <file_sep>''' @Author: <NAME> @Date: 2020-02-14 11:06:23 @LastEditTime: 2020-04-03 14:43:47 @LastEditors: Please set LastEditors @Description: In User Settings Edit @FilePath: \QuantumForest\python-package\quantum_forest\QForest_Net.py ''' import torch.nn as nn import seaborn as sns; sns.set() import numpy as np from .DecisionBlock import * import matplotlib.pyplot as plt from .some_utils import * from cnn_models import * class Simple_CNN(nn.Module): def __init__(self, num_blocks, in_channel=3,out_channel=10): super(Simple_CNN, self).__init__() self.in_planes = 64 nK=128 self.conv1 = nn.Conv2d(in_channel, nK, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(nK) #self.linear = nn.Linear(512*block.expansion, num_classes) #self.linear = nn.Linear(1024, out_channel) 有意思 def forward(self, x): if False: #仅用于调试 shape=x.shape x=x.view(shape[0],1,shape[1],shape[2]) x=x.view(shape[0],shape[1],shape[2]) x = torch.max(x,dim=-1).values x = x.mean(dim=-1) return x else: out = F.relu(self.bn1(self.conv1(x))) #out = self.bn1(self.conv1(x)) out = F.avg_pool2d(out, 8) #out = F.max_pool2d(out, 8) out = out.view(out.size(0), -1) if hasattr(self,"linear"): out = self.linear(out) else: out = out.mean(dim=-1) #out = torch.max(out,-1).values 略差 return out class Simple_VGG(nn.Module): def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.constant_(m.bias, 0) def _make_layers(self, cfg, in_channel=3): layers = [] in_channels = in_channel for x in cfg: if x == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1), nn.BatchNorm2d(x), #nn.ReLU(inplace=True) ] in_channels = x #layers += [nn.AvgPool2d(kernel_size=1, stride=1)] return nn.Sequential(*layers) def __init__(self, num_blocks, in_channel=3,out_channel=10): super(Simple_VGG, self).__init__() self.cfg = { 'VGG_1': [64,'M'], 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], } self.type = 'VGG_1' self.features = self._make_layers(self.cfg[self.type],in_channel=in_channel) self.out_channel = out_channel #self.init_weights() #引起振荡,莫名其妙 if False and self.out_channel>1: self.linear = nn.Linear(4096, self.out_channel) nn.init.kaiming_normal_(self.linear.weight) print(self) def forward(self, x): out = self.features(x) out = out.view(out.size(0), -1) if hasattr(self,"linear"): out = self.linear(out) else: if self.out_channel>1: #"classification": out = out.view(out.size(0), -1,self.out_channel) assert len(out.shape)==3 out = out.mean(dim=-2) else: out = out.mean(dim=-1) return out class QForest_Net(nn.Module): def pick_cnn(self): self.back_bone = 'resnet18_x' in_channel = self.config.response_dim if self.config.problem()=="classification": out_channel = self.config.response_dim else: out_channel = 1 # model_name='dpn92' # model_name='senet154' # model_name='densenet121' # model_name='alexnet' # model_name='senet154' #cnn_model = ResNet_custom([2,2,2,2],in_channel=1,out_channel=1) ;#models.resnet18(pretrained=True) cnn_model = Simple_VGG([2,2,2,2],in_channel=in_channel,out_channel=out_channel) return cnn_model def __init__(self, in_features, config,feat_info=None,visual=None): super(QForest_Net, self).__init__() config.feat_info = feat_info self.layers = nn.ModuleList() self.nTree = config.nTree self.config = config #self.gates_cp = nn.Parameter(torch.zeros([1]), requires_grad=True) self.reg_L1 = 0. self.L_gate = 0. if config.leaf_output == "distri2CNN": self.cnn_model = self.pick_cnn() #self.nAtt, self.nzAtt = 0, 0 #sparse attention if self.config.data_normal=="NN": #将来可替换为deepFM self.emb_dims = [in_features,256] #multilayer未见效果 0.590(差于0.569) self.emb_dims = [in_features,128] #self.embedding = nn.ModuleList([nn.Embedding(m, d) for m, d in emb_szs]) nEmb = len(self.emb_dims)-1 self.embeddings = nn.ModuleList( [nn.Linear(self.emb_dims[i], self.emb_dims[i + 1]) for i in range(nEmb)] ) nFeat = self.emb_dims[nEmb] for layer in self.embeddings: nn.init.kaiming_normal_ (layer.weight.data) else: self.embeddings = None nFeat = in_features for i in range(config.nLayers): if i > 0: nFeat = config.nTree feat_info = None hasBN = config.data_normal == "BN" and i > 0 self.layers.append( DecisionBlock(nFeat, config,hasBN=hasBN, flatten_output=False,feat_info=feat_info) #MultiBlock(nFeat, config, flatten_output=False, feat_info=feat_info) ) self.pooling = None self.visual = visual #self.nFeatInX = nFeat print("====== QForest_Net::__init__ OK!!!") #print(self) dump_model_params(self) def forward(self, x): nBatch = x.shape[0] if self.config.feature_fraction<1: x=x[:,self.config.trainer.feat_cands] if self.embeddings is not None: for layer in self.embeddings: x = layer(x) for layer in self.layers: x = layer(x) self.Regularization() #统计Regularization if self.config.leaf_output == "distri2CNN": out = self.cnn_model(x) #x1 = x.contiguous().view(nBatch, -1).mean(dim=-1) #可惜效果不明显 #out += x1 return out else: if self.config.problem()=="classification": assert len(x.shape)==3 x = x.mean(dim=-2) elif self.config.problem()=="regression_N": pass else: x = x.mean(dim=-1) #self.pooling(x) #x = torch.max(x,dim=-1).values return x def Regularization(self): dict_val = self.get_variables({"attention":[],"gate_values":[]}) reg,l1,l2 = 0,0,0 for att in dict_val["attention"]: a = torch.sum(torch.abs(att))/att.numel() l1 = l1+a self.reg_L1 = l1 reg = self.reg_L1*self.config.reg_L1 for gate_values in dict_val["gate_values"]: if self.config.support_vector=="0": a = torch.sum(torch.pow(gate_values, 2))/gate_values.numel() else: gmin,gmax = torch.min(gate_values).item(),torch.max(gate_values).item() a = torch.sum(gate_values)/gate_values.numel() l2 = l2+a self.L_gate = l2 #if self.config.reg_Gate>0: reg = reg+self.L_gate*self.config.reg_Gate #return reg return reg def get_variables(self,var_dic): for layer in self.layers: var_dic = layer.get_variables(var_dic) #attentions.append(att) #all_att = torch.cat(attentions) return var_dic def AfterEpoch(self, isBetter=False, epoch=0, accu=0): attentions=[] if False: for layer in self.layers: #self.nAtt, self.nzAtt = self.nAtt+layer.nAtt, self.nzAtt+layer.nzAtt layer.AfterEpoch(epoch) for att,_ in layer.get_variables(): attentions.append(att.data.detach().cpu().numpy()) else: dict_val = self.get_variables({"attention":[]}) for att in dict_val["attention"]: attentions.append(att.data.detach().cpu().numpy()) attention = np.concatenate(attentions) #.reshape(-1) self.nAtt = attention.size # sparse attention self.nzAtt = self.nAtt - np.count_nonzero(attention) #print(f"\t[nzAttention={self.nAtt} zeros={self.nzAtt},{self.nzAtt * 100.0 / self.nAtt:.4f}%]") #plt.hist(attention) #histo不明显 if self.config.plot_attention: nFeat,nCol = attention.shape[0],attention.shape[1] nCol = min(nFeat*3,attention.shape[1]) cols = random.choices(population = list(range(attention.shape[1])),k = nCol) type="" if self.config.feat_info is None else "sparse" if self.visual is not None: path = f"{self.config.data_set}_{type}_{epoch}" params = {'title':f"{epoch} - {accu:.4f}",'cmap':sns.cm.rocket} self.visual.image(path,attention[:,cols],params=params) else: plt.imshow(attention[:,cols]) plt.grid(b=None) plt.show() return def freeze_some_params(self,freeze_info): for layer in self.layers: layer.freeze_some_params(freeze_info) <file_sep>''' @Author: <NAME> @Date: 2020-02-11 11:22:03 @LastEditTime: 2020-03-07 16:51:19 @LastEditors: Please set LastEditors @Description: In User Settings Edit @FilePath: \QuantumForest\python-package\quantum_forest\__init__.py ''' from .Visualizing import * from .tabular_data import * from .QForest import * from .some_utils import * from .DifferentiableTree import * from .QForest_Net import * from .experiment import * from .LinearRegressor import *
ee1656dc4f9a7e824dd5c655a1c6898f352060bc
[ "Markdown", "Python" ]
4
Python
atangfan/QuantumForest
f884147eadbbc610d943cac8c852c9267a6a1c93
7f44ebd6446978b96a44bf0bbbd1093b01647df7
refs/heads/master
<file_sep>// ArduinoSerialPlotter.cpp : Defines the entry point for the application. // #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #include "ArduinoSerialPlotter.h" #include "real_vector.h" #include "SerialClass.h" // Library described above #include <charconv> #include <fmt/core.h> #include <fmt/format.h> #include <math.h> #include <ostream> #include <stdio.h> #include <string> #include <tchar.h> #include <unordered_map> #include "simdjson.h" using namespace simdjson; #include <GL/glew.h> #include <GLFW/glfw3.h> // chart plotter api allows up to 6 colors, we'll do 8 // #define NK_CHART_MAX_SLOT 8 #define NK_PRIVATE true #define NK_SINGLE_FILE true #define NK_API #define NK_LIB #define NK_MEMCPY std::memcpy #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_STANDARD_VARARGS #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT #define NK_INCLUDE_FONT_BAKING #define NK_INCLUDE_DEFAULT_FONT #define NK_IMPLEMENTATION #define NK_GLFW_GL4_IMPLEMENTATION #define NK_KEYSTATE_BASED_INPUT #include "nuklear.h" #include "nuklear_glfw_gl4.h" NK_API void nk_noop() {} // x,y -> 4 per float, 8 per x,y ergo #define MAX_VERTEX_BUFFER 512 * 1024 #define MAX_ELEMENT_BUFFER (MAX_VERTEX_BUFFER / 4) //#define MAX_VERTEX_BUFFER 4096 * 1024 //#define MAX_ELEMENT_BUFFER 1024 * 1024 //#define MAX_VERTEX_BUFFER 512 * 1024 //#define MAX_ELEMENT_BUFFER 128 * 1024 #ifdef min #undef min #endif #ifdef max #undef max #endif // pcg-random.org typedef struct { uint64_t state; uint64_t inc; } pcg32_random_t; uint32_t pcg32_random_r(pcg32_random_t *rng) { uint64_t oldstate = rng->state; // Advance internal state rng->state = oldstate * 6364136223846793005ULL + (rng->inc | 1); // Calculate output function (XSH RR), uses old state for max ILP uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u; uint32_t rot = oldstate >> 59u; return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); } std::unordered_map<std::string_view, nk_color> color_map = { {"red", nk_color{255, 0, 0, 255}}, {"green", nk_color{0, 255, 0, 255}}, {"blue", nk_color{0, 0, 255, 255}}, {"orange", nk_color{255, 153, 51, 255}}, {"yellow", nk_color{255, 255, 0, 255}}, {"pink", nk_color{255, 51, 204, 255}}, {"purple", nk_color{172, 0, 230, 255}}, {"cyan", nk_color{0, 255, 255, 255}}, {"white", nk_color{255, 255, 255, 255}}}; nk_color get_color(std::string_view v) { auto it = color_map.find(v); if (it != color_map.end()) { return it->second; } else { // return a consistant color for the word by using the hash size_t h = color_map.hash_function()(v); size_t idx = h % color_map.size(); return std::next(color_map.begin(), idx)->second; } } template <typename T> struct smooth_data { T value; T lerp_v; T get_delta(T v) { return v - value; } T get_next_smooth(T v) { // smooth logarithmic curve value = std::lerp(value, v, lerp_v); return value; } T get_next_smooth_lower(T v) { if (v < value) return value = v; else return value = std::lerp(value, v, lerp_v); } T get_next_smooth_upper(T v) { if (v > value) return value = v; else return value = std::lerp(value, v, lerp_v); } }; std::string example_json = R"raw({"t": 5649, "ng": 5, "lu": 4086, "g": [ { "t": "Temps", "xvy": 0, "pd": 60, "sz": 3, "l": [ "Low Temp", "High Temp", "Smooth Avg" ], "c": [ "green", "orange", "cyan" ], "d": [ 80.48750305, 80.82499694, 80.65625 ] }, { "t": "Pump Status", "xvy": 0, "pd": 60, "sz": 3, "l": [ "Pump", "Thermal", "Light" ], "c": [ "green", "orange", "cyan" ], "d": [ 0, 0, 0 ] }, { "t": "Lux", "xvy": 0, "pd": 60, "sz": 4, "l": [ "Value", "Smooth", "Low", "High" ], "c": [ "green", "orange", "cyan", "yellow" ], "d": [ 2274.62939453, 2277.45947265, 4050, 4500 ] }, { "t": "Temp Diff", "xvy": 0, "pd": 60, "sz": 4, "l": [ "dFarenheit", "sum", "Low", "High" ], "c": [ "green", "orange", "cyan", "yellow" ], "d": [ 0, 0, 0.5, 10 ] }, { "t": "Power", "xvy": 0, "pd": 60, "sz": 3, "l": [ "watts (est. ligth)", "watts (1.9~gpm)", "watts (1gpm)" ], "c": [ "green", "orange", "cyan" ], "d": [ 181.78063964, 114.88922882, 59.35943603 ] } ] } 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 )raw"; std::string mangled_example_json = R"raw( { "t": "Temp Diff", "xvy": 0, "pd": 60, "sz": 4, "l": [ "dFarenheit", "sum", "Low", "High" ], "c": [ "green", "orange", "cyan", "yellow" ], "d": [ 0, 0, 0.5, 10 ] }, { "t": "Power", "xvy": 0, "pd": 60, "sz": 3, "l": [ "watts (est. ligth)", "watts (1.9~gpm)", "watts (1gpm)" ], "c": [ "green", "orange", "cyan" ], "d": [ 181.78063964, 114.88922882, 59.35943603 ] } ] } !@#$%^&*()`;'?><.0123456789some_errant_data {"t": 5649, "ng": 5, "lu": 4086, "g": [ { "t": "Temps", "xvy": 0, "pd": 60, "sz": 3, "l": [ "Low Temp", "High Temp", "Smooth Avg" ], "c": [ "green", "orange", "cyan" ], "d": [ 80.48750305, 80.82499694, 80.65625 ] }, { "t": "Pump Status", "xvy": 0, "pd": 60, "sz": 3, "l": [ "Pump", "Thermal", "Light" ], "c": [ "green", "orange", "cyan" ], "d": [ 0, 0, 0 ] }, { "t": "Lux", "xvy": 0, "pd": 60, "sz": 4, "l": [ "Value", "Smooth", "Low", "High" ], "c": [ "green", "orange", "cyan", "yellow" ], "d": [ 2274.62939453, 2277.45947265, 4050, 4500 ] }, )raw"; static void error_callback(int e, const char *d) { printf("Error %d: %s\n", e, d); } std::string cout_buffer; template <typename... Args> void print_out(Args &&...args) { fmt::format_to(std::back_inserter(cout_buffer), std::forward<Args>(args)...); std::cout << cout_buffer; cout_buffer.clear(); } template <typename... Args> void format_out(Args &&...args) { fmt::format_to(std::back_inserter(cout_buffer), std::forward<Args>(args)...); std::cout << cout_buffer; // cout_buffer.clear(); } struct graph_t { real::vector<real::vector<struct nk_vec2>> values; // x (evens), y (odds) real::vector<float> points; real::vector<std::string> labels; real::vector<nk_color> colors; smooth_data<float> upper_value; smooth_data<float> lower_value; size_t limit = 60; size_t slots = 0; std::string title; }; size_t get_lsb_set(unsigned int v) noexcept { // find the number of trailing zeros in 32-bit v int r; // result goes here static const int MultiplyDeBruijnBitPosition[32] = {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27]; return r; } void nk_plot_multi(struct nk_context *ctx, enum nk_chart_type type, const float **values, int count, int offset, int slots) { int i = 0; int j = 0; float min_value; float max_value; NK_ASSERT(ctx); NK_ASSERT(values); if (!ctx || !values || !count || !slots) return; min_value = values[0][offset]; max_value = values[0][offset]; for (j = 0; j < slots; ++j) { for (i = 0; i < count; ++i) { min_value = NK_MIN(values[j][i + offset], min_value); max_value = NK_MAX(values[j][i + offset], max_value); } } if (nk_chart_begin(ctx, type, count, min_value, max_value)) { for (j = 0; j < slots; ++j) { for (i = 0; i < count; ++i) { nk_chart_push_slot(ctx, values[j][i + offset], j); } } nk_chart_end(ctx); } } nk_flags nk_chart_draw_yticks(struct nk_context *ctx, struct nk_window *win, struct nk_chart *g, float yoffset, float xoffset, float spacing, nk_flags alignment) { struct nk_panel *layout = win->layout; const struct nk_input *i = &ctx->input; struct nk_command_buffer *out = &win->buffer; nk_flags ret = 0; struct nk_vec2 cur; struct nk_rect bounds; struct nk_color color; float step; float range; float ratio; step = g->w / (float)g->slots[0].count; range = g->slots[0].max - g->slots[0].min; // ratio = (value - g->slots[slot].min) / range; float half_step = step * 0.5f; float h = g->h; const struct nk_style *style; struct nk_vec2 item_padding; struct nk_text text; style = &ctx->style; item_padding = style->text.padding; text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; text.text = ctx->style.text.color; color = g->slots[0].color; color.a = 128; // cur.x = g->x + (float)(step * (float)g->slots[slot].index); cur.x = g->x; // skip a half step cur.y = yoffset; float bottom = (g->y + g->h); if (alignment & NK_TEXT_ALIGN_LEFT) { float style_offset = bottom - (style->font->height / 2.0f); bounds.x = g->x + step + xoffset; bounds.h = style->font->height; // half_step + xoffset; // bounds.w = 20.0f; for (; cur.y < h; cur.y += spacing) { nk_stroke_line(out, g->x, bottom - cur.y, g->x + half_step, bottom - cur.y, 2.0f, nk_color{255, 255, 255, 255}); float percentage = cur.y / h; float value = std::lerp(g->slots[0].min, g->slots[0].max, percentage); char floating_point[64]; auto label = std::to_chars(floating_point, (floating_point) + 64, value); *label.ptr = 0; size_t len = label.ptr - floating_point; bounds.y = style_offset - cur.y; // get the width so we can print w/ a solid background // bounds.w = style->font->width(style->font->userdata, style->font->height, (const char *)floating_point, // len); bounds.w = 30.0f; // write text nk_fill_rect(&win->buffer, bounds, 0.0f, style->chart.background.data.color); nk_widget_text(&win->buffer, bounds, floating_point, len, &text, NK_TEXT_ALIGN_LEFT | NK_TEXT_ALIGN_BOTTOM, style->font); } } else { // NK_TEXT_ALIGN_RIGHT float style_offset = bottom - (style->font->height / 2.0f); float right = (g->x + g->w); bounds.h = style->font->height; bounds.w = half_step + xoffset; bounds.x = ((right - step) - bounds.w) - xoffset; for (; cur.y < h; cur.y += spacing) { nk_stroke_line(out, right - half_step, bottom - cur.y, right, bottom - cur.y, 2.0f, nk_color{255, 255, 255, 255}); float percentage = cur.y / h; float value = std::lerp(g->slots[0].min, g->slots[0].max, percentage); char floating_point[64]; auto label = std::to_chars(floating_point, (floating_point) + 64, value); *label.ptr = 0; size_t len = label.ptr - floating_point; bounds.y = style_offset - cur.y; // get the width so we can print w/ a solid background // bounds.w = style->font->width(style->font->userdata, style->font->height, (const char *)floating_point, // len); bounds.w = 30.0f; // write text nk_fill_rect(&win->buffer, bounds, 0.0f, style->chart.background.data.color); nk_widget_text(&win->buffer, bounds, floating_point, len, &text, NK_TEXT_ALIGN_LEFT | NK_TEXT_ALIGN_BOTTOM, style->font); } } return ret; } nk_flags nk_chart_draw_line(struct nk_context *ctx, struct nk_rect chart_bounds, float min_value, float max_value, float value, float line_length, float line_thickness, nk_color color, nk_flags alignment) { // nk_tooltip(ctx, "text"); float range = max_value - min_value; // ctx->current-> if (alignment & NK_TEXT_ALIGN_LEFT) { float y = (chart_bounds.y + chart_bounds.h) - ((value - min_value) / range) * chart_bounds.h; nk_stroke_line(&ctx->current->buffer, chart_bounds.x, y, chart_bounds.x + line_length, y, line_thickness, color); } else if (alignment & NK_TEXT_ALIGN_TOP) { float x = (chart_bounds.x) + ((value - min_value) / range) * chart_bounds.w; nk_stroke_line(&ctx->current->buffer, x, chart_bounds.y, x, chart_bounds.y + line_length, line_thickness, color); } else if (alignment & NK_TEXT_ALIGN_BOTTOM) { float x = (chart_bounds.x) + ((value - min_value) / range) * chart_bounds.w; float bottom = chart_bounds.y + chart_bounds.h; nk_stroke_line(&ctx->current->buffer, x, bottom, x, bottom - line_length, line_thickness, color); } else { float y = (chart_bounds.y + chart_bounds.h) - ((value - min_value) / range) * chart_bounds.h; float right = chart_bounds.x + chart_bounds.w; nk_stroke_line(&ctx->current->buffer, right, y, right - line_length, y, line_thickness, color); } return 0; } nk_flags nk_chart_draw_value(struct nk_context *ctx, struct nk_rect chart_bounds, float min_value, float max_value, float value, float line_length, float line_thickness, nk_color color, nk_flags alignment, nk_flags text_alignment) { float range = max_value - min_value; char text_value[64]; auto chrs = std::to_chars(text_value, text_value + 64, value); *chrs.ptr = 0; size_t len = chrs.ptr - text_value; struct nk_text text; struct nk_vec2 item_padding; item_padding = (&ctx->style)->text.padding; // text settings text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = (&ctx->style)->window.background; text.text = color; if (alignment & NK_TEXT_ALIGN_LEFT) { float y = (chart_bounds.y + chart_bounds.h) - ((value - min_value) / range) * chart_bounds.h; struct nk_rect text_bounds = chart_bounds; text_bounds.y = y - (text.padding.y + (ctx->style.font->height) / 2.0); text_bounds.h = ctx->style.font->height; text_bounds.x += line_length; text_bounds.w -= 2 * line_length; nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); // nk_draw_text(&ctx->current->buffer, , , , ctx->style.font, color, color); } else if (alignment & NK_TEXT_ALIGN_TOP) { float x = (chart_bounds.x) + ((value - min_value) / range) * chart_bounds.w; float text_w = ctx->style.font->width(ctx->style.font->userdata, ctx->style.font->height, (const char *)text_value, len); struct nk_rect text_bounds = chart_bounds; text_bounds.y += line_length; text_bounds.h -= 2 * line_length; text_bounds.x = x - ((text_w + (2.0f * text.padding.x)) / 2.0f); text_bounds.w = text_w + (2.0f * text.padding.x); nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); } else if (alignment & NK_TEXT_ALIGN_BOTTOM) { float x = (chart_bounds.x) + ((value - min_value) / range) * chart_bounds.w; float text_w = ctx->style.font->width(ctx->style.font->userdata, ctx->style.font->height, (const char *)text_value, len); struct nk_rect text_bounds = chart_bounds; text_bounds.y += line_length; text_bounds.h -= 2 * line_length; text_bounds.x = x - ((text_w + (2.0f * text.padding.x)) / 2.0f); text_bounds.w = text_w + (2.0f * text.padding.x); nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); } else { float y = (chart_bounds.y + chart_bounds.h) - ((value - min_value) / range) * chart_bounds.h; struct nk_rect text_bounds = chart_bounds; text_bounds.y = y - (ctx->style.font->height) / 2.0; text_bounds.h = ctx->style.font->height; text_bounds.x += line_length; text_bounds.w -= 2 * line_length; nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); } return 0; } nk_flags nk_chart_draw_line_uv(struct nk_context *ctx, struct nk_rect chart_bounds, float uv, float line_length, float line_thickness, nk_color color, nk_flags alignment) { if (alignment & NK_TEXT_ALIGN_LEFT) { float y = (chart_bounds.y + chart_bounds.h) - (uv * chart_bounds.h); nk_stroke_line(&ctx->current->buffer, chart_bounds.x, y, chart_bounds.x + line_length, y, line_thickness, color); } else if (alignment & NK_TEXT_ALIGN_TOP) { float x = (chart_bounds.x) + (uv * chart_bounds.w); nk_stroke_line(&ctx->current->buffer, x, chart_bounds.y, x, chart_bounds.y + line_length, line_thickness, color); } else if (alignment & NK_TEXT_ALIGN_BOTTOM) { float x = (chart_bounds.x) + (uv * chart_bounds.w); float bottom = chart_bounds.y + chart_bounds.h; nk_stroke_line(&ctx->current->buffer, x, bottom, x, bottom - line_length, line_thickness, color); } else { float y = (chart_bounds.y + chart_bounds.h) - (uv * chart_bounds.h); float right = chart_bounds.x + chart_bounds.w; nk_stroke_line(&ctx->current->buffer, right, y, right - line_length, y, line_thickness, color); } return 0; } nk_flags nk_chart_draw_value_uv(struct nk_context *ctx, struct nk_rect chart_bounds, float min_value, float max_value, float uv, float line_length, float line_thickness, nk_color color, nk_flags alignment, nk_flags text_alignment) { float range = max_value - min_value; float value = min_value + (uv * range); char text_value[64]; auto chrs = std::to_chars(text_value, text_value + 64, value); *chrs.ptr = 0; size_t len = chrs.ptr - text_value; struct nk_text text; struct nk_vec2 item_padding; item_padding = (&ctx->style)->text.padding; // text settings text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = (&ctx->style)->window.background; text.text = color; if (alignment & NK_TEXT_ALIGN_LEFT) { float y = (chart_bounds.y + chart_bounds.h) - (uv * chart_bounds.h); struct nk_rect text_bounds = chart_bounds; text_bounds.y = y - (text.padding.y + (ctx->style.font->height) / 2.0); text_bounds.h = ctx->style.font->height; text_bounds.x += line_length; text_bounds.w -= 2 * line_length; nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); // nk_draw_text(&ctx->current->buffer, , , , ctx->style.font, color, color); } else if (alignment & NK_TEXT_ALIGN_TOP) { float x = (chart_bounds.x) + (uv * chart_bounds.w); float text_w = ctx->style.font->width(ctx->style.font->userdata, ctx->style.font->height, (const char *)text_value, len); struct nk_rect text_bounds = chart_bounds; text_bounds.y += line_length; text_bounds.h -= 2 * line_length; text_bounds.x = x - ((text_w + (2.0f * text.padding.x)) / 2.0f); text_bounds.w = text_w + (2.0f * text.padding.x); nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); } else if (alignment & NK_TEXT_ALIGN_BOTTOM) { float x = (chart_bounds.x) + (uv * chart_bounds.w); float text_w = ctx->style.font->width(ctx->style.font->userdata, ctx->style.font->height, (const char *)text_value, len); struct nk_rect text_bounds = chart_bounds; text_bounds.y += line_length; text_bounds.h -= 2 * line_length; text_bounds.x = x - ((text_w + (2.0f * text.padding.x)) / 2.0f); text_bounds.w = text_w + (2.0f * text.padding.x); nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); } else { float y = (chart_bounds.y + chart_bounds.h) - (uv * chart_bounds.h); struct nk_rect text_bounds = chart_bounds; text_bounds.y = y - (ctx->style.font->height) / 2.0; text_bounds.h = ctx->style.font->height; text_bounds.x += line_length; text_bounds.w -= 2 * line_length; nk_widget_text(&ctx->current->buffer, text_bounds, text_value, len, &text, text_alignment, ctx->style.font); } return 0; } std::string stream_buffer; // returns the number of graphs to draw, 0 -> no data / no change size_t handle_json(ondemand::parser &parser, struct nk_context *ctx, real::vector<graph_t> &graphs, const char *ptr, uint32_t read_count) { size_t graphs_to_display = 0; if (read_count) { // make room for simdjson's scratchbuffer and the incoming data if (stream_buffer.capacity() < (stream_buffer.size() + read_count + (SIMDJSON_PADDING + 1))) stream_buffer.reserve((stream_buffer.size() + read_count) * 2 + (SIMDJSON_PADDING + 1)); // append the data in case we had incomplete data before. stream_buffer.append(ptr, read_count); // wait for buffer to be a decent size if (stream_buffer.size() < 512) return graphs_to_display; // validate buffer is utf8 once if (!simdjson::validate_utf8(stream_buffer.data(), stream_buffer.size())) return graphs_to_display; ondemand::document graph_data; do { auto lbrace = std::find(stream_buffer.data(), stream_buffer.data() + stream_buffer.size(), '{'); size_t dist = lbrace - stream_buffer.data(); padded_string_view json(stream_buffer.data() + dist, stream_buffer.size() - dist, stream_buffer.capacity() - dist); auto error = parser.iterate(json).get(graph_data); size_t g = 0; if (!error) { #if 1 // bool result = true; std::string_view v; try { // get the view of the json object // this effectively validates that we have a complete json object (no errors) in our buffer // seems like additional effort auto error = simdjson::to_json_string(graph_data).get(v); if (error == simdjson::INCOMPLETE_ARRAY_OR_OBJECT) { // wait for object to complete in a another call return graphs_to_display; } else if (error != simdjson::SUCCESS) { // general failure move buffer over by one stream_buffer.erase(stream_buffer.begin()); return graphs_to_display; } // now we extract the data we need /* ondemand::object obj; auto objerr = graph_data.get_object().get(obj); if (objerr == simdjson::INCOMPLETE_ARRAY_OR_OBJECT) { //nothing to parse here return graphs_to_display; } else if (objerr != simdjson::SUCCESS) { stream_buffer.erase(stream_buffer.begin()); return graphs_to_display; } else { //ok? v = {stream_buffer.data()+dist, 1}; //stream_buffer.capacity()-dist } */ /* ondemand::json_type t; auto error = graph_data.type().get(t); if (error == simdjson::INCOMPLETE_ARRAY_OR_OBJECT) { // wait for object to complete in a another call return graphs_to_display; } else if (error != simdjson::SUCCESS) { stream_buffer.erase(stream_buffer.begin()); return graphs_to_display; } if (t != ondemand::json_type::object) { stream_buffer.erase(stream_buffer.begin()); return graphs_to_display; } */ // size_t ts; // auto err = graph_data.get_object().find_field("t").get(ts); size_t ts; auto err = graph_data["t"].get_uint64().get(ts); if (err) { // could not find timestamp field // erase the object we read from the stream stream_buffer.erase(size_t{0}, (v.data() + v.size()) - stream_buffer.data()); continue; } else { ondemand::array graphs_array; auto graphs_err = graph_data["g"].get_array().get(graphs_array); if (graphs_err) { // could not find the g field (graphs) // erase the object we read from the stream stream_buffer.erase(size_t{0}, (v.data() + v.size()) - stream_buffer.data()); continue; // return graphs_to_display; } else { for (auto graph : graphs_array) { // add graph to keep track of if (g >= graphs.size()) { graphs.emplace_back(); // graphs[g].values.reserve(128); }; std::string_view title; if (auto title_err = graph["t"].get_string().get(title)) { } else { graphs[g].title = title; } ondemand::array labels_array; if (auto labels_err = graph["l"].get_array().get(labels_array)) { } else { size_t count = 0; for (auto label : labels_array) { if (count >= graphs[g].values.size()) { graphs[g].values.emplace_back(); graphs[g].values[count].reserve(graphs[g].limit); graphs[g].labels.emplace_back(""); graphs[g].colors.emplace_back(ctx->style.chart.color); } auto v = label.get_string(); auto vw = v.value(); graphs[g].labels[count] = vw; graphs[g].colors[count] = get_color(vw); count++; } } // if we have a color for the index it overrides the hashed one ondemand::array colors_array; if (auto color_err = graph["c"].get_array().get(colors_array)) { } else { size_t count = 0; for (auto color : colors_array) { if (count >= graphs[g].values.size()) { graphs[g].values.emplace_back(); graphs[g].values[count].reserve(graphs[g].limit); graphs[g].labels.emplace_back(""); graphs[g].colors.emplace_back(ctx->style.chart.color); } auto v = color.get_string(); auto vw = v.value(); graphs[g].colors[count] = get_color(vw); count++; } } size_t limit = 60; if (auto pd_err = graph["pd"].get(limit)) { // err } else { // clamp to at least 1 data point graphs[g].limit = limit > 0 ? limit : 1; } float mn = std::numeric_limits<float>::max(); float mx = std::numeric_limits<float>::min(); uint32_t count = 0; float flt_ts = ts; ondemand::array data_points; if (auto d_err = graph["d"].get_array().get(data_points)) { return false; } else { // go through data points; for (auto value : data_points) { if (count >= graphs[g].values.size()) { graphs[g].values.emplace_back(); graphs[g].values[count].reserve(graphs[g].limit); graphs[g].labels.emplace_back(""); graphs[g].colors.emplace_back(ctx->style.chart.color); } struct nk_vec2 point; point.x = flt_ts; point.y = (float)(double)value; graphs[g].values[count].emplace_back(point); // if (graphs[g].values[count].size() > graphs[g].limit) { graphs[g].values[count].erase(graphs[g].values[count].begin()); } count++; } graphs[g].slots = count; g++; } } // send the object out to console, make room from the start if (v.size() > (cout_buffer.capacity() - cout_buffer.size())) { if (v.size() > cout_buffer.capacity()) cout_buffer.reserve(cout_buffer.capacity() * 2); cout_buffer.erase(size_t{0}, v.size()); } // fmt::format_to(std::back_inserter(cout_buffer), "{}", v); cout_buffer.append(v); // erase whatever we just read stream_buffer.erase(size_t{0}, (v.data() + v.size()) - stream_buffer.data()); } } } catch (const std::exception &err) { cout_buffer.clear(); fmt::format_to(std::back_inserter(cout_buffer), "{}\n\n{}", err.what(), v); // format_out("{}\n\n", err.what(), v); // shouldn't allocate in a catch block g = 0; stream_buffer.erase(stream_buffer.begin()); return graphs_to_display; } graphs_to_display = g > 0 ? g : graphs_to_display; #endif } else { stream_buffer.erase(size_t{0}, dist ? dist : size_t{1}); // stream_buffer.erase(stream_buffer.begin()); return graphs_to_display = 0; } } while (stream_buffer.size() >= 512); return graphs_to_display; } else { return graphs_to_display; } } void clear_data(real::vector<graph_t> &graphs) { for (size_t i = 0; i < graphs.size(); i++) { for (size_t s = 0; s < graphs[s].values.size(); s++) graphs[i].values[s].clear(); graphs[i].colors.clear(); graphs[i].title.clear(); graphs[i].points.clear(); graphs[i].upper_value.value = 0.0f; graphs[i].lower_value.value = 0.0f; } } void nk_scroll(struct nk_context *ctx, float v) { struct nk_window *win = ctx->current; win->edit.scrollbar.y = v; } int main(int argc, char *argv[]) { pcg32_random_t rng; rng.inc = (ptrdiff_t)&rng; pcg32_random_r(&rng); rng.state = std::chrono::steady_clock::now().time_since_epoch().count(); pcg32_random_r(&rng); simdjson::ondemand::parser parser; // pcg32_random_r real::vector<graph_t> graphs; graphs.reserve(32); cout_buffer.reserve(1024); stream_buffer.reserve(4096); /*GUI THINGS*/ /* Platform */ static GLFWwindow *win; int width = 0, height = 0; struct nk_context *ctx; struct nk_colorf bg; struct nk_image img; uint32_t window_width = 1920; uint32_t window_height = 1080; int graph_width = 500; int graph_height = 500; int antialiasing = true; /* GLFW */ glfwSetErrorCallback(error_callback); if (!glfwInit()) { fprintf(stdout, "[GFLW] failed to init!\n"); exit(1); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif win = glfwCreateWindow(window_width, window_height, "Serial Plotter", NULL, NULL); glfwMakeContextCurrent(win); glfwGetWindowSize(win, &width, &height); /* OpenGL */ glViewport(0, 0, width, height); glewExperimental = 1; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to setup GLEW\n"); exit(1); } ctx = nk_glfw3_init(win, NK_GLFW3_INSTALL_CALLBACKS, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); // load fonts { struct nk_font_atlas *atlas; nk_glfw3_font_stash_begin(&atlas); /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, * "../../../extra_font/DroidSans.ttf", 14, 0);*/ /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, * "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/ /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, * "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/ struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0); /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, * "../../../extra_font/ProggyTiny.ttf", 10, 0);*/ /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, * "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/ nk_glfw3_font_stash_end(); if (clean) nk_style_set_font(ctx, &clean->handle); /*nk_style_load_all_cursors(ctx, atlas->cursors);*/ /*nk_style_set_font(ctx, &droid->handle);*/ } int xticks = 4; int yticks = 4; size_t mx_width = 1024; size_t alloc_width = 1024 + SIMDJSON_PADDING; char *ptr = (char *)calloc(alloc_width, 1); size_t sz = _msize(ptr); sz = sz > alloc_width ? sz : alloc_width; char *edit_ptr = (char *)calloc(alloc_width, 1); size_t edit_sz = _msize(edit_ptr); edit_sz = edit_sz > alloc_width ? edit_sz : alloc_width; char *txtedit = (char *)calloc(alloc_width, 1); size_t txtedit_sz = _msize(txtedit); txtedit_sz = txtedit_sz > alloc_width ? txtedit_sz : alloc_width; int txtedit_len[2] = {0, 0}; char *compath = (char *)calloc(128, 1); size_t compath_sz = 128; // don't connect Serial SerialPort{}; auto SerialPorts = SerialPort.ListAvailable(); // go to fill in first available port for (size_t i = 0; i < SerialPorts.size(); i++) { if (SerialPorts[i]) { size_t port_num = get_lsb_set(SerialPorts[i]); auto result = std::to_chars(txtedit, (txtedit + txtedit_sz), port_num); *result.ptr = 0; txtedit_len[0] = result.ptr - txtedit; break; } } int read_count = 0; int edit_count = 0; // make sure we 0 ptr[0] = 0; char *bufend = ptr; size_t i = 0; std::string comport_path; std::string graph_title; std::string edit_string; size_t last_timestamp = std::chrono::steady_clock::now().time_since_epoch().count(); size_t last_ok_timestamp = last_timestamp; int demo_mode = true; int data_auto_scroll = true; int example_json_mode = false; int baud_rate = 115200; size_t graphs_to_display = 0; float zoom_factor = 0.20; float zoom_rate = 0.01f; float line_width = 1.0f; /* Main Loop */ struct nk_rect window_bounds = nk_rect(0, 0, width, height); /* int fps_limit = glfwGetVideoMode(glfwGetPrimaryMonitor())->refreshRate; */ int fps_cap = true; int vsync = true; int fps_delay = 16; const size_t bytes_per_second = baud_rate / 8; const size_t full_buffer = (mx_width - (2 * SIMDJSON_PADDING)); const size_t ns_per_second = 1'000'000'000; const size_t ms_per_ns = 1'000'000; size_t baud_delay = ((full_buffer * ns_per_second) / bytes_per_second) + (2 * ms_per_ns); size_t frame_rate_delay = 33'000'000; size_t delay = 33'000'000; delay = NK_MIN(baud_delay, frame_rate_delay); /* Turn on VSYNC */ glfwSwapInterval(vsync); size_t previous_timestamp = 0; while (!glfwWindowShouldClose(win)) { /* Input */ glfwPollEvents(); nk_glfw3_new_frame(); size_t vw_height = graphs.size() * 240 + 200; /* Do timestamp things */ size_t current_timestamp = std::chrono::steady_clock::now().time_since_epoch().count(); size_t timestamp_diff = current_timestamp - previous_timestamp; previous_timestamp = current_timestamp; const struct nk_rect bounds = nk_rect(0, 0, width, height); if (nk_begin(ctx, "Serial Plotter", bounds, NK_WINDOW_BORDER)) { if (nk_tree_push_hashed(ctx, NK_TREE_TAB, "Options", nk_collapse_states::NK_MAXIMIZED, "_", 1, __LINE__)) { nk_layout_row_dynamic(ctx, 30, 4); nk_label(ctx, "COM Port:", NK_TEXT_LEFT); nk_edit_string(ctx, NK_EDIT_SIMPLE, txtedit, txtedit_len, 4, nk_filter_decimal); nk_property_int(ctx, "Baud", 9600, &baud_rate, INT_MAX, 1, 1.0f); if (SerialPort.IsConnected()) { if (demo_mode) { // if we were in demo mode clear data clear_data(graphs); graphs_to_display = 0; } demo_mode = false; if (nk_button_label(ctx, "Disconnect")) { SerialPort.Disconnect(); } } else { if (nk_button_label(ctx, "Connect")) { comport_path.clear(); fmt::format_to(std::back_inserter(comport_path), std::string_view{"\\\\.\\COM{}"}, std::string_view{txtedit, (size_t)txtedit_len[0]}); // print_out(std::string_view{"attempting to connect to {}...\n"}, comport_path); fmt::format_to(std::back_inserter(cout_buffer), "attempting to connect to {}...", comport_path); uint32_t port_num = 0; std::from_chars(txtedit, (txtedit + ((size_t)txtedit_len)), port_num, 10); int result = SerialPort.Connect(port_num, false, baud_rate); if (result == 0) result = SerialPort.Connect(comport_path.data(), false, baud_rate); // print_out(std::string_view{"{}"}, result != 0 ? std::string_view{"success!"} : // std::string_view{"failed!"}); fmt::format_to(std::back_inserter(cout_buffer), std::string_view{"{}"}, result != 0 ? std::string_view{"success!"} : std::string_view{"failed!"}); if (result) { const size_t bytes_per_second = baud_rate / 8; const size_t full_buffer = (mx_width - (2 * SIMDJSON_PADDING)); const size_t ns_per_second = 1'000'000'000; const size_t ns_per_ms = 1'000'000; size_t baud_delay = ((full_buffer * ns_per_second) / bytes_per_second) + (2 * ns_per_ms); delay = baud_delay; } if (result) demo_mode = false; } } if (nk_tree_push_hashed(ctx, NK_TREE_TAB, "Gui", nk_collapse_states::NK_MINIMIZED, "_", 1, __LINE__)) { nk_layout_row_dynamic(ctx, 30, 2); nk_label(ctx, "Marks (x-axis)", NK_TEXT_ALIGN_LEFT); nk_slider_int(ctx, 2, &xticks, 20, 1); nk_label(ctx, "Marks (y-axis)", NK_TEXT_ALIGN_LEFT); nk_slider_int(ctx, 2, &yticks, 20, 1); //nk_property_int(ctx, "Marks (x-axis)", 1, &xticks, 10, 1, 0.1f); //nk_property_int(ctx, "Marks (y-axis)", 1, &yticks, 10, 1, 0.1f); nk_property_int(ctx, "Width", 100, &graph_width, 0xffff, 1, 1.0f); nk_property_int(ctx, "Height", 100, &graph_height, 0xffff, 1, 1.0f); // nk_label(ctx, "Zoom: ", NK_TEXT_LEFT); // nk_slider_float(ctx, 0.0f, &zoom_factor, 1.5f, 0.001f); nk_property_float(ctx, "Zoom", 0.0, &zoom_factor, 1.5f, 0.01f, 0.01f); nk_property_float(ctx, "Rate", 0.0, &zoom_rate, 1.0, 0.0001f, 0.0001f); nk_property_float(ctx, "Line Width", 1.0f, &line_width, 50.0f, 0.5f, 0.5f); //pretend we have an extra widget to fill the space struct nk_rect b; nk_widget(&b, ctx); nk_layout_row_dynamic(ctx, 30, 1); //nk_widget(ctx); nk_checkbox_label(ctx, "Demo", &demo_mode); nk_checkbox_label(ctx, "Random/Json", &example_json_mode); nk_checkbox_label(ctx, "Anti-Aliasing", &antialiasing); nk_checkbox_label(ctx, "VSync", &vsync); //nk_checkbox_label(ctx, "FPS Cap", &fps_cap); //nk_property_int(ctx, "FPS Limit", 24, &fps_limit, 200, 1, 1.0f); //fps_delay = fps_cap ? (1000 / fps_limit) : (1000 / 2000); /* Update VSync */ glfwSwapInterval(vsync); nk_tree_pop(ctx); } if (nk_tree_push_hashed(ctx, NK_TREE_TAB, "Data", nk_collapse_states::NK_MINIMIZED, "_", 1, __LINE__)) { nk_layout_row_dynamic(ctx, 30, 2); nk_label(ctx, "Data:", NK_TEXT_LEFT); nk_checkbox_label(ctx, "Autoscroll", &data_auto_scroll); int len = 2048 < cout_buffer.size() ? 2048 : cout_buffer.size(); nk_layout_row_dynamic(ctx, 278, 1); if (data_auto_scroll) { nk_edit_focus(ctx, ctx->current->edit.mode); // make sure we're absolutely going to scroll to the end nk_scroll(ctx, (&ctx->style)->font->height * len); } nk_edit_string(ctx, (NK_EDIT_BOX), (cout_buffer.data() + cout_buffer.size()) - len, &len, len, nk_filter_default); nk_tree_pop(ctx); } if (nk_tree_push_hashed(ctx, NK_TREE_TAB, "Input", nk_collapse_states::NK_MINIMIZED, "_", 1, __LINE__)) { nk_layout_row_dynamic(ctx, 30, 2); nk_label(ctx, "Data:", NK_TEXT_LEFT); if (nk_button_label(ctx, "Send")) { // make sure we have padding for simdjson edit_string.reserve(edit_string.size() + (2 * SIMDJSON_PADDING)); size_t g = handle_json(parser, ctx, graphs, edit_string.data(), edit_string.size()); graphs_to_display = (g > 0 && g != graphs_to_display) ? g : graphs_to_display; edit_string.clear(); edit_count = 0; } nk_layout_row_dynamic(ctx, 278, 1); // get the area for the next widget struct nk_rect edit_bounds = nk_widget_bounds(ctx); // check if the user is doing something with the keyboard bool any_key = ctx->input.keyboard.text_len > 0; if (any_key) { edit_string.reserve(edit_string.size() + ctx->input.keyboard.text_len); } if (nk_input_is_mouse_hovering_rect(&ctx->input, edit_bounds) && nk_input_is_key_down(&ctx->input, nk_keys::NK_KEY_PASTE)) { const char *clipboard = glfwGetClipboardString(glfw.win); edit_string.reserve(edit_string.size() + strlen(clipboard)); } edit_count = edit_string.size(); nk_edit_string(ctx, NK_EDIT_BOX, edit_string.data(), &edit_count, edit_string.capacity(), nk_filter_default); // change data to fit edit_string.assign(edit_string.data(), edit_string.data() + edit_count); nk_tree_pop(ctx); } nk_layout_row_dynamic(ctx, 30, 5); char recieved[64] = "timestamp: "; auto chrs = std::to_chars(recieved + 11, recieved + 64, last_ok_timestamp); *chrs.ptr = 0; nk_label(ctx, recieved, NK_TEXT_LEFT); char recieved2[64] = "last: "; chrs = std::to_chars(recieved2 + 6, recieved2 + 64, last_timestamp); *chrs.ptr = 0; nk_label(ctx, recieved2, NK_TEXT_LEFT); char delay_text[64] = "delay (ms): "; chrs = std::to_chars(delay_text + 12, delay_text + 64, delay / 1000000); *chrs.ptr = 0; nk_label(ctx, delay_text, NK_TEXT_LEFT); char delay_text2[64] = "delay (ns): "; chrs = std::to_chars(delay_text2 + 12, delay_text2 + 64, delay); *chrs.ptr = 0; nk_label(ctx, delay_text2, NK_TEXT_LEFT); float fps = 1.0f / ((double)timestamp_diff / (double)ns_per_second); char fps_text[64] = "fps: "; chrs = std::to_chars(fps_text + 5, fps_text + 64, fps, std::chars_format::general, 3); *chrs.ptr = 0; nk_label(ctx, fps_text, NK_TEXT_LEFT); nk_tree_pop(ctx); } /* COM GUI */ bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; // 1'000'000'000 ns => 1 second size_t timestamp_diff = (current_timestamp - last_timestamp); if (SerialPort.IsConnected() && (timestamp_diff > delay)) { /* Serial Stuff */ last_timestamp = current_timestamp; read_count = SerialPort.ReadData(ptr, (mx_width - (2 * SIMDJSON_PADDING))); ptr[read_count] = 0; if (read_count > 0) { // -1 is failure so check > 0 size_t g = handle_json(parser, ctx, graphs, ptr, read_count); graphs_to_display = (g > 0 && g != graphs_to_display) ? g : graphs_to_display; } } else if (demo_mode && example_json_mode) { /* Parsing Json Data */ size_t g = handle_json(parser, ctx, graphs, mangled_example_json.data(), mangled_example_json.size()); graphs_to_display = (g > 0 && g != graphs_to_display) ? g : graphs_to_display; last_ok_timestamp = current_timestamp; float flt_ts = current_timestamp / 1000000.0f; for (size_t i = 0; i < graphs_to_display; i++) { for (size_t s = 0; s < graphs[i].values.size(); s++) { graphs[i].values[s].back().x = flt_ts; } } } else if (demo_mode) { /* Randomly Generated Data */ last_ok_timestamp = current_timestamp; graphs_to_display = 6; float flt_ts = current_timestamp / 1000000.0f; for (size_t i = 0; i < graphs_to_display; i++) { if (i >= graphs.size()) { graphs.emplace_back(); } // number of data points to show graphs[i].limit = 60; graphs[i].slots = 2; if (graphs[i].title.empty()) { graphs[i].title.clear(); fmt::format_to(std::back_inserter(graphs[i].title), "graph #{}", i); } // fill with all the potential colors if (graphs[i].colors.size() < color_map.size()) { size_t s = 0; for (auto it = color_map.begin(); it != color_map.end(); it++) { if (s >= NK_CHART_MAX_SLOT) break; graphs[i].colors.emplace_back(it->second); s++; } } graphs[i].values.reserve(graphs[i].colors.size()); graphs[i].labels.reserve(graphs[i].colors.size()); // make sure we have enough graphs for all the colors while (graphs[i].values.size() < graphs[i].colors.size()) { graphs[i].values.emplace_back(); graphs[i].labels.emplace_back(); } // reserve to the limit for (size_t s = 0; s < graphs[i].values.size(); s++) { if (graphs[i].labels[s].empty()) { graphs[i].labels[s].clear(); fmt::format_to(std::back_inserter(graphs[i].labels[s]), "data #{}", s); } if (graphs[i].values[s].capacity() < (graphs[i].limit + 1)) graphs[i].values[s].reserve(graphs[i].limit + 1); for (size_t l = graphs[i].values[s].size(); l < graphs[i].limit; l++) { #if __clang__ // graphs[i].values[s].emplace_back(); #else if (graphs[i].values[s].size() < 1) graphs[i].values[s].emplace_back(0.0f, 0.0f); else graphs[i].values[s].emplace_back(graphs[i].values[s].back().x + 0.001f, graphs[i].values[s].back().y + ((pcg32_random_r(&rng) % 256) / 1024.0f) - (128 / 1024.0f)); #endif } } for (size_t s = 0; s < graphs[i].values.size(); s++) { // fill with data point auto it = graphs[i].values[s].end(); float rnd_value = ((pcg32_random_r(&rng) % 256) / 1024.0f) - (128 / 1024.0f); struct nk_vec2 &point = graphs[i].values[s].unchecked_emplace_back(); point.y = it->y + rnd_value; point.x = flt_ts; if (graphs[i].values[s].size() > graphs[i].limit) { graphs[i].values[s].erase(graphs[i].values[s].begin()); } /* //if using std::vector #if __clang__ struct nk_vec2 &vec = graphs[i].values[s].emplace_back(); if (graphs[i].values[s].size()) { vec.x = flt_ts; vec.y = graphs[i].values[s][graphs[i].values[s].size() - 1].y + ((pcg32_random_r(&rng) % 256) / 1024.0f) - (128 / 1024.0f); } if (graphs[i].values[s].size() > graphs[i].limit) { graphs[i].values[s].erase(graphs[i].values[s].begin()); } #else if (graphs[i].values[s].size() < 1) graphs[i].values[s].emplace_back(flt_ts, 0.0f); graphs[i].values[s].emplace_back(flt_ts, graphs[i].values[s].back().y + ((pcg32_random_r(&rng) % 256) / 1024.0f) - (128 / 1024.0f)); if (graphs[i].values[s].size() > graphs[i].limit) { graphs[i].values[s].erase(graphs[i].values[s].begin()); } #endif */ } } } struct nk_rect window_bounds_2 = nk_window_get_bounds(ctx); struct nk_rect content_region = nk_window_get_content_region(ctx); /* Dynamic render to fit graphs */ nk_layout_row_dynamic(ctx, graph_height, (content_region.w / graph_width)); for (size_t i = 0; i < graphs.size() && i < graphs_to_display; i++) { float min_value; float max_value; float min_ts; float max_ts; size_t offset = 0; if (graphs[i].values.size()) { // figure out the ranges the data fills min_ts = graphs[i].values[0][offset].x; max_ts = graphs[i].values[0][offset].x; min_value = graphs[i].values[0][offset].y; max_value = graphs[i].values[0][offset].y; for (size_t s = 0; s < graphs[i].values.size() && s < graphs[i].slots; s++) { for (size_t idx = offset; idx < graphs[i].values[s].size(); idx++) { min_ts = NK_MIN(graphs[i].values[s][idx].x, min_ts); max_ts = NK_MAX(graphs[i].values[s][idx].x, max_ts); min_value = NK_MIN(graphs[i].values[s][idx].y, min_value); max_value = NK_MAX(graphs[i].values[s][idx].y, max_value); } } // widen the view if somehow the data's perfectly flat if (min_value == max_value) { max_value = min_value + 1.0f; graphs[i].upper_value.value = max_value; graphs[i].lower_value.value = min_value; } if (min_ts == max_ts) { max_ts = min_ts + 1.0f; } char hi_buffer[64]; auto num = std::to_chars(hi_buffer, hi_buffer + 64, max_value); *num.ptr = 0; char lo_buffer[64]; auto num2 = std::to_chars(lo_buffer, lo_buffer + 64, min_value); *num2.ptr = 0; { struct nk_window *win; struct nk_chart *chart; const struct nk_style *config; const struct nk_style_chart *style; const struct nk_style_item *background; // struct nk_rect widget_bounds = nk_widget_bounds(ctx); struct nk_rect widget_bounds; // reserve space for our graph if (!ctx || !ctx->current || !ctx->current->layout) { continue; } if (!nk_widget(&widget_bounds, ctx)) { continue; } win = ctx->current; config = &ctx->style; chart = &win->layout->chart; style = &config->chart; background = &style->background; struct nk_rect graph_bounds; graph_bounds.x = widget_bounds.x + style->padding.x; graph_bounds.y = widget_bounds.y + style->padding.y; graph_bounds.w = widget_bounds.w - 2 * style->padding.x; graph_bounds.h = widget_bounds.h - 2 * style->padding.y; graph_bounds.w = NK_MAX(graph_bounds.w, 2 * style->padding.x); graph_bounds.h = NK_MAX(graph_bounds.h, 2 * style->padding.y); // draw our background if (background->type == NK_STYLE_ITEM_IMAGE) { nk_draw_image(&win->buffer, widget_bounds, &background->data.image, nk_white); } else { nk_fill_rect(&win->buffer, widget_bounds, style->rounding, style->border_color); nk_fill_rect(&win->buffer, nk_shrink_rect(widget_bounds, style->border), style->rounding, style->background.data.color); } // draw our lines size_t point_idx = 0; // we clear here so reserve doesn't copy what should be an empty buffer graphs[i].points.clear(); size_t coordinates = 0; for (size_t s = 0; s < graphs[i].values.size(); s++) coordinates += graphs[i].values[s].size(); if (coordinates > graphs[i].points.capacity()) graphs[i].points.reserve(coordinates * 4); // graphs[i].points.reserve(graphs[i].limit * graphs[i].values.size()); float *data = graphs[i].points.data(); float xrange = max_ts - min_ts; float yrange = max_value - min_value; // make this an option graphs[i].upper_value.lerp_v = zoom_rate; graphs[i].lower_value.lerp_v = zoom_rate; // make 0.05 an option float yupper = graphs[i].upper_value.get_next_smooth_upper(max_value + (zoom_factor * yrange)); float ylower = graphs[i].lower_value.get_next_smooth_lower(min_value - (zoom_factor * yrange)); float x_range = max_ts - min_ts; float y_range = yupper - ylower; // float y_range = max_value - min_value; float ylimrange = yupper - ylower; float yspacing = ylimrange / (float)(yticks + 1); // float yoffset = yspacing / 2.0f; // float xstep = graph_bounds.w / graphs[i].limit; for (size_t s = 0; s < graphs[i].values.size() && s < graphs[i].slots; s++) { float *line_data = data + point_idx; // for (size_t idx = 0; idx < graphs[i].values[s].size(); idx++) { line_data[idx * 2] = widget_bounds.x + (widget_bounds.w * ((graphs[i].values[s][idx].x - min_ts) / x_range)); // std::lerp(0.0f, x_range, ); line_data[(idx * 2) + 1] = (widget_bounds.y + widget_bounds.h) - (((graphs[i].values[s][idx].y - ylower) / ylimrange) * widget_bounds.h); point_idx += 2; } nk_stroke_polyline_float(&ctx->current->buffer, line_data, graphs[i].values[s].size(), line_width, graphs[i].colors[s]); // struct nk_handle h; // h.ptr = &graphs[i].lin // nk_push_custom(&ctx->current->buffer, graph_bounds, render_polyline, ); struct nk_vec2 item_padding; struct nk_text slot_text; item_padding = (&ctx->style)->text.padding; slot_text.padding.x = item_padding.x; slot_text.padding.y = item_padding.y; slot_text.background = (&ctx->style)->window.background; slot_text.text = graphs[i].colors[s]; // chart.slots[slot].color; // slot title struct nk_rect slot_bounds; slot_bounds = graph_bounds; slot_bounds.y += (((&ctx->style)->font->height + 2.0f) * (s + 2)); slot_bounds.h -= 2 * (((&ctx->style)->font->height + 2.0f) * (s + 2)); slot_bounds.x += 2 * (graph_bounds.w / graphs[i].limit); slot_bounds.w -= 4 * (graph_bounds.w / graphs[i].limit); nk_widget_text(&ctx->current->buffer, slot_bounds, graphs[i].labels[s].c_str(), graphs[i].labels[s].size(), &slot_text, NK_TEXT_ALIGN_RIGHT, (&ctx->style)->font); } // use these uv functions b/c otherwise the coordinates can do a little dance // draw ticks along vertical axis float ydiv = 1.0f / (float)(yticks + 1); for (size_t t = 0; t < yticks; t++) { nk_chart_draw_line_uv(ctx, graph_bounds, (ydiv * (t + 1)), 10.0f, 2.0f, nk_color{255, 255, 255, 255}, NK_TEXT_ALIGN_LEFT); nk_chart_draw_value_uv(ctx, graph_bounds, ylower, yupper, (ydiv * (t + 1)), 10.0f, 2.0f, nk_color{255, 255, 255, 255}, NK_TEXT_ALIGN_LEFT, NK_TEXT_ALIGN_MIDDLE | NK_TEXT_ALIGN_LEFT); } // draw ticks along horizontal axis float xdiv = 1.0f / (float)(xticks + 1); for (size_t t = 0; t < xticks; t++) { nk_chart_draw_line_uv(ctx, graph_bounds, xdiv * (t + 1), 10.0f, 2.0f, nk_color{255, 255, 255, 255}, NK_TEXT_ALIGN_BOTTOM); nk_chart_draw_value_uv(ctx, graph_bounds, min_ts, max_ts, xdiv * (t + 1), 10.0f, 2.0f, nk_color{255, 255, 255, 255}, NK_TEXT_ALIGN_BOTTOM, NK_TEXT_ALIGN_BOTTOM | NK_TEXT_ALIGN_CENTERED); } // Draw the title top centered struct nk_text text_opts; struct nk_vec2 item_padding; item_padding = (&ctx->style)->text.padding; // text settings text_opts.padding.x = item_padding.x; text_opts.padding.y = item_padding.y; text_opts.background = (&ctx->style)->window.background; text_opts.text = nk_color{255, 255, 255, 255}; // ctx->style.text.color; nk_widget_text(&ctx->current->buffer, graph_bounds, graphs[i].title.data(), graphs[i].title.size(), &text_opts, NK_TEXT_ALIGN_CENTERED | NK_TEXT_ALIGN_TOP, ctx->style.font); // handle some user interfacing // nk_flags ret; // size_t hover_point; if (!(ctx->current->layout->flags & NK_WINDOW_ROM)) { // check if we're in bounds of a point /* for (size_t p = 0; p < point_idx; p += 2) { struct nk_rect point_of_interest; point_of_interest.x = data[p] - 2; point_of_interest.y = data[p + 1] - 2; point_of_interest.w = 6; point_of_interest.h = 6; ret = nk_input_is_mouse_hovering_rect(&ctx->input, point_of_interest); if (ret) { ret = NK_CHART_HOVERING; ret |= ((&ctx->input)->mouse.buttons[NK_BUTTON_LEFT].down && (&ctx->input)->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED : 0; } else { continue; } if (ret & NK_CHART_HOVERING) { // do something when hoving over a point (show its x, y coordinate) char text[64]; auto xchrs = std::to_chars(text, text + 64, data[p]); *xchrs.ptr = ','; auto chrs = std::to_chars(xchrs.ptr + 1, text + 64, data[p + 1]); size_t text_len = chrs.ptr - text; const struct nk_style *style = &ctx->style; struct nk_vec2 padding = style->window.padding; float text_width = style->font->width(style->font->userdata, style->font->height, text, text_len); text_width += (4 * padding.x); float text_height = (style->font->height + 2 * padding.y); if (nk_tooltip_begin(ctx, (float)text_width)) { nk_layout_row_dynamic(ctx, (float)text_height, 1); nk_text(ctx, text, text_len, NK_TEXT_LEFT); nk_tooltip_end(ctx); } } } */ if (nk_input_is_mouse_hovering_rect(&ctx->input, graph_bounds) && (&ctx->input)->mouse.buttons[NK_BUTTON_LEFT].down) { char text[64]; float xval = std::lerp( min_ts, max_ts, (((&ctx->input)->mouse.pos.x - graph_bounds.x) / graph_bounds.w)); auto xchrs = std::to_chars(text, text + 64, xval); *xchrs.ptr = ','; float yval = std::lerp( yupper, ylower, (((&ctx->input)->mouse.pos.y - graph_bounds.y) / graph_bounds.h)); auto chrs = std::to_chars(xchrs.ptr + 1, text + 64, yval); size_t text_len = chrs.ptr - text; const struct nk_style *style = &ctx->style; struct nk_vec2 padding = style->window.padding; float text_width = style->font->width(style->font->userdata, style->font->height, text, text_len); text_width += (4 * padding.x); float text_height = (style->font->height + 2 * padding.y); if (nk_tooltip_begin(ctx, (float)text_width)) { nk_layout_row_dynamic(ctx, (float)text_height, 1); nk_text(ctx, text, text_len, NK_TEXT_LEFT); nk_tooltip_end(ctx); } } if (nk_input_is_mouse_hovering_rect(&ctx->input, graph_bounds) && (&ctx->input)->keyboard.keys[NK_KEY_COPY].down && (&ctx->input)->keyboard.keys[NK_KEY_COPY].clicked) { /* cout_buffer = graphs_to_string(graphs); std::cout << cout_buffer; glfwSetClipboardString(glfw.win, cout_buffer.c_str()); cout_buffer.clear(); */ } } } } } } nk_end(ctx); /* Draw */ glfwGetWindowSize(win, &width, &height); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glClearColor(bg.r, bg.g, bg.b, bg.a); /* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state * with blending, scissor, face culling, depth test and viewport and * defaults everything back into a default state. * Make sure to either a.) save and restore or b.) reset your own * state after rendering the UI. */ nk_glfw3_render((nk_anti_aliasing)antialiasing); // NK_ANTI_ALIASING_ON glfwSwapBuffers(win); // Sleep(fps_delay); // Sleep(16); // Sleep(24); // Sleep(100); } if (SerialPort.IsConnected()) fmt::print("{}", "disconnecting..."); nk_glfw3_shutdown(); glfwTerminate(); return 0; }<file_sep># CMakeList.txt : CMake project for ArduinoSerialPlotter, include source and define # project specific logic here. # cmake_minimum_required (VERSION 3.8) #set(VCPKG_BUILD_TYPE release) find_package(GLEW REQUIRED) find_package(glfw3 CONFIG REQUIRED) find_package(fmt CONFIG REQUIRED) #target_link_libraries(main PRIVATE glfw) # Add source to this project's executable. add_executable (ArduinoSerialPlotter "ArduinoSerialPlotter.cpp" "ArduinoSerialPlotter.h" "SerialClass.h" "simdjson.h" "simdjson.cpp" "nuklear_glfw_gl4.h" "nuklear.h" "real_vector.h") target_link_libraries(ArduinoSerialPlotter PRIVATE GLEW::GLEW glfw fmt::fmt-header-only) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 23) # TODO: Add tests and install targets if needed. <file_sep># Arduino-Serial-Plotter Nuklear driven graph monitor for use in combination with https://github.com/devinaconley/arduino-plotter <!--![example](https://user-images.githubusercontent.com/25020235/135802654-96345113-1916-4d33-92b9-1e4b1cf7f931.png)--> <!--![TjwGi7kLoC](https://user-images.githubusercontent.com/25020235/136124350-dfc99226-8b70-46f6-a251-1ff3db09ea32.gif)--> ![gui in demo mode](https://user-images.githubusercontent.com/25020235/136124484-5220ac64-de19-4d21-800d-ee8ad84a8265.gif) # Compiling Quick and easy install vcpkg and integrate it with msvc then run (if msvc doesn't pick up on the required libs anyway) ``` vcpkg install glew:x64-windows-static vcpkg install glfw3:x64-windows-static ``` In your cmake settings make sure to set the same triplet (or add them directly to the CMakeLists.txt) ``` set(VCPKG_TARGET_TRIPLET "x64-windows-static") ``` Worst comes to worst with vcpkg not kicking in, manually set the paths ``` set(GLEW_DIR "<whereever you installed vcpkg>\installed\x64-windows-static\share\glew") set(glfw3_DIR "<whereever you installed vcpkg>\installed\x64-windows-static\share\glfw") ```<file_sep>#pragma once #ifndef SERIALCLASS_H_INCLUDED #define SERIALCLASS_H_INCLUDED #define ARDUINO_WAIT_TIME 2000 #include <windows.h> #include <stdio.h> #include <stdlib.h> //#include <format> #include <fmt/core.h> #include <fmt/format.h> #include <string> #include <array> #include <memory> #include <memory_resource> class Serial { private: //Serial comm handler HANDLE hSerial = nullptr; //Connection status bool connected = false; //Get various information about the connection COMSTAT status = {}; //Keep track of last error DWORD errors = 0; public: //Create a Serial Object in an unconnected state Serial() noexcept { } //Initialize Serial communication with the given COM port Serial(const char* portName) { Connect(portName, true, CBR_9600); }; Serial(const char* portName, bool reset, uint32_t baud_rate) { Connect(portName, reset, baud_rate); }; //Close the connection ~Serial() { //Check if we are connected before trying to disconnect if (this->connected) { //We're no longer connected this->connected = false; //Close the serial handler CloseHandle(this->hSerial); } } //Read data in a buffer, if nbChar is greater than the //maximum number of bytes available, it will return only the //bytes available. The function return -1 when nothing could //be read, the number of bytes actually read. int ReadData(char* buffer, unsigned int nbChar) { //Number of bytes we'll have read DWORD bytesRead; //Number of bytes we'll really ask to read unsigned int toRead; //Use the ClearCommError function to get status info on the Serial port ClearCommError(this->hSerial, &this->errors, &this->status); //Check if there is something to read if (this->status.cbInQue > 0) { //If there is we check if there is enough data to read the required number //of characters, if not we'll read only the available characters to prevent //locking of the application. if (this->status.cbInQue > nbChar) { toRead = nbChar; } else { toRead = this->status.cbInQue; } //Try to read the require number of chars, and return the number of read bytes on success if (ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL)) { return bytesRead; } } //If nothing has been read, or that an error was detected return 0 return 0; }; //Writes data from a buffer through the Serial connection //return true on success. bool WriteData(const char* buffer, unsigned int nbChar) { DWORD bytesSend; //Try to write the buffer on the Serial port if (!WriteFile(this->hSerial, (void*)buffer, nbChar, &bytesSend, 0)) { //In case it don't work get comm error and return false ClearCommError(this->hSerial, &this->errors, &this->status); return false; } else return true; }; //Check if we are actually connected bool IsConnected() { //Simply return the connection status return this->connected; }; int Connect(const char* portName, bool reset, uint32_t baud_rate) { //We're not yet connected this->connected = false; //Try to connect to the given port throuh CreateFile this->hSerial = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //Check if the connection was successfull if (this->hSerial == INVALID_HANDLE_VALUE) { //If not success full display an Error if (GetLastError() == ERROR_FILE_NOT_FOUND) { //Print Error if neccessary printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName); } else { printf("ERROR!!!"); } } else { //If connected we try to set the comm parameters DCB dcbSerialParams = { 0 }; //Try to get the current if (!GetCommState(this->hSerial, &dcbSerialParams)) { //If impossible, show an error printf("failed to get current serial parameters!"); } else { //Define serial connection parameters for the arduino board dcbSerialParams.BaudRate = baud_rate;//CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; //Setting the DTR to Control_Enable ensures that the Arduino is properly //reset upon establishing a connection dcbSerialParams.fDtrControl = reset ? DTR_CONTROL_ENABLE : DTR_CONTROL_DISABLE; dcbSerialParams.ErrorChar = '~'; //Set the parameters and check for their proper application if (!SetCommState(hSerial, &dcbSerialParams)) { printf("ALERT: Could not set Serial Port parameters"); } else { //If everything went fine we're connected this->connected = true; //Flush any remaining characters in the buffers PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR); if (reset) { //We wait 2s as the arduino board will be reseting Sleep(ARDUINO_WAIT_TIME); } } } } return this->connected; } int Connect(int portIndex, bool reset, uint32_t baud_rate) { char lpTargetPath[5000]; // buffer to store the path of the COMPORTS char buffer[64]; std::pmr::monotonic_buffer_resource m(buffer, 64); std::pmr::string str(&m); str.reserve(64); //std::string str; fmt::format_to(std::back_inserter(str), std::string_view{ "COM{}" }, portIndex); DWORD test = QueryDosDevice(str.c_str(), lpTargetPath, 5000); if (test != 0) { //OK to continue } else { return false; } if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { return false; } return Connect(lpTargetPath, reset, baud_rate); } int Disconnect() { if (this->connected) { //We're no longer connected this->connected = false; //Close the serial handler CloseHandle(this->hSerial); this->hSerial = nullptr; return true; } else { return false; } } std::array<uint32_t, 8> ListAvailable() { std::array<uint32_t, 8> ret; for (size_t i = 0; i < ret.size(); i++) ret[i] = 0; char lpTargetPath[5000]; // buffer to store the path of the COMPORTS char buffer[64]; std::pmr::monotonic_buffer_resource m(buffer, 64); std::pmr::string str(&m); str.reserve(64); for (int i = 0; i < 255; i++) // checking ports from COM0 to COM255 { //std::string str = "COM" + std::to_string(i); // converting to COM0, COM1, COM2 str.clear(); fmt::format_to(std::back_inserter(str), std::string_view{ "COM{}" }, i); DWORD test = QueryDosDevice(str.c_str(), lpTargetPath, 5000); // Test the return value and error if any ret[i / (sizeof(uint32_t)*8)] |= (test != 0 ? 1 : 0) << (i % (sizeof(uint32_t)*8)); } return ret; } std::array<std::string, 256> List() { std::array<std::string, 256> ret; char lpTargetPath[5000]; // buffer to store the path of the COMPORTS char buffer[64]; std::pmr::monotonic_buffer_resource m(buffer, 64); std::pmr::string str(&m); str.reserve(64); for (int i = 0; i < 255; i++) // checking ports from COM0 to COM255 { //std::string str = "COM" + std::to_string(i); // converting to COM0, COM1, COM2 str.clear(); fmt::format_to(std::back_inserter(str), std::string_view{ "COM{}" }, i); DWORD test = QueryDosDevice(str.c_str(), lpTargetPath, 5000); // Test the return value and error if any if (test != 0) //QueryDosDevice returns zero if it didn't find an object { ret[i] = std::string{ lpTargetPath };//std::format("{}", lpTargetPath); //std::cout << str << ": " << lpTargetPath << std::endl; } else { ret[i] = ""; } if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { } } return ret; } }; #endif<file_sep>#pragma once #include <algorithm> #include <cassert> #include <cstdint> #include <initializer_list> #include <iterator> #include <memory> #include <memory_resource> #include <stdexcept> #include <utility> namespace real { template <typename Pointer> struct allocation_result { Pointer ptr = {}; size_t count = {}; }; namespace details { template <typename T> constexpr void destroy_at(T *const ptr) { if constexpr (!std::is_trivially_destructible_v<T>) ptr->~T(); } template <typename Iterator> constexpr void destroy(Iterator first, Iterator last) { std::destroy(first, last); /* using iterator_traits = std::iterator_traits<Iterator>; if constexpr (!std::is_trivially_destructible_v<iterator_traits::value_type>) { for (; first != last; ++first) destroy_at(&(*first)); //::std::addressof(*first) } */ } // ripped from llvm libcxx struct default_init_tag {}; struct value_init_tag {}; struct zero_then_variadic_args_t {}; struct one_then_variadic_args_t {}; // propagate on container move assignment template <typename Alloc> constexpr void pocma(Alloc &left, Alloc &right) noexcept { if constexpr (::std::allocator_traits<Alloc>::propagate_on_container_move_assignment::value) { left = ::std::move(right); } } template <typename Alloc> constexpr void pocca(Alloc &left, Alloc &right) noexcept { if constexpr (::std::allocator_traits<Alloc>::propagate_on_container_copy_assignment::value) { left = right; } } template <typename Alloc> constexpr bool should_pocma(Alloc &) noexcept { return ::std::allocator_traits<Alloc>::propagate_on_container_move_assignment::value; } template <typename Alloc> constexpr bool should_pocca(Alloc &) noexcept { return ::std::allocator_traits<Alloc>::propagate_on_container_copy_assignment::value; } template <typename T, bool> struct dependent_type : public T {}; // can optimize Ty1 away (empty base class optimization) template <typename Ty1, typename Ty2, bool emptyBaseClass = ::std::is_empty_v<Ty1> && !::std::is_final_v<Ty1>> struct compressed_pair final : private Ty1 { Ty2 _value2; template <class... Args1, class... Args2, size_t... Idxs1, size_t... Idxs2> constexpr explicit compressed_pair(std::tuple<Args1...> first_args, std::tuple<Args2...> second_args, std::index_sequence<Idxs1...>, std::index_sequence<Idxs2...>) : Ty1(::std::forward<Args1>(::std::get<Idxs1>(first_args))...), _value2(::std::forward<Args2>(::std::get<Idxs2>(second_args))...) {} template <class... Args1, class... Args2> constexpr explicit compressed_pair(::std::piecewise_construct_t t, std::tuple<Args1...> first_args, std::tuple<Args2...> second_args) : compressed_pair(first_args, second_args, std::make_index_sequence<sizeof...(Args1)>(), std::make_index_sequence<sizeof...(Args2)>()) {} template <class... Args> constexpr explicit compressed_pair(zero_then_variadic_args_t, Args &&...args) noexcept( ::std::conjunction_v<::std::is_nothrow_default_constructible<Ty1>, ::std::is_nothrow_constructible<Ty2, Args...>>) : Ty1(), _value2(::std::forward<Args>(args)...){}; template <class Arg, class... Args> constexpr compressed_pair(one_then_variadic_args_t, Arg &&arg, Args &&...args) noexcept( ::std::conjunction_v<::std::is_nothrow_default_constructible<Ty1>, ::std::is_nothrow_constructible<Ty2, Args...>>) : Ty1(::std::forward<Arg>(arg)), _value2(::std::forward<Args>(args)...){}; constexpr Ty1 &first() noexcept { return *this; } constexpr const Ty1 &first() const noexcept { return *this; } constexpr Ty2 &second() noexcept { return _value2; } constexpr const Ty2 &second() const noexcept { return _value2; } }; template <typename Ty1, typename Ty2> struct compressed_pair<Ty1, Ty2, false> final { Ty1 _value1; Ty2 _value2; template <class... Args1, class... Args2, size_t... Idxs1, size_t... Idxs2> constexpr explicit compressed_pair(std::tuple<Args1...> first_args, std::tuple<Args2...> second_args, std::index_sequence<Idxs1...>, std::index_sequence<Idxs2...>) : _value1(::std::forward<Args1>(::std::get<Idxs1>(first_args))...), _value2(::std::forward<Args2>(::std::get<Idxs2>(second_args))...) {} template <class... Args1, class... Args2> constexpr explicit compressed_pair(::std::piecewise_construct_t t, std::tuple<Args1...> first_args, std::tuple<Args2...> second_args) : compressed_pair(first_args, second_args, std::make_index_sequence<sizeof...(Args1)>(), std::make_index_sequence<sizeof...(Args2)>()) {} template <class... Args> constexpr explicit compressed_pair(zero_then_variadic_args_t, Args &&...args) noexcept( ::std::conjunction_v<::std::is_nothrow_default_constructible<Ty1>, ::std::is_nothrow_constructible<Ty2, Args...>>) : _value1(), _value2(::std::forward<Args>(args)...){}; template <class Arg, class... Args> constexpr compressed_pair(one_then_variadic_args_t, Arg &&arg, Args &&...args) noexcept( ::std::conjunction_v<::std::is_nothrow_default_constructible<Ty1>, ::std::is_nothrow_constructible<Ty2, Args...>>) : _value1(::std::forward<Arg>(arg)), _value2(::std::forward<Args>(args)...){}; constexpr Ty1 &first() noexcept { return _value1; } constexpr const Ty1 &first() const noexcept { return _value1; } constexpr Ty2 &second() noexcept { return _value2; } constexpr const Ty2 &second() const noexcept { return _value2; } }; template <typename Ty1, typename Ty2> struct easy_pair final { Ty1 _value1; Ty2 _value2; constexpr Ty1 &first() noexcept { return _value1; } constexpr const Ty1 &first() const noexcept { return _value1; } constexpr Ty2 &second() noexcept { return _value2; } constexpr const Ty2 &second() const noexcept { return _value2; } }; } // namespace details struct default_expansion_policy { [[nodiscard]] constexpr size_t grow_capacity(size_t size, size_t capacity, size_t required_capacity) noexcept { return required_capacity; } }; template <size_t N> struct geometric_int_expansion_policy { [[nodiscard]] constexpr size_t grow_capacity(size_t size, size_t capacity, size_t required_capacity) noexcept { const size_t expanded_capacity = (capacity ? capacity : 1) * N; return (expanded_capacity < required_capacity ? required_capacity : expanded_capacity); } }; template <double N> struct geometric_double_expansion_policy { [[nodiscard]] constexpr size_t grow_capacity(size_t size, size_t capacity, size_t required_capacity) noexcept { const size_t expanded_capacity = (capacity ? capacity : 1) * N; return (expanded_capacity < required_capacity ? required_capacity : expanded_capacity); } }; template <typename T, typename Allocator = std::allocator<T>> class vector { public: using element_type = T; using value_type = typename ::std::remove_cv<T>::type; using const_reference = const value_type &; using size_type = ::std::size_t; using difference_type = ::std::ptrdiff_t; using pointer = element_type *; using const_pointer = const element_type *; using reference = element_type &; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = ::std::reverse_iterator<iterator>; using const_reverse_iterator = ::std::reverse_iterator<const_iterator>; using allocator_type = Allocator; using rebind_allocator_type = typename ::std::allocator_traits<allocator_type>::template rebind_alloc<value_type>; private: // data members T *_begin = {}; T *_end = {}; /* LLVM and MSVC make these a "compressed_pair" size_t _capacity = {}; //because we don't need this as a member (but it could have members of its own) Allocator _alloc = {}; */ details::compressed_pair<Allocator, size_t> _capacity_allocator; private: constexpr void _cleanup() noexcept { // orphan iterators? if (_begin) { details::destroy(_begin, _end); get_allocator().deallocate(_begin, capacity()); _begin = nullptr; _end = nullptr; _capacity_allocator.second() = 0ULL; } } public: constexpr ~vector() noexcept { _cleanup(); } private: template <typename Iterator, typename ExpansionPolicy> constexpr iterator insert_range(const_iterator pos, Iterator first, Iterator last, ExpansionPolicy) { size_type insert_idx = pos - cbegin(); iterator ret_it = begin() + insert_idx; // insert input range [first, last) at _Where if (first == last) { return ret_it; // nothing to do } assert(pos >= cbegin() && pos <= cend() && "insert iterator is out of bounds"); const size_type old_size = size(); if constexpr (::std::is_same<::std::random_access_iterator_tag, ::std::iterator_traits<Iterator>::iterator_category>::value) { size_type insert_count = last - first; if (!can_store(insert_count)) { size_t target_capacity = ExpansionPolicy{}.grow_capacity(old_size, _capacity_allocator.second(), _capacity_allocator.second() + insert_count); reserve(target_capacity); } // already safe from check above* ::std::uninitialized_copy(first, last, end()); _end += insert_count; //_size += insert_count; } else { // bounds check each emplace_back, saturating for (; first != last && size() < capacity(); ++first) { unchecked_emplace_back(*first); } for (; first != last; ++first) { emplace_back(*first); } } ::std::rotate(begin() + insert_idx, begin() + old_size, end()); return ret_it; } public: [[nodiscard]] constexpr allocator_type get_allocator() const noexcept { return static_cast<allocator_type>(_capacity_allocator.first()); } constexpr vector() noexcept(::std::is_nothrow_default_constructible_v<rebind_allocator_type>) : _capacity_allocator(details::zero_then_variadic_args_t{}) {} constexpr explicit vector(const Allocator &alloc) noexcept : _capacity_allocator(details::one_then_variadic_args_t{}, alloc) {} constexpr vector(size_type count, const value_type &value) : _capacity_allocator(details::zero_then_variadic_args_t{}) { if (count) { cleared_reserve(count); ::std::uninitialized_fill(_begin, _begin + count, value); _end = _begin + count; } } constexpr explicit vector(size_type count, const value_type &value, const allocator_type &alloc) : _capacity_allocator(details::one_then_variadic_args_t{}, alloc) { if (count) { cleared_reserve(count); ::std::uninitialized_fill(_begin, _begin + count, value); _end = _begin + count; } } template <class Iterator> constexpr vector(Iterator first, Iterator last) : _capacity_allocator(details::zero_then_variadic_args_t{}) { size_type count = std::distance(first, last); if (count) { cleared_reserve(count); ::std::uninitialized_copy(first, last, _begin); _end = _begin + count; } } constexpr vector(const vector &other) : _capacity_allocator(details::one_then_variadic_args_t{}, ::std::allocator_traits<allocator_type>::select_on_container_copy_construction( other._capacity_allocator.first())) { size_t count = other.size(); if (count) { cleared_reserve(count); ::std::uninitialized_copy(other.begin(), other.end(), _begin); _end = _begin + count; } } constexpr vector(const vector &other, const allocator_type &alloc) : _capacity_allocator(details::one_then_variadic_args_t{}, alloc) { if (!other.empty()) this->operator=(other); } constexpr vector(vector &&other) : _capacity_allocator(details::zero_then_variadic_args_t{}) { if (!other.empty()) this->operator=(::std::move(other)); } constexpr void set_vector(const pointer data, const size_type new_size, const size_type new_capacity) { T *old_begin = _begin; T *old_end = _end; size_t old_capacity = _capacity_allocator.second(); size_t required_capacity = std::max(new_size, new_capacity); if (_begin) { details::destroy(old_begin, old_end); get_allocator().deallocate(_begin, static_cast<size_type>(_end - _begin)); } _begin = data; _end = data + new_size; _capacity_allocator.second() = required_capacity; } // note: like shrink_to_fit constexpr void unchecked_reserve(size_type new_capacity) { T *old_begin = _begin; T *old_end = _end; size_t old_size = static_cast<size_type>(old_end - old_begin); size_t old_capacity = _capacity_allocator.second(); size_t required_capacity = std::max(old_size, new_capacity); const pointer newdata = get_allocator().allocate(required_capacity); try { // move data over ::std::uninitialized_copy(::std::make_move_iterator(old_begin), ::std::make_move_iterator(old_end), newdata); } catch (...) { get_allocator().deallocate(newdata, required_capacity); throw; } if (old_begin) { // already moved, delete get_allocator().deallocate(old_begin, old_capacity); } _begin = newdata; _end = newdata + old_size; _capacity_allocator.second() = required_capacity; } constexpr void reserve(size_type new_capacity) { T *old_begin = _begin; T *old_end = _end; size_t old_size = static_cast<size_type>(old_end - old_begin); size_t old_capacity = _capacity_allocator.second(); // size_t required_capacity = std::max(old_size, new_capacity); if (old_capacity < new_capacity) { if (new_capacity > max_size()) { throw std::length_error("cannot allocate larger than max_size"); } const pointer newdata = get_allocator().allocate(new_capacity); try { // copy data over ::std::uninitialized_copy(std::make_move_iterator(old_begin), std::make_move_iterator(old_end), newdata); } catch (...) { get_allocator().deallocate(newdata, new_capacity); throw; } if (old_begin) { // already moved, delete get_allocator().deallocate(old_begin, old_capacity); } _begin = newdata; _end = newdata + old_size; _capacity_allocator.second() = new_capacity; } } // note: use only after clear(); constexpr void cleared_reserve(size_type new_capacity) { const pointer newdata = get_allocator().allocate(new_capacity); if (_begin) { details::destroy(_begin, _end); get_allocator().deallocate(_begin, capacity()); } _begin = newdata; _end = newdata; _capacity_allocator.second() = new_capacity; } //[]'s [[nodiscard]] constexpr reference operator[](size_type pos) { assert(pos < size()); return _begin[pos]; }; [[nodiscard]] constexpr const_reference operator[](size_type pos) const { assert(pos < size()); return _begin[pos]; }; // front [[nodiscard]] constexpr reference front() { assert(!empty()); return _begin[0]; }; [[nodiscard]] constexpr const_reference front() const { assert(!empty()); return _begin[0]; }; // back's [[nodiscard]] constexpr reference back() { assert(!empty()); return _begin[static_cast<size_type>(_end - _begin) - 1]; }; [[nodiscard]] constexpr const_reference back() const { assert(!empty()); return _begin[static_cast<size_type>(_end - _begin) - 1]; }; // data's [[nodiscard]] constexpr T *data() noexcept { return _begin; }; [[nodiscard]] constexpr const T *data() const noexcept { return _begin; }; // at's [[nodiscard]] constexpr reference at(size_type pos) { if (!(pos < size())) throw std::out_of_range("accessing index out of range of vector"); return _begin[pos]; }; [[nodiscard]] constexpr const_reference at(size_type pos) const { if (!(pos < size())) throw std::out_of_range("accessing index out of range of vector"); return _begin[pos]; }; // begin's [[nodiscard]] constexpr iterator begin() noexcept { return _begin; }; [[nodiscard]] constexpr const_iterator begin() const noexcept { return _begin; }; [[nodiscard]] constexpr const_iterator cbegin() const noexcept { return _begin; }; // rbegin's [[nodiscard]] constexpr reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }; [[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }; [[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); }; // end's [[nodiscard]] constexpr iterator end() noexcept { return &_begin[0] + size(); }; [[nodiscard]] constexpr const_iterator end() const noexcept { return &_begin[0] + size(); }; [[nodiscard]] constexpr const_iterator cend() const noexcept { return &_begin[0] + size(); }; // rend's [[nodiscard]] constexpr reverse_iterator rend() noexcept { return reverse_iterator(begin()); }; [[nodiscard]] constexpr const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }; [[nodiscard]] constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); }; // empty's [[nodiscard]] constexpr bool empty() const noexcept { return size() == 0; }; // full (non standard) [[nodiscard]] constexpr bool full() const noexcept { return size() >= capacity(); }; [[nodiscard]] constexpr bool initialized() const noexcept { return _begin && _capacity_allocator.second(); }; [[nodiscard]] constexpr bool uncorrupted() const noexcept { return (_begin == nullptr && _end == nullptr && _capacity_allocator.second() == 0) || (_begin && _end >= _begin && (_end <= (_begin + _capacity_allocator.second()))); } // can_store (non standard) [[nodiscard]] constexpr bool can_store(size_t count) const noexcept { return (capacity() - size()) >= count; } // size constexpr size_type size() const noexcept { return static_cast<size_type>(_end - _begin); }; // capacity constexpr size_type capacity() const noexcept { return _capacity_allocator.second(); }; // max_size (constant) constexpr size_type max_size() const noexcept { constexpr size_type system_max_size = ((~size_type{0}) / sizeof(T)); const size_type allocator_max_size = std::allocator_traits<allocator_type>::max_size(get_allocator()); const size_type result = (system_max_size < allocator_max_size) ? system_max_size : allocator_max_size; return result; }; // emplace_back's template <class... Args> constexpr reference emplace_back(Args &&...args) { if (full()) { size_t target_capacity = geometric_int_expansion_policy<2>{}.grow_capacity( size(), _capacity_allocator.second(), _capacity_allocator.second() + 1); reserve(target_capacity); } iterator it = _end; _end += 1; ::new ((void *)it) value_type(::std::forward<Args>(args)...); return *it; }; // emplace_back_with_policy template <typename... Args, typename ExpansionPolicy> constexpr reference emplace_back_with_policy(Args &&...args, ExpansionPolicy) { if (full()) { size_t target_capacity = ExpansionPolicy{}.grow_capacity(size(), _capacity_allocator.second(), _capacity_allocator.second() + 1); reserve(target_capacity); } iterator it = _end; _end += 1; ::new ((void *)it) T(::std::forward<Args>(args)...); return *it; } // unechecked_emplace_back (non-standard) template <typename... Args> constexpr reference unchecked_emplace_back(Args &&...args) { iterator it = _end; _end += 1; ::new ((void *)it) T(::std::forward<Args>(args)...); /* ::std::allocator_traits<allocator_type>::construct(_capacity_allocator.first(), ::std::to_address(it), std::forward<Args>(args)...); */ return *it; }; // push_back's constexpr void push_back(const T &value) { emplace_back(::std::forward<const T &>(value)); } constexpr void push_back(T &&value) { emplace_back(::std::forward<T &&>(value)); }; // push_back_with_policy template <typename ExpansionPolicy = geometric_int_expansion_policy<2>> constexpr void push_back_with_policy(const T &value) { emplace_back_with_policy(::std::forward<const T &>(value), ExpansionPolicy{}); } template <typename ExpansionPolicy = geometric_int_expansion_policy<2>> constexpr void push_back_with_policy(T &&value) { emplace_back_with_policy(::std::forward<T &&>(value), ExpansionPolicy{}); } // pop_back's constexpr void pop_back() { if (size()) [[likely]] { if constexpr (::std::is_trivially_destructible<element_type>::value) { _end -= 1; } else { _end -= 1; end()->~element_type(); // destroy the tailing value } } else { // error ? } }; // clear constexpr void clear() noexcept { if constexpr (!::std::is_trivially_constructible<element_type>::value) { details::destroy(_begin, _end); } _end = _begin; } // insert's constexpr iterator insert(const_iterator pos, const T &value) { return emplace(pos, value); } constexpr iterator insert(const_iterator pos, T &&value) { return emplace(pos, ::std::move(value)); } constexpr iterator insert(const_iterator pos, size_type count, const T &value) { if (count) { size_type remaining_capacity = capacity() - size(); // const bool one_at_back = (remaining_capacity == 1) && (pos == cend()); const size_type insert_idx = cend() - pos; iterator insert_point = begin() + (cend() - pos); if (count > remaining_capacity) { // reserve(size()+count); const size_type new_capacity = size() + count; pointer newdata = get_allocator().allocate(new_capacity); try { ::std::uninitialized_copy(::std::make_move_iterator(begin()), ::std::make_move_iterator(insert_point), newdata); ::std::uninitialized_fill(newdata + insert_point, newdata + insert_point + count, value); ::std::uninitialized_copy(::std::make_move_iterator(insert_point), ::std::make_move_iterator(end()), newdata + insert_point + count); } catch (...) { get_allocator().deallocate(newdata, new_capacity); throw; } if (_begin) { // already moved, delete get_allocator().deallocate(_begin, capacity()); } _begin = newdata; _end = newdata + new_capacity; _capacity_allocator.second() = new_capacity; } else { iterator start = end(); iterator last = start; iterator target = start + count; // uninitialized_move_backward for (; target != last; target--, start--) { ::std::allocator_traits<allocator_type>::construct(_capacity_allocator.first(), ::std::to_address(target), ::std::move(*start)); } ::std::uninitialized_fill(pos, pos + count, value); _end = target; } } } template <class InputIt> constexpr iterator insert(const_iterator pos, InputIt first, InputIt last) { return insert_range(pos, first, last); }; constexpr iterator insert(const_iterator pos, ::std::initializer_list<T> ilist) { return insert(pos, ilist.begin(), ilist.end()); }; // emplace's template <class... Args> constexpr iterator emplace(const_iterator pos, Args &&...args) { size_type insert_idx = pos - cbegin(); assert(pos >= cbegin() && pos <= cend() && "emplace iterator does not refer to this vector"); if (size() < capacity()) { if (pos == cend()) { unchecked_emplace_back(::std::forward<Args>(args)...); } else { iterator start = end(); iterator last = start; iterator target = start + 1; // uninitialized_move_backward for (; target != last; target--, start--) { ::std::allocator_traits<allocator_type>::construct(_capacity_allocator.first(), ::std::to_address(target), ::std::move(*start)); } ::std::allocator_traits<allocator_type>::construct(_capacity_allocator.first(), ::std::to_address(pos), std::forward<Args>(args)...); _end = target; } } else { // emplace_back(std::forward<Args>(args)...); if (pos == cend()) { emplace_back(::std::forward<Args>(args)...); } else { size_type new_capacity = geometric_int_expansion_policy<2>{}.grow_capacity(size(), capacity(), capacity() + 1); const pointer newdata = _capacity_allocator.first().allocate(new_capacity); try { ::std::allocator_traits<allocator_type>::construct( _capacity_allocator.first(), newdata + insert_idx, std::forward<Args>(args)...); ::std::uninitialized_copy(::std::make_move_iterator(begin()), ::std::make_move_iterator(begin() + insert_idx), newdata); ::std::uninitialized_copy(::std::make_move_iterator(begin() + insert_idx), ::std::make_move_iterator(end()), newdata + insert_idx + 1); } catch (...) { details::destroy(newdata, newdata + insert_idx + 1); _capacity_allocator.first().deallocate(newdata, new_capacity); } if (_begin) { _capacity_allocator.first().deallocate(_begin, capacity()); } size_type old_size = size(); _begin = newdata; _end = newdata + old_size + 1; _capacity_allocator.second() = new_capacity; } } return begin() + insert_idx; } // erase's constexpr iterator erase(const_iterator pos) noexcept(::std::is_nothrow_move_assignable_v<value_type>) { size_type erase_idx = pos - cbegin(); assert(pos >= cbegin() && pos < cend() && "erase iterator is out of bounds of the vector"); // move on top iterator first = begin() + erase_idx + 1; iterator last = end(); iterator dest = begin() + erase_idx; for (; first != last; ++dest, (void)++first) { *dest = ::std::move(*first); } details::destroy_at(end() - 1); _end -= 1; return begin() + erase_idx; } constexpr iterator erase(const_iterator first, const_iterator last) noexcept(::std::is_nothrow_move_assignable_v<value_type>) { size_type erase_idx = first - cbegin(); assert(first >= cbegin() && first <= cend() && "first erase iterator is out of bounds of the vector"); assert(last >= cbegin() && last <= cend() && "last erase iterator is out of bounds of the vector"); if (first != last) { size_type erase_count = last - first; iterator _first = begin() + (erase_idx + erase_count); iterator _last = end(); iterator dest = begin() + erase_idx; for (; _first != _last; ++dest, (void)++_first) { *dest = ::std::move(*_first); } details::destroy(end() - erase_count, end()); _end -= erase_count; } return begin() + erase_idx; } // assign's constexpr void assign(size_type count, const T &value) { clear(); if (count > capacity()) cleared_reserve(count); ::std::uninitialized_fill(_begin, _begin + count, value); _end = _begin + count; }; template <typename Iterator> constexpr void assign(Iterator first, Iterator last) { if constexpr (::std::is_same<::std::random_access_iterator_tag, ::std::iterator_traits<Iterator>::iterator_category>::value) { size_type count = static_cast<size_type>(last - first); clear(); if (count > capacity()) cleared_reserve(count); ::std::uninitialized_copy(first, last, end()); _end = _begin + count; } else { size_type count = std::distance(first, last); clear(); if (count > capacity()) cleared_reserve(count); for (; first != last; ++first) { unchecked_emplace_back(*first); } } } constexpr void assign(::std::initializer_list<T> ilist) { assign(ilist.begin(), ilist.end()); }; constexpr vector &operator=(vector &&other) noexcept( ::std::is_nothrow_move_assignable<details::compressed_pair<Allocator, size_t>>::value) { if (this != &other) { _cleanup(); details::pocma(_capacity_allocator.first(), other._capacity_allocator.first()); _begin = ::std::move(other._begin); _end = ::std::move(other._end); _capacity_allocator.second() = ::std::move(other._capacity_allocator.second()); } return *this; } constexpr vector &operator=(const vector &other) { if (this != &other) { if constexpr (details::should_pocca(_capacity_allocator.first())) { if (!::std::allocator_traits<Allocator>::is_always_equal::value && _capacity_allocator.first() != other._capacity_allocator.first()) { _cleanup(); } details::pocca(_capacity_allocator.first(), other._capacity_allocator.first()); assign(other.begin(), other.end()); } else { assign(other.begin(), other.end()); } } return *this; } constexpr vector &operator=(::std::initializer_list<T> ilist) { assign(ilist.begin(), ilist.end()); return *this; } constexpr void shrink_to_fit() { if (size() != capacity()) { if (_begin == _end) { _cleanup(); } else { unchecked_reserve(size()); } } } }; } // namespace real namespace pmr { namespace real { template <class T> using vector = ::real::vector<T, ::std::pmr::polymorphic_allocator<T>>; }; } // namespace pmr
afd3c4a7df8f75d1eb814d96e149231b571bc062
[ "Markdown", "CMake", "C++" ]
5
C++
Andersama/Arduino-Serial-Plotter
ac00dc46e675362e6bd1dc05ff1aa7dbdc50f7a0
8ffcd46bb2ba52bfb7ec2528107cecab302d1ede
refs/heads/master
<repo_name>estebancas/MyTunes<file_sep>/app/common/footer.component.ts import {Component} from 'angular2/core'; @Component ({ selector: 'footer-component', template: ` <footer class="footer"> <div class="container"> <a class="text-muted" href="/"><NAME>, {{year}}</a> <a class="text-muted" href="https://twitter.com/estebancasful" target="_blank"><li class="fa fa-twitter"></li> @estebancasful</a> <a class="text-muted" href="https://www.linkedin.com/in/esteban-castro-cordero-928784137/" target="_blank"><li class="fa fa-linkedin"></li>LinkedIn </a> </div> </footer> `, styles : [` footer { position: absolute; bottom: 0; width: 100%; height: 60px; background-color: #f5f5f5; } .container { height : 60px; } a { height : 60px; line-height : 60px; margin-right : 5rem; } `] }) export class FooterComponent { private year : number = (new Date()).getFullYear(); }<file_sep>/app/common/pagination.component.ts import {Component, Input, OnInit} from 'angular2/core'; import {Router, RouteParams} from 'angular2/router'; import {ForRangeDirective} from './directives/forRange.directive'; import {IPager} from '../common/models/ipager'; @Component ({ selector: 'pagination-component', template: ` <nav *ngIf="pager"> <ul class="pagination"> <li * forRange = "pager.pages; #i=index" (click)="goToPage(i)" ><a>{{i}}</a></li> </ul> </nav> `, directives: [ForRangeDirective] }) export class PaginationComponent implements OnInit { @Input() pager:IPager; @Input() pathName:string; private query:string; constructor(private router:Router, private routeParams:RouteParams) {} ngOnInit(): any { this.query = this.routeParams.get("query"); } goToPage(i:number) { var params = {} if(this.query) { params["query"] = this.query; } params["page"] = i; this.router.navigate([this.pathName, params]); } }<file_sep>/app/common/models/pager.ts import {IPager} from './ipager'; export class Pager implements IPager { public pages:number = 0; constructor(public itemsPerPage:number, public startIndex:number, public totalResults: number, private maxPages: number = 10) { var realMaxPages = Math.ceil(this.totalResults/this.itemsPerPage); if(realMaxPages <= this.maxPages) { this.pages = realMaxPages; } else { this.pages = this.maxPages; } } }<file_sep>/app/common/welcome.component.ts import {Component} from 'angular2/core'; @Component ({ selector: 'welcome-component', template: ` <div class="jumbotron"> <h1>welcome to MyTunes</h1> <p></p> <p><a class="btn btn-primary btn-lg" role="button" (click)="showMoreInfo(moreInfo)" *ngIf="!moreInfo">Learn more</a></p> <div *ngIf="moreInfo"> <p>Angular 2 application for learning the following concepts:</p> <ul> <li>Components</li> <li>Directives: *ngFor, *ngIf</li> <li>Routing</li> <li>Services</li> <li>TypeScript</li> <li>RxJS</li> <li>Styles</li> <li>Data Input, Data Output</li> <li>Forms</li> </ul> </div> </div> `, }) export class WelcomeComponent { public moreInfo:boolean = false; showMoreInfo(moreInfo:boolean) { this.moreInfo = !moreInfo; } }<file_sep>/README.txt this is a sample project develop by <NAME> consist in a webapp that consumes APIs to bring the discography from a musical group search it by what you type!! and also an login with firebase auth! <file_sep>/app/music/albums.component.ts import {Component, OnInit, Input} from 'angular2/core'; import {Observable} from 'rxjs/Observable'; import {ROUTER_DIRECTIVES, RouteParams} from 'angular2/router'; import {IAlbum, AlbumImageSize} from './models/ialbum'; import {MusicService} from './services/music.srv'; import {AlbumComponent} from './album.component'; import {EllipsisPipe} from '../common/pipes/ellipsis.pipe'; import {HightLightDirective} from '../common/directives/highlight.directive'; import {PaginationComponent} from '../common/pagination.component'; import {IPager} from '../common/models/ipager'; @Component ({ selector: 'albums-component', template: ` <ul class="media-list"> <li class="media" *ngFor="#album of albums" [routerLink]="['Album', { id : album.id }]" appHighLight [hoverColor]="'whitesmoke'" [activeColor] = "'gray'"> <div class="media-left"> <a> <img class="media-object" [src]="album.getImage(albumImageSize)"> </a> </div> <div class="media-body"> <h4 class="media-heading">{{album.name | ellipsis:40}}</h4> <p>{{album.artist}}</p> </div> </li> </ul> <pagination-component [pager]="pager" [pathName]="'Albums'"></pagination-component> `, providers: [MusicService], directives: [ROUTER_DIRECTIVES, HightLightDirective, PaginationComponent], pipes: [EllipsisPipe] }) export class AlbumsComponent implements OnInit { public albums:Array<IAlbum> = []; public albumImageSize:AlbumImageSize = AlbumImageSize.MEDIUM; public pager:IPager; constructor(private musicService : MusicService, private routeParams: RouteParams) {} ngOnInit() { this.albumsSearch(this.routeParams.get("query"), this.routeParams.get("page")); } albumsSearch(query:string, page:any) { if(query) { this.musicService.albumsSearch(query, parseInt(page)) .subscribe(res => { this.albums = res.albums; this.pager = res.pager; }); } else { this.albums = []; } } }<file_sep>/app/user/models/iuser.ts export interface IUser { userName : string; email : string; password : <PASSWORD>; country? : string; birthday : Date; }<file_sep>/README.md # MyTunes this is a sample project develop by <NAME> consist in a webapp that consumes APIs to bring the discography from a musical group search it by what you type!! and also an login with firebase auth! #to install 1 - clone the repo! 2 - $ npm install 3 - $ npm start note: you'll may need to log in http://lastfm.com and get a APIkey and change it in the user.svc.ts <file_sep>/app/common/models/isearchquery.ts export interface ISearchQuery { query : string; }<file_sep>/app/user/login.component.ts import {Component} from 'angular2/core'; import {Router} from 'angular2/router'; import {UserService} from './services/user.srv'; @Component ({ selector: 'login-component', template: ` <form #loginForm="ngForm"> <div class="alert alert-danger" role="alert" *ngIf="error">{{error}}</div> <div class="form-group"> <label for="login">Login</label> <input type="text" placeholder="Login" class="form-control" required ngControl="userName" #userName="ngForm"/> <div [hidden]="userName.valid || userName.pristine" class="alert alert-danger">Password required</div> </div> <div class="form-group"> <label for="password">Password</label> <input type="<PASSWORD>" placeholder="<PASSWORD>" class="form-control" required ngControl="password" #password="<PASSWORD>"/> <div [hidden]="password.valid || password.pri<PASSWORD>" class="alert alert-danger">Password required</div> </div> <button type="submit" class="btn btn-default" (click)="login(userName.value, password.value)" [disabled]="!loginForm.form.valid">login</button> </form> `, providers: [UserService] }) export class LoginComponent { public error:string; constructor(private userService:UserService, private router:Router) {} public login(userName, password) { this.userService.login(userName, password) .subscribe(result => { this.router.navigateByUrl("/"); }, error => { this.error = error; }); } }<file_sep>/app/user/services/user.srv.ts import {Observable} from 'rxjs/Observable'; import {IUser} from '../models/iuser'; import {User} from '../models/user'; export class UserService { firebaseUrl: string = "https://mytunes-5b979.firebaseio.com/"; firebaseRef:Firebase; constructor() { this.firebaseRef = new Firebase(this.firebaseUrl); } getUser () : Observable { return new Observable(observable => { this.firebaseRef.onAuth(authData => { let authData = this.firebaseRef.getAuth(); let user; if(authData) { user = new User(authData); } observable.next(user); }); }); } login(userName: string, password: string) : Observable { return new Observable(observable => { this.firebaseRef.authWithPassword({ email : userName, password : <PASSWORD> }, (error, authData) => { if(error) { observable.error(error); } else { observable.next(new User (authData)); } }); }); } register(userName: string, email:string, password:string, country?:string, birthday?:Date) : Observable { return new Observable(observable => { this.firebaseRef.createUser({ userName : userName, email : email, password : <PASSWORD> }, (error, userData) => { if(error) { observable.error(error); } else { observable.next(userData); } }); }); } logout() { return new Observable(Observable => { this.firebaseRef.unauth(); observable.next(); }) } }<file_sep>/app/common/directives/forRange.directive.ts import {Directive, Input, TemplateRef, ViewContainerRef, View, EmbeddedViewRef} from 'angular2/core'; @Directive({ selector: '[forRange]' }) export class ForRangeDirective { @Input() set forRange(value:number) { this.render(value); } constructor(private _templateRef: TemplateRef, private _viewContainer: ViewContainerRef) { } render(range:number) { for (let i = 0; i < range; i++) { var view:EmbeddedViewRef = this._viewContainer.createEmbeddedView(this._templateRef, i); view.setLocal("index", i); } } }<file_sep>/app/music/models/album.ts import {IAlbum} from './ialbum'; import {ISong} from './isong'; export class Album implements IAlbum { constructor(public id : number, public name : string, public artist : string, public url : string, public images? : Array<string>, public songs? : Array<ISong> ) {} getImage(size: string) { let image = this.images.find((image) => (image["size"] == size)); return image ? image["#text"] : undefined; } }<file_sep>/app/common/models/ipager.ts export interface IPager { itemsPerPage : number; startIndex : number; totalResults : number; pages : number; }<file_sep>/app/user/registration.component.ts import {Component} from 'angular2/core'; import {Router} from 'angular2/router'; import {UserService} from './services/user.srv'; import {CountryService} from '../common/services/country.srv'; import {IUser} from './models/iuser'; import {ICountry} from '../common/models/icountry'; @Component ({ selector: 'registration-component', template: ` <form #registrationForm="ngForm"> <div class="form-group"> <input type="text" required placeholder="username" ngControl="userName" #userName="ngForm"/> <div class="alert alert-danger" [hidden]="userName.valid || userName.pristine">Username required</div> </div> <div class="form-group"> <input type="text" required placeholder="email" ngControl="email" #email="ngForm"/> <div class="alert alert-danger" [hidden]="email.valid || email.pristine">Email required</div> </div> <div class="form-group"> <input type="password" required placeholder="<PASSWORD>" ngControl="password" #password="ngForm"/> <div class="alert alert-danger" [hidden]=" password.valid || password.pristine">Password required</div> </div> <div class="form-group"> <select class="form-control" ngControl="country" #country="ngForm"> <option value="">Select a country</option> <option *ngFor="#c of countries" [value]="c.alpha2Core">{{c.name}}</option> </select> </div> <div class="form-group"> <input type="date" ngControl="birthday" #birthday="ngForm"/> </div> <button type="submit" class="btn btn-default" [disabled]="!registrationForm.valid" (click)="register(userName.value, email.value, password.value, country.value, birthday.value)"> Register </button> </form> `, providers: [UserService, CountryService] }) export class RegistrationComponent { public countries:Array<ICountry> = []; constructor(private userService:UserService, private countryService: CountryService, private router:Router) { this.countryService.getCountries() .subscribe(countries => { this.countries = countries; }) } register(username:string, email:string, password:string, country?:string, birthday?:Date) { this.userService.register(username, email, password, country, birthday) .subscribe(user => { this.router.navigateByUrl("/"); }); } }<file_sep>/app/common/models/icountry.ts export interface ICountry { alpha2Code : string, name : string }<file_sep>/app/user/models/user.ts import {IUser} from './iuser'; export class User implements IUser { userName:string; email:string; password:string; country:string; birthday:Date; constructor(authData:any) { this.email = authData.password.email; } } /* constructor(public userName : string, public email : string, public password : string, public country? : string, public birthday? : string) { } */ <file_sep>/app/common/search.component.ts import {Component, Input, Output, EventEmitter} from 'angular2/core'; import {ISearchQuery} from './models/isearchquery'; @Component ({ selector: 'search-component', template: ` <div class="form-group"> <input type="text" placeholder="Search" class="from-control" [(ngModel)]="_query" (keypress)="search(_query, $event)"/> </div> <button type="button" class="btn btn-default" (click)="search(_query)">Search</button> `, }) export class SearchComponent { @Input() query:string; @Output() queryChange = new EventEmitter(); constructor() {} search(_query:string, $event?:KeyboardEvent) { if(!$event || $event.keyCode == 13) { this.queryChange.next(_query); } } }<file_sep>/app/common/models/country.ts import {ICountry} from './icountry'; export class Country implements ICountry { constructor(public name:string, public alpha2Code:string) { } }
4e0b542b6e9a6909c619c0b50496b008528d2a73
[ "Markdown", "TypeScript", "Text" ]
19
TypeScript
estebancas/MyTunes
e5ddf5348dc59cdd8096edd8ff3da23513dc7302
3ab21e133e425f76766b146798a9d422086feb99
refs/heads/master
<repo_name>remfath/ssh-run<file_sep>/cmd/cmdServer/list.go package cmdServer import ( "github.com/olekukonko/tablewriter" "github.com/procroner/ssh-run/core/coreServer" "os" "fmt" "strconv" ) func List() { servers := coreServer.All() if len(servers) == 0 { fmt.Println("No servers") return } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"ID", "Name", "User", "Host", "Auth Type", "Password", "Private Key Path", "Proxy Server ID"}) for _, server := range servers { row := []string{ strconv.Itoa(int(server.ID)), server.Name, server.User, server.Host, server.AuthType, server.Pass, server.PrivateKeyPath, strconv.Itoa(int(server.ProxyServerId)), } table.Append(row) } table.Render() } <file_sep>/README.md # sshrun - execute commands on remote server Introduction ------------ sshrun is a tool for executing commands on remote server from local config file or database. Todo --------- - [ ] CLI support - [ ] Log support - [ ] REPL support - [ ] Task storage in database - [ ] Web api - [ ] Documentation - [ ] Add test file<file_sep>/core/coreJob/job.go package coreJob import ( "errors" "github.com/jinzhu/gorm" "github.com/procroner/ssh-run/core/coreDb" "time" "github.com/procroner/ssh-run/core/coreLog" "fmt" "github.com/procroner/ssh-run/core/coreServer" "github.com/procroner/ssh-run/core/coreServer/coreConnect" ) const ( STATUS_DISABLE = iota STATUS_ENABLE STATUS_RUNNING STATUS_STOP STATUS_WATING ) var StatusDesc = map[int]string{ 0: "disable", 1: "enable", 2: "running", 3: "stop", 4: "waiting", } type Job struct { gorm.Model Title string ServerId int Command string `gorm:"type:longtext"` Status int } func Migrate() { db := coreDb.Connect() defer db.Close() db.AutoMigrate(&Job{}) } func Query(jobId int) Job { db := coreDb.Connect() defer db.Close() var job Job db.First(&job, jobId) return job } func All() []Job { db := coreDb.Connect() defer db.Close() var jobs []Job db.Find(&jobs) return jobs } func (job *Job) Run() (result string, err error) { startTime := time.Now() if job.Status != STATUS_ENABLE { result, err = "", errors.New("job is disabled") } else { server := coreServer.Query(job.ServerId) if server.AuthType == "pass" { if server.Pass == "" { result, err = coreConnect.RunCommandAskPass(server.User, server.Host, job.Command) } result, err = coreConnect.RunCommandWithPass(server.User, server.Host, server.Pass, job.Command) } else if server.AuthType == "key" { result, err = coreConnect.RunCommandWithKey(server.User, server.Host, server.PrivateKeyPath, job.Command) } else { result, err = "", errors.New("auth type is not allowed") } } endTime := time.Now() var runStatus int if err != nil { runStatus = 1 } var errMsg string if err != nil { errMsg = fmt.Sprintf("%s", err) } log := coreLog.Log{ JobId: int(job.ID), StartTime: &startTime, EndTime: &endTime, Output: result, Error: errMsg, Status: runStatus, Command: job.Command, } coreLog.Create(log) return } <file_sep>/cmd/cmdJob/run.go package cmdJob import ( "fmt" "github.com/procroner/ssh-run/core/coreJob" ) func runAll() { jobs := coreJob.All() for _, job := range jobs { result, err := job.Run() fmt.Printf("\n %s\n", job.Title) fmt.Println("----------------------------------------") if err != nil { fmt.Printf(" ERROR: %s\n", err) } else { fmt.Println(result) } fmt.Printf("\n\n") } } func Run(jobId int) { if jobId == 0 { runAll() } else { job := coreJob.Query(jobId) job.Run() } } <file_sep>/cmd/cmd.go package cmd import ( "github.com/spf13/cobra" "github.com/procroner/ssh-run/cmd/cmdServer" "github.com/procroner/ssh-run/cmd/cmdJob" "github.com/procroner/ssh-run/cmd/cmdTable" ) func Run() { //server command var cServer = &cobra.Command{ Use: "server [add|delete|edit|list|ping]", Short: "Add, delete, edit, list or ping server", Long: "Command server is for server management, providing add, delete, edit or list commands", Args: cobra.MinimumNArgs(1), } var cServerList = &cobra.Command{ Use: "list", Short: "List servers", Long: "List all servers", Args: cobra.MinimumNArgs(0), Run: func(cmd *cobra.Command, args []string) { cmdServer.List() }, } var cServerPing = &cobra.Command{ Use: "ping", Short: "Ping servers", Long: "Ping all servers", Args: cobra.MinimumNArgs(0), Run: func(cmd *cobra.Command, args []string) { cmdServer.Ping() }, } cServer.AddCommand(cServerList, cServerPing) //job command var cJob = &cobra.Command{ Use: "job [add|delete|edit|list]", Short: "Add, delete, edit or list cmdJob", Long: "Command job is for job management, providing add, delete, edit or list commands", Args: cobra.MinimumNArgs(1), } var cJobList = &cobra.Command{ Use: "list", Short: "List jobs", Long: "List all jobs", Args: cobra.MinimumNArgs(0), Run: func(cmd *cobra.Command, args []string) { cmdJob.List() }, } var jobId int var cJobRun = &cobra.Command{ Use: "run", Short: "Run all jobs", Long: "Run all jobs", Args: cobra.MinimumNArgs(0), Run: func(cmd *cobra.Command, args []string) { cmdJob.Run(jobId) }, } cJobRun.Flags().IntVarP(&jobId, "job", "j", 0, "jobs that willing be run, separated by comma") cJob.AddCommand(cJobList, cJobRun) //table command var cTable = &cobra.Command{ Use: "table", Short: "Table management", Long: "Init tables", Args: cobra.MinimumNArgs(1), } var tableName string var cTableMigrate = &cobra.Command{ Use: "migrate", Short: "Migrate tables", Long: "Migrate tables including jobs, logs and servers", Args: cobra.MinimumNArgs(0), Run: func(cmd *cobra.Command, args []string) { cmdTable.MigrateTables(tableName) }, } cTableMigrate.Flags().StringVarP(&tableName, "table", "t", "", "tables names to init, multiple tables separated by comma") cTable.AddCommand(cTableMigrate) var rootCmd = &cobra.Command{Use: "ssh-run"} rootCmd.AddCommand(cServer, cJob, cTable) rootCmd.Execute() } <file_sep>/core/coreError/error.go package coreError import ( "fmt" "log" "os" ) func HandleError(msg string, err error) { if err != nil { msg := fmt.Sprintf("[%s]: %v", msg, err) fmt.Println(msg) log.Fatalln(msg) os.Exit(1) } } <file_sep>/.env.example DB_HOST=127.0.0.1 DB_USER=root DB_PASSWORD=<PASSWORD> DB_NAME=sshrun <file_sep>/core/coreServer/coreConnect/connect.go package coreConnect import ( "fmt" "golang.org/x/crypto/ssh" "io/ioutil" ) func RunCommandWithPass(user, host, pass, cmd string) (string, error) { client, session, err := connectWithPass(user, host, pass) if err != nil { return "", err } defer client.Close() return runCommand(session, cmd) } func RunCommandAskPass(user, host, cmd string) (string, error) { client, session, err := connectAskPass(user, host) if err != nil { return "", err } defer client.Close() return runCommand(session, cmd) } func RunCommandWithKey(user, host, privateKeyPath, cmd string) (string, error) { client, session, err := connectWithKey(user, host, privateKeyPath) if err != nil { return "", err } defer client.Close() return runCommand(session, cmd) } func runCommand(session *ssh.Session, cmd string) (string, error) { output, err := session.CombinedOutput(cmd) if err != nil { return "", err } return string(output), nil } func connectWithKey(user, host, privateKeyPath string) (*ssh.Client, *ssh.Session, error) { buffer, err := ioutil.ReadFile(privateKeyPath) if err != nil { return nil, nil, err } key, err := ssh.ParsePrivateKey(buffer) if err != nil { return nil, nil, err } sshConfig := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.PublicKeys(key)}, } return connect(sshConfig, host) } func connectAskPass(user, host string) (*ssh.Client, *ssh.Session, error) { var pass string fmt.Print("Password: ") fmt.Scanf("%s\n", &pass) return connectWithPass(user, host, pass) } func connectWithPass(user, host, pass string) (*ssh.Client, *ssh.Session, error) { sshConfig := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.Password(pass)}, } return connect(sshConfig, host) } func connect(sshConfig *ssh.ClientConfig, host string) (*ssh.Client, *ssh.Session, error) { sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey() client, err := ssh.Dial("tcp", host, sshConfig) if err != nil { return nil, nil, err } session, err := client.NewSession() if err != nil { client.Close() return nil, nil, err } return client, session, nil } <file_sep>/cmd/cmdTable/migrate.go package cmdTable import ( "github.com/procroner/ssh-run/core/coreError" "fmt" "strings" "github.com/procroner/ssh-run/core/coreJob" "github.com/procroner/ssh-run/core/coreServer" "github.com/procroner/ssh-run/core/coreLog" "errors" ) func MigrateTables(tables string) { if tables == "" { coreServer.Migrate() coreJob.Migrate() coreLog.Migrate() } else { tablesSlice := strings.Split(tables, ",") for _, table := range tablesSlice { switch table { case "servers", "server": coreServer.Migrate() case "jobs", "job": coreJob.Migrate() case "logs", "log": coreLog.Migrate() default: coreError.HandleError("db", errors.New(fmt.Sprintf("DB: table %s is not needed.", table))) } } } } <file_sep>/core/coreLog/log.go package coreLog import ( "github.com/procroner/ssh-run/core/coreDb" "github.com/jinzhu/gorm" "time" ) type Log struct { gorm.Model JobId int Command string `gorm:"type:longtext"` StartTime *time.Time EndTime *time.Time Output string `gorm:"type:longtext"` Error string `gorm:"type:longtext"` Input string Status int } func Migrate() { db := coreDb.Connect() defer db.Close() db.AutoMigrate(&Log{}) } func Query(logId int) Log { db := coreDb.Connect() defer db.Close() var log Log db.First(&log, logId) return log } func All() []Log { db := coreDb.Connect() defer db.Close() var logs []Log db.Find(&logs) return logs } func Create(log Log) { db := coreDb.Connect() defer db.Close() db.Create(&log) } <file_sep>/cmd/cmdServer/ping.go package cmdServer func Ping() { } <file_sep>/core/coreServer/server.go package coreServer import ( "github.com/procroner/ssh-run/core/coreDb" "github.com/jinzhu/gorm" ) type Server struct { gorm.Model Name string User string Host string AuthType string Pass string PrivateKeyPath string ProxyServerId int } func Migrate() { db := coreDb.Connect() defer db.Close() db.AutoMigrate(&Server{}) } func Query(serverId int) Server { db := coreDb.Connect() defer db.Close() var server Server db.First(&server, serverId) return server } func All() []Server { db := coreDb.Connect() defer db.Close() var servers []Server db.Find(&servers) return servers }<file_sep>/cmd/cmdJob/list.go package cmdJob import ( "github.com/olekukonko/tablewriter" "os" "github.com/procroner/ssh-run/core/coreServer" "github.com/procroner/ssh-run/core/coreJob" "strconv" ) func List() { table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) table.SetHeader([]string{"ID", "Title", "Server Host", "Command", "Status"}) jobs := coreJob.All() for _, job := range jobs { server := coreServer.Query(job.ServerId) row := []string{ strconv.Itoa(int(job.ID)), job.Title, server.Host, job.Command, coreJob.StatusDesc[job.Status], } table.Append(row) } table.Render() }
91d5dbc90f8b70fe58f6ffaa42897fe062186860
[ "Markdown", "Go", "Shell" ]
13
Go
remfath/ssh-run
40e8a6555570e8bdba62e7dfdda9ac60b10ecd6a
97c2b2dd644e6470152b30a018f3eb600184942d
refs/heads/master
<repo_name>XiaoHang1006/Table3D<file_sep>/Table3D/Assets/Scripts/MenuScript/RankLayer.cs using UnityEngine; using System.Collections; public class RankLayer : MonoBehaviour { //显示数字的rect的宽和高 public float groupX = 177, groupY = 0, groupW = 300, groupH = 240; //移动的最大距离 private int maxHeight; //数字图片的大小 private int numSize = 19; //背景图片 public Texture2D bg; //中间显示的背景图片 public Texture2D box; //时间按钮图片 public Texture2D date; //分数按钮图片 public Texture2D score; //数字图片数组 public Texture2D[] textures; //GUIStyle public GUIStyle style; //初始字符串 private string txt = ""; //位置比变量 private float oldPosY; private float currPosY; //分数数组 private string[] showRecords; //GUI自适应矩阵 private Matrix4x4 guiMatrix; void Start() { //获取GUI自适应矩阵 guiMatrix = ConstOfMenu.getMatrix(); //通过调用LoadData方法初始化数组 showRecords = Result.LoadData(); //计算最大高度 maxHeight = numSize * showRecords.Length - 192; } void Update() { //计算每天记录移动 if (Input.GetMouseButtonDown(0)) { oldPosY = Input.mousePosition.y; } if (Input.GetMouseButton(0)) { currPosY = Input.mousePosition.y; groupY = Mathf.Clamp((groupY - currPosY + oldPosY), -maxHeight, 0); oldPosY = currPosY; } } void OnGUI() { //设置GUI自适应矩阵 GUI.matrix = guiMatrix; //绘制背景图片 GUI.DrawTexture(new Rect(0, 0, 800, 480), bg); //绘制中心小图 GUI.DrawTexture(new Rect(150, 150, 530, 294), box); if (GUI.Button(new Rect(230, 180, 130, 40), date, style)) { //通过调用LoadData方法初始化数组 string[] records = Result.LoadData(); showRecords = records; } if (GUI.Button(new Rect(470, 180, 130, 40), score, style)) { //通过调用LoadData方法初始化数组 string[] records = Result.LoadData(); RecordsSort(ref records); showRecords = records; } GUI.BeginGroup(new Rect(177, 220, 476, 192)); GUI.BeginGroup(new Rect(0, groupY, 476, numSize * showRecords.Length)); if (showRecords[0] != "") { DrawRecrods(showRecords); } GUI.EndGroup(); GUI.EndGroup(); } public void DrawRecrods(string[] records) { for (int i = 0; i < records.Length; i++) { string date = records[i].Split(',')[0]; string score = records[i].Split(',')[1]; int[] dateNum = StringToNumber(date); int[] scoreNum = StringToNumber(score); for (int j = 0; j < dateNum.Length; j++) { GUI.DrawTexture(new Rect((j + 1) * numSize, i * numSize, numSize, numSize), textures[dateNum[j]]); } for (int j = 0; j < scoreNum.Length; j++) { GUI.DrawTexture(new Rect((j + 17) * numSize, i * numSize, numSize, numSize), textures[scoreNum[j]]); } } } public void RecordsSort(ref string[] records) { for (int i = 0; i < records.Length - 1; i++) { for (int j = i + 1; j < records.Length; j++) { if (int.Parse(records[i].Split(',')[1]) < int.Parse(records[j].Split(',')[1])) {//当前一个元素小于后一个元素时,交换位置 string tempRecord = records[i];//赋值 records[i] = records[j];//赋值 records[j] = tempRecord;//赋值,最后实现了位置的交换 } } } } public static int[] StringToNumber(string str) { int[] result = new int[str.Length]; for (int i = 0; i < str.Length; i++) { char c = str[i]; if (c == '-') { result[i] = 10; } else { result[i] = str[i] - '0'; } } return result; } } <file_sep>/Table3D/Assets/Scripts/MenuScript/MusicLayer.cs using UnityEngine; using System.Collections; public class MusicLayer : MonoBehaviour { //菜单界面背景图片 public Texture backgroundOfMusicLayer; //声明音乐按钮数组 public Texture2D[] musicBtns; //声音按钮对应的图片 public Texture2D[] musicTex; //声明音效按钮数组 public Texture2D[] effectBtns; //音效按钮对应的图片 public Texture2D[] effectTex; //音效索引 private int effectIndex; //音乐索引 private int musicIndex; //按钮样式 public GUIStyle btStyle; //GUI自适应矩阵 private Matrix4x4 guiMatrix; void Start() { //初始化音效索引 effectIndex = PlayerPrefs.GetInt("offEffect"); //初始化音乐索引 musicIndex = PlayerPrefs.GetInt("offMusic"); //初始化GUI自适应矩阵 guiMatrix = ConstOfMenu.getMatrix(); } void OnGUI() { //设置GUI矩阵 GUI.matrix = guiMatrix; //绘制背景图片 GUI.DrawTexture(new Rect(0, 0, ConstOfMenu.desiginWidth, ConstOfMenu.desiginHeight), backgroundOfMusicLayer); //273,80为图片的实际大小,主要是为了适配资源不变形 GUI.DrawTexture(new Rect(200, 180, 273, 80), musicTex[musicIndex % 2]); //这里它给的图片资源不太好,所以通过数字进行调整 if (GUI.Button(new Rect(473, 190, 110, 80), musicBtns[musicIndex % 2], btStyle)) { //按钮索引加一 musicIndex++; //将新的按钮索引存入prefer中 PlayerPrefs.SetInt("offMusic", musicIndex % 2); } //绘制显示图片 GUI.DrawTexture(new Rect(200, 320, 273, 80), effectTex[effectIndex % 2]);//273,80为图片的实际大小,主要是为了适配资源不变形 if (GUI.Button(new Rect(473, 330, 110, 80), effectBtns[effectIndex % 2], btStyle))//这里它给的图片资源不太好,所以通过数字进行调整 { //按钮索引加一 effectIndex++; //将新的按钮索引存入prefer中 PlayerPrefs.SetInt("offEffect", effectIndex % 2); } } }<file_sep>/Table3D/Assets/Scripts/GameScript/GameLayer.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class GameLayer : MonoBehaviour { enum ButtonS { Go = 0, Far, Near, Left, Right, M, firstV, freeV, thirdV } //����ģʽ�µ�2�������б� public static ArrayList BallGroup_ONE_EIGHT = new ArrayList(); public static ArrayList BallGroup_TWO_EIGHT = new ArrayList(); //9��ģʽ�µ�һ�������б� public static ArrayList BallGroup_ONE_NINE = new ArrayList(); //���������б� public static ArrayList BallGroup_TOTAL = new ArrayList(); //���������� public static int ballInNum = 0; //��Y��������ת�Ƕ� public static float totalRotation = 0.0f; //�����밴ť�Ƿ����õ��ܱ�־λ public static bool TOTAL_FLAG = true; //�����Ƿ��˶����ܱ�־Ϊ public static bool isStartAction = false; //���½���ʾ��ť�ı�־λ private bool isFirstView; //��һ���˶��Ƿ������ı�־λ private bool isFirstActionOver; //�ڶ����˶��Ƿ������ı�־λ private bool isSecondActionOver; //�������½�ͼƬ�ı��� private int tbtIndex; //gui������Ӧ���� Matrix4x4 guiMatrix; //��ť��Style public GUIStyle[] btnStyle; //�����Ӱ�ť��GUIStyle����Ϊ�Ǻ��ּ���ȥ�����в���������Styleд��һ�� public GUIStyle fbtnStyle; //���߼������� Logic logic; //С��ͼ���� MiniMap miniMap; //��ʼ������������ InitAllBalls initClass; public Texture2D[] nums; //��������Ч public AudioClip startSound; void Start() { //���½���ʾ��ť�ı�־λ isFirstView = true; //��һ���˶��Ƿ������ı�־λ isFirstActionOver = false; //�ڶ����˶��Ƿ������ı�־λ isSecondActionOver = false; //���Ƚ�ĸ����Ҳ����0�������ӽ����б� GameLayer.BallGroup_TOTAL.Add(GameObject.Find("CueBall")); initClass = GetComponent("InitAllBalls") as InitAllBalls; miniMap = GetComponent("MiniMap") as MiniMap; //��ʼ�����е����� initClass.initAllBalls(PlayerPrefs.GetInt("billiard")); //��ȡ������ logic = GetComponent("Logic") as Logic; //���ű������ֵ��ж� if (PlayerPrefs.GetInt("offMusic") != 0) { //���ű������� GetComponent<AudioSource>().Pause(); } //��ȡGUI���� guiMatrix = ConstOfMenu.getMatrix(); } // Update is called once per frame void Update() { //�������µ��Ƿ��ؼ� if (Input.GetKeyDown(KeyCode.Escape)) { //����LevelSelectScene���� Application.LoadLevel("MenuScene"); } } void OnGUI() { //����GUI�ľ��� GUI.matrix = guiMatrix; //������ʾUI GUI.DrawTexture(new Rect(770, 10, 30, 30), nums[GameLayer.ballInNum]); //���ư�ť DrawButtons(); //����mini��ͼ miniMap.drawMiniMap(); //�������������˶�����־λ�ȷ��������ڴ棬 if (GameLayer.isStartAction) { //����ִ�ж��� cueRunAction(); } } //���ư�ť void DrawButtons() { //Go��ť if (GUI.Button(new Rect(0, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.Go])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { GameLayer.TOTAL_FLAG = false; //��һ���˶��Ƿ������ı�־λ isFirstActionOver = false; //�ڶ����˶��Ƿ������ı�־λ isSecondActionOver = false; //�����ƶ��ı�־λ GameLayer.isStartAction = true; logic.cuePosition = logic.cueBall.transform.position; } } //Far��ť if (GUI.RepeatButton(new Rect(100, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.Far])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { (GetComponent("CamControl") as CamControl).moveCame(-5); } } //Near��ť if (GUI.RepeatButton(new Rect(200, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.Near])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { (GetComponent("CamControl") as CamControl).moveCame(5); } } //����ת��ť if (GUI.RepeatButton(new Rect(300, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.Left])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { //�����ܵ���ת�Ƕ� GameLayer.totalRotation -= ConstOfGame.rotationStep; //�������˵���ת�Ƕ� logic.cueObject.transform.RotateAround(logic.cueBall.transform.position, Vector3.up, -ConstOfGame.rotationStep); } } //����ת��ť if (GUI.RepeatButton(new Rect(460, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.Right])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { //�����ܵ���ת�Ƕ� GameLayer.totalRotation += ConstOfGame.rotationStep; //�������˵���ת�Ƕ� logic.cueObject.transform.RotateAround(logic.cueBall.transform.position, Vector3.up, ConstOfGame.rotationStep); } } //M��ť if (GUI.Button(new Rect(550, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.M])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { //�������û���С��ͼ�ı�־λ MiniMap.isMiniMap = !MiniMap.isMiniMap; } } //F��ť if (GUI.Button(new Rect(650, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", fbtnStyle)) { //����������ť������ if (GameLayer.TOTAL_FLAG) { //������Ӧ�뷨����������Active�����������ߣ��븨���� logic.assistBall.SetActive(!logic.assistBall.activeSelf); logic.line.SetActive(!logic.line.activeSelf); } } if (isFirstView) { if (GUI.Button(new Rect(740, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.firstV])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { (GetComponent("CamControl") as CamControl).ChangeCam(2); isFirstView = !isFirstView; } } } else { if (GUI.Button(new Rect(740, ConstOfGame.btnPositonY, ConstOfGame.btnSize, ConstOfGame.btnSize), "", btnStyle[(int)ButtonS.freeV])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { (GetComponent("CamControl") as CamControl).ChangeCam(1); isFirstView = !isFirstView; } } } if (GUI.Button(new Rect(730, 10, 30, 30), "", btnStyle[(int)ButtonS.thirdV])) { //����������ť������ if (GameLayer.TOTAL_FLAG) { (GetComponent("CamControl") as CamControl).ChangeCam(0); } } } void cueRunAction() { //������һ��û���˶��� if (!isFirstActionOver) { logic.cue.transform.Translate(new Vector3(0, 0, Time.deltaTime)); if (logic.cue.transform.localPosition.z <= -2) { //��һ���˶����� isFirstActionOver = true; } } else if (!isSecondActionOver && isFirstActionOver)//��һ���˶��������ڶ����˶�û�н��� { logic.cue.transform.Translate(new Vector3(0, 0, -2 * Time.deltaTime)); if (logic.cue.transform.localPosition.z >= -0.45f) { //��һ���˶����� isSecondActionOver = true; } } else//ȫ���˶������� { //����������Ч if (PlayerPrefs.GetInt("offEffect") == 0) { GetComponent<AudioSource>().PlayOneShot(startSound); } //����������λ�� logic.cue.transform.localPosition = new Vector3(0, 0, -1); //����һ�����Ĵ�С���������ܸ���������ô�͸�һ�����ٶ�,����������1-2������ʧ��������ʵһ�� //�������˲��ɼ� logic.cue.GetComponent<Renderer>().enabled = false; //�������˿ɼ� logic.assistBall.transform.position = new Vector3(100, 0.98f, 100); //�������߿ɼ� logic.line.GetComponent<Renderer>().enabled = false; //�����������ٶ� logic.cueBall.GetComponent<Rigidbody>().velocity = new Vector3((PowerBar.restBars - 1) / 22.0f * ConstOfGame.MAX_SPEED * Mathf.Sin(GameLayer.totalRotation / 180.0f * Mathf.PI), 0, (PowerBar.restBars - 1) / 22.0f * ConstOfGame.MAX_SPEED * Mathf.Cos(GameLayer.totalRotation / 180.0f * Mathf.PI)); //�������˶� GameLayer.isStartAction = false; } } //��ס�Ժ�����ʹ�þ�̬ȫ�ֱ��� public static void resetAllStaticData() { //�����б� BallGroup_ONE_EIGHT.Clear(); BallGroup_TWO_EIGHT.Clear(); BallGroup_ONE_NINE.Clear(); BallGroup_TOTAL.Clear(); //���������� ballInNum = 0; //��Y��������ת�Ƕ� totalRotation = 0.0f; //�����밴ť�Ƿ����õ��ܱ�־λ TOTAL_FLAG = true; //�����Ƿ��˶����ܱ�־Ϊ isStartAction = false; //�������� CamControl.curCam = 1; //��һ�εĴ���λ�� CamControl.prePosition = Vector3.zero; //���صı�־λ CamControl.touchFlag = true; //ʣ��ʱ�� PowerBar.showTime = 720; //���������Ӵ�С PowerBar.restBars = 22; } }<file_sep>/Table3D/Assets/Scripts/MenuScript/HelpBoard/HelpBoardSlider.cs using UnityEngine; using System.Collections; public class HelpBoardSlider : MonoBehaviour { public RectTransform Child; private Vector3 endPostion; private Vector3 touchPosition; private float offset; private Vector2 Distance; private bool IsMoving; void Start () { endPostion = Vector3.zero; touchPosition = Vector3.zero; IsMoving = false; offset = 0; } void Update () { if (Input.GetMouseButtonDown (0) && !IsMoving) { touchPosition = Input.mousePosition; Distance = Child.anchoredPosition; } else if (Input.GetMouseButtonUp (0) && !IsMoving) { endPostion = Input.mousePosition; offset = endPostion.x - touchPosition.x; if (Mathf.Abs (offset) > 20) { if ((offset < 0 && Child.localPosition.x >= -13440) || (offset > 0 && Child.localPosition.x < -1920)) { Distance += new Vector2 (Mathf.Sign (offset) * 1920, 0); IsMoving = true; } } } if (IsMoving) { if (offset > 0) { if (Child.anchoredPosition.x > (Distance + Vector2.right * 50).x) { Child.anchoredPosition = Distance; IsMoving = false; } else { Child.anchoredPosition += Vector2.right * 1920 * Time.deltaTime; } } else if (offset < 0) { if (Child.anchoredPosition.x < (Distance + Vector2.right * 50).x) { Child.anchoredPosition = Distance; IsMoving = false; } else { Child.anchoredPosition += Vector2.left * 1920 * Time.deltaTime; } } } } } <file_sep>/Table3D/Assets/Scripts/GameScript/CamControl.cs using UnityEngine; using System.Collections; public class CamControl : MonoBehaviour { public LayerMask mask = -1; public GameObject cueBall; //��X������ת�Ƕ� private float total_RotationX; //free�ӽ�ʱ��Y������ת�Ƕ� public float freeViewRotationMatrixY = 0; //��ȡ������ Logic logic; //���������飬���е�4��������Ϊ�ն�������Ϊ�������������ĸ��ڵ㣬���ڴ�����������λ�á� public GameObject []cameras; //��ǰ���������� public static int curCam = 1; //��ʼ����һ�δ��ص���λ�� public static Vector3 prePosition = Vector3.zero; //�Ƿ��������صı�־λ public static bool touchFlag = true; //gui������������Ҫ������ת�������꣬��Ϊ������ת��ʱ���䲻����gui����Ӧ�����ǣ��� Matrix4x4 inverse; //��¼��ʼ�ij�ʼ��תλ�õı��� Quaternion qua; //��¼��ʼλ�õı�������������Ҫ����һ�� Vector3 vec; // Use this for initialization void Start () { //��¼��ʼλ�ã���Ҫ�����ڻָ�λ�� qua = cameras[4].transform.rotation; vec = cameras[4].transform.position; //��������Ӧ�������ӿ�����ʱ�Ứ������ע�͵� for (int i = 0; i < 3; i++) { //�����ӿڵ����ű� cameras[i].GetComponent<Camera>().aspect = 800.0f / 480.0f; //�����ӿڵ�GUI���� float lux = (Screen.width - ConstOfMenu.desiginWidth * Screen.height / ConstOfMenu.desiginHeight) / 2.0f; cameras[i].GetComponent<Camera>().pixelRect = new Rect(lux, 0, Screen.width - 2 * lux, Screen.height); } //������ʵ��ת�Ƕ�13�ȣ� total_RotationX = 13; //��ȡ�ű����� logic = GetComponent("Logic") as Logic; //��ȡ������ inverse = ConstOfMenu.getInvertMatrix(); } // Update is called once per frame void Update () { //���ﴥ�ص�Ҫ���Ƚ��ϸ񣬵��������������������������������Ƕȣ�������PawerBar�н������� if (!touchFlag) { return; } //�����������ص� if (!GameLayer.TOTAL_FLAG) { return; } //��ָ����ʱ�Ļص����� if (Input.GetMouseButton(0)) { //������Y������ת�Ƕ� float angleY = (Input.mousePosition.x - prePosition.x)/ConstOfGame.SCALEX; //������X������ת�Ƕ� float angleX = (Input.mousePosition.y - prePosition.y) / ConstOfGame.SCALEY; Vector3 newPoint = ConstOfMenu.getInvertMatrix().MultiplyVector(Input.mousePosition); switch (curCam) { //��ͬ��������ִ�в�ͬ�ķ��� case 0: mainFunction(Input.mousePosition); break; case 1: firstFunction(angleY, angleX); break; case 2: freeFunction(angleY, angleX); break; } //��¼��һ�εĴ���λ�� prePosition = Input.mousePosition; } } public void ChangeCam(int index) { //ÿ���л�ʱ������freeʱ����transform=first�ӽǵ� setFreeCame(); //���õ�ǰ������������ cameras[curCam].SetActive(false); //������Ӧ������ cameras[index].SetActive(true); //���õ�ǰ���������� curCam = index; } //���������������ĸ�����Ϣ public void setFreeCame() { cameras[3].transform.rotation = cameras[4].transform.rotation; cameras[3].transform.position = cameras[4].transform.position; freeViewRotationMatrixY = GameLayer.totalRotation; //����������ת�ǶȵĶ��� total_RotationX = 13; cameras[2].transform.position = cameras[4].transform.position; cameras[2].transform.rotation = cameras[4].transform.rotation; cameras[1].transform.position = cameras[4].transform.position; cameras[1].transform.rotation = cameras[4].transform.rotation; } void mainFunction(Vector3 pos) { //��ȡ������̨�Ľ������꣬Ȼ�����øõ����������������������¼������˵���ת�Ƕȵȡ� RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(pos); if (Physics.Raycast(ray, out hit, 100, mask.value)) { //����λ���Լ���ת�Ƕ� cameras[3].transform.rotation = qua; cameras[3].transform.position = vec; Vector3 hitPoint = hit.point; Vector3 cubBallPoint = cueBall.transform.position; float angle = 180 - Mathf.Atan2(cubBallPoint.x - hitPoint.x, cubBallPoint.z - hitPoint.z) * Mathf.Rad2Deg; //�����ܵ���ת�Ƕ� GameLayer.totalRotation = -angle; //��ת�㲢��Ӱ����ת�Ƕ� cameras[3].transform.transform.RotateAround(ConstOfGame.CUEBALL_POSITION, Vector3.up, GameLayer.totalRotation); //�������˵���ת�Ƕ� logic.cueObject.transform.rotation = cameras[3].transform.rotation; } } //��Ӧ��gameLayer���е�far��near��ť�� public void moveCame(int sign) { cameras[curCam].transform.Translate(new Vector3(0, 0, sign * Time.deltaTime)); Vector3 posCueBall= cameras[curCam].transform.InverseTransformPoint(cueBall.transform.position); //�����ƶ����������������¼�¼ if (posCueBall.z > 35 || posCueBall.z < 7) { cameras[curCam].transform.Translate(new Vector3(0, 0, -sign * Time.deltaTime)); } } //��һ�˳��ӽǵĻص����� void firstFunction(float angleY,float angleX) { //ֻ����һ����������ת�����������ܲ��ÿ���Ч����Y����תû�����ƣ�X����ת��0-90֮�� if (Mathf.Abs(angleY) > Mathf.Abs(angleX) && Mathf.Abs(angleY)>1f) { //����Y����ת�Ƕ� GameLayer.totalRotation += angleY; //�������˵���ת�Ƕ� logic.cueObject.transform.RotateAround(logic.cueBall.transform.position, Vector3.up, angleY); } else { if (total_RotationX + angleX > 10 && total_RotationX + angleX < 90) { if (Mathf.Abs(angleX) > 1f) { //������ת�� Vector3 right = new Vector3(Mathf.Cos(-GameLayer.totalRotation / 180.0f * Mathf.PI), 0, Mathf.Sin(-GameLayer.totalRotation / 180.0f * Mathf.PI)); //����X��������ת�Ƕ� total_RotationX += angleX; //��������ת cameras[1].transform.RotateAround(logic.cueBall.transform.position, right, angleX); } } } } //�����˳��ӽǵĻص����� void freeFunction(float angleY, float angleX) { if (Mathf.Abs(angleY) > 0.5f) { //����Y����ת�Ƕ� freeViewRotationMatrixY += angleY; //�������˵���ת�Ƕ� cameras[2].transform.RotateAround(logic.cueBall.transform.position, Vector3.up, angleY); } else { if (total_RotationX + angleX > 10 && total_RotationX + angleX < 90f) { //������ת�� //Vector3 right = new Vector3(Mathf.Cos(-freeViewRotationMatrixY / 180.0f * Mathf.PI), 0, Mathf.Sin(-freeViewRotationMatrixY / 180.0f * Mathf.PI)); Vector3 right = cameras[curCam].transform.TransformDirection(Vector3.right); //����X��������ת�Ƕ�,����ת�Ƕ���Ҫ��������ת�ķ��� total_RotationX += angleX; //��������ת cameras[2].transform.RotateAround(logic.cueBall.transform.position, right, angleX); } } } } <file_sep>/Table3D/Assets/Scripts/GameScript/PowerBar.cs using UnityEngine; using System.Collections; public class PowerBar : MonoBehaviour { public static int tipIndex; public Texture2D[] tipTexture; public Texture2D bg;//力量滑动条背景图片 public Texture2D bar;//力量块整张图片 private int groupX = 0, groupY = 120, groupWidth = 100, groupHeight = 230,//背景图片矩形框参数 barX = 5, barY = 5, barW = 40, barH = 220;//力量块图片矩形参数 private float texX = 0, texY = 0, texW = 1, texH = 1;//纹理矩形参数 private int totalBars = 22;//力量块的个数 private int barWidth;//每个力量块的宽度 private Rect groupRect;//声明群组矩形变量 public static int restBars = 22;//定义私有变量 private Matrix4x4 invertMatrix; Vector3 movePosition; Vector3 startPositon; //与计时器相关的变量 public Texture2D[] textures; public bool isStartTime; private int totalTime; private int countTime; public static int showTime = 720; private int startTime; private int x = 300, y = 30, numWidth = 32, numHeight = 32, span = 6; //结果类的引用 private Result result; // Use this for initialization void Start() { result = GetComponent("Result") as Result; //如果是八球模式 if (PlayerPrefs.GetInt("billiard") == 8) { tipIndex = 0; } else { tipIndex = 3; } startTime = (int)Time.time; countTime = 0; totalTime = 720; //是否为倒计时模式的标志位 isStartTime = PlayerPrefs.GetInt("isTime") > 0; startPositon = Vector3.zero; movePosition = Vector3.zero; invertMatrix = ConstOfMenu.getInvertMatrix(); groupRect = new Rect(groupX, groupY, groupWidth, groupHeight + 100);//初始化变量 barWidth = barH / totalBars;//计算每个力量块的宽度 } void Update() { //如果为倒计时模式 if (isStartTime) { countTime = (int)Time.time - startTime; showTime = totalTime - countTime; //如果时间小于0则表示游戏失败 if (showTime<=0) { //调用result组件的goLoseScene方法进入到失败界面 result.goLoseScene(); } } if (GameLayer.TOTAL_FLAG) { if (Input.GetMouseButtonDown(0)) { CamControl.prePosition = Input.mousePosition; CamControl.touchFlag = false; startPositon = invertMatrix.MultiplyPoint3x4(Input.mousePosition); movePosition = startPositon; } //当鼠标点击屏幕或在屏幕上滑动时 if (Input.GetMouseButton(0)) { //得到鼠标位置,井进行自适应 movePosition = invertMatrix.MultiplyPoint3x4(Input.mousePosition); } if (Input.GetMouseButtonUp(0)) { CamControl.touchFlag = false; } } } void OnGUI() { GUI.matrix = ConstOfMenu.getMatrix(); GUI.DrawTexture(new Rect(272, 5, 256, 16), tipTexture[tipIndex]); if (isStartTime) { DrawTime(showTime); } GUI.BeginGroup(groupRect);//开始群组 GUI.DrawTexture(new Rect(0, 0, groupWidth, groupHeight), bg);//绘制力量条背景 GUI.DrawTextureWithTexCoords(new Rect(barX, barY + barWidth * (totalBars - restBars), barW, barWidth * restBars), bar, new Rect(texX, texY, texW, texH * restBars / totalBars));//绘制力量块 GUI.EndGroup();//结束群组 if (new Rect(barX + groupX, barY + groupY, barW, barH).Contains(new Vector2(startPositon.x, 480.0f - startPositon.y))) { //如果鼠标力量条区域 CamControl.touchFlag = false; //如果鼠标位于力量条矩形内时 restBars = Mathf.Clamp(totalBars - (int)(480.0f - movePosition.y - barY - groupY) / barWidth, 1, 22);//计算需要绘制的力量块个数 } else { if (new Rect(0, 420, 800, 60).Contains(new Vector2(movePosition.x, 480.0f - movePosition.y))) { if (new Rect(0, 420, 800, 60).Contains(new Vector2(startPositon.x, 480.0f - startPositon.y))) { //如果鼠标按钮区域 CamControl.touchFlag = false; } } else if (new Rect(730, 10, 30, 30).Contains(new Vector2(movePosition.x, 480.0f - movePosition.y))) { if (new Rect(730, 10, 30, 30).Contains(new Vector2(startPositon.x, 480.0f - startPositon.y))) { //如果鼠标按钮区域 CamControl.touchFlag = false; } } else { CamControl.touchFlag = true; } } } void DrawTime(int time) { int minute = time / 60; int seconds = time % 60; int num1 = minute / 10; int num2 = minute % 10; int num3 = seconds / 10; int num4 = seconds % 10; GUI.BeginGroup(new Rect(x, y, 5 * (numWidth + span), numHeight)); GUI.DrawTexture(new Rect(0, 0, numWidth, numHeight), textures[num1]); GUI.DrawTexture(new Rect((numWidth + span), 0, numWidth, numHeight), textures[num2]); GUI.DrawTexture(new Rect(2 * (numWidth + span), 0, numWidth, numHeight), textures[textures.Length - 1]); GUI.DrawTexture(new Rect(3 * (numWidth + span), 0, numWidth, numHeight), textures[num3]); GUI.DrawTexture(new Rect(4 * (numWidth + span), 0, numWidth, numHeight), textures[num4]); GUI.EndGroup(); } }<file_sep>/Table3D/Assets/Scripts/MenuScript/ConstOfMenu.cs using UnityEngine; using System.Collections; public class ConstOfMenu : MonoBehaviour { //标准屏的宽与高度 public static float desiginWidth = 800.0f; public static float desiginHeight = 480.0f; //各个界面中按钮图片索引 public static int START_BUTTON = 0; public static int MUSSIC_BUTTON = 1; public static int HELP_BUTTON = 2; public static int ABOUT_BUTTON = 3; public static int EIGHT_BUTTON = 0; public static int NINE_BUTTON = 1; public static int COUNTDOW_BUTTON = 0; public static int PRACTICE_BUTTON = 1; public static int RANK_BUTTON = 2; //主界面按钮的移动速度 public static float movingSpeed = 80f; //主界面按钮的位置 public static float[] ButtonPositionOfX = new float[4] { 128, 416, 128, 416 }; //主界面按钮的移动方向 public static float[] ButtonMovingStep = new float[4] { 1, -1, 1, -1 }; //ModeChoiceLayer界面按钮的位置 public static float[] BPositionXOfMode = new float[3] { 128, 416, 128 }; //ModeChoiceLayer界面按钮的移动方向 public static float[] BMovingXStepOfMode = new float[3] { -1, 1, -1 }; //该界面按钮的移动速度 public static float movingSpeedOFMode = 80f; //界面ID方便管理 public static int MainID = 1; public static int ChoiceID = 2; public static int SoundID = 3; public static int HelpID = 4; public static int AboutID = 5; public static int ModeChoiceID = 6; public static int RankID = 7; //GUI自适应矩阵 public static Matrix4x4 getMatrix() { //获取单位矩阵 Matrix4x4 guiMatrix = Matrix4x4.identity; //计算位移距离 float lux = (Screen.width - ConstOfMenu.desiginWidth * Screen.height / ConstOfMenu.desiginHeight) / 2.0f; //设置GUI矩阵,标准屏幕800*480 guiMatrix.SetTRS(new Vector3(lux,0,0), Quaternion.identity, new Vector3(Screen.height / ConstOfMenu.desiginHeight, Screen.height / ConstOfMenu.desiginHeight, 1)); //返回该矩阵 return guiMatrix; } //GUI逆矩阵 public static Matrix4x4 getInvertMatrix() { //获取GUI矩阵 Matrix4x4 guiInverseMatrix = getMatrix(); //计算GUI逆矩阵 guiInverseMatrix = Matrix4x4.Inverse(guiInverseMatrix); //返回该矩阵 return guiInverseMatrix; } } <file_sep>/Table3D/Assets/Scripts/MenuScript/MainLayer.cs using UnityEngine; using System.Collections; public class MainLayer : MonoBehaviour { //菜单界面背景图片 public Texture backgroundOfMainMenu; //菜单界面按钮图样式 public GUIStyle[] buttonStyleOfMain; //首先需要创建数组 private float[] ButtonPositionOfX = new float[4]; //按钮直接的高度差 private float buttonOfficerOfHeight; //第一个按钮的起始Y坐标 private float startYOfMainMenu; //主菜单界面按钮是否进行移动动作的标志位 public bool moveFlag; //主菜单界面按钮当前移动的距离 private float buttonOfCurrentMovingDistance; //主菜单界面按钮移动的最大距离 private float buttonOfMaxDistance; //GUI矩阵 private Matrix4x4 guiMatrix; // Use this for initialization void Start () { //初始图片的高度 buttonOfficerOfHeight = 75; //Main界面最上面那个按钮的高度,其余按钮的高度在此基础上进行计算 startYOfMainMenu = 150; //移动的标志位 moveFlag = true; //重新设置位置等信息 restData(); //按钮移动距离 buttonOfCurrentMovingDistance = 0; //按钮最大移动距离 buttonOfMaxDistance = 80; //获取GUI自适应矩阵 guiMatrix = ConstOfMenu.getMatrix(); } void OnGUI() { //设置GUI自适应矩阵 GUI.matrix = guiMatrix; //绘制背景图片 GUI.DrawTexture(new Rect(0, 0, ConstOfMenu.desiginWidth, ConstOfMenu.desiginHeight), backgroundOfMainMenu); //绘制menu界面 DrawMainMenu(); //判断是否允许移动 if (moveFlag) { //如果按钮需要移动就移动吧 ButtonOfManiMenuMove(); } } //绘制主菜单界面 void DrawMainMenu() { if (GUI.Button(new Rect(ButtonPositionOfX[ConstOfMenu.START_BUTTON], startYOfMainMenu + buttonOfficerOfHeight * 0, 256, 64), "", buttonStyleOfMain[ConstOfMenu.START_BUTTON])) { if (!moveFlag) { //如果按钮没有移动 (GetComponent("Constroler") as Constroler).ChangeScrip(ConstOfMenu.MainID, ConstOfMenu.ChoiceID); } } if (GUI.Button(new Rect(ButtonPositionOfX[ConstOfMenu.MUSSIC_BUTTON], startYOfMainMenu + buttonOfficerOfHeight * 1, 256, 64), "", buttonStyleOfMain[ConstOfMenu.MUSSIC_BUTTON])) { if (!moveFlag) { //如果按钮没有移动 (GetComponent("Constroler") as Constroler).ChangeScrip(ConstOfMenu.MainID, ConstOfMenu.SoundID); } } if (GUI.Button(new Rect(ButtonPositionOfX[ConstOfMenu.HELP_BUTTON], startYOfMainMenu + buttonOfficerOfHeight * 2, 256, 64), "", buttonStyleOfMain[ConstOfMenu.HELP_BUTTON])) { if (!moveFlag) { //如果按钮没有移动 (GetComponent("Constroler") as Constroler).ChangeScrip(ConstOfMenu.MainID, ConstOfMenu.HelpID); } } if (GUI.Button(new Rect(ButtonPositionOfX[ConstOfMenu.ABOUT_BUTTON], startYOfMainMenu + buttonOfficerOfHeight * 3, 256, 64), "", buttonStyleOfMain[ConstOfMenu.ABOUT_BUTTON])) { if (!moveFlag) { //如果按钮没有移动 (GetComponent("Constroler") as Constroler).ChangeScrip(ConstOfMenu.MainID, ConstOfMenu.AboutID); } } } //按钮移动的方法 void ButtonOfManiMenuMove() { //按钮移动的距离 float length = ConstOfMenu.movingSpeed * Time.deltaTime; //按钮移动一下 buttonOfCurrentMovingDistance += length; //设置按钮的位置,ConstOfMenu.ButtonMovingStep[i]表示每个按钮的移动方向 for (int i = 0; i < ButtonPositionOfX.Length; i++) { ButtonPositionOfX[i] += (ConstOfMenu.ButtonMovingStep[i] * length); } //计算是否移动到最大距离 moveFlag = buttonOfCurrentMovingDistance < buttonOfMaxDistance; } //重新设置数据的方法 public void restData() { for (int i = 0; i < ConstOfMenu.ButtonPositionOfX.Length; i++) { //设置位置 ButtonPositionOfX[i] = ConstOfMenu.ButtonPositionOfX[i]; } //重置当前移动距离为0 buttonOfCurrentMovingDistance = 0; //移动的标志位 moveFlag = true; } } <file_sep>/Table3D/Assets/Scripts/MenuScript/MainBoard/VolumnControllerBoard.cs using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UI{ public class VolumnControllerBoard : MonoBehaviour { public Button soundOpen; public Button soundClose; public Button effectOpen; public Button effectClose; public void Start() { soundOpen.onClick.AddListener (SoundOpenOnClick); soundClose.onClick.AddListener (SoundCloseOnClick); effectOpen.onClick.AddListener (EffectOpenOnClick); effectClose.onClick.AddListener (EffectCloseOnClick); } /// <summary> /// Sounds the open on click. /// </summary> public void SoundOpenOnClick() { soundClose.gameObject.SetActive (true); soundOpen.gameObject.SetActive (false); } /// <summary> /// Sounds the close on click. /// </summary> public void SoundCloseOnClick() { soundClose.gameObject.SetActive (false); soundOpen.gameObject.SetActive (true); } /// <summary> /// Effects the open on click. /// </summary> public void EffectOpenOnClick() { effectOpen.gameObject.SetActive (false); effectClose.gameObject.SetActive (true); } /// <summary> /// Effects the close on click. /// </summary> public void EffectCloseOnClick() { effectOpen.gameObject.SetActive (true); effectClose.gameObject.SetActive (false); } } } <file_sep>/Table3D/Assets/Scripts/MenuScript/HelpLayer.cs using UnityEngine; using System.Collections; public class HelpLayer : MonoBehaviour { //Help界面的图片 public Texture2D[] helpTexture; //第一张图片的位置 private float positionY; //图片直接Y方向的偏移量 private float officerY; //GUI自适应矩阵 private Matrix4x4 guiMatrix; //当前显示图片的索引 private int currentIndex; //触控点坐标 private Vector2 touchPoint ; //当前移动距离 private float currentDistance; //自适应的滑动距离缩放系数 private float scale; //图片是否移动 private bool isMoving; //图片移动的步径 private float moveStep; //移动距离的正负行,这里比较复杂,不要深究 private int stepHao; //上一次触控点的位置 private Vector2 prePositon; // Use this for initialization void Start () { //初始化2维向量 touchPoint = Vector2.zero; prePositon = Vector2.zero; //当前图片索引 currentIndex = 0; //移动的Y距离 positionY = 0.0f; //移动步径 moveStep = 300; //当前移动距离 currentDistance = 0; //是否移动的标志位 isMoving = false; //屏幕高度 officerY = ConstOfMenu.desiginHeight; //获取GUI自适应矩阵 guiMatrix = ConstOfMenu.getMatrix(); //滑动自适应系数 scale = Screen.height / 480.0f; } void Update(){ //判断是否允许触控,帮助图片在移动过程中不允许触控移动 if(!isMoving && Input.touchCount>0) { //获取一个触控点 Touch touch = Input.GetTouch(0); //按钮按下时的回调方法 if (touch.phase == TouchPhase.Began) { touchPoint = touch.position;//记录down点 prePositon = touch.position;//记录down点 } else if (touch.phase == TouchPhase.Moved) { //=号后面为move的距离 float newPositonY= positionY - touch.position.y + prePositon.y; //positionY的范围-480*7-0 positionY = (newPositonY > 0) ? 0 : (newPositonY > (-480 * 7) ? newPositonY : (-480 * 7)); //记录上一次的触控点 prePositon = touch.position; } else if (touch.phase == TouchPhase.Ended) { //手指抬起来时,图片开始自动移动 isMoving = true; //计算从触控开始到抬起的距离 currentDistance = (touch.position.y - touchPoint.y) / scale; //执行移动方法 stepHao = (Mathf.Abs(currentDistance) > 150.0f) ? (currentDistance > 0 ? 1 : (-1)) : 0; //计算当前移动步径 moveStep = (Mathf.Abs(currentDistance) > 150.0f) ? (currentDistance > 0 ? -Mathf.Abs(moveStep) : Mathf.Abs(moveStep)) : (currentDistance > 0 ? Mathf.Abs(moveStep) : -Mathf.Abs(moveStep)); //调用indexChange方法修改移动索引值 indexChange(stepHao); } } } void OnGUI(){ //设置GUI自适应矩阵 GUI.matrix = guiMatrix; //循环数组 for (int i = 0; i < helpTexture.Length; i++){ //每次只绘制3章图片即可,即当前显示图片与上下两张 if (Mathf.Abs(currentIndex - i) < 2){ GUI.DrawTexture(new Rect(0, positionY + officerY * i, ConstOfMenu.desiginWidth, ConstOfMenu.desiginHeight), helpTexture[i]); } } //如果允许图片移动,则移动 if(isMoving){ //调用textureMove方法 textureMove(); } } void textureMove(){ //计算新位置 float positionYOfNew = positionY + moveStep * Time.deltaTime; //计算positonY的最大值 float minDistance = -480*Mathf.Abs(currentIndex); //判断移动方向 if (stepHao==1) { //计算positionY的值 positionY = Mathf.Max(positionYOfNew, minDistance); } else if (stepHao == -1) { //计算positionY的值 positionY = Mathf.Min(positionYOfNew, minDistance); } else { if (moveStep > 0) { //计算positionY的值 positionY = Mathf.Min(positionYOfNew, minDistance); } else { //计算positionY的值 positionY = Mathf.Max(positionYOfNew, minDistance); } } //计算是否可移动的标志位 isMoving = !(positionY == minDistance); } void indexChange(int step){ //计算当前编号 int newIndex = currentIndex+step; //如果编号超出边界 if (newIndex>7||newIndex<0) { return; } //修改当前索引值currentIndex确保其在0-6直接 currentIndex = newIndex; //设置为可移动 isMoving = true; } public void restData() { //重新设置当前所有 currentIndex = 0; //重新设置Y的位置 positionY = 0.0f; //设置移动步径 moveStep = 300; //设置移动距离 currentDistance = 0; //设置移动的标志位 isMoving = false; } } <file_sep>/Table3D/Assets/Scripts/MenuScript/ModeChoiceLayer.cs using UnityEngine; using System.Collections; public class ModeChoiceLayer : MonoBehaviour { //菜单界面背景图片 public Texture backgroundOfModeChoicerMenu; //菜单界面按钮图样式 public GUIStyle[] buttonStyleOfModeChoice; //首先需要创建数组 private float[] ButtonPositionOfX = new float[3]; //按钮移动的距离 private float buttonOfCurrentMovingDistance; //按钮移动的最大距离 private float buttonOfMaxDistance; //第一个按钮的起始Y坐标 private float startYOfModeChoice; //按钮直接的高度差 private float buttonOfficerOfHeight; //按钮移动的标志位 private bool moveFlag; //定义GUI自适应矩阵 private Matrix4x4 guiMatrix; void Start () { //移动的标志位 moveFlag = true; //获取主菜单界面4个按钮的X方向位置 restData(); //按钮当前移动的距离 buttonOfCurrentMovingDistance = 0; //按钮移动的最大距离,根据图片大小等计算的。这里不用深究 buttonOfMaxDistance = 144f; //按钮起始高度 startYOfModeChoice = 180f; //按钮间距 buttonOfficerOfHeight = 90f; //GUI自适应矩阵 guiMatrix = ConstOfMenu.getMatrix(); } void OnGUI() { //设置GUI的自适应矩阵 GUI.matrix = guiMatrix; //绘制背景图片 GUI.DrawTexture(new Rect(0, 0, ConstOfMenu.desiginWidth, ConstOfMenu.desiginHeight), backgroundOfModeChoicerMenu); if (GUI.Button(new Rect(ButtonPositionOfX[ConstOfMenu.COUNTDOW_BUTTON], startYOfModeChoice, 256, 64), "", buttonStyleOfModeChoice[ConstOfMenu.COUNTDOW_BUTTON])) { if (!moveFlag) { //倒计时模式 PlayerPrefs.SetInt("isTime", 1); //设置游戏界面的静态变量数据 GameLayer.resetAllStaticData(); //加载LevelSelectScene场景 Application.LoadLevel("GameScene"); } } if (GUI.Button(new Rect(ButtonPositionOfX[ConstOfMenu.PRACTICE_BUTTON], startYOfModeChoice + buttonOfficerOfHeight * 1, 256, 64), "", buttonStyleOfModeChoice[ConstOfMenu.PRACTICE_BUTTON])) { if (!moveFlag) { //练习模式 PlayerPrefs.SetInt("isTime", 0); //设置游戏界面的静态变量数据 GameLayer.resetAllStaticData(); //加载LevelSelectScene场景 Application.LoadLevel("GameScene"); } } if (GUI.Button(new Rect(ButtonPositionOfX[ConstOfMenu.RANK_BUTTON], startYOfModeChoice + buttonOfficerOfHeight * 2, 256, 64), "", buttonStyleOfModeChoice[ConstOfMenu.RANK_BUTTON])) { if (!moveFlag) { //切换到历史记录界面 (GetComponent("Constroler") as Constroler).ChangeScrip(ConstOfMenu.ModeChoiceID, ConstOfMenu.RankID); } } if (moveFlag) { //如果按钮需要移动就移动吧 ButtonMove(); } } void ButtonMove() { //计算移动距离 float length = ConstOfMenu.movingSpeedOFMode * Time.deltaTime; //按钮移动 buttonOfCurrentMovingDistance += length; for (int i = 0; i < ButtonPositionOfX.Length; i++) { ButtonPositionOfX[i] += (ConstOfMenu.ButtonMovingStep[i] * length); } //计算是否移动到最大距离,即移动的标志位 moveFlag = buttonOfCurrentMovingDistance < buttonOfMaxDistance; } public void restData() { for (int i = 0; i < ConstOfMenu.BPositionXOfMode.Length; i++) { //设置位置 ButtonPositionOfX[i] = ConstOfMenu.BPositionXOfMode[i]; } //重置当前移动距离为0 buttonOfCurrentMovingDistance = 0; //运行移动 moveFlag = true; } } <file_sep>/Table3D/Assets/Scripts/MenuScript/Tools/MainUIController.cs using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace UI{ public class MainUIController : MonoBehaviour { public static MainUIController Ins; public List<GameObject> Gameobjects; private Stack<MenuType> MainUIStack; void Awake () { MainUIStack = new Stack<MenuType>(); Show (MenuType.Main); Ins = this; } public void Show(MenuType name) { if (MainUIStack.Count > 0) { MenuType last = MainUIStack.Peek (); for (int i = 0; i < Gameobjects.Count; i++) { if (Gameobjects [i].name.Equals (last.ToString ())) { Gameobjects [i].SetActive (false); break; } } for (int i = 0; i < Gameobjects.Count; i++) { if (Gameobjects [i].name.Equals (name.ToString ())) { Gameobjects [i].SetActive (true); break; } } } MainUIStack.Push (name); } public void Back() { if (MainUIStack.Count >= 2) { MenuType last = MainUIStack.Pop(); for (int i = 0; i < Gameobjects.Count; i++) { if (Gameobjects [i].name.Equals (last.ToString ())) { Gameobjects [i].SetActive (false); break; } } MenuType CurrentLast = MainUIStack.Peek (); for (int i = 0; i < Gameobjects.Count; i++) { if (Gameobjects [i].name.Equals (CurrentLast.ToString ())) { Gameobjects [i].SetActive (true); break; } } } } } } <file_sep>/Table3D/Assets/Scripts/MenuScript/MainBoard/GameModeBoard.cs using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UI { public class GameModeBoard : MonoBehaviour { public Button CountDown; public Button Practise; public Button Rank; public void Start() { CountDown.onClick.AddListener (OnCountDownClick); Practise.onClick.AddListener (OnPractiseClick); Rank.onClick.AddListener (OnRankClick); } /// <summary> /// Raises the count down click event. /// </summary> public void OnCountDownClick() { } public void OnPractiseClick() { } public void OnRankClick() { } } } <file_sep>/Table3D/Assets/Scripts/GameScript/Logic.cs using UnityEngine; using System.Collections; public class Logic : MonoBehaviour { //ģʽ�ı�־λ private bool isEightMode; //��һ�λ����Ƿ������ı�־λ private bool isJudgeOver; //�����Ƿ�����λ�õı�־λ public bool resetPositionFlag; //���� ���� public GameObject cue; //���߶��� public GameObject line; //���������� public GameObject assistBall; //���˵ĸ��ڵ�,��Ҫ���𵽼������˼����ķ��� public GameObject cueObject; //ĸ������ public GameObject cueBall; //���ڴ������˸��ڵ�λ�õı��� public Vector3 cuePosition; //����ɾ���б� ArrayList ballNeedRemove; //��ֵ���� private float t = 0; //������������ private Result result; // Use this for initialization void Start () { result = GetComponent("Result") as Result; cuePosition = cueBall.transform.position; //ģʽ�ı�־λ isEightMode = PlayerPrefs.GetInt("billiard") < 9; //��һ�λ����Ƿ������ı�־λ,����Ҳ��8��ģʽ��9��ģʽ����Ϊ9��ģʽ����Ҫ���е�һ�λ������жϣ�ֻҪ������ɫ8������������ isJudgeOver = PlayerPrefs.GetInt("billiard") == 9; ; //�������õı�־λ resetPositionFlag = false; //����ɾ���б� ballNeedRemove = new ArrayList(); } // Update is called once per frame void Update() { //ѭ��������Ҫ�б����ҵ���Ҫɾ���� for (int i = 0; i < GameLayer.BallGroup_TOTAL.Count; i++) { GameObject tran = GameLayer.BallGroup_TOTAL[i] as GameObject; //��ȡ�ű����� BallScript ballScript = tran.GetComponent("BallScript") as BallScript; //�ж��Ƿ�����ɾ�� if (ballScript.isAlowRemove) { ballNeedRemove.Add(tran); } } //����removeBalls������ɾ��������ɾ���������� removeBalls(); //������ť�ʹ��ؿ��ã��򲻽������淽����ִ�У�������ִ�бȱ�־λ�����ڴ� if (!GameLayer.TOTAL_FLAG && !GameLayer.isStartAction) { //ѭ���ж�����ȥ���Ƿ�ֹͣ�˶� for (int i = 1; i < GameLayer.BallGroup_TOTAL.Count; i++) { GameObject obj = (GameLayer.BallGroup_TOTAL[i] as GameObject); //�ж����Ƿ�ֹͣ if (obj.GetComponent<Rigidbody>().velocity.sqrMagnitude > 0.01f) { return; } } //�����˱�־λtrue����ʾ������������̨���˴�������isAlowRemove�� if (resetPositionFlag) { //���ô˷��� afterBallStopCallback(); } //������������ͣ�� ��ͬ��Ҳ���ø÷��� if (cueBall.GetComponent<Rigidbody>().velocity.sqrMagnitude < 0.01f) { afterBallStopCallback(); } } } void removeBalls() { //���ַ�ʽ��8��ģʽ������9��ģʽ if (isEightMode) { //������ʾ���жϣ�����1-7����9-15����ȫ����������ʾ���Ի�����ɫ�˺��� if (GameLayer.BallGroup_ONE_EIGHT.Count == 0 || GameLayer.BallGroup_TWO_EIGHT.Count == 0) { //����Ϊ4 PowerBar.tipIndex = 4; } for (int i = ballNeedRemove.Count - 1; i >= 0; i--) { //removeBall((Transform)ballNeedRemove[i]); GameObject tran = ballNeedRemove[i] as GameObject; //��ȡ�ű����� BallScript ballScript = tran.GetComponent("BallScript") as BallScript; //������0���� if (ballScript.ballId == 0) { //���ð���λ�õı�־λ��Ϊture resetPositionFlag = true; //��������ɾ���ı�־λΪfalse ballScript.isAlowRemove = false; //��������0������λ�ã�����Ļ���� tran.transform.GetComponent<Renderer>().enabled = false; //���ð������ٶ� tran.GetComponent<Rigidbody>().velocity = Vector3.zero; tran.GetComponent<Rigidbody>().angularVelocity = Vector3.zero; } else if (ballScript.ballId< 8) { //ɾ�������� GameLayer.BallGroup_ONE_EIGHT.Remove(tran); GameLayer.BallGroup_TOTAL.Remove(tran); DestroyImmediate(tran); //��������һ GameLayer.ballInNum++; if (ConstOfGame.kitBallNum == 2) { //ʧ�� result.goLoseScene(); } } else if (ballScript.ballId == 8) { //ɾ�������� GameLayer.BallGroup_TOTAL.Remove(tran); DestroyImmediate(tran); if (GameLayer.BallGroup_ONE_EIGHT.Count == 0 || GameLayer.BallGroup_TWO_EIGHT.Count == 0) { //ʤ�� result.goVectorScene(); } else { //ʧ�� result.goLoseScene(); } } else { //PowerBar.tipIndex = 2; //ɾ�������� GameLayer.BallGroup_TWO_EIGHT.Remove(tran); GameLayer.BallGroup_TOTAL.Remove(tran); DestroyImmediate(tran); //��������һ GameLayer.ballInNum++; if (ConstOfGame.kitBallNum == 1) { //ʧ�� result.goLoseScene(); } } } } else { //��������ɫ�˺���ȫ����������ʾ���Ի�����ɫ�˺��� if (GameLayer.BallGroup_ONE_NINE.Count == 0) { PowerBar.tipIndex = 4; } for (int i = ballNeedRemove.Count - 1; i >= 0; i--) { //��ȡ���� GameObject tran = ballNeedRemove[i] as GameObject; //��ȡ�ű����� BallScript ballScript = tran.GetComponent("BallScript") as BallScript; //������0���� if (ballScript.ballId == 0) { //���ð���λ�õı�־λ��Ϊture resetPositionFlag = true; //��������ɾ���ı�־λΪfalse ballScript.isAlowRemove = false; //��������0������λ�ã�����Ļ���� tran.transform.GetComponent<Renderer>().enabled = false; //���ð��������ٶ������ٶ� tran.GetComponent<Rigidbody>().velocity = Vector3.zero; tran.GetComponent<Rigidbody>().angularVelocity = Vector3.zero; } else if (ballScript.ballId == 8) { //ɾ�������� GameLayer.BallGroup_ONE_NINE.Remove(tran); GameLayer.BallGroup_TOTAL.Remove(tran); DestroyImmediate(tran); if (GameLayer.BallGroup_ONE_NINE.Count == 0) { //ʤ�� result.goVectorScene(); } else { //ʧ�� result.goLoseScene(); } } else { PowerBar.tipIndex =3; //ɾ������������ GameLayer.BallGroup_ONE_NINE.Remove(tran); GameLayer.BallGroup_TOTAL.Remove(tran); DestroyImmediate(tran); GameLayer.ballInNum++; } } } //�����б� ballNeedRemove.Clear(); } private void afterBallStopCallback() { //�����ǵ�һ�˳����������棬�������������˳ƣ����������棬ֱ�������������˵�λ�ã���������������λ�� if (CamControl.curCam == 1) { if (resetPositionFlag) { setData(); resetData(); } else { //���в�ֵ���� t = Mathf.Min(t + Time.deltaTime / 2.0f, 1); //����cueObject��λ�� cueObject.transform.position = Vector3.Lerp(cuePosition, cueBall.transform.position, t); //����1֮����ʼ��������һЩ��Ϣ if (t == 1) { setData(); t = 0; } } } else { setData(); } } private void setData() { if (resetPositionFlag) { //����־λ�÷� resetPositionFlag = false; //�������ڰ�����λ�� cueBall.transform.position = ConstOfGame.CUEBALL_POSITION; //�������ð������ٶ� cueBall.transform.GetComponent<Rigidbody>().velocity = Vector3.zero; //��������0������λ�ã�����Ļ���� cueBall.transform.GetComponent<Renderer>().enabled = true; } //�������ǵ�һ�λ��� if (!isJudgeOver) { int one_count = GameLayer.BallGroup_ONE_EIGHT.Count; int two_count = GameLayer.BallGroup_TWO_EIGHT.Count; //���������������Ĵ�С�ж�Ӧ�ô򼸺��� if (one_count == two_count) { //����ʱ������������ ConstOfGame.kitBallNum = 0; PowerBar.tipIndex = 0; } else if (one_count < two_count) { //�Ǹ��б�С��ʾӦ��ȥ����һ������ ConstOfGame.kitBallNum = 1; //���ñ�־λ����ʾ��һ�λ������� isJudgeOver = true; PowerBar.tipIndex = 1; } else { //�Ǹ��б�С��ʾӦ��ȥ����һ������ ConstOfGame.kitBallNum = 2; //���ñ�־λ����ʾ��һ�λ������� PowerBar.tipIndex = 2; isJudgeOver = true; } } //�������˸��ڵ���λ�� cueObject.transform.position = cueBall.transform.position; //�������˿ɼ� cue.GetComponent<Renderer>().enabled = true; //�������߿ɼ� line.GetComponent<Renderer>().enabled = true; //���д����Լ���ť������ GameLayer.TOTAL_FLAG = true; } //�������ø�����Ϣ void resetData() { //��һ�˳�ʱ����������֮����Ҫ�����˰����Ȼص���ʼ�� GameLayer.totalRotation = 0; //13�Ǹ���������ʼ��ת�Ƕ� cueObject.transform.rotation = new Quaternion(1,0,0,13); //����CamControl����setFreeCame����������������������Ϣ (GetComponent("CamControl") as CamControl).setFreeCame(); } } <file_sep>/Table3D/Assets/Scripts/MenuScript/Tools/GeneralButton.cs using UnityEngine; using System.Collections; using UnityEngine.EventSystems; namespace UI { public class GeneralButton : MonoBehaviour,IPointerClickHandler { public void OnPointerClick(PointerEventData eventData) { MainUIController.Ins.Back (); } } } <file_sep>/Table3D/Assets/Scripts/GameScript/InitAllBalls.cs using UnityEngine; using System.Collections; public class InitAllBalls : MonoBehaviour { //Ԥ������ public GameObject ball; //����ͼƬ public Texture2D[] textures; //��ʼ�������ķ��� public void initAllBalls(int billiard) { int[] randomArray = RandomArray(billiard,7); //�ж�ģʽ>0Ϊ9��ģʽ bool init = (billiard - 8) > 0; int sum = 0; if (!init) { //������8��ģʽ����ʼ��16������ͼ textures = new Texture2D[16]; for (int i = 0; i < 16; i++) { //��������ͼ textures[i] = Resources.Load("snooker" + i) as Texture2D; } for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { //����������λ�� Vector3 ballPosition = new Vector3(-(0.5f + 0.05f) * (i - 1) + (j - 1) * (0.5f + 0.05f) * 2, 0.98f, 5.8f + (0.5f + 0.05f) * 2 * (i - 1)); //ʵ�������� //Transform obj = Instantiate(ball, ballPosition, Quaternion.identity) as Transform; GameObject obj = Instantiate(ball, ballPosition, new Quaternion(1,0,0,Mathf.PI/2)) as GameObject; //��������ͼƬ obj.transform.GetComponent<Renderer>().material.mainTexture = textures[randomArray[sum + j - 1] + 1]; //����������ID���� (obj.GetComponent("BallScript") as BallScript).ballId = randomArray[sum + j - 1] + 1; //��1-7�������ӵ�����ģʽ�µ�1���б� if ((randomArray[sum + j - 1] + 1) < 8) { GameLayer.BallGroup_ONE_EIGHT.Add(obj); } else if ((randomArray[sum + j - 1] + 1) > 8)//��9-15�������ӵ�����ģʽ�µ�2���б� { GameLayer.BallGroup_TWO_EIGHT.Add(obj); } GameLayer.BallGroup_TOTAL.Add(obj); } sum += i; } } else { //������9��ģʽ��ʼ��10��ͼƬ textures = new Texture2D[10]; for (int i = 0; i < 10; i++) { //��������ͼ textures[i] = Resources.Load("snooker" + i) as Texture2D; } for (int i = 1; i <= 5; i++) { //����ÿһ�������ĸ��� int max = (i % 4 == 0) ? 2 : i % 4; for (int j = 1; j <= max; j++) { sum++; //����������λ�� Vector3 ballPosition = new Vector3(-(0.5f + 0.05f) * (max - 1) + (j - 1) * (0.5f + 0.05f) * 2, 0.98f, 5.8f + (0.5f + 0.05f) * 2 * (i - 1)); //ʵ�������� GameObject obj = Instantiate(ball, ballPosition, new Quaternion(1, 0, 0, Mathf.PI / 2)) as GameObject; ; //����������λ�� obj.transform.GetComponent<Renderer>().material.mainTexture = textures[randomArray[sum - 1] +1]; //����������ID���� (obj.GetComponent("BallScript") as BallScript).ballId = randomArray[sum - 1] + 1; //���Ǻ�ɫ�˺������ӵ�����ģʽ�µ��б� if ((randomArray[sum - 1] + 1) != 8) { GameLayer.BallGroup_ONE_NINE.Add(obj); } GameLayer.BallGroup_TOTAL.Add(obj); } } } } ////���������������ڷ�������id�������ο�һ�¼��� //private ArrayList randomNum(int billiard) //{ // ArrayList list1 = new ArrayList(); // ArrayList list2 = new ArrayList(); // if ((billiard - 8) > 0) // { // for (int i = 1; i < 10; i++) // { // if (i != 8) // { // list1.Add(i); // } // } // for (int i = 1; i < 9; i++) // { // int m = (int)Random.Range(0, list1.Count - 0.1f); // list2.Add((int)list1[m]); // list1.RemoveAt(m); // } // list2.Insert(4, 8); // } // else // { // for (int i = 1; i < 16; i++) // { // if (i != 8) // { // list1.Add(i); // } // } // for (int i = 1; i < 15; i++) // { // int m = (int)Random.Range(0, list1.Count - 0.1f); // list2.Add((int)list1[m]); // list1.RemoveAt(m); // } // list2.Insert(4, 8); // } // return list2; //} //���������������ڷ�������id private int[] RandomArray(int length, int index) { length = length > 8 ? 9 : 15; //�����ض����������е����� ArrayList origin = new ArrayList();//ʵ����һ��ArrayList int[] result = new int[length];//ʵ����һ������Ϊlength�����飬���󷵻ظ����� for (int i = 0; i < length; i++) {//�����б�����ʼ�� if (i == index) {//����������index��Ԫ��ʱ continue;//����indexԪ�ط����б� } origin.Add(i);//��iԪ�ؼ����б��� } for (int i = 0; i < length; i++) {//�������� if (i == 4) {//����������index��Ԫ��ʱ result[i] = index;//Ϊ��index��Ԫ�ظ��̶���ֵ continue;//������һ�α��� } int tempIndex = (int)Random.Range(0, origin.Count - 0.1f);//��������λ�� result[i] = (int)origin[tempIndex];//�����б�������λ����ȡ����Ԫ�ظ�ֵ������ origin.RemoveAt(tempIndex);//���б���ɾ����Ӧ��ȡ����Ԫ�� } return result;//���ؽ��� } } <file_sep>/Table3D/Assets/Scripts/MenuScript/AboutLayer.cs using UnityEngine; using System.Collections; public class AboutLayer : MonoBehaviour { //界面背景图片 public Texture backgroundOfAboutLayer; //关于界面背景图片 public Texture aboutOfAboutLayer; //GUI自适应矩阵 private Matrix4x4 guiMatrix; // Use this for initialization void Start () { //获取GUI自适应矩阵 guiMatrix = ConstOfMenu.getMatrix(); } void OnGUI() { //设置GUI矩阵 GUI.matrix = guiMatrix; //绘制大背景 GUI.DrawTexture(new Rect(0, 0, ConstOfMenu.desiginWidth, ConstOfMenu.desiginHeight), backgroundOfAboutLayer); //绘制关于图片 GUI.DrawTexture(new Rect(148, 150, 504, 299), aboutOfAboutLayer); } } <file_sep>/Table3D/Assets/Scripts/GameScript/CalculateLine.cs using UnityEngine; using System.Collections; public class CalculateLine : MonoBehaviour { ////����ײ�����˶��켣 //public GameObject lineHitBallObject; ////������ //public GameObject lineHitBall; //�����߶�����ʵ����һ��plan���е����� public GameObject line; //ĸ������ public GameObject cueBall; //��ΪInitAllBalls��������ͼƬ��Դ��ֱ���ù������˾� public GameObject allScript; //initAllBalls�ű����� InitAllBalls initAllBalls; //camControl�ű����� CamControl camControl; //����ϵͳ public ParticleSystem particle; public Color c = Color.green; //�õ�ģʽ��������ʽ private int mode; void Start() { mode = PlayerPrefs.GetInt("billiard"); //��ȡinitAllBalls������Ŀ����Ҫ��Ϊ��ʹ�����Ѿ����غõ�����ͼ initAllBalls = allScript.GetComponent("InitAllBalls") as InitAllBalls; camControl = allScript.GetComponent("CamControl") as CamControl; } // Update is called once per frame void Update() { //Ϊ�˼��ټ��㣬���˱�־��ֻ���ڿ������л���ĸ����ǰ���£���ȥ���㸨���� if (GameLayer.TOTAL_FLAG) { //��������ĸ������������������ GameObject tableBall_N = calculateBall(); //���㸨���ߵ�λ�ã����ȣ��Լ���������λ�õ� calculateUtil(tableBall_N); //������˸�ķ��� ParticalBlint(tableBall_N); } } //�ҵ����������������Ǹ��� GameObject calculateBall() { //��ʼ��һ�������� GameObject tableBall_N = null; //�ж�б���Ƿ����� if (Mathf.Abs(GameLayer.totalRotation) == 90) { return null; } //��ȡ������λ�ã���ת����2Dƽ�� Vector2 position0 = new Vector2(cueBall.transform.position.z,-cueBall.transform.position.x); //���㷽������ Vector2 forceVector = new Vector2(Mathf.Cos(-GameLayer.totalRotation / 180.0f * Mathf.PI), Mathf.Sin(-GameLayer.totalRotation / 180.0f * Mathf.PI)); //����б�� float k = forceVector.y / forceVector.x; //ѭ�������б���Ѱ�Ҿ��븨�����������Ǹ��� for (int i = 1; i < GameLayer.BallGroup_TOTAL.Count; i++) { //��ȡ����λ�� GameObject tableBall_M = GameLayer.BallGroup_TOTAL[i] as GameObject; //��ȡ�ű����� BallScript ballScript = tableBall_M.GetComponent("BallScript") as BallScript; Vector2 position_M = new Vector2(tableBall_M.transform.position.z, -tableBall_M.transform.position.x); //���������� Vector2 vectorM_0 = new Vector2(position_M.x - position0.x, position_M.y - position0.y); //�������� float length = Mathf.Abs(position_M.y - k * position_M.x - position0.y + position0.x * k) / Mathf.Sqrt(1 + k * k); //���İ뾶Ϊ0.5���������븨���ߵľ���С��1��ĸ���ͻ���������ײ�����ǿ��ǵ�֮�������߷��䷽�������������㣬���Լ��˽Ƕ����� if (length <= 1 && Vector2.Angle(vectorM_0, forceVector) < Mathf.Acos(1 / 2) * Mathf.Rad2Deg) { //tableBall_N���ڣ�����tableBall_M��������һϵ�бȽ� if(tableBall_N) { //�ҵ�����λ�� Vector2 position_A = new Vector2(tableBall_N.transform.position.z, -tableBall_N.transform.position.x); //���ж�����λ�� Vector2 position_B = position_M; //�ȽϹ������Ǹ�������ĸ������tableBall_N�����Ǹ��� float length1 = Vector2.SqrMagnitude(new Vector2(position_A.x - position0.x, position_A.y - position0.y)); float length2 = Vector2.SqrMagnitude(new Vector2(position_B.x - position0.x, position_B.y - position0.y)); if (length1 > length2) { tableBall_N = tableBall_M; } } else { //����tableBall_N�����ڣ��򲻱������Ƚ�ֱ�Ӹ�ֵ tableBall_N = tableBall_M; } } } return tableBall_N; } //����������ײ���ķ��� void calculateUtil(GameObject tableBall_N ) { //���㷽������ Vector2 forceVector = new Vector2(Mathf.Cos(-GameLayer.totalRotation / 180.0f * Mathf.PI), Mathf.Sin(-GameLayer.totalRotation / 180.0f * Mathf.PI)); if (tableBall_N) { //��ȡ�ű����� BallScript ballScript = tableBall_N.GetComponent("BallScript") as BallScript; transform.LookAt(camControl.cameras[CamControl.curCam].transform.position); //����б�� float k = forceVector.y / forceVector.x; //��ȡ������λ�� Vector2 position_N = new Vector2(tableBall_N.transform.position.z, -tableBall_N.transform.position.x); //������λ�� Vector2 position0 = new Vector2(cueBall.transform.position.z, -cueBall.transform.position.x); //�������������������� Vector2 vector0_N = new Vector2(position_N.x - position0.x, position_N.y - position0.y); //��������ֱ�ߵľ��� float length1 = Mathf.Abs(position_N.y - k * position_N.x - position0.y + position0.x * k) / Mathf.Sqrt(1 + k * k); //����������֮���ľ�����ƽ���� float length2 = Vector2.SqrMagnitude(vector0_N); //�������룬�Լ���ͼ����1�ĺ������������İ뾶���� float length3 = Mathf.Sqrt(1 - length1 * length1); float length4 = Mathf.Sqrt(length2 - length1 * length1) - length3; Vector2 point1 = forceVector * length4; //��������λ�� Vector2 point2 = position0 + point1; transform.position = new Vector3(-point2.y, 0.98f, point2.x); //�ߵij��� Vector2 point3 = forceVector * length4; //���򷢳��ĸ����ߵ�λ�õ���Ϣ Vector2 point4 = position0 + point3 / 2; line.transform.position = new Vector3(-point4.y, 0.98f, point4.x); line.transform.localScale = new Vector3(0.005f, 1, (length4 - 1f) / 10.0f); line.GetComponent<Renderer>().material.mainTextureOffset = new Vector2(0, Time.time * 0.03f); line.GetComponent<Renderer>().material.mainTextureScale = new Vector2(1, (length4 - 1) / 12); //����ײ�����˶��켣�ĸ����� //�����˸����ߵķ��������� //Vector2 fPoint1 = position_N - point2; //��������ת��Ϊ�Ƕ� //float fAngle1 = Mathf.Atan2(fPoint1.y, fPoint1.x)*Mathf.Rad2Deg; ////���㸨��������λ�� //Vector2 fPoint2 = position_N + fPoint1; //���ø����������˶���λ�ã��䳤��Ϊ2�� //lineHitBallObject.transform.position = tableBall_N.transform.position; //Quaternion rotation = Quaternion.identity; //rotation.eulerAngles = new Vector3(0, -fAngle1, 0); //��������Ч�� //lineHitBallObject.transform.rotation = rotation; //lineHitBall.renderer.material.mainTextureOffset = new Vector2(0, Time.time * 0.03f); //lineHitBall.renderer.material.mainTextureScale = new Vector2(1, 0.2f); } else { Vector3 hitPoint3 = HitPoint(); Vector2 hitPoint = new Vector2(hitPoint3.z, -hitPoint3.x); //������λ�� Vector2 position0 = new Vector2(cueBall.transform.position.z, -cueBall.transform.position.x); //�������������������� Vector2 vector0_N = new Vector2(hitPoint.x - position0.x, hitPoint.y - position0.y); //������Ҫ��ȡ�ij��ȣ� float cutLenght = 0; if(Mathf.Abs(hitPoint3.z)>12.2f) { cutLenght = 0.5f / Mathf.Cos(GameLayer.totalRotation / 180 * Mathf.PI); } else { cutLenght = 0.5f / Mathf.Sin(GameLayer.totalRotation/180*Mathf.PI); } //ʵ�ʳ��� float tureLength1 = Vector2.Distance(Vector2.zero, vector0_N); float tureLength2 = tureLength1 - Mathf.Abs(cutLenght); Vector2 turePoint = forceVector * tureLength2; Vector2 ballPoint = position0 + turePoint; //���ø�������λ�� transform.position = new Vector3(-ballPoint.y, 0.98f, ballPoint.x); Vector2 point1 = position0 + turePoint / 2; //�����������ľ�����ȥ����2���뾶���� float length1 = tureLength2 - 1; //���ø����ߵ�λ�ã����űȣ�ͼƬƫ�������Լ����ű� line.transform.position = new Vector3(-point1.y, 0.98f, point1.x); line.transform.localScale = new Vector3(0.005f, 1, length1 / 10.0f); line.GetComponent<Renderer>().material.mainTextureOffset = new Vector2(0, Time.time * 0.03f); line.GetComponent<Renderer>().material.mainTextureScale = new Vector2(1, length1 / 12); //���ø������IJ��ʣ���ɫ transform.GetComponent<Renderer>().material.mainTexture = initAllBalls.textures[0]; //��ɫ��˸�����Ի��� GreenColor(); particle.startColor = c; } } Vector3 HitPoint() { //��ȡ��ײ�ĵ㣬���ォ�뾶��������һ�㼰table�㣬������ײ���⣬��ײ���ĵ����ڼ����ߵ�λ���Լ��ߵij��� Vector3 point = Vector3.zero; RaycastHit hit; if(Physics.Raycast(cueBall.transform.position,line.transform.forward,out hit,100)) { if (hit.transform.tag == "table") { point = hit.point; } } return point; } void ParticalBlint(GameObject tableBall_N) { if (tableBall_N) { //��ȡ�ű����� BallScript ballScript = tableBall_N.GetComponent("BallScript") as BallScript; //���ø������IJ��� transform.GetComponent<Renderer>().material.mainTexture = initAllBalls.textures[ballScript.ballId]; //���ø���������˸��ɫ int num = ConstOfGame.kitBallNum; //������8��ģʽ������15���� if (mode < 9) { //��ʾ�ɻ��������� if (num == 0) { if (ballScript.ballId == 8) { //��ɫ���治�ɻ��� RedColor(); } else { //��ɫ��˸�����Ի��� GreenColor(); //FullColor(); } } else if (num == 1)//����ȫɫ�� { if (ballScript.ballId > 8) { //��ɫ��˸����ʾ���棬���ɻ��� RedColor(); } else if (ballScript.ballId == 8) { int one_count = GameLayer.BallGroup_ONE_EIGHT.Count; int two_count = GameLayer.BallGroup_TWO_EIGHT.Count; if (one_count == 0 || two_count == 0) { //��ʾͬһ����ȫ����������ɫ��˸����ʾ����֮��ȡ��ʤ�� FullColor(); } else { //��ɫ��˸����ʾ���棬���ɻ��� RedColor(); } } else//����ȫɫ�� { //��ɫ��˸�����Ի��� } } else//������ɫ�� { if (ballScript.ballId > 8) { //��ɫ��˸�����Ի��� GreenColor(); } else if (ballScript.ballId == 8) { int one_count = GameLayer.BallGroup_ONE_EIGHT.Count; int two_count = GameLayer.BallGroup_TWO_EIGHT.Count; if (one_count == 0 || two_count == 0) { //��ʾͬһ����ȫ����������ɫ��˸����ʾ����֮��ȡ��ʤ�� FullColor(); } else { //��ɫ��˸����ʾ���棬���ɻ��� RedColor(); } } else//����ȫɫ�� { //��ɫ��˸����ʾ���棬���ɻ��� RedColor(); } } } else//������9��ģʽ������9���� { if (ballScript.ballId == 8) { int one_nine = GameLayer.BallGroup_ONE_NINE.Count; if (one_nine == 0) { //��ʾ�ɻ�����ɫ�˺�����������ɫ��˸ FullColor(); } else { //��ɫ��˸����ʾ���ɻ��� RedColor(); } } else { //�ɼ���������������ɫ��˸ GreenColor(); } } particle.startColor = c; } } //�����к�ɫ��˸ void RedColor() { c = Color.Lerp(Color.red, Color.red/2, Mathf.PingPong(Time.time, 1)); } //��������ɫ��˸ void GreenColor() { c = Color.Lerp(Color.green, Color.green/2, Mathf.PingPong(Time.time, 1)); } //�����в�ɫ��˸ void FullColor() { c = Color.Lerp(Color.yellow, Color.blue, Mathf.PingPong(Time.time, 1)); } } <file_sep>/Table3D/Assets/Scripts/GameScript/Cube.cs using UnityEngine; using System.Collections; public class Cube : MonoBehaviour { //��������Ч public AudioClip BallinEffect; //������ײʱ�Ļص����� void OnCollisionEnter(Collision other) { //�������ʹ˸�����ײ�����������Ѿ����� if (other.gameObject.tag == "Balls") { //����������Ч if (PlayerPrefs.GetInt("offEffect") == 0) { //������Ч GetComponent<AudioSource>().PlayOneShot(BallinEffect); } //������ɾ���ı�־λΪtrue����ʾ��������ɾ�� (other.gameObject.GetComponent("BallScript") as BallScript).isAlowRemove = true; } } } <file_sep>/Table3D/Assets/Scripts/GameScript/ConstOfGame.cs using UnityEngine; using System.Collections; public class ConstOfGame : MonoBehaviour { //按钮的大小 public static float btnSize = 60; //按钮的Y方向位置, public static float btnPositonY = 420; //微调步径 public static float rotationStep = 0.1f; //白球的初始位置 public static Vector3 CUEBALL_POSITION = new Vector3(0,0.98f,-8); //击球种类的全局变量,0-可以击打任意球,1-可以击球花色球,2-可以击打全色球 public static int kitBallNum = 0; //桌球的最大速度 public static float MAX_SPEED = 50; //整体的缩放比 public static float miniMapScale = 2; //饶X轴旋转的最大角度,因为起始的旋转角度就是13度,所以这里的总旋转角度为77度 public static float MAX_ROTATION_X = 77; //因为要自适应多种屏幕分辨率,而且需要在不同的手机上滑动效果是一样的,所以即使缩放比 public static float SCALEX = 4*Screen.width / 800.0f; public static float SCALEY = 4*Screen.height / 480.0f; } <file_sep>/Table3D/Assets/Scripts/GameScript/MiniMap.cs using UnityEngine; using System.Collections; public class MiniMap : MonoBehaviour { //�Ƿ�����С��ͼ�ı�־λ public static bool isMiniMap = true; //����ͼƬ private Texture2D[] textures; //mini��̨��ͼƬ private Texture2D miniTable; //���˵�ͼƬ private Texture2D cue; //���ű� private float scale; //��ת�� private Vector2 pivotPoint; //��ȡgui�������� Matrix4x4 guiInvert; void Start() { guiInvert = ConstOfMenu.getMatrix(); //��ʼ�����ű� scale = ConstOfGame.miniMapScale; //��ʼ������ͼƬ InitMiniTexture(PlayerPrefs.GetInt("billiard")); //��ʼ��mini��̨��ͼƬ miniTable = Resources.Load("minitable") as Texture2D; //��ʼ���˵�ͼƬ cue = Resources.Load("cueMini") as Texture2D; } public void drawMiniMap() { if (MiniMap.isMiniMap) { GUI.DrawTexture(new Rect(0, 0, 283.0f / scale, 153.0f / scale), miniTable); for (int i = 0; i < GameLayer.BallGroup_TOTAL.Count; i++) { //��ȡ�����������ĽŲ����Ӷ��õ���������Idֵ GameObject tran = GameLayer.BallGroup_TOTAL[i] as GameObject; //��ȡ�ű����� BallScript ballScript = tran.GetComponent("BallScript") as BallScript; //������λ�� Vector3 ballPosition = tran.transform.position; //��ȡ������ID int ballId = ballScript.ballId; GUI.DrawTexture(new Rect(ballPosition.z * 5 + 70, ballPosition.x * 5 + 35f, 5, 5), textures[ballId]); } //�������˿ɼ������������� if ((GameObject.Find("Cue") as GameObject).GetComponent<Renderer>().enabled) { //�������о���ʱ����Ҫ����������ô�����ģ���ֻ��Ҫ�������㷽�����ɣ��������ĸ�ת��api�� Vector3 cuePosition = (GameObject.Find("CueObject") as GameObject).transform.position; Vector3 cueBallPosition = (GameObject.Find("CueBall") as GameObject).transform.position; pivotPoint = new Vector2(cueBallPosition.z * 5 + 72.5f, cueBallPosition.x * 5 + 37f); Vector3 m = guiInvert.MultiplyPoint3x4(new Vector3(pivotPoint.x, pivotPoint.y,0)); GUIUtility.RotateAroundPivot(GameLayer.totalRotation, new Vector2(m.x, m.y)); GUI.DrawTexture(new Rect(cuePosition.z * 5 + 45, cuePosition.x * 5 + 37f, 20, 2), cue); } } } void InitMiniTexture(int billiard) { //�ж�ģʽ bool init = (billiard - 8) > 0; if (!init) { //������8��ģʽ����ʼ��16������ͼ textures = new Texture2D[16]; for (int i = 0; i < 16; i++) { //��������ͼ textures[i] = Resources.Load("minimap" + i) as Texture2D; } } else { textures = new Texture2D[10]; for (int i = 0; i < 10; i++) { //��������ͼ textures[i] = Resources.Load("minimap" + i) as Texture2D; } } } } <file_sep>/Table3D/Assets/Scripts/GameScript/Result.cs using UnityEngine; using System.Collections; public class Result : MonoBehaviour { //�Ƿ��Ѿ����������ı�־λ private bool isResult; //����ͼƬ public Texture2D backGround; //���ı���ͼƬ public Texture2D dialog; //��ʾ��ϢͼƬ public Texture2D[] tipTexture; //��ʾ��Ϣ���� private int tipIndex; //GUI����Ӧ���� Matrix4x4 guiMatrix; //��ť��ʽ public GUIStyle[] guiSytle; //��ȡlogic�Ų����� Logic logic; //��ȡPowerBar�Ų����� PowerBar powerBar; void Awake() { logic = GetComponent("Logic") as Logic; powerBar = GetComponent("PowerBar") as PowerBar; tipIndex = 0; guiMatrix = ConstOfMenu.getMatrix(); isResult = false; } //ʤ�������ķ��� public void goVectorScene() { powerBar.isStartTime = false; logic.enabled = false; //ѭ��������Ҫ�б����������ٶ�����Ϊ0 for (int i = 0; i < GameLayer.BallGroup_TOTAL.Count; i++) { GameObject ball = GameLayer.BallGroup_TOTAL[i] as GameObject; ball.transform.GetComponent<Rigidbody>().velocity = Vector3.zero; ball.transform.GetComponent<Rigidbody>().angularVelocity = Vector3.zero; } isResult = true; tipIndex = 1; if (PowerBar.showTime != 720) { //���ݴ洢����ʱ���Ѵ���ճ���� SaveData(PowerBar.showTime); } } //ʧ�ܽ����ķ��� public void goLoseScene() { powerBar.isStartTime = false; logic.enabled = false; //ѭ��������Ҫ�б����������ٶ�����Ϊ0 for (int i = 0; i < GameLayer.BallGroup_TOTAL.Count; i++) { GameObject ball = GameLayer.BallGroup_TOTAL[i] as GameObject; ball.transform.GetComponent<Rigidbody>().velocity = Vector3.zero; ball.transform.GetComponent<Rigidbody>().angularVelocity = Vector3.zero; } isResult = true; tipIndex = 0; } void OnGUI() { if (isResult) { GameLayer.TOTAL_FLAG = false; GUI.matrix = guiMatrix; //���ƻ�ɫ�ı���ͼƬ GUI.DrawTexture(new Rect(0, 0, 800, 480), backGround); //�趨�� GUI.BeginGroup(new Rect(200,150,400,180)); //���Ʊ��� GUI.DrawTexture(new Rect(0, 0, 400, 180), dialog); //������ʾ��Ϣ����Ϸʧ�ܣ���Ϸʤ���Ǹ� GUI.DrawTexture(new Rect(100, 20, 200,50), tipTexture[tipIndex]); if (GUI.Button(new Rect(30,100,150,50), "", guiSytle[0])) { //�������¿�ʼ�������½��г��������ã� GameLayer.resetAllStaticData(); //���¼��ظó��� Application.LoadLevel("GameScene"); } if (GUI.Button(new Rect(220, 100, 150, 50), "", guiSytle[1])) { //�����˳���Ϸ����Ϸ�˳� Application.Quit(); } GUI.EndGroup(); } } public static void SaveData(int score) { //���ݱ��淽�� int year = System.DateTime.Now.Year;//��ȡ���� int month = System.DateTime.Now.Month;//��ȡ���� int day = System.DateTime.Now.Day;//��ȡ���� string date = year + "-" + month + "-" + day;//��ȡ���� string oldData = PlayerPrefs.GetString("gameData"); string gameData = "";//������Ϸ���ݴ洢���� if (oldData == "") {//���洢Ϊ��ʱ gameData = date + "," + score;//Ϊ��Ϸ���ݴ洢������ֵ } else { gameData = oldData + ";" + date + "," + score;//Ϊ��Ϸ���ݴ洢������ֵ } PlayerPrefs.SetString("gameData", gameData);//������Ϸ���� } public static string[] LoadData() { string[] records = PlayerPrefs.GetString("gameData").Split(';'); return records; } } <file_sep>/Table3D/Assets/Scripts/GameScript/Shadow.cs using UnityEngine; using System.Collections; public class Shadow : MonoBehaviour { //桌球的位置变量 Vector3 parentPosition; void Update () { //获取其父类位置 parentPosition = transform.parent.position; //设置阴影屏幕的旋转角度,0.32f不必深究 transform.rotation = new Quaternion(1,0,0,-Mathf.PI*0.32f); //根据桌球的位置,设置阴影的位置 transform.position = new Vector3(parentPosition.x, 0.55f, parentPosition.z - 0.4f); } } <file_sep>/Table3D/Assets/Scripts/MenuScript/ChoiceLayer.cs using UnityEngine; using System.Collections; public class ChoiceLayer : MonoBehaviour { //菜单界面背景图片 public Texture backgroundOfChoiceMenu; //菜单界面按钮图样式 public GUIStyle[] buttonStyleOfChoice; //进行缩放的标志位 private bool scaleFlag; //缩放因子 private float scaleFactor; //按钮大小 private float buttonSize; //按钮X方向位置 private float buttonStartX; //按钮Y方向位置 private float buttonStartY; //GUI自适应矩阵 private Matrix4x4 guiMatrix; // Use this for initialization void Start () { //初始化缩放的标志位 scaleFlag = true; //设置缩放因子 scaleFactor = 0.0f; //按钮大小 buttonSize = 120; //按钮X方向位置 buttonStartX = 200; //按钮Y方向的位置 buttonStartY = 220; //获取GUI自适应矩阵 guiMatrix = ConstOfMenu.getMatrix(); } void OnGUI() { //设置GUI自适应矩阵 GUI.matrix = guiMatrix; //绘制背景图片 GUI.DrawTexture(new Rect(0, 0, ConstOfMenu.desiginWidth, ConstOfMenu.desiginHeight), backgroundOfChoiceMenu); //按钮的执行缩放动作 ButtonScale(); if (GUI.Button(new Rect(buttonStartX, buttonStartY, buttonSize * scaleFactor, buttonSize * scaleFactor), "", buttonStyleOfChoice[ConstOfMenu.EIGHT_BUTTON])) { if (!scaleFlag) { //8球模式标志存入,这里就不在修改,存0-1好一些 PlayerPrefs.SetInt("billiard", 8); //调用ChangeScrip方法进行界面切换 (GetComponent("Constroler") as Constroler).ChangeScrip(ConstOfMenu.ChoiceID, ConstOfMenu.ModeChoiceID); } } if (GUI.Button(new Rect(buttonStartX+240.0f, buttonStartY, buttonSize * scaleFactor, buttonSize * scaleFactor), "", buttonStyleOfChoice[ConstOfMenu.NINE_BUTTON])) { if (!scaleFlag) { //9球模式标志存入,这里就不在修改,存0-1好一些 PlayerPrefs.SetInt("billiard", 9); //调用ChangeScrip方法进行界面切换 (GetComponent("Constroler") as Constroler).ChangeScrip(ConstOfMenu.ChoiceID, ConstOfMenu.ModeChoiceID); } } } //按钮执行缩放动作 void ButtonScale() { //计算缩放比 scaleFactor = Mathf.Min(1.0f, scaleFactor + Time.deltaTime); //计算缩放标志位 scaleFlag = (scaleFactor != 1f); } //重置缩放比 public void restData() { //设置缩放标志位 scaleFlag = true; //计算缩放因子 scaleFactor = 0.0f; } } <file_sep>/Table3D/Assets/Scripts/MenuScript/MainBoard/ModeSelectBoard.cs using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UI { public class ModeSelectBoard : MonoBehaviour { public Button NineButton; public Button EightButton; public void Start() { NineButton.onClick.AddListener (NineButtonClick); EightButton.onClick.AddListener (EightButtonClick); } /// <summary> /// Nines the button click. /// </summary> public void NineButtonClick() { MainBoard.Ins.ModeSelectBoardNineClick (); } /// <summary> /// Eights the button click. /// </summary> public void EightButtonClick() { MainBoard.Ins.ModeSelectBoardEightClick (); } } } <file_sep>/Table3D/Assets/Scripts/MenuScript/MainBoard/MainBoard.cs using UnityEngine; using System.Collections; namespace UI { public enum MenuType { Main, ModeSelect, GameMode, VolumnController, About, Help, } public class MainBoard : MonoBehaviour { public static MainBoard Ins; public MainBoard_Main MainBoard_Main; public ModeSelectBoard ModeSelectBoard; public GameModeBoard GameModeBoard; public VolumnControllerBoard VolumnControllerBoard; public AboutBoard AboutBoard; public HelpBoard HelpBoard; public void Awake() { Ins = this; } /// <summary> /// Mains the board start game click. /// </summary> public void MainBoardStartGameClick() { // MainBoard_Main.gameObject.SetActive (false); // ModeSelectBoard.gameObject.SetActive (true); MainUIController.Ins.Show (MenuType.ModeSelect); } /// <summary> /// Mians the board volumn controller click. /// </summary> public void MainBoardVolumnControllerClick() { // MainBoard_Main.gameObject.SetActive (false); // VolumnControllerBoard.gameObject.SetActive (true); MainUIController.Ins.Show (MenuType.VolumnController); } /// <summary> /// Mains the board help click. /// </summary> public void MainBoardHelpClick() { // MainBoard_Main.gameObject.SetActive (false); // HelpBoard.gameObject.SetActive (true); MainUIController.Ins.Show (MenuType.Help); } /// <summary> /// Mains the board about click. /// </summary> public void MainBoardAboutClick() { // MainBoard_Main.gameObject.SetActive (false); // AboutBoard.gameObject.SetActive (true); MainUIController.Ins.Show (MenuType.About); } /// <summary> /// Modes the select board nine click. /// </summary> public void ModeSelectBoardNineClick() { // ModeSelectBoard.gameObject.SetActive (false); // GameModeBoard.gameObject.SetActive (true); MainUIController.Ins.Show (MenuType.GameMode); } /// <summary> /// Modes the select board eight click. /// </summary> public void ModeSelectBoardEightClick() { // ModeSelectBoard.gameObject.SetActive (false); // GameModeBoard.gameObject.SetActive (true); MainUIController.Ins.Show (MenuType.GameMode); } /// <summary> /// Games the mode count down click. /// </summary> public void GameModeCountDownClick() { } /// <summary> /// Games the mode practise click. /// </summary> public void GameModePractiseClick() { } /// <summary> /// Games the mode rank click. /// </summary> public void GameModeRankClick() { } } } <file_sep>/Table3D/Assets/Scripts/MenuScript/Tools/DontDistoryByGameObject.cs using UnityEngine; using System.Collections; namespace GameClient { public class DontDistoryByGameObject : MonoBehaviour { public void Awake() { DontDestroyOnLoad (gameObject); } } } <file_sep>/Table3D/Assets/Scripts/MenuScript/MainBoard/MainBoard_Main.cs using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UI{ public class MainBoard_Main : MonoBehaviour { public Button StartGame; public Button VolumnController; public Button Help; public Button About; public void Start() { StartGame.onClick.AddListener (OnStartGameClick); VolumnController.onClick.AddListener (VolumnControllerClick); Help.onClick.AddListener (HelpClick); About.onClick.AddListener (AboutClick); } /// <summary> /// Raises the start game click event. /// </summary> public void OnStartGameClick() { MainBoard.Ins.MainBoardStartGameClick (); } /// <summary> /// Volumns the controller click. /// </summary> public void VolumnControllerClick() { MainBoard.Ins.MainBoardVolumnControllerClick (); } /// <summary> /// Helps the click. /// </summary> public void HelpClick() { MainBoard.Ins.MainBoardHelpClick (); } /// <summary> /// Abouts the click. /// </summary> public void AboutClick() { MainBoard.Ins.MainBoardAboutClick (); } } } <file_sep>/Table3D/Assets/Scripts/GameScript/LineTool.cs using UnityEngine; using System.Collections; public class LineTool : MonoBehaviour { private Quaternion rotation; // Use this for initialization void Start () { rotation = transform.rotation; } // Update is called once per frame void Update () { transform.rotation = rotation; transform.RotateAround(Vector3.up, GameLayer.totalRotation*Mathf.Deg2Rad); } } <file_sep>/Table3D/Assets/Scripts/MenuScript/Tools/SoundManager.cs using UnityEngine; using System.Collections; namespace GameClient{ public enum MusicType{ //背景音乐1 BG_1, //背景音乐2 BG_2, } public class SoundManager : MonoBehaviour { public static SoundManager Ins; public AudioSource audioSource; public void Awake() { Ins = this; } /// <summary> /// Sets the background music. /// </summary> /// <param name="name">Name.</param> public void SetBackgroundMusic(MusicType name) { AudioClip clip = Resources.Load<AudioClip> (name.ToString()); audioSource.clip = clip; } public void SetMusic(MusicType name) { AudioClip clip = Resources.Load<AudioClip> (name.ToString()); audioSource.PlayOneShot (clip, audioSource.volume); } } } <file_sep>/Table3D/Assets/Scripts/GameScript/BallScript.cs using UnityEngine; using System.Collections; public class BallScript : MonoBehaviour { //�Ƿ�ɾ���ı�־λ public bool isAlowRemove = false; //����ID public int ballId = 0; //����������ײ���������� public AudioClip BallHit; //�Ƿ������������ٵı�־λ����Ϊ���򳬹���Χ֮�󣬿��ܻᵯ��������ʱ����û�н����� public bool setData = true; void Update() { //�������汾����ģ�⿴������̫��ʵ����������һЩ�������������Լ������ٶ�˥�� this.transform.GetComponent<Rigidbody>().velocity = this.transform.GetComponent<Rigidbody>().velocity * 0.988f; this.transform.GetComponent<Rigidbody>().angularVelocity = this.transform.GetComponent<Rigidbody>().angularVelocity * 0.988f; //�����ٶ���ֵ if (this.transform.GetComponent<Rigidbody>().velocity.sqrMagnitude < 0.01f) { this.transform.GetComponent<Rigidbody>().velocity = Vector3.zero; } if (Mathf.Abs(this.transform.position.z) > 12.3f || Mathf.Abs(this.transform.position.x) > 6.1f) { if (setData) { //���õ���ϵ������Ϊ�����ĵ���̫����������Ե��Ӧ̫����������һ�����ڣ�ʹ�俴�������� GetComponent<Collider>().material.bounciness = 0.2f; //�����������ٶ� this.transform.GetComponent<Rigidbody>().velocity = this.transform.GetComponent<Rigidbody>().velocity / 4; //�����������ݵı�־λΪfalse setData = false; } } else { //��ֹ���������� if (Mathf.Abs(this.transform.GetComponent<Rigidbody>().velocity.y) >= 3f) { this.transform.GetComponent<Rigidbody>().velocity = Vector3.zero; } //�������õ���ϵ�������ڼ�ʹ���򵽴��򶴴���Ҳ���ܵ����ˣ�������һ��ϸ�ڴ��� GetComponent<Collider>().material.bounciness = 1; //�����������õ����ݵı�־λ setData = true; } } void OnCollisionEnter(Collision collision) { //����������Ч if (PlayerPrefs.GetInt("offEffect") == 0) { //��ͼ��������֮������ײ if (collision.gameObject.tag == "Balls") { //�Ƚ����������ٶȴ�С float speedOfMySelf = gameObject.GetComponent<Rigidbody>().velocity.magnitude; float speedOfAnother = collision.rigidbody.velocity.magnitude; //�ٶȴ��IJ�����Ч if (speedOfMySelf > speedOfAnother) { //��Ч�IJ��Ŵ�С�������������ľ������� GetComponent<AudioSource>().volume = speedOfMySelf / ConstOfGame.MAX_SPEED; //������ײ��Ч GetComponent<AudioSource>().PlayOneShot(BallHit); } } } } } <file_sep>/Table3D/Assets/Scripts/MenuScript/Constroler.cs using UnityEngine; using System.Collections; public class Constroler : MonoBehaviour { //初始当前界面ID private int currentID = ConstOfMenu.MainID; //声明脚本组件 MonoBehaviour[] script; void Awake() { //定义脚本组件 script = GetComponents<MonoBehaviour>(); } // Update is called once per frame void Update () { //返回键监听 if(Input.GetKeyDown(KeyCode.Escape)) { //调用EscapeEvent方法 EscapeEvent(); } } //修改界面的方法 public void ChangeScrip(int offID,int onID ) { //切换界面之前首先要将其他界面的数据从新设置,例如主界面中按钮的位置等 restData(); //禁用当前界面脚本组件 script[offID].enabled = false; //启用需要进入界面的脚本组件 script[onID].enabled = true; //设置当前界面ID currentID = onID; } //返回键调用的方法 void EscapeEvent() { //每次按下返回键检测应该跳转到那个界面 switch (currentID) { //脚本组件0-n是按顺序加载的,对着这写下返回的方法 case 1: if ((GetComponent("MainLayer") as MainLayer).moveFlag) { break; }Application.Quit(); break; case 2: case 3: case 4: case 5: ChangeScrip(currentID,ConstOfMenu.MainID); break; case 6: ChangeScrip(currentID,ConstOfMenu.ChoiceID); break; case 7: ChangeScrip(currentID,ConstOfMenu.ModeChoiceID); break; } } //调用各个脚本组件的重新设置数据的方法,具体内容参照各个restData方法 private void restData() { (GetComponent("MainLayer") as MainLayer).restData(); (GetComponent("ChoiceLayer") as ChoiceLayer).restData(); (GetComponent("ModeChoiceLayer") as ModeChoiceLayer).restData(); HelpLayer helpLayer = GetComponent("HelpLayer") as HelpLayer; helpLayer.restData(); } }
1c3fb31bbb381053fb0aa12454a81ad384a855e5
[ "C#" ]
32
C#
XiaoHang1006/Table3D
baf5ab7b0031b6e1e06942a1be29fe9cab83f2f9
b364e7e0a319ed0bd5c5d94da8ac2d779c524908
refs/heads/master
<file_sep>let isMouseDown = false let selector = document.querySelector('.selection') let container = document.querySelector('.container') let origin = { x: 0, y: 0, } var thisQQ=[] let boxes = Array.from(document.querySelectorAll('.box')) const positionSelector = (e) => { const x = e.clientX const y = e.clientY selector.style.top = y + 'px' selector.style.left = x + 'px' } const createSelector = (e) => { isMouseDown = true selector = document.createElement('div') selector.classList.add('selection') container.appendChild(selector) origin.x = e.pageX origin.y = e.pageY positionSelector.call(this, e) resizeSelector.call(this, e) } const removeSelector = () => { origin.x = 0 origin.y = 0 container.removeChild(selector) isMouseDown = false } const removeSelections = () => { const selections = Array.from(document.querySelectorAll('.selected')) if (selections) { selections.map(s => s.classList.remove('selected')) } } const resizeSelector = (e) => { if (!isMouseDown) { return } const isLeft = e.clientX < origin.x const isUp = e.clientY < origin.y if (isLeft) { selector.style.left = e.clientX + 'px' selector.style.width = origin.x - e.clientX + 'px' } else { selector.style.right = e.clientX + 'px' selector.style.width = e.clientX - origin.x + 'px' } if (isUp) { selector.style.top = e.clientY + 'px' selector.style.height = origin.y - e.clientY + 'px' } else { selector.style.bottom = e.clientY + 'px' selector.style.height = e.clientY - origin.y + 'px' } boxes.map(box => { if (!checkOverlap(box, selector)) { box.classList.add('selected') //if QQ isn't in list, add it if(thisQQ.indexOf(box.id)===-1){ thisQQ.push(box.id); //box.classList.add('selected') }//else{ //thisQQ.splice(indexOf(box.id),1); //box.classList.remove('selected') //} } else { box.classList.remove('selected'); //if QQ is in list, remove it //thisQQ.splice(indexOf(box.id),1); //document.getElementById('list').innerHTML=box.id } //thisQQ.splice(indexOf(box.id),1); document.getElementById('list').innerHTML=thisQQ; }) } const checkOverlap = (box, selection) => { const a = box.getBoundingClientRect() const b = selection.getBoundingClientRect() return ( (b.right <= a.left) || (b.left >= a.right) || (b.bottom <= a.top) || (b.top >= a.bottom) ) } /* for(i=0;i<boxes.length;i++){ if(boxes[i].classList!=='selected'){ if(indexOf(boxes[i].id)>-1){ thisQQ.splice(indexOf(boxes[i].id),1); document.getElementById('list').innerHTML=thisQQ; } } } */ function clearQQs(){ thisQQ=[]; document.getElementById("list").innerHTML="Quarter-Quarters"; for(i=0;i<boxes.length;i++){ boxes[i].classList.remove('selected'); } } container.addEventListener('mousedown', createSelector) document.addEventListener('mouseup', removeSelector) container.addEventListener('mousemove', resizeSelector)
dcfb5999b872d494141a4f42e5acaf0dafbd16ad
[ "JavaScript" ]
1
JavaScript
Nippers/bugs1
974512cb6e341027c599f21b2ce75fe1faacee0a
9d41713b880d3789dbbe93aa5a48bf6a131e11a1
refs/heads/master
<repo_name>demas/docker-setup<file_sep>/cowl/docker-compose.yml version: '2.1' services: cowl-services: container_name: cowl-services image: demas/cowl-services restart: always ports: - 3000:3000 <file_sep>/cowl/crawler.sh #!/bin/bash docker run -i --rm --name cowl-crawler demas/cowl-crawler &>> ~/output.log <file_sep>/clojure.sh sudo docker run -i -t clojure /bin/bash <file_sep>/mongodb.sh sudo docker run -itd --name mongodb --restart always \ --volume /mnt/qnap/docker/data/mongodb:/bitnami/mongodb \ --publish 27017:27017 \ --env 'MONGODB_USERNAME=demas' --env 'MONGODB_PASSWORD=<PASSWORD>' --env 'MONGODB_DATABASE=mydb' \ bitnami/mongodb:latest <file_sep>/nginx/access_log.sh docker exec -it nginx tail -f /var/log/nginx/access.log <file_sep>/nginx/docker-compose.yml version: '2.1' services: nginx: container_name: nginx image: sameersbn/nginx:1.10.2-2 restart: always ports: - 80:80 volumes: - /mnt/qnap/docker/containers/run/nginx/nginx.conf:/etc/nginx/nginx.conf - /mnt/qnap/docker/containers/run/nginx/sites-enabled:/etc/nginx/sites-enabled - /mnt/qnap/docker/data/nginx:/www <file_sep>/postgresql.sh sudo docker run --name postgresql -itd --restart always \ --publish 5432:5432 \ --volume /mnt/qnap/docker/data/postgresql:/var/lib/postgresql \ --env 'PG_PASSWORD=<PASSWORD>' \ --env 'DB_NAME=news' \ --env 'DB_USER=demas' --env 'DB_PASS=<PASSWORD>' \ sameersbn/postgresql:9.6-2
810ca395254f3aa42ce8fb7261c1e6b806279131
[ "YAML", "Shell" ]
7
YAML
demas/docker-setup
be34b7d81d0120112df4d7d10f8f69c6728d096b
1bdde11ad5b6ec72567089d71cbe820ce33a5bb2
refs/heads/master
<repo_name>ilcarbo/HOoop<file_sep>/blanco.py """ Un blanco que atraviesa un medio puede recibir una señal del radar y reflejarla, siendo detectado de esta manera """ import random class Blanco(object): """ Define un blanco a ser detectado por un radar """ def __init__(self, amplitud, tiempo_inicial, tiempo_final): self.amplitud = amplitud self.tiempo_inicial = tiempo_inicial self.tiempo_final = tiempo_final def reflejar(self, señal, tiempo_inicial_detect, tiempo_final_detect): #si los tiempos de "existencia" del blanco están dentro de los tiempos de detección del radar, reflejar if tiempo_inicial_detect <= self.tiempo_inicial <= tiempo_final_detect \ and tiempo_inicial_detect <= self.tiempo_final <= tiempo_final_detect: # modificar la señal que llega, modificando la amplitud según el parámetro propio del blanco # y cambiando la fase de manera arbitraria. # devolver señal modificada return [x + self.amplitud for x in señal[random.randint(1,50):]] else: return False #TODO ver como se encajan los tiempos del blanco y del intervalo de tiempo #(interseccion de invervalos) # despues aplicar los parametros del blanco sobre ese intervalo de tiempo #pass <file_sep>/README.md # Object oriented project hands on ## Radar El objetivo de esta sesion es realizar una simulación de un radar usando para ello un diseño orientado a objetos. Inicialmente deben bajar todos los archivos .py en su home. El proyecto cuenta con varios archivos **python**, que corresponden a las diversas clases utilizadas en la simulación. Las clases son: radar, generador de señal, receptor de señal, medio y blanco. Un radar es un equipo genera y transmite señales hacia un medio donde pueden o no existir blancos. En caso de que la señal encuentre en su camino un blanco, éste puede reflejar la misma hacia el radar. La señal es recepcionada en el equipo para luego ser procesada por el detector. La clase detección determina si existe un blanco o no. ## Tareas 1. Completar la implementación de los métodos faltantes en las diferentes clases. 2. Completar el modulo main con la construcción de un radar e implementar algunos ejemplos 3. Existe un tipo especial de blanco denominado Clutter. Estos son blancos estaticos que en el momento de ser iluminados por el radar reflejan grandes cantidades de energia lo que puede "cegar" al radar impidiendo la detección de otros blancos presentes. Un ejemplo de Clutter es una montaña. Se pide rediseñar la simulación de manera que se cree una subclase de blanco denominada blanco_clutter. Cuando el Clutter refleja una onda incidente, produce una señal de mayor amplitud que supera a la señal transmitida. 4. Implementar el método del radar plotear_senal() para visualizar las senales antes y despues de impactar en un blanco <file_sep>/medio.py """ Los medios albergan los blancos que reflejan las señales del radar """ class Medio(object): def __init__(self, blancos = 0): self.blancos = blancos def reflejar(self, una_senal, tiempo_inicial, tiempo_final): """ Los blancos en el medio reflejan la señal """ #el medio solo refleja si posee blancos dentro de él if self.blancos == 0: return False #si hay blancos, reflejar señal elif self.blancos != 0: #el blanco dentro del medio refleja la seña return self.blancos.reflejar(una_senal, tiempo_inicial, tiempo_final) <file_sep>/radar.py """ El radar es el encargado de generar una señal con su generador y detectar la existencia de blancos en el medio al que apunta """ import matplotlib.pyplot as plt class Radar(object): def __init__(self, generador, detector): self.generador = generador self.detector = detector self.signal = False self.detected_signal = False def detectar(self, medio, tiempo_inicial, tiempo_final, threshold): """ Detecta si hay un blanco en un medio, en un intervalo de tiempo. """ # El generador propio del radar genera una señal. self.signal = self.generador.generar(tiempo_inicial, tiempo_final) # La señal se refleja (o no) en el medio al que el radar apunta self.reflected_signal = medio.reflejar(self.signal, tiempo_inicial, tiempo_final) # El detector propio del radar recibe la señal reflejada y la compara con la señal enviada # para saber si existe un blanco return self.detector.detectar(self.reflected_signal, self.signal, threshold) def plotear_señal(self, own_signal, signal): plt.plot(own_signal, color = 'blue', label= 'señal propia') plt.plot(signal, color = 'red', label= 'señal detectada') plt.legend(loc='upper right') plt.show() <file_sep>/generador.py """ Un generador de señal es el responsable de generar una senal portadora. """ import math import numpy as np class Generador(object): def __init__(self, amplitud, fase, frecuencia): self.amplitud = amplitud self.fase = fase self.frecuencia = frecuencia # muestras por segundo self.frecuencia_muestreo = frecuencia*3 def generar(self, tiempo_inicial, tiempo_final): cantidad_muestras = (tiempo_final - tiempo_inicial).seconds/\ self.frecuencia_muestreo #hacer entera la cantidad de muestras para poder utilizar range y luego generar señal. muestras = range(int(cantidad_muestras)) #generar la señal limpia sig = [self.amplitud*math.sin(2*(1/self.frecuencia)*i+self.fase) \ for i in muestras] #transformar la señal en un array de numpy retarray = np.asarray(sig) #generar el ruido para la señal noise = np.random.normal(0, 0.01, retarray.shape) #devolver la señal con el ruido incluido en forma de lista return (retarray + noise).tolist() <file_sep>/blancoCluter.py import Blanco class Blancocluter(Blanco): """ Define un Blancocluter a ser detectado por un radar """ def __init__(self, amplitud, tiempo_inicial, tiempo_final): #TODO: completar con la inicializacion de los parametros del objeto pass def reflejar(self, senal, tiempo_inicial, tiempo_final): #TODO ver como se encajan los timepos del blanco y del intervalo de tiempo # senal.insert(self.instante, senal[instante]+self.amplitud) # modificar la senal conlos parametros del blanco pass <file_sep>/detector.py """ El detector es el encargado de comparar la señal que recibe del medio y determinar si existe un blanco """ class Detector(object): def __init__(self): pass def detectar(self, signal, own_signal, threshold): """ comparar la señal que proviene del medio con la propia con un umbral determinado """ # Comparar solo si existe una señal proveniente del medio if signal != False: # comparar fase y amplitud de las señales (teniendo en cuenta el umbral para esta última) if ((max(signal) - min(signal)) / 2) / ((max(own_signal) - min(own_signal)) / 2) > threshold \ and signal.index(max(signal)) != own_signal.index(max(own_signal)): return True else: return False <file_sep>/main.py import radar import medio import blanco import generador import detector import math import datetime def main(): # Intervalo de tiempo en el que vamos a medir tiempo_inicial = datetime.datetime(2016, 3, 5, 1) tiempo_final = datetime.datetime(2016, 3, 5, 10) # parametros del generador de senales amplitud = 0.2 fase = 1 frecuencia = 20*math.pi # construir un nuevo genrador de senales generador1 = generador.Generador(amplitud, fase, frecuencia) # construir un detector detector1 = detector.Detector() # establecer un umbral para la detección threshold = 0.01 # construir un nuevo radar con su propio generador y detector radar1 = radar.Radar(generador1, detector1) # parametros para un blanco amplitud_de_frecuencia_del_blanco = amplitud * 0.06 tiempo_inicial_del_blanco = datetime.datetime(2016, 3, 5, 2) tiempo_final_del_blanco = datetime.datetime(2016, 3, 5, 4) # construir un nuevo blanco con sus propios tiempos blanquito = blanco.Blanco(amplitud_de_frecuencia_del_blanco, tiempo_inicial_del_blanco, tiempo_final_del_blanco) # construir un medio que contenga el blanco previamente construido medium = medio.Medio(blanquito) # Hacer que el radar detecte si existe un blanco en el medio al que apunta. detected = radar1.detectar(medium, tiempo_inicial, tiempo_final, threshold) # si el radar detecta un blanco, imprime un mensaje y plotea las dos señales if detected: print('Target detected') radar1.plotear_señal(radar1.signal, radar1.reflected_signal) # si el radar no detecta un blanco, imprime un mensaje. else: print('No target detected') if __name__ == "__main__": main()
fe74ca53d46833ac77ce4ff1548a32796faef457
[ "Markdown", "Python" ]
8
Python
ilcarbo/HOoop
e2163939ed8c716c29f752f5acb7ceeb3565b34e
8e72573547785a353f2388429183264d4cb86b1b
refs/heads/master
<file_sep>/* * OpenVPN LDAP Command * Copyright (C) 2017 <NAME> <<EMAIL>>. * * @SYZDEK_BSD_LICENSE_START@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of <NAME> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @SYZDEK_BSD_LICENSE_END@ */ #include <stdio.h> #include <string.h> #include <strings.h> #include <ldap.h> #include <stdarg.h> #include <stdlib.h> #include <inttypes.h> #include <unistd.h> char * prog_name; extern char **environ; int main(int argc, char * argv[]); int log_err(const char * fmt, ...); void ldap_opt_int(LDAP * ld, int opt, const char * name); void ldap_opt_str(LDAP * ld, int opt, const char * name); int log_err(const char * buff, ...) { va_list ap; char fmt[1024]; snprintf(fmt, sizeof(fmt), "%s: %s\n", prog_name, buff); va_start(ap, buff); return(vfprintf(stderr, fmt, ap)); va_end(ap); return(0); } void ldap_opt_int(LDAP * ld, int opt, const char * name) { int val; val = -1; ldap_get_option(ld, opt, &val); printf(" %-35s %i\n", name, val); return; }; void ldap_opt_str(LDAP * ld, int opt, const char * name) { char * val; val = NULL; ldap_get_option(ld, opt, &val); if ((val)) { printf(" %-35s %s\n", name, val); ldap_memfree(val); } else { printf(" %-35s N/A\n", name); }; return; }; void ldap_opt_tim(LDAP * ld, int opt, const char * name) { struct timeval * val; val = NULL; ldap_get_option(ld, opt, &val); if ((val)) { printf(" %-35s %" PRIuMAX ".%06" PRIuMAX "\n", name, (uintmax_t)val->tv_sec, (uintmax_t)val->tv_usec); ldap_memfree(val); } else { printf(" %-35s N/A\n", name); }; return; }; int main(int argc, char * argv[]) { int rc; LDAP * ld; int val_int; int c; prog_name = argv[0]; if ((prog_name = rindex(argv[0], '/')) != NULL) prog_name++; opterr = 0; while ((c = getopt (argc, argv, "c:h")) != -1) { switch (c) { case '?': fprintf(stderr, "%s: [ -c file ]\n", prog_name); return(1); case 'c': setenv("LDAPCONF", optarg, 1); break; default: break; }; }; if (optind < argc) { ldap_set_option(NULL, LDAP_OPT_URI, argv[optind]); }; if ((rc = ldap_initialize(&ld, NULL)) != LDAP_SUCCESS) { log_err("ldap_initialize(): %s", ldap_err2string(rc)); return(1); }; c = 1; ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &c); printf("LDAP environment variables:\n"); for(c = 0; environ[c]; c++) if (!(strncasecmp("ldap", environ[c], 4))) printf(" %s\n", environ[c]); printf("\n"); printf("options:\n"); ldap_opt_int(ld, LDAP_OPT_CONNECT_ASYNC, "LDAP_OPT_CONNECT_ASYNC"); ldap_opt_int(ld, LDAP_OPT_DEBUG_LEVEL, "LDAP_OPT_DEBUG_LEVEL"); ldap_opt_str(ld, LDAP_OPT_DEFBASE, "LDAP_OPT_DEFBASE"); ldap_get_option(ld, LDAP_OPT_DEREF, &val_int); printf(" %-35s %i (never %i/searching %i/finding %i/always %i)\n", "LDAP_OPT_DEREF:", val_int, LDAP_DEREF_NEVER, LDAP_DEREF_SEARCHING, LDAP_DEREF_FINDING, LDAP_DEREF_ALWAYS); ldap_opt_int(ld, LDAP_OPT_DESC, "LDAP_OPT_DESC"); ldap_opt_str(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, "LDAP_OPT_DIAGNOSTIC_MESSAGE"); ldap_opt_str(ld, LDAP_OPT_HOST_NAME, "LDAP_OPT_HOST_NAME"); ldap_opt_str(ld, LDAP_OPT_MATCHED_DN, "LDAP_OPT_MATCHED_DN"); ldap_opt_tim(ld, LDAP_OPT_NETWORK_TIMEOUT, "LDAP_OPT_NETWORK_TIMEOUT"); ldap_opt_int(ld, LDAP_OPT_PROTOCOL_VERSION, "LDAP_OPT_PROTOCOL_VERSION"); ldap_opt_str(ld, LDAP_OPT_REFERRAL_URLS, "LDAP_OPT_REFERRAL_URLS"); ldap_opt_int(ld, LDAP_OPT_REFERRALS, "LDAP_OPT_REFERRALS"); ldap_opt_int(ld, LDAP_OPT_RESTART, "LDAP_OPT_RESTART"); ldap_opt_int(ld, LDAP_OPT_RESULT_CODE, "LDAP_OPT_RESULT_CODE"); ldap_opt_int(ld, LDAP_OPT_SESSION_REFCNT, "LDAP_OPT_SESSION_REFCNT"); ldap_opt_int(ld, LDAP_OPT_SIZELIMIT, "LDAP_OPT_SIZELIMIT"); ldap_opt_int(ld, LDAP_OPT_TIMELIMIT, "LDAP_OPT_TIMELIMIT"); ldap_opt_tim(ld, LDAP_OPT_TIMEOUT, "LDAP_OPT_TIMEOUT"); ldap_opt_str(ld, LDAP_OPT_URI, "LDAP_OPT_URI"); printf("\n"); printf("SASL options:\n"); ldap_opt_str(ld, LDAP_OPT_X_SASL_AUTHCID, "LDAP_OPT_X_SASL_AUTHCID"); ldap_opt_str(ld, LDAP_OPT_X_SASL_AUTHZID, "LDAP_OPT_X_SASL_AUTHZID"); ldap_opt_str(ld, LDAP_OPT_X_SASL_MECH, "LDAP_OPT_X_SASL_MECH"); ldap_opt_int(ld, LDAP_OPT_X_SASL_NOCANON, "LDAP_OPT_X_SASL_NOCANON"); ldap_opt_str(ld, LDAP_OPT_X_SASL_REALM, "LDAP_OPT_X_SASL_REALM"); ldap_opt_str(ld, LDAP_OPT_X_SASL_USERNAME, "LDAP_OPT_X_SASL_USERNAME"); printf("\n"); printf("TCP options:\n"); ldap_opt_int(ld, LDAP_OPT_X_KEEPALIVE_IDLE, "LDAP_OPT_X_KEEPALIVE_IDLE"); ldap_opt_int(ld, LDAP_OPT_X_KEEPALIVE_PROBES, "LDAP_OPT_X_KEEPALIVE_PROBES"); ldap_opt_int(ld, LDAP_OPT_X_KEEPALIVE_INTERVAL, "LDAP_OPT_X_KEEPALIVE_INTERVAL"); printf("\n"); printf("TLS options:\n"); ldap_opt_str(ld, LDAP_OPT_X_TLS_CACERTDIR, "LDAP_OPT_X_TLS_CACERTDIR"); ldap_opt_str(ld, LDAP_OPT_X_TLS_CACERTFILE, "LDAP_OPT_X_TLS_CACERTFILE"); ldap_opt_str(ld, LDAP_OPT_X_TLS_CERTFILE, "LDAP_OPT_X_TLS_CERTFILE"); ldap_opt_str(ld, LDAP_OPT_X_TLS_CIPHER_SUITE, "LDAP_OPT_X_TLS_CIPHER_SUITE"); ldap_opt_int(ld, LDAP_OPT_X_TLS_CRLCHECK, "LDAP_OPT_X_TLS_CRLCHECK"); ldap_opt_str(ld, LDAP_OPT_X_TLS_CRLFILE, "LDAP_OPT_X_TLS_CRLFILE"); ldap_opt_str(ld, LDAP_OPT_X_TLS_DHFILE, "LDAP_OPT_X_TLS_DHFILE"); ldap_opt_str(ld, LDAP_OPT_X_TLS_KEYFILE, "LDAP_OPT_X_TLS_KEYFILE"); ldap_opt_int(ld, LDAP_OPT_X_TLS_NEWCTX, "LDAP_OPT_X_TLS_NEWCTX"); ldap_opt_int(ld, LDAP_OPT_X_TLS_PROTOCOL_MIN, "LDAP_OPT_X_TLS_PROTOCOL_MIN"); ldap_opt_str(ld, LDAP_OPT_X_TLS_RANDOM_FILE, "LDAP_OPT_X_TLS_RANDOM_FILE"); ldap_opt_int(ld, LDAP_OPT_X_TLS_REQUIRE_CERT, "LDAP_OPT_X_TLS_REQUIRE_CERT"); printf("\n"); ldap_unbind_ext_s(ld, NULL, NULL); return(0); } <file_sep> OpenVPN LDAP Command ==================== Contents -------- 1. Disclaimer 2. Maintainers 3. Background 4. Source Code 5. Package Maintence Notes Disclaimer ========== This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall <NAME> be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. Software Requirements ===================== * OpenLDAP Maintainers =========== <NAME> <EMAIL> Source Code =========== The source code for this project is maintained using git (http://git-scm.com). The following contains information to checkout the source code from the git repository. Browse Source: https://github.com/syzdek/openvpn-ldapcmd Git URLs: https://github.com/syzdek/openvpn-ldapcmd.git git@<EMAIL>:syzdek/openvpn-ldapcmd.git Downloading Source: $ git clone https://github.com/syzdek/openvpn-ldapcmd.git Preparing Source: $ cd openvpn-ldapcmd $ ./autogen.sh Git Branches: master - Current release of packages. next - changes staged for next release pu - proposed updates for next release xx/yy+ - branch for testing new changes before merging to 'pu' branch Package Maintence Notes ======================= This is a collection of notes for developers to use when maintaining this package. New Release Checklist: - Switch to 'master' branch in Git repository. - Update version in configure.ac. - Update date and version in ChangeLog. - Commit configure.ac and ChangeLog changes to repository. - Create tag in git repository: $ git tag -s v${MAJOR}.${MINOR} - Push repository to publishing server: $ git push --tags origin master:master next:next pu:pu Creating Source Distribution Archives: $ ./configure $ make update $ make distcheck $ make dist-bzip2 <file_sep>#!/bin/bash # # OpenVPN LDAP Command # Copyright (C) 2017 <NAME> <<EMAIL>>. # # @SYZDEK_BSD_LICENSE_START@ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of <NAME> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # @SYZDEK_BSD_LICENSE_END@ # if test ${#} != 3;then echo "Usage: $(basename "${0}") <infile> <outfile> <name>" exit 1 fi INFILE="${1}" OUTFILE="${2}" SCHEMANAME="${3}" SRCFILE=$(basename "${INFILE}") if test ! -f "${INFILE}";then echo "$(basename "${0}"): ${INFILE}: does not exist" exit 1 fi grep '^##' "${INFILE}" > "${OUTFILE}" cat << EOF >> "${OUTFILE}" # # This file was automatically generated from $SRCFILE; # see that file for complete references. # dn: cn=${SCHEMANAME},cn=schema,cn=config objectClass: olcSchemaConfig cn: $SCHEMANAME EOF perl -p0e 's/\n //g' ${INFILE} \ |sed \ -e 's/ \{2,\}/ /g' \ -e 's/^[aA][tT][tT][rR][iI][bB][uU][tT][eE][tT][yY][pP][eE] /olcAttributeTypes: /g' \ -e 's/^[oO][bB][jJ][eE][cC][tT][cC][lL][aA][sS][sS] /olcObjectClasses: /g' \ |egrep -v '^#|^$' \ |awk 'length > 78 { while ( length($0) > 78 ) { printf "%s\n ", substr($0,1,78); $0 = substr($0,79) } if (length) print; next } {print}' \ >> "${OUTFILE}" # end of script <file_sep>/* * OpenVPN LDAP Command * Copyright (C) 2017 <NAME> <<EMAIL>>. * * @SYZDEK_BSD_LICENSE_START@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of <NAME> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @SYZDEK_BSD_LICENSE_END@ */ #define __COMMON_C 1 #include "common.h" /////////////// // // // Headers // // // /////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Headers #endif #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <syslog.h> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "log.h" ///////////////// // // // Variables // // // ///////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Variables #endif extern char **environ; ovlc_code syslog_facilities[] = { { "kern", LOG_KERN }, { "user", LOG_USER }, { "mail", LOG_MAIL }, { "daemon", LOG_DAEMON }, { "auth", LOG_AUTH }, { "syslog", LOG_SYSLOG }, { "lpr", LOG_LPR }, { "news", LOG_NEWS }, { "uucp", LOG_UUCP }, { "cron", LOG_CRON }, { "authpriv", LOG_AUTHPRIV }, { "ftp", LOG_FTP }, { "local0", LOG_LOCAL0 }, { "local1", LOG_LOCAL1 }, { "local2", LOG_LOCAL2 }, { "local3", LOG_LOCAL3 }, { "local4", LOG_LOCAL4 }, { "local5", LOG_LOCAL5 }, { "local6", LOG_LOCAL6 }, { "local7", LOG_LOCAL7 }, { NULL, -1 } }; ////////////////// // // // Prototypes // // // ////////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Prototypes #endif ///////////////// // // // Functions // // // ///////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Functions #endif void ovlc_destroy(ovlc * od) { assert(od != NULL); if (od->cmd_arg != NULL) free(od->cmd_arg); if (od->ldap_basedn != NULL) free(od->ldap_basedn); if (od->ldap_filter != NULL) free(od->ldap_filter); if (od->ldap_uri != NULL) free(od->ldap_uri); if (od->ovpn_untrusted_ip != NULL) free(od->ovpn_untrusted_ip); if (od->ovpn_trusted_ip != NULL) free(od->ovpn_trusted_ip); if (od->ovpn_pool_remote_ip != NULL) free(od->ovpn_pool_remote_ip); if (od->ovpn_pool_remote_ip6 != NULL) free(od->ovpn_pool_remote_ip6); if (od->ovpn_common_name != NULL) free(od->ovpn_common_name); if (od->ovpn_username != NULL) free(od->ovpn_username); if (od->ovpn_password != NULL) free(od->ovpn_password); if (od->ovpn_profile != NULL) free(od->ovpn_profile); if (od->ovpn_profiledir != NULL) free(od->ovpn_profiledir); if (od->prog_conf != NULL) free(od->prog_conf); if (od->prog_name != NULL) free(od->prog_name); if (od->ld != NULL) ldap_unbind_ext_s(od->ld, NULL, NULL); bzero(od, sizeof(ovlc)); free(od); return; } int ovlc_parseopt(ovlc * od, int argc, char ** argv) { int rc; int c; int pos; int opt_index; char * endptr; const ovlc_code * code; struct stat sb; static char short_opt[] = "a:b:cd:F:f:H:hl:P:p:Q:qs:vVxZ"; static struct option long_opt[] = { { "help", no_argument, 0, 'h'}, { "version", no_argument, 0, 'V'}, { "version-terse", no_argument, 0, 'V'}, { NULL, 0, 0, 0 } }; assert(od != NULL); assert(argv != NULL); while((c = getopt_long(argc, argv, short_opt, long_opt, &opt_index)) != -1) { switch(c) { case -1: /* no more arguments */ case 0: /* long options toggles */ break; case 'a': if (!(strcasecmp(optarg, "never"))) od->ldap_deref = LDAP_DEREF_NEVER; else if (!(strcasecmp(optarg, "search"))) od->ldap_deref = LDAP_DEREF_SEARCHING; else if (!(strcasecmp(optarg, "find"))) od->ldap_deref = LDAP_DEREF_FINDING; else if (!(strcasecmp(optarg, "always"))) od->ldap_deref = LDAP_DEREF_ALWAYS; else { fprintf(stderr, "%s: invalid value for `-%c'\n", od->prog_name, c); fprintf(stderr, "Try `%s --help' for more information.\n", od->prog_name); return(1); }; break; case 'b': if ((od->ldap_basedn)) free(od->ldap_basedn); if ((od->ldap_basedn = strdup(optarg)) == NULL) { fprintf(stderr, "%s: strdup(): %s\n", od->prog_name, strerror(errno)); return(1); }; break; case 'c': od->continue_on_error = 1; break; case 'd': od->ldap_debug = (int) strtol(optarg, &endptr, 10); if (endptr == optarg) { fprintf(stderr, "%s: invalid value for `-%c'\n", od->prog_name, c); fprintf(stderr, "Try `%s --help' for more information.\n", od->prog_name); return(1); }; break; case 'F': for (pos = 0, code = NULL; ((syslog_facilities[pos].c_name != NULL) && (code != NULL)); pos++) if (!(strcasecmp(optarg, (syslog_facilities[pos].c_name)))) code = &syslog_facilities[pos]; if (!(code)) { fprintf(stderr, "%s: invalid value for `-%c'\n", od->prog_name, c); fprintf(stderr, "Try `%s --help' for more information.\n", od->prog_name); return(1); }; closelog(); openlog(PROGRAM_NAME, LOG_PID, code->c_value); break; case 'f': if ((rc = stat(optarg, &sb)) == -1) { fprintf(stderr, "%s: stat(%s): %s\n", od->prog_name, optarg, strerror(errno)); return(1); }; if ((od->prog_conf)) free(od->prog_conf); if ((od->prog_conf = strdup(optarg)) == NULL) { fprintf(stderr, "%s: strdup(): %s\n", od->prog_name, strerror(errno)); return(1); }; if ((rc = setenv("LDAPCONF", optarg, 1)) == -1) { fprintf(stderr, "%s: setenv(LDAPCONF): %s\n", od->prog_name, strerror(errno)); return(1); }; break; case 'H': if ((od->ldap_uri)) free(od->ldap_uri); if ((od->ldap_uri = strdup(optarg)) == NULL) { fprintf(stderr, "%s: strdup(): %s\n", od->prog_name, strerror(errno)); return(1); }; break; case 'h': ovlc_usage(od); return(-1); case 'l': od->ldap_limit = (int) strtol(optarg, &endptr, 10); if (endptr == optarg) { fprintf(stderr, "%s: invalid value for `-%c'\n", od->prog_name, c); fprintf(stderr, "Try `%s --help' for more information.\n", od->prog_name); return(1); }; break; case 'P': od->ldap_version = (int) strtol(optarg, &endptr, 10); if (endptr == optarg) { fprintf(stderr, "%s: invalid value for `-%c'\n", od->prog_name, c); fprintf(stderr, "Try `%s --help' for more information.\n", od->prog_name); return(1); }; break; case 'p': if ((od->ovpn_profile)) free(od->ovpn_profile); if ((od->ovpn_profile = strdup(optarg)) == NULL) { fprintf(stderr, "%s: strdup(): %s\n", od->prog_name, strerror(errno)); return(1); }; break; case 'Q': if ((rc = stat(optarg, &sb)) == -1) { fprintf(stderr, "%s: stat(%s): %s\n", od->prog_name, optarg, strerror(errno)); return(1); }; if ((od->ovpn_profiledir)) free(od->ovpn_profiledir); if ((od->ovpn_profiledir = strdup(optarg)) == NULL) { fprintf(stderr, "%s: strdup(): %s\n", od->prog_name, strerror(errno)); return(1); }; break; case 'q': break; case 's': if (!(strcasecmp(optarg, "base"))) od->ldap_scope = LDAP_SCOPE_BASE; else if (!(strcasecmp(optarg, "one"))) od->ldap_scope = LDAP_SCOPE_ONELEVEL; else if (!(strcasecmp(optarg, "sub"))) od->ldap_scope = LDAP_SCOPE_SUBTREE; else if (!(strcasecmp(optarg, "child"))) od->ldap_scope = LDAP_SCOPE_CHILDREN; else { fprintf(stderr, "%s: invalid value for `-%c'\n", od->prog_name, c); fprintf(stderr, "Try `%s --help' for more information.\n", od->prog_name); return(1); }; break; case 'V': ovlc_version(od); return(-1); case 'v': od->verbose++; break; case 'Z': od->ldap_tls_cert++; break; default: fprintf(stderr, "%s: unrecognized option `--%c'\n", od->prog_name, c); fprintf(stderr, "Try `%s --help' for more information.\n", od->prog_name); return(1); }; }; return(0); } int ovlc_initialize(ovlc ** odp, const char * arg1) { int i; const char * str; char * name; char * endptr; ovlc * od; assert(odp != NULL); // clear unwanted variables from environment for (i = 0; environ[i]; i++) { if ((name = strdup(environ[i])) == NULL) { fprintf(stderr, "%s: strdup(): %s\n", PROGRAM_NAME, strerror(errno)); return(1); }; if ((endptr = index(name, '=')) != NULL) endptr[0] = '\0'; if (!(strncmp(name, "LDAP", 4))) { unsetenv(name); i--; }; }; // allocate configuration memory if ((od = malloc(sizeof(ovlc))) == NULL) { ovlc_log(od, LOG_ERR, "malloc(): %s", strerror(errno)); return(-1); }; bzero(od, sizeof(ovlc)); // store program name if ((str = arg1) != NULL) if ((str = rindex(arg1, '/')) != NULL) str = (str[1] != '\0') ? &str[1] : PROGRAM_NAME; str = (str != NULL) ? str : PROGRAM_NAME; if ((od->prog_name = strdup(str)) == NULL) { ovlc_log(od, LOG_ERR, "strdup(): %s", strerror(errno)); ovlc_destroy(od); return(1); }; // OpenVPN environment variables str = ((str = getenv("untrusted_ip")) != NULL) ? str : ""; if ((od->ovpn_untrusted_ip = strdup(str)) == NULL) { ovlc_log(od, LOG_ERR, "strdup(): %s", strerror(errno)); ovlc_destroy(od); return(1); }; str = ((str = getenv("trusted_ip")) != NULL) ? str : ""; if ((od->ovpn_trusted_ip = strdup(str)) == NULL) { ovlc_log(od, LOG_ERR, "strdup(): %s", strerror(errno)); ovlc_destroy(od); return(1); }; str = ((str = getenv("pool_remote_ip")) != NULL) ? str : ""; if ((od->ovpn_pool_remote_ip = strdup(str)) == NULL) { ovlc_log(od, LOG_ERR, "strdup(): %s", strerror(errno)); ovlc_destroy(od); return(1); }; str = ((str = getenv("pool_remote_ip6")) != NULL) ? str : ""; if ((od->ovpn_pool_remote_ip6 = strdup(str)) == NULL) { ovlc_log(od, LOG_ERR, "strdup(): %s", strerror(errno)); ovlc_destroy(od); return(1); }; str = ((str = getenv("common_name")) != NULL) ? str : ""; if ((od->ovpn_common_name = strdup(str)) == NULL) { ovlc_log(od, LOG_ERR, "strdup(): %s", strerror(errno)); ovlc_destroy(od); return(1); }; // parse environment variable (script_type) str = ((str = getenv("script_type")) != NULL) ? str : ""; if (!(strcasecmp(str, "user-pass-verify"))) od->script_type = UserPassVerify; else if (!(strcasecmp(str, "client-connect"))) od->script_type = ClientConnect; else if (!(strcasecmp(str, "client-disconnect"))) od->script_type = ClientDisconnect; else od->script_type = Unknown; // parse environment variable (verb) str = ((str = getenv("verb")) != NULL) ? str : "3"; od->ovpn_verb = (int) strtol(str, &endptr, 10); if (endptr == str) od->ovpn_verb = 3; // initialize values od->ldap_deref = -1; od->ldap_debug = -1; od->ldap_limit = -1; od->ldap_scope = LDAP_SCOPE_DEFAULT; od->ldap_tls_cert = 0; od->ldap_version = -1; *odp = od; return(0); } void ovlc_usage(ovlc * od) { printf("Usage: %s [OPTIONS] pattern [file]\n", od->prog_name); printf( "Where:\n" " pattern LDAP search filter containing escape codes\n" " file user-pass-verify input or client-connect output\n" "Options:\n" " -a deref either never (default), always, search, or find\n" " -b basedn base dn for search\n" " -c return success if LDAP error occurs\n" " -d level set debug level\n" " -F facility syslog facility\n" " -f file LDAP/command configuration file\n" " -H URI LDAP Uniform Resource Identifier(s)\n" " -h, --help print this help and exit\n" " -l limit time limit for search\n" " -P version protocol version (default: 3)\n" " -p profile default account profile (default: none)\n" " -Q dir directory containing account profiles\n" " -q, --quiet, --silent do not print messages\n" " -s scope one of base, one, sub or children (search scope)\n" " -v, --verbose run in verbose mode (diagnostics to stderr)\n" " -V, --version print version number and exit\n" " -x Simple authentication\n" " -Z Start TLS request (-ZZ to require)\n" "Pattern Codes:\n" " %%%% expands to '%%' character\n" " %%c expands to common name from SSL certificate\n" " %%I expands to session's trusted IP address\n" " %%i expands to session's untrusted IP address\n" " %%R expands to session's remote pool IPv6 address\n" " %%r expands to session's remote pool IPv4 address\n" " %%U expands to username\n" " %%u expands to username, if available, or common name\n" "Exit Codes:\n" " 0 success\n" " 1 general error\n" " 2 bad username/password\n" " 3 bad user configuration\n" " 4 multiple LDAP entries found\n" "\n" ); return; } void ovlc_version(ovlc * od) { printf("%s (%s) %s\n", od->prog_name, PACKAGE_TARNAME, GIT_PACKAGE_VERSION_BUILD); printf("\n"); return; }; /* end of source */ <file_sep>/* * OpenVPN LDAP Command * Copyright (C) 2017 <NAME> <<EMAIL>>. * * @SYZDEK_BSD_LICENSE_START@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of <NAME> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @SYZDEK_BSD_LICENSE_END@ */ #define __LOG_C 1 #include "log.h" /////////////// // // // Headers // // // /////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Headers #endif #include <syslog.h> #include <stdio.h> #include <stdarg.h> ///////////////// // // // Variables // // // ///////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Variables #endif ////////////////// // // // Prototypes // // // ////////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Prototypes #endif ///////////////// // // // Functions // // // ///////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Functions #endif void ovlc_log(ovlc * od, int priority, const char *format, ...) { int verbose; va_list ap; FILE * stream; verbose = (od != NULL) ? od->verbose : 2; stream = NULL; if (verbose != 0) { if (priority <= LOG_WARNING) stream = stderr; else if (priority <= LOG_NOTICE) stream = stdout; else if (verbose > 1) stream = stdout; }; if ((stream)) { fprintf(stream, "%s: ", PROGRAM_NAME); va_start(ap, format); vfprintf(stream, format, ap); va_end(ap); fprintf(stream, "\n"); }; va_start(ap, format); vsyslog(priority, format, ap); va_end(ap); return; } /* end of source */ <file_sep>/* * OpenVPN LDAP Command * Copyright (C) 2017 <NAME> <<EMAIL>>. * * @SYZDEK_BSD_LICENSE_START@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of <NAME> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @SYZDEK_BSD_LICENSE_END@ */ #ifndef __COMMON_H #define __COMMON_H 1 /////////////// // // // Headers // // // /////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Headers #endif #ifdef HAVE_CONFIG_H # include "config.h" #else # include "git-package-version.h" #endif #ifdef __APPLE__ # include "TargetConditionals.h" # define USE_CUSTOM_PTHREAD_MUTEX_TIMEDLOCK 1 # define USE_IPV6 1 #endif #ifdef TARGET_OS_MAC #include <libkern/OSAtomic.h> #endif #include <inttypes.h> #include <ldap.h> #include <assert.h> /////////////////// // // // Definitions // // // /////////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Definitions #endif #ifndef PACKAGE_TARNAME #define PACKAGE_TARNAME "openvpn-ldapcmd" #endif #ifndef PROGRAM_NAME #define PROGRAM_NAME "openvpn-ldapcmd" #endif #ifndef PKGCONFDIR #define PKGCONFDIR "/etc/openvpn" #endif ///////////////// // // // Datatypes // // // ///////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Datatypes #endif struct openvpn_code { const char * c_name; int c_value; }; typedef struct openvpn_code ovlc_code; enum openvpn_type { Unknown = -1, Undefined = 0, UserPassVerify = 1, ClientConnect = 2, ClientDisconnect = 3, }; typedef enum openvpn_type ovlc_type; struct openvpn_ldapcmd { char * cmd_arg; char * ldap_basedn; char * ldap_binddn; char * ldap_filter; char * ldap_uri; char * ovpn_untrusted_ip; char * ovpn_trusted_ip; char * ovpn_pool_remote_ip; char * ovpn_pool_remote_ip6; char * ovpn_common_name; char * ovpn_username; char * ovpn_password; char * ovpn_profile; char * ovpn_profiledir; char * prog_conf; char * prog_name; int ldap_deref; int ldap_debug; int ldap_limit; int ldap_scope; int ldap_tls_cert; int ldap_version; int ovpn_verb; int verbose; int continue_on_error; ovlc_type script_type; LDAP * ld; BerValue * servercred; BerValue ldap_cred; }; typedef struct openvpn_ldapcmd ovlc; ////////////////// // // // Prototypes // // // ////////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Prototypes #endif void ovlc_destroy(ovlc * od); int ovlc_parseopt(ovlc * od, int argc, char ** argv); int ovlc_initialize(ovlc ** odp, const char * arg1); void ovlc_usage(ovlc * od); void ovlc_version(ovlc * od); #endif /* Header_h */ <file_sep>#!/bin/bash # # OpenVPN LDAP Command # Copyright (C) 2017 <NAME> <<EMAIL>>. # # @SYZDEK_BSD_LICENSE_START@ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of <NAME> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # @SYZDEK_BSD_LICENSE_END@ # unset OPENVPN_LDAPCMD_VAR_LIST OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} username" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} common_name" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} config" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} trusted_ip" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} untrusted_ip" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} ifconfig_pool_remote_ip" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} ifconfig_pool_remote_ip6" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} script_context" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} script_type" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} tmp_dir" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} openvpn_ldapcmd_tmp_template" OPENVPN_LDAPCMD_VAR_LIST="${OPENVPN_LDAPCMD_VAR_LIST} openvpn_ldapcmd_ldap_filter" unset OPENVPN_LDAPCMD_VAR_LIST_INTERNAL OPENVPN_LDAPCMD_VAR_LIST_INTERNAL="${OPENVPN_LDAPCMD_VAR_LIST_INTERNAL} openvpn_ldapcmd_tmp_file" OPENVPN_LDAPCMD_VAR_LIST_INTERNAL="${OPENVPN_LDAPCMD_VAR_LIST_INTERNAL} password" OPENVPN_LDAPCMD_VAR_LIST_INTERNAL="${OPENVPN_LDAPCMD_VAR_LIST_INTERNAL} OPENVPN_LDAPCMD_SETUP" unset OPENVPN_LDAPCMD_FUNC_LIST OPENVPN_LDAPCMD_FUNC_LIST="${OPENVPN_LDAPCMD_FUNC_LIST} openvpn_ldapcmd_cleanup" OPENVPN_LDAPCMD_FUNC_LIST="${OPENVPN_LDAPCMD_FUNC_LIST} openvpn_ldapcmd_client_connect" OPENVPN_LDAPCMD_FUNC_LIST="${OPENVPN_LDAPCMD_FUNC_LIST} openvpn_ldapcmd_client_disconnect" OPENVPN_LDAPCMD_FUNC_LIST="${OPENVPN_LDAPCMD_FUNC_LIST} openvpn_ldapcmd_gen_temp_file" OPENVPN_LDAPCMD_FUNC_LIST="${OPENVPN_LDAPCMD_FUNC_LIST} openvpn_ldapcmd_setup" OPENVPN_LDAPCMD_FUNC_LIST="${OPENVPN_LDAPCMD_FUNC_LIST} openvpn_ldapcmd_user_pass_verify" OPENVPN_LDAPCMD_FUNC_LIST="${OPENVPN_LDAPCMD_FUNC_LIST} openvpn_ldapcmd_version" openvpn_ldapcmd_cleanup() { test ! -z "${openvpn_ldapcmd_tmp_file}" \ && rm -f "${openvpn_ldapcmd_tmp_file}" unset password } openvpn_ldapcmd_client_connect() { # generate temp file openvpn_ldapcmd_gen_temp_file || return 1 openvpn-ldapcmd ${@} RC=$? echo "" echo "Dynamic Client Config:" sed -e 's/^/ /g' "${openvpn_ldapcmd_tmp_file}" echo "" echo "" echo "Result: $RC" echo "" return $RC } openvpn_ldapcmd_client_disconnect() { openvpn-ldapcmd ${@} RC=$? echo "" echo "Result: $RC" echo "" return $RC } openvpn_ldapcmd_gen_temp_file() { unset openvpn_ldapcmd_tmp_file openvpn_ldapcmd_tmp_file=$(mktemp "${openvpn_ldapcmd_tmp_template}") if test -z "${openvpn_ldapcmd_tmp_file}";then return 1 fi } openvpn_ldapcmd_setup() { unset openvpn_ldapcmd_tmp_file common_name=${common_name:-${USER}} username=${username:-${common_name}} export common_name username script_context=${script_context:-init} script_type=${script_type:-user-pass-verify} config=${config:-/etc/openvpn/openvpn.ovpn} export config script_context script_type trusted_ip=${trusted_ip:-172.16.31.10} untrusted_ip=${untrusted_ip:-172.16.31.10} export untrusted_ip trusted_ip ifconfig_pool_remote_ip=${ifconfig_pool_remote_ip:-10.0.48.194} ifconfig_pool_remote_ip6=${ifconfig_pool_remote_ip6:-fc00:e968:6179::de52:7100} export ifconfig_pool_remote_ip ifconfig_pool_remote_ip6 tmp_dir=${tmp_dir:-/dev/shm} openvpn_ldapcmd_tmp_template=${openvpn_ldapcmd_tmp_template:-${tmp_dir}/debug-openvpn-ldapcmd-XXXXXXXXXXXX} openvpn_ldapcmd_ldap_filter=${openvpn_ldapcmd_ldap_filter:-(&(uid=%u)(openvpnUserStatus=active))} CONTINUE=whoknows while test "x${CONTINUE}" != "xyes";do if test "x${CONTINUE}" == "xno";then echo " " echo "OpenVPN LDAP Command Environment:" for VAR in ${OPENVPN_LDAPCMD_VAR_LIST};do read -p " $VAR [${!VAR}]: " INPUT if test "${INPUT}" != "${INPUT// }";then INPUT="\"${INPUT}\"" fi eval "$VAR=${INPUT:-\"${!VAR}\"}" done fi echo "" echo "Environmental Variables:" for VAR in script_type script_context ${OPENVPN_LDAPCMD_VAR_LIST} SKIP_PROMPTS;do printf " %-30s %s\n" "${VAR}:" "${!VAR:-n/a}" done echo "" if test "x${SKIP_PROMPTS}" == "xyes";then INPUT=yes else read -p "Is the above correct (yes/no/abort)? " INPUT fi CONTINUE=$(echo $INPUT |tr A-Z a-z) if test "x${CONTINUE}" == "xabort";then exit 1 fi done OPENVPN_LDAPCMD_SETUP=yes export OPENVPN_LDAPCMD_SETUP } openvpn_ldapcmdunload() { openvpn_ldapcmd_cleanup VARS="" VARS="${VARS} ${OPENVPN_LDAPCMD_VAR_LIST}" VARS="${VARS} ${OPENVPN_LDAPCMD_VAR_LIST_INTERNAL}" VARS="${VARS} ${OPENVPN_LDAPCMD_FUNC_LIST}" VARS="${VARS} OPENVPN_LDAPCMD_VAR_LIST" VARS="${VARS} OPENVPN_LDAPCMD_VAR_LIST_INTERNAL" VARS="${VARS} OPENVPN_LDAPCMD_FUNC_LIST" for VAR in ${VARS};do eval "unset $VAR" done unset VAR unset VARS unset openvpn_ldapcmdunload unset openvpn_ldapcmd_unload } openvpn_ldapcmd_unload() { openvpn_ldapcmdunload } openvpn_ldapcmd_user_pass_verify() { # generate temp file openvpn_ldapcmd_gen_temp_file || return 1 # read user's password read -s -p "Enter ${username}'s password: " password echo '' # populate auth file echo "${username}" > "${openvpn_ldapcmd_tmp_file}" set |grep '^password=' |cut -d= -f2 |head -1 >> "${openvpn_ldapcmd_tmp_file}" unset password openvpn-ldapcmd ${@} RC=$? echo "" echo "Result: $RC" echo "" return $RC } openvpn_ldapcmd_version() { echo "openvpn-ldapcmd.profile (@PACKAGE_TARNAME@) @GIT_PACKAGE_VERSION_BUILD@ ..." } # end of bash profile<file_sep>#!/bin/bash # # OpenVPN LDAP Command # Copyright (C) 2017 <NAME> <<EMAIL>>. # # @SYZDEK_BSD_LICENSE_START@ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of <NAME> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # @SYZDEK_BSD_LICENSE_END@ # PROG_NAME=$(basename ${0}) export PROG_NAME # loads shared profile if test "x@builddir@" == "x$(pwd)";then PATH=@builddir@/src/:${PATH} export PATH . @builddir@/src/openvpn-ldapcmd.profile else . @pkgdatadir@/openvpn-ldapcmd.profile fi trap 'openvpn_ldapcmd_cleanup' QUIT trap 'openvpn_ldapcmd_cleanup' INT trap 'openvpn_ldapcmd_cleanup' HUP script_type="${1}" case "${script_type}" in user-pass-verify|client-connect|client-disconnect) ;; --help) echo "Usage: $PROG_NAME scripttype pattern [ OPTIONS ]" cat << " EOF" |sed -e 's/^ //g' SCRIPT TYPES: user-pass-verify client-connect client-disconnect PATTERN: See 'openvpn-ldapcmd --help' for PATTERN. OPTIONS: See 'openvpn-ldapcmd --help' for OPTIONS. EOF exit 0 ;; --version) openvpn_ldapcmd_version openvpn-ldapcmd --version exit 0 ;; *) echo "${PROG_NAME}: invalid or missing script type" 2>&1 echo "See '${PROG_NAME} --help' for more information." 2>&1 exit 1 ;; esac shift SKIP_PROMPTS=${SKIP_PROMPTS:-yes} openvpn_ldapcmd_setup case "${script_type}" in user-pass-verify) openvpn_ldapcmd_user_pass_verify ${@} RC=$? ;; client-connect) openvpn_ldapcmd_client_connect ${@} RC=$? ;; *) openvpn_ldapcmd_client_disconnect ${@} RC=$? ;; esac openvpn_ldapcmd_cleanup exit $RC # end of script <file_sep># # OpenVPN LDAP Command # Copyright (C) 2017 <NAME> <<EMAIL>>. # # @SYZDEK_BSD_LICENSE_START@ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of <NAME> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # @SYZDEK_BSD_LICENSE_END@ # # @configure_input@ # # Makefile.am - automate compiling on a unix platform # # Sub directories SUBDIRS = DIST_SUBDIRS = # directory locations pkgconfdir = $(sysconfdir)/$(package_tarname) doxygendir = $(docdir)/doxygen # Global flags AM_LIBS = AM_LDFLAGS = AM_CFLAGS = -O2 $(CFLAGS_WARNINGS) AM_CXXFLAGS = -O2 @AM_CXXFLAGS@ AM_OBJCFLAGS = -O2 @AM_OBJCFLAGS@ AM_CPPFLAGS = -O2 -UPMARK -DHAVE_CONFIG_H=1 \ -I$(top_builddir)/include \ -I$(top_srcdir)/include \ -DSYSCONFDIR="\"$(sysconfdir)\"" ACLOCAL_AMFLAGS = -I m4 -W all -W error AM_MAKEINFOFLAGS = --no-split DEFS = LDADD = $(lib_LTLIBRARIES) \ $(noinst_LTLIBRARIES) \ $(noinst_LIBRARIES) # automake targets check_PROGRAMS = doc_DATA = AUTHORS \ COPYING \ ChangeLog.md \ INSTALL \ NEWS.md \ README.md \ doc/openvpn-ldapcmd.ldif \ doc/openvpn-ldapcmd.schema doxygen_DATA = include_HEADERS = lib_LTLIBRARIES = libexec_SCRIPTS = man_MANS = info_TEXINFOS = noinst_DATA = noinst_LTLIBRARIES = noinst_LIBRARIES = noinst_HEADERS = noinst_PROGRAMS = bin_PROGRAMS = bin_SCRIPTS = pkgconf_DATA = pkgdata_DATA = src/openvpn-ldapcmd.profile sbin_PROGRAMS = src/openvpn-ldapcmd sbin_SCRIPTS = src/debug-openvpn-ldapcmd # lists AM_INSTALLCHECK_STD_OPTIONS_EXEMPT = BUILT_SOURCES = TESTS = XFAIL_TESTS = EXTRA_MANS = EXTRA_DIST = \ ChangeLog.md \ NEWS.md \ README.md \ doc/genldif.sh \ doc/openvpn-ldapcmd.schema \ src/Makefile \ src/openvpn-ldapcmd.profile.in \ src/debug-openvpn-ldapcmd.in CLEANFILES = \ $(builddir)/a.out $(srcdir)/a.out \ $(builddir)/*/a.out $(srcdir)/*/a.out \ config.h.in~ $(srcdir)/config.h.in~ \ $(man_MANS) \ $(pkgconf_DATA) \ $(pkgdata_DATA) \ $(bin_SCRIPTS) \ $(sbin_SCRIPTS) \ $(libexec_SCRIPTS) \ @PACKAGE_TARNAME@-*.tar.* \ @PACKAGE_TARNAME@-*.txz \ @PACKAGE_TARNAME@-*.zip \ doc/openvpn-ldapcmd.ldif \ src/openvpn-ldapcmd.profile DISTCHECK_CONFIGURE_FLAGS = --enable-strictwarnings \ --enable-ldapoptions # macros for doc/doxygen if ENABLE_DOXYGEN #noinst_DATA += doc/doxygen/html/index.html endif # macros for src/ldapoptions if ENABLE_LDAPOPTIONS noinst_PROGRAMS += src/ldapoptions endif src_ldapoptions_DEPENDENCIES = src_ldapoptions_SOURCES = \ $(include_HEADERS) \ $(noinst_HEADERS) \ src/ldapoptions.c # macros for src/openvpn-ldapcmd src_openvpn_ldapcmd_DEPENDENCIES = src_openvpn_ldapcmd_SOURCES = \ $(include_HEADERS) \ $(noinst_HEADERS) \ src/common.c \ src/common.h \ src/ldapfnc.c \ src/ldapfnc.h \ src/log.c \ src/log.h \ src/openvpn-ldapcmd.c # Makefile includes GIT_PACKAGE_VERSION_DIR=include SUBST_EXPRESSIONS = include $(srcdir)/@bindletools_srcdir@/build-aux/makefile-autotools.am include $(srcdir)/@bindletools_srcdir@/build-aux/makefile-subst.am include $(srcdir)/@bindletools_srcdir@/build-aux/makefile-version.am # custom targets .PHONY: doc/openvpn-ldapcmd.ldif: Makefile doc/genldif.sh doc/openvpn-ldapcmd.schema @mkdir -p doc $(top_srcdir)/doc/genldif.sh $(top_srcdir)/doc/openvpn-ldapcmd.schema $(@) openvpn-ldapcmd src/openvpn-ldapcmd.profile: Makefile src/openvpn-ldapcmd.profile.in @$(do_subst_dt) src/debug-openvpn-ldapcmd: Makefile src/debug-openvpn-ldapcmd.in @$(do_subst_fn) # local targets install-exec-local: install-data-local: install-data-hook: uninstall-local: clean-local: distclean-local: rm -fR $(srcdir)/autom4te.cache # end of automake file <file_sep> OpenVPN LDAP Command Copyright (C) 2017 <NAME> <<EMAIL>> 0.1 - starting project (syzdek) <file_sep>/* * OpenVPN LDAP Command * Copyright (C) 2017 <NAME> <<EMAIL>>. * * @SYZDEK_BSD_LICENSE_START@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of <NAME> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @SYZDEK_BSD_LICENSE_END@ */ #ifndef __LDAPFNC_H #define __LDAPFNC_H 1 /////////////// // // // Headers // // // /////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Headers #endif #include "common.h" /////////////////// // // // Definitions // // // /////////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Definitions #endif ///////////////// // // // Datatypes // // // ///////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Datatypes #endif ////////////////// // // // Prototypes // // // ////////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Prototypes #endif int ovlc_ldap_initialize(ovlc * od); int ovlc_ldap_opt_dump(ovlc * od); void ovlc_ldap_opt_dump_int(ovlc * od, int opt, const char * name); void ovlc_ldap_opt_dump_str(ovlc * od, int opt, const char * name); void ovlc_ldap_opt_dump_tim(ovlc * od, int opt, const char * name); int ovlc_ldap_search_user(ovlc * od); int ovlc_ldap_set_option_int(LDAP *ld, int option, const int invalue); int ovlc_ldap_set_option_str(LDAP *ld, int option, const char * invalue); int ovlc_ldap_set_option_time(LDAP *ld, int option, const struct timeval *invalue); #endif /* Header_h */ <file_sep># # OpenVPN LDAP Command # Copyright (C) 2017 <NAME> <<EMAIL>> # # @SYZDEK_BSD_LICENSE_START@ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of <NAME> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # @SYZDEK_BSD_LICENSE_END@ # # configure.in - automate compiling on a unix platform # AC_PREREQ([2.65]) AC_COPYRIGHT([Copyright (C) 2017 <NAME> <<EMAIL>>.]) AC_REVISION(0.1) AC_INIT([OpenVPN LDAP Command],[0.0],[<EMAIL>],[openvpn-ldapcmd]) AC_SUBST([RELEASE_MONTH],["August 2016"]) # directory locations AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_SRCDIR([build-aux/git-tar-name.txt]) #AC_CONFIG_LIBOBJ_DIR(compat) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_MACRO_DIR([m4]) # determines host type AC_CANONICAL_BUILD AC_CANONICAL_HOST AC_CANONICAL_TARGET # configures for automake AM_INIT_AUTOMAKE(gnu std-options subdir-objects) # Compilers AC_PROG_CC #AC_PROG_OBJC AC_PROG_CXX AM_PROG_CC_C_O AC_PROG_INSTALL AC_PROG_MAKE_SET AC_USE_SYSTEM_EXTENSIONS # replaces AC_AIX AC_GNU_SOURCE AC_MINIX AC_C_BIGENDIAN AC_C_INLINE AC_C_RESTRICT AC_C_VOLATILE AC_C_CONST # Version Info: # Current -- the current version number of this API # Revision -- the revision of the implementation of the API version # Age -- How many seqential past API versions is supported by # this implementation # Format => Current:Revision:Age # Convenience macro: # AC_BINDLE_LIBTOOL_VERSION_INFO(current, revision, age) AC_BINDLE_LIBTOOL_VERSION_INFO(0, 0, 0) # binary locations AC_PATH_PROG([SHELL], sh bash, [AC_MSG_ERROR([missing "sh"])], [$PATH]) AC_CHECK_TOOLS(AR, ar gar, [AC_MSG_ERROR([missing binutil "ar"])]) AC_CHECK_TOOLS(LD, ld gld, [AC_MSG_ERROR([missing binutil "ld"])]) AC_CHECK_TOOLS(NM, nm gnm, [AC_MSG_ERROR([missing binutil "nm"])]) AC_CHECK_TOOLS(RANLIB, ranlib granlib, [AC_MSG_ERROR([missing binutil "ranlib"])]) AC_CHECK_TOOLS(STRIP, strip gstrip, [AC_MSG_ERROR([missing binutil "strip"])]) # shell programs AC_PROG_AWK AC_PROG_EGREP AC_PROG_FGREP AM_PROG_LEX AC_PROG_LN_S # GNU Libtool Support LT_INIT(dlopen disable-fast-install win32-dll) # check for common functions AC_FUNC_CHOWN AC_FUNC_FORK AC_FUNC_MALLOC AC_FUNC_REALLOC AC_FUNC_STRERROR_R # Type checks AC_TYPE_INT8_T AC_TYPE_INT16_T AC_TYPE_INT32_T AC_TYPE_INT64_T AC_TYPE_SIZE_T AC_TYPE_SSIZE_T AC_TYPE_UID_T AC_TYPE_UINT8_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T # check for required functions AC_CHECK_FUNCS([bzero], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([getnameinfo], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([gettimeofday], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([memmove], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([memset], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([regcomp], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([setenv], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([socket], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([strchr], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([strdup], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([strerror], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([strncasecmp], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([strtol], [], [AC_MSG_ERROR([missing required functions])]) AC_CHECK_FUNCS([strtoumax], [], [AC_MSG_ERROR([missing required functions])]) # check for required libraries AC_SEARCH_LIBS([ldap_err2string], [ldap], [], [AC_MSG_ERROR([missing required library])]) AC_SEARCH_LIBS([ldap_get_option], [ldap], [], [AC_MSG_ERROR([missing required library])]) AC_SEARCH_LIBS([ldap_initialize], [ldap], [], [AC_MSG_ERROR([missing required library])]) AC_SEARCH_LIBS([ldap_memfree], [ldap], [], [AC_MSG_ERROR([missing required library])]) AC_SEARCH_LIBS([ldap_sasl_bind], [ldap], [], [AC_MSG_ERROR([missing required library])]) AC_SEARCH_LIBS([ldap_sasl_bind_s], [ldap], [], [AC_MSG_ERROR([missing required library])]) AC_SEARCH_LIBS([ldap_set_option], [ldap], [], [AC_MSG_ERROR([missing required library])]) # check for headers AC_CHECK_HEADERS([getopt.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([ldap.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([stddef.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([string.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([sys/socket.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([sys/time.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([sys/types.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([syslog.h], [], [AC_MSG_ERROR([missing required headers])]) AC_CHECK_HEADERS([unistd.h], [], [AC_MSG_ERROR([missing required headers])]) # check for struct members AC_CHECK_MEMBERS([struct stat.st_blksize], [], [AC_MSG_ERROR([struct missing required members])]) # initiates bindle tools macros AC_BINDLE(contrib/bindletools) # determine PACKAGE_VERSION via Git AC_BINDLE_GIT_PACKAGE_VERSION([contrib/bindletools/build-aux/git-package-version.sh]) # custom configure options AC_BINDLE_ENABLE_WARNINGS AC_BINDLE_WITH_DOXYGEN AC_OPENVPN_LDAPCMD_COMPONENTS # enables getopt_long if header and functions were found AC_CHECK_HEADERS([getopt.h], [AC_DEFINE_UNQUOTED(USE_GETOPT_LONG, 1, [Use GNU getopt_long])]) # Creates outputs AC_CONFIG_FILES([Makefile]) AC_OUTPUT # Show local config AC_MSG_NOTICE([ ]) AC_MSG_NOTICE([ OpenVPN LDAP Command $GIT_PACKAGE_VERSION ($GIT_PACKAGE_BUILD)]) AC_MSG_NOTICE([ ]) AC_MSG_NOTICE([ Features:]) AC_MSG_NOTICE([ Doxygen Docs: ${ENABLE_DOXYGEN}]) AC_MSG_NOTICE([ LDAP Options Utility: ${ENABLE_LDAPOPTIONS}]) AC_MSG_NOTICE([ ]) AC_MSG_NOTICE([ Options:]) AC_MSG_NOTICE([ ]) AC_MSG_NOTICE([ Please send suggestions to: $PACKAGE_BUGREPORT]) AC_MSG_NOTICE([ ]) AC_MSG_NOTICE([ run 'make all']) AC_MSG_NOTICE([ ]) # end of configure.ac <file_sep>/* * OpenVPN LDAP Command * Copyright (C) 2017 <NAME> <<EMAIL>>. * * @SYZDEK_BSD_LICENSE_START@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of <NAME> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @SYZDEK_BSD_LICENSE_END@ */ /* * Simple Build: * echo '#define GIT_PACKAGE_VERSION_BUILD "n/a"' > git-package-version.h * gcc -W -Wall -O2 -c common.c * gcc -W -Wall -O2 -c ldapfnc.c * gcc -W -Wall -O2 -c main.c * gcc -W -Wall -O2 -lldap -o openvpn-ldapcmd common.o ldapfnc.o main.o * * Simple Clean: * rm -f *.o openvpn-ldapcmd git-package-version.h * * GNU Libtool Build: * echo '#define GIT_PACKAGE_VERSION_BUILD "n/a"' > git-package-version.h * libtool --tag=CC --mode=compile gcc -W -Wall -g -O2 -c common.c * libtool --tag=CC --mode=compile gcc -W -Wall -g -O2 -c ldapfnc.c * libtool --tag=CC --mode=compile gcc -W -Wall -g -O2 -c main.c * libtool --tag=CC --mode=link gcc -W -Wall -g -O2 -lldap \ * -o openvpn-ldapcmd common.o ldapfnc.o main.o * * GNU Libtool Install: * libtool --mode=install install -c openvpn-ldapcmd \ * /usr/local/bin/openvpn-ldapcmd * * GNU Libtool Clean: * libtool --mode=clean rm -f common.lo * libtool --mode=clean rm -f ldapfnc.lo * libtool --mode=clean rm -f main.lo * libtool --mode=clean rm -f openvpn-ldapcmd * libtool --mode=clean rm -f git-package-version.h */ #define __MAIN_C 1 #undef __OVPNLDAPCMD_PMARK /////////////// // // // Headers // // // /////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Headers #endif #include "common.h" #include "ldapfnc.h" #include "log.h" #include <errno.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <stdlib.h> #include <getopt.h> #include <syslog.h> /////////////////// // // // Definitions // // // /////////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Definitions #endif ////////////////// // // // Prototypes // // // ////////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Prototypes #endif int main(int argc, char * argv[]); ///////////////// // // // Functions // // // ///////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Functions #endif int main(int argc, char * argv[]) { int rc; ovlc * od; // initialize syslog openlog(PROGRAM_NAME, LOG_PID, LOG_DAEMON); // initialize memory if ((rc = ovlc_initialize(&od, argv[0])) != 0) return(1); // parse CLI arguments if ((rc = ovlc_parseopt(od, argc, argv)) != 0) { ovlc_destroy(od); rc = (rc == -1) ? 0 : rc; return(rc); }; // initialize LDAP if ((rc = ovlc_ldap_initialize(od)) != 0) { ovlc_destroy(od); return(1); }; ovlc_ldap_opt_dump(od); // free resources ovlc_destroy(od); return(0); } /* end of source */<file_sep> OpenVPN LDAP Command Copyright (C) 2017 <NAME> <<EMAIL>> <file_sep>/* * OpenVPN LDAP Command * Copyright (C) 2017 <NAME> <<EMAIL>>. * * @SYZDEK_BSD_LICENSE_START@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of <NAME> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @SYZDEK_BSD_LICENSE_END@ */ #define __LDAPFNC_C 1 #include "ldapfnc.h" /////////////// // // // Headers // // // /////////////// #ifdef __OVPNLDAPCMD_PMARK #pragma mark - Headers #endif #include <syslog.h> #include <stdio.h> #include <inttypes.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "log.h" ///////////////// // // // Variables // // // ///////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Variables #endif extern char **environ; ////////////////// // // // Prototypes // // // ////////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Prototypes #endif ///////////////// // // // Functions // // // ///////////////// #ifdef __RACKGNOME_PMARK #pragma mark - Functions #endif int ovlc_ldap_initialize(ovlc * od) { int rc; char * diagmsg; BerValue cred; assert(od != NULL); if ((rc = ovlc_ldap_set_option_int(NULL, LDAP_OPT_DEBUG_LEVEL, od->ldap_debug)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_set_option(LDAP_OPT_DEBUG_LEVEL): %s", ldap_err2string(rc)); return(1); }; if ((rc = ldap_initialize(&od->ld, od->ldap_uri)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_initialize(): %s", ldap_err2string(rc)); return(1); }; if ((rc = ovlc_ldap_set_option_int(od->ld, LDAP_OPT_SIZELIMIT, 5)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_set_option(LDAP_OPT_SIZELIMIT): %s", ldap_err2string(rc)); return(1); }; if ((rc = ovlc_ldap_set_option_int(od->ld, LDAP_OPT_DEREF, od->ldap_deref)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_set_option(LDAP_OPT_DEREF): %s", ldap_err2string(rc)); return(1); }; if ((rc = ovlc_ldap_set_option_int(od->ld, LDAP_OPT_TIMELIMIT, od->ldap_limit)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_set_option(LDAP_OPT_TIMELIMIT): %s", ldap_err2string(rc)); return(1); }; if (od->ldap_tls_cert == 0) od->ldap_tls_cert = LDAP_OPT_X_TLS_NEVER; else if (od->ldap_tls_cert == 1) od->ldap_tls_cert = LDAP_OPT_X_TLS_TRY; else od->ldap_tls_cert = LDAP_OPT_X_TLS_HARD; if ((rc = ovlc_ldap_set_option_int(od->ld, LDAP_OPT_X_TLS_REQUIRE_CERT, od->ldap_tls_cert)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_set_option(LDAP_OPT_X_TLS_REQUIRE_CERT): %s", ldap_err2string(rc)); return(1); }; if ((rc = ovlc_ldap_set_option_int(od->ld, LDAP_OPT_PROTOCOL_VERSION, od->ldap_version)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_set_option(LDAP_OPT_PROTOCOL_VERSION): %s", ldap_err2string(rc)); return(1); }; bzero(&cred, sizeof(BerValue)); if ((rc = ldap_sasl_bind_s(od->ld, NULL, LDAP_SASL_SIMPLE, &cred, NULL, NULL, &od->servercred)) != LDAP_SUCCESS) { ovlc_log(od, LOG_ERR, "ldap_sasl_bind_s(): %s", ldap_err2string(rc)); if ((rc = ldap_get_option(od->ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, &diagmsg)) == LDAP_SUCCESS) if ((diagmsg)) ovlc_log(od, LOG_ERR, "ldap_sasl_bind_s(): %s", diagmsg); return(1); }; return(0); } int ovlc_ldap_opt_dump(ovlc * od) { int c; if ((od)) if (od->verbose < 2) return(0); ovlc_log(od, LOG_DEBUG, "LDAP environment variables:"); for(c = 0; environ[c]; c++) if (!(strncasecmp("ldap", environ[c], 4))) ovlc_log(od, LOG_DEBUG, " %s", environ[c]); ovlc_log(od, LOG_DEBUG, "options:"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_CONNECT_ASYNC, "LDAP_OPT_CONNECT_ASYNC"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_DEBUG_LEVEL, "LDAP_OPT_DEBUG_LEVEL"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_DEFBASE, "LDAP_OPT_DEFBASE"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_DEREF, "LDAP_OPT_DEREF"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_DESC, "LDAP_OPT_DESC"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_DIAGNOSTIC_MESSAGE, "LDAP_OPT_DIAGNOSTIC_MESSAGE"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_HOST_NAME, "LDAP_OPT_HOST_NAME"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_MATCHED_DN, "LDAP_OPT_MATCHED_DN"); ovlc_ldap_opt_dump_tim(od, LDAP_OPT_NETWORK_TIMEOUT, "LDAP_OPT_NETWORK_TIMEOUT"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_PROTOCOL_VERSION, "LDAP_OPT_PROTOCOL_VERSION"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_REFERRAL_URLS, "LDAP_OPT_REFERRAL_URLS"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_REFERRALS, "LDAP_OPT_REFERRALS"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_RESTART, "LDAP_OPT_RESTART"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_RESULT_CODE, "LDAP_OPT_RESULT_CODE"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_SESSION_REFCNT, "LDAP_OPT_SESSION_REFCNT"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_SIZELIMIT, "LDAP_OPT_SIZELIMIT"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_TIMELIMIT, "LDAP_OPT_TIMELIMIT"); ovlc_ldap_opt_dump_tim(od, LDAP_OPT_TIMEOUT, "LDAP_OPT_TIMEOUT"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_URI, "LDAP_OPT_URI"); ovlc_log(od, LOG_DEBUG, "SASL options:"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_SASL_AUTHCID, "LDAP_OPT_X_SASL_AUTHCID"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_SASL_AUTHZID, "LDAP_OPT_X_SASL_AUTHZID"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_SASL_MECH, "LDAP_OPT_X_SASL_MECH"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_SASL_NOCANON, "LDAP_OPT_X_SASL_NOCANON"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_SASL_REALM, "LDAP_OPT_X_SASL_REALM"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_SASL_USERNAME, "LDAP_OPT_X_SASL_USERNAME"); ovlc_log(od, LOG_DEBUG, "TCP options:"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_KEEPALIVE_IDLE, "LDAP_OPT_X_KEEPALIVE_IDLE"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_KEEPALIVE_PROBES, "LDAP_OPT_X_KEEPALIVE_PROBES"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_KEEPALIVE_INTERVAL, "LDAP_OPT_X_KEEPALIVE_INTERVAL"); ovlc_log(od, LOG_DEBUG, "TLS options:"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_CACERTDIR, "LDAP_OPT_X_TLS_CACERTDIR"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_CACERTFILE, "LDAP_OPT_X_TLS_CACERTFILE"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_CERTFILE, "LDAP_OPT_X_TLS_CERTFILE"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_CIPHER_SUITE, "LDAP_OPT_X_TLS_CIPHER_SUITE"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_TLS_CRLCHECK, "LDAP_OPT_X_TLS_CRLCHECK"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_CRLFILE, "LDAP_OPT_X_TLS_CRLFILE"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_DHFILE, "LDAP_OPT_X_TLS_DHFILE"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_KEYFILE, "LDAP_OPT_X_TLS_KEYFILE"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_TLS_NEWCTX, "LDAP_OPT_X_TLS_NEWCTX"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_TLS_PROTOCOL_MIN, "LDAP_OPT_X_TLS_PROTOCOL_MIN"); ovlc_ldap_opt_dump_str(od, LDAP_OPT_X_TLS_RANDOM_FILE, "LDAP_OPT_X_TLS_RANDOM_FILE"); ovlc_ldap_opt_dump_int(od, LDAP_OPT_X_TLS_REQUIRE_CERT, "LDAP_OPT_X_TLS_REQUIRE_CERT"); return(0); } void ovlc_ldap_opt_dump_int(ovlc * od, int opt, const char * name) { int val; val = -1; ldap_get_option((((od)) ? od->ld : NULL), opt, &val); ovlc_log(od, LOG_DEBUG, " %-35s %i", name, val); return; } void ovlc_ldap_opt_dump_str(ovlc * od, int opt, const char * name) { char * val; val = NULL; ldap_get_option((((od)) ? od->ld : NULL), opt, &val); if ((val)) { ovlc_log(od, LOG_DEBUG, " %-35s %s", name, val); ldap_memfree(val); } else { ovlc_log(od, LOG_DEBUG, " %-35s N/A", name); }; return; } void ovlc_ldap_opt_dump_tim(ovlc * od, int opt, const char * name) { struct timeval * val; val = NULL; ldap_get_option((((od)) ? od->ld : NULL), opt, &val); if ((val)) { ovlc_log(od, LOG_DEBUG, " %-35s %" PRIuMAX ".%06" PRIuMAX, name, (uintmax_t)val->tv_sec, (uintmax_t)val->tv_usec); ldap_memfree(val); } else { ovlc_log(od, LOG_DEBUG, " %-35s N/A", name); }; return; } int ovlc_ldap_set_option_int(LDAP *ld, int option, const int invalue) { if (invalue == -1) return(LDAP_SUCCESS); return(ldap_set_option(ld, option, &invalue)); } int ovlc_ldap_set_option_str(LDAP *ld, int option, const char * invalue) { if (invalue == NULL) return(LDAP_SUCCESS); return(ldap_set_option(ld, option, &invalue)); } int ovlc_ldap_set_option_time(LDAP *ld, int option, const struct timeval *invalue) { return(ldap_set_option(ld, option, invalue)); } /* end of source */
042ff813241f4d2ce70eae778f05ff46c920efe6
[ "Markdown", "Makefile", "C", "M4Sugar", "Shell" ]
15
C
syzdek/openvpn-ldapcmd
ced4ca773e1d9ecae4fe6b5470f4087c86543788
115a00051317e0e1bc8301edabb9b4a9adde775a
refs/heads/master
<repo_name>sebastian5555/Proyecto_programacion<file_sep>/prueba.py import Estudiante std1 = Estudiante.Student("n","a","Id","s") std1.setname() std1.setlastname() std1.setid() std1.setsemester() print (std1) materias_std1 = Estudiante.Materias_x_semestre(std1.getsemester()) materias_std1.materias_vistas() horario_std1 = Estudiante.Horario(materias_std1.get_materias_proximo_semestre()) horario_std1.numero_max_materias() horario_std1.comparacion_y_horario_de_materias() horario_std1.dias_del_hoario() horario_std1.esquema_del_horario()
13ceb58774f5b7d60f0fbd748fb43d1117c40138
[ "Python" ]
1
Python
sebastian5555/Proyecto_programacion
f61deffb1a228ba95c272e59241e7d6b0223ad87
bdf13a2c730aeb08a1d5070b72858fe027b0f6ea
refs/heads/main
<repo_name>MahjourMorad/xmlJava<file_sep>/src/filmapplication/FilmProjet.java package filmapplication; import static filmapplication.FilmProjet.xmlToTable; import java.awt.GridLayout; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Nouha */ public class FilmProjet extends javax.swing.JFrame { /** * Creates new form FilmProjet */ ArrayList<FilmClass> Film = new ArrayList<FilmClass>(); File F = new File(""); static DefaultTableModel model; String titre = ""; String genre = ""; String pays = ""; String annee = ""; String mes = ""; String resume = ""; public static String chaine =""; static String affiche(Document file){ try{ XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); sortie.output(file, System.out); chaine = sortie.outputString(file); } catch(java.io.IOException e){} return chaine; } // static String[][] xmlToTable(File file) { static void xmlToTable(File file) throws ParserConfigurationException { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); org.w3c.dom.Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("FILM"); NodeList nList2 = doc.getElementsByTagName("MES"); System.out.println(nList); for (int i=0;i<10;i++) { System.out.println("---------------------------------------------------------------"); } System.out.println("---------------------------------------------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); Node nNode2 = nList2.item(temp); // System.out.println("\nCurrent Element :" + nNode.getNodeName()); // System.out.println("\nCurrent Element :" + nNode.getChildNodes()); Node eElement = nNode; Node eElement2 = nNode2; /* * System.out.println("Annee : " + ((org.w3c.dom.Element) eElement).getAttribute("Annee")); System.out.println("TITRE : " + ((org.w3c.dom.Element) eElement).getElementsByTagName("TITRE").item(0).getTextContent()); System.out.println("GENRE : " + ((org.w3c.dom.Element) eElement).getElementsByTagName("GENRE").item(0).getTextContent()); System.out.println("PAYS: " + ((org.w3c.dom.Element) eElement).getElementsByTagName("PAYS").item(0).getTextContent()); System.out.println("MES: " + ((org.w3c.dom.Element) eElement2).getAttribute("idref")); */ jTable1.setValueAt(((org.w3c.dom.Element) eElement).getElementsByTagName("TITRE").item(0).getTextContent(), temp, 0); jTable1.setValueAt(((org.w3c.dom.Element) eElement).getElementsByTagName("GENRE").item(0).getTextContent(), temp, 1); jTable1.setValueAt(((org.w3c.dom.Element) eElement).getElementsByTagName("PAYS").item(0).getTextContent(), temp, 2); jTable1.setValueAt(((org.w3c.dom.Element) eElement).getAttribute("Annee"), temp, 3); jTable1.setValueAt(((org.w3c.dom.Element) eElement2).getAttribute("idref"), temp, 4); jTable1.setValueAt(((org.w3c.dom.Element) eElement).getElementsByTagName("RESUME").item(0).getTextContent(), temp, 5); System.out.println("---------------------------------------------------------------"); } } catch (Exception e) { e.printStackTrace(); } } Element root; public FilmProjet() { initComponents(); root = null; this.setTitle("Liste des films"); this.setSize(840, 490); this.setResizable(false); model = (DefaultTableModel) jTable1.getModel(); //jTextArea1.setText(""); this.setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel5 = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); tab1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); tab2 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); tab3 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); tab4 = new javax.swing.JPanel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jp1 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jp2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jp3 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton3 = new javax.swing.JButton(); jPanel7 = new javax.swing.JPanel(); jButton4 = new javax.swing.JButton(); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jButton2.setText("jButton2"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(54, 33, 89)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Arial Black", 2, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("AppFilm"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 30, -1, -1)); jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 72, 120, -1)); tab1.setBackground(new java.awt.Color(54, 33, 89)); tab1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tab1MouseClicked(evt); } }); tab1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Home"); tab1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 20, -1, -1)); jLabel7.setIcon(new javax.swing.ImageIcon("C:\\Users\\Nouha\\NetBeansProjects\\FilmApplication6\\FilmApplication\\icon\\icons8-home-32.png")); // NOI18N tab1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, 30)); jPanel1.add(tab1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 130, 230, 50)); tab2.setBackground(new java.awt.Color(54, 33, 89)); tab2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tab2MouseClicked(evt); } }); tab2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel3.setBackground(new java.awt.Color(255, 255, 255)); jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("ShowXml"); tab2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 20, -1, -1)); jLabel8.setIcon(new javax.swing.ImageIcon("C:\\Users\\Nouha\\NetBeansProjects\\FilmApplication6\\FilmApplication\\icon\\icons8-fichier-xml-24.png")); // NOI18N tab2.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 14, 30, 30)); jPanel1.add(tab2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 190, 230, 50)); tab3.setBackground(new java.awt.Color(54, 33, 89)); tab3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tab3MouseClicked(evt); } }); tab3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel4.setBackground(new java.awt.Color(54, 33, 89)); jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("ViewFilm"); tab3.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(44, 13, -1, -1)); jLabel9.setIcon(new javax.swing.ImageIcon("C:\\Users\\Nouha\\NetBeansProjects\\FilmApplication6\\FilmApplication\\icon\\icons8-table-24.png")); // NOI18N tab3.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 30, -1)); jPanel1.add(tab3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 260, 230, 50)); tab4.setBackground(new java.awt.Color(54, 33, 89)); tab4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tab4MouseClicked(evt); } }); tab4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel12.setBackground(new java.awt.Color(54, 33, 89)); jLabel12.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel12.setForeground(new java.awt.Color(255, 255, 255)); jLabel12.setText("Exit"); tab4.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(44, 13, -1, -1)); jLabel13.setIcon(new javax.swing.ImageIcon("C:\\Users\\Nouha\\NetBeansProjects\\FilmApplication6\\FilmApplication\\icon\\icons8-sortie-26.png")); // NOI18N tab4.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 30, -1)); jPanel1.add(tab4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 320, 230, 50)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(-1, 0, 230, 450)); jPanel2.setLayout(new javax.swing.OverlayLayout(jPanel2)); jp1.setBackground(new java.awt.Color(255, 255, 255)); jp1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 50)); // NOI18N jLabel5.setText("Welcome!"); jp1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 120, -1, -1)); jPanel6.setBackground(new java.awt.Color(122, 79, 221)); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 690, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 80, Short.MAX_VALUE) ); jp1.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 690, 80)); jLabel6.setIcon(new javax.swing.ImageIcon("C:\\Users\\Nouha\\NetBeansProjects\\FilmApplication6\\FilmApplication\\icon\\imagHome.png")); // NOI18N jp1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 180, 210, 190)); jPanel2.add(jp1); jp2.setBackground(new java.awt.Color(255, 255, 255)); jp2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jp2.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 110, 520, 280)); jButton1.setText("Show XML"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jp2.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 400, -1, -1)); jPanel3.setBackground(new java.awt.Color(122, 79, 221)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 590, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 80, Short.MAX_VALUE) ); jp2.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 590, 80)); jPanel2.add(jp2); jp3.setBackground(new java.awt.Color(255, 255, 255)); jp3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null} }, new String [] { "Titre", "Genre", "Pays", "Annee", "Mes", "Resume" } )); jScrollPane2.setViewportView(jTable1); jp3.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, 620, 230)); jButton3.setText("Ajouter"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jp3.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 380, -1, -1)); jPanel7.setBackground(new java.awt.Color(122, 79, 221)); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 620, Short.MAX_VALUE) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 80, Short.MAX_VALUE) ); jp3.add(jPanel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 620, 80)); jButton4.setText("Sauvegarder"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jp3.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 380, -1, -1)); jPanel2.add(jp3); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 0, 590, 450)); pack(); }// </editor-fold>//GEN-END:initComponents private void tab2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tab2MouseClicked // TODO add your handling code here: jp2.setVisible(true); jp1.setVisible(false); jp3.setVisible(false); }//GEN-LAST:event_tab2MouseClicked private void tab3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tab3MouseClicked // TODO add your handling code here: jp3.setVisible(true); jp1.setVisible(false); jp2.setVisible(false); }//GEN-LAST:event_tab3MouseClicked private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: AjouteFilm(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: JFileChooser chooser = new JFileChooser("."); int res = chooser.showOpenDialog(this); if(res != JFileChooser.APPROVE_OPTION) return; File f = chooser.getSelectedFile(); try { // String[][] donnes = xmlToTable(f); xmlToTable(f); } catch (ParserConfigurationException ex) { Logger.getLogger(FilmProjet.class.getName()).log(Level.SEVERE, null, ex); } String[] titres = new String []{ "Titre", "Genre", "Pays", "Année", "Mes", "Resume" }; // jTable1.setModel(new DefaultTableModel(donnes,titres)); SAXBuilder builder = new SAXBuilder(); Document document = null; try{ document = builder.build(f); //here affiche(document); jTextArea1.setText(chaine); }catch (JDOMException ex){ Logger.getLogger(FilmProjet.class.getName()).log(Level.SEVERE, null, ex); }catch (IOException ex){ Logger.getLogger(FilmProjet.class.getName()).log(Level.SEVERE, null, ex); } //Element root = document.getRootElement(); }//GEN-LAST:event_jButton1ActionPerformed private void tab1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tab1MouseClicked // TODO add your handling code here: jp1.setVisible(true); jp2.setVisible(false); jp3.setVisible(false); }//GEN-LAST:event_tab1MouseClicked private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: FilmApplication.save("Films2.xml"); }//GEN-LAST:event_jButton4ActionPerformed private void tab4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tab4MouseClicked // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_tab4MouseClicked private void AjouteFilm(){ String[] items= {"1","2","3"}; JTextField titre = new JTextField(""); JTextField genre = new JTextField(""); JTextField pays = new JTextField(""); JTextField annee = new JTextField(""); JComboBox mes = new JComboBox(items); JTextField resume = new JTextField(""); JPanel panel; panel = new JPanel(new GridLayout(0,1)); panel.add(new JLabel("Titre")); panel.add(titre); panel.add(new JLabel("Genre")); panel.add(genre); panel.add(new JLabel("Pays")); panel.add(pays); panel.add(new JLabel("Annee")); panel.add(annee); panel.add(new JLabel("Mes")); panel.add(mes); panel.add(new JLabel("Resume")); panel.add(resume); int result = JOptionPane.showConfirmDialog(null, panel, "Test", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { System.out.println("Ajouter Film" + " " + titre.getText() + " " + genre.getText() + " " + pays.getText() + " " + annee.getText() + " " + mes.getSelectedItem() + " " + resume.getText() ); String[] nvFilm = { titre.getText(), genre.getText(), pays.getText(), annee.getText(), //mes.getSelectedItem(), resume.getText(), }; DefaultTableModel model = (DefaultTableModel)jTable1.getModel(); model.addRow(nvFilm); } else { System.out.println("call"); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FilmProjet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FilmProjet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FilmProjet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FilmProjet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> SAXBuilder builder = new SAXBuilder(); Document xml= null ; try { xml = builder.build(new File("Film.xml")) ; //xml = builder.build(new File("Film2.xml")) ; }catch (IOException e) { } catch (JDOMException ex) { Logger.getLogger(FilmApplication.class.getName()).log(Level.SEVERE, null, ex); } org.jdom2.Element root= xml.getRootElement(); System.out.println("La racine"+root.getName()); // afficher le fichier fil.sml chaine = affiche(xml); /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FilmProjet().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private static javax.swing.JTable jTable1; private javax.swing.JTextArea jTextArea1; private javax.swing.JPanel jp1; private javax.swing.JPanel jp2; private javax.swing.JPanel jp3; private javax.swing.JPanel tab1; private javax.swing.JPanel tab2; private javax.swing.JPanel tab3; private javax.swing.JPanel tab4; // End of variables declaration//GEN-END:variables }
604f22dd1f5c4bf5f341e56cd48c874148352322
[ "Java" ]
1
Java
MahjourMorad/xmlJava
f4796536a3248d1b9a20ae7eec594276d2c318ae
2557e1e172d988a6d2b5aa9bac0fab358a080b34
refs/heads/master
<file_sep>package provider; import entity.Person; import java.util.Scanner; public class ProviderPerson { public Person createPerson() { Person person = new Person(); Scanner scanner = new Scanner (System.in); System.out.println("Имя читателя:"); String firstname = scanner.nextLine(); person.setFName(firstname); System.out.println("Фамилия читателя:"); String secondname = scanner.nextLine(); person.setSName(secondname); System.out.println("Статус:"); String status = scanner.nextLine(); person.setStatus(status); return person; } } <file_sep>package entity; import java.io.Serializable; import java.util.Date; public class Journal implements Serializable { private Date giveOutJournal; private Date returnJournal; private String ocenka; private Person person; private Subject subject; public Journal() { } public Journal(Date giveOutJournal, Date returnJournal, String ocenka, Person person, Person secondName, Subject subject) { this.giveOutJournal = giveOutJournal; this.returnJournal = returnJournal; this.ocenka = ocenka; this.person = person; this.subject = subject; } public Date getGiveOutJournal() { return giveOutJournal; } public void setGiveOutJournal(Date giveOutJournal) { this.giveOutJournal = giveOutJournal; } public Date getReturnJournal() { return returnJournal; } public void setReturnJournal(Date returnJournal) { this.returnJournal = returnJournal; } public String getOcenka() { return ocenka; } public void setOcenka(String ocenka) { this.ocenka = ocenka; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; } @Override public String toString() { return "Journal{" + "giveOutJournal=" + giveOutJournal + ", returnJournal=" + returnJournal + ", mark=" + ocenka + ", person=" + person.getFName() + " " + person.getSName() + ", subject=" + subject.getSchoolSubject() + '}'; } }<file_sep>package entity; import java.io.Serializable; public class Person implements Serializable { private String fname; private String sname; private String status; public String getFName() { return fname; } public void setFName(String fname) { this.fname = fname; } public String getSName() { return sname; } public void setSName(String sname) { this.sname = sname; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String toString() { return "Person{" +"Имя = " + fname + " Фамилия = " + sname + ", status = "+ status +"}"; } }
d3e6b307137cdb1db8ec5d104c57a39d2ae4266c
[ "Java" ]
3
Java
OlegHarlamov/Java
81b81470a5afe90e6e448b469741891a8d8f3c49
c96eee3d27c8cc7c27374a9c99ef6272bb980269
refs/heads/master
<file_sep>from asteroids import Asteroids # Create an object for managing the game game = Asteroids( "Asteroids", 640, 480 ) # Start the main game loop game.runGame() <file_sep>from circle import Circle class Star(Circle): def __init__(self, x, y, r, rotation ): super().__init__(x, y, r, rotation) <file_sep>from polygon import Polygon from point import Point import random class Spacerock3(Polygon): def __init__(self, x, y, rotation): Polygon.__init__(self, points=[Point(10,10), Point(30,-14), Point(60,0), Point(60,60), Point(60,60), Point(14,76), Point(10,60)], x=x, y=y, rotation=rotation) self.accelerate(0.5) self.rotate(random.randrange(180)) self.angular_velocity = (random.randrange(0,120)/100) <file_sep># Asteroid-Python-<file_sep>from polygon import Polygon from point import Point class Ship(Polygon): def __init__(self,name, width, height): super().__init__( points=[ Point(0,0), Point(-10,10), Point(15,0), Point(-10,-10) ] ) self.name = True self.alive = True self.health = 100 self.armor = 3 self.shot = 1 def __str__(self): if self.alive: return "%s (%i armor)" % (self.name) else: return "%s (Game Over)" % self.name def fire_at(self, spacerock): if self.shot >= 1: self.shot -= 1 print .self.name, "Target Hit!", spacerock.name spacerock.hit() else: print .self.name, "Target Miss!" def hit(self): self.armor -= 2 print .self.name, "Hit" if self.armor <= 0: print .self.armor, "Critical Hit" self.life -= 1 print .self.name if self.name <= 0: self.explode() def explode(self): self.alive = False print .self.name, "Ship Destroyed!" <file_sep>from polygon import Polygon from point import Point import random class Spacerock2(Polygon): def __init__(self, x, y, rotation): Polygon.__init__(self, points=[Point(0,0), Point(13,-7), Point(20,0), Point(30,17), Point(30,30), Point(7,38), Point(0,20)], x=x, y=y, rotation=rotation) self.accelerate(0.8) self.rotate(random.randrange(360)) self.angular_velocity = (random.randrange(0,190)/100) <file_sep>from polygon import Polygon from point import Point import random class Spacerock(Polygon): def __init__(self, x, y, rotation): Polygon.__init__(self, points=[Point(-10,-10), Point(7,-4), Point(15,-15), Point(15,8), Point(15,15), Point(7,9), Point(0,7)], x=x, y=y, rotation=rotation) self.accelerate(1.5) self.rotate(random.randrange(720)) self.angular_velocity = (random.randrange(0,300)/100) <file_sep>from polygon import Polygon from point import Point class Enemyship(Polygon): def __init__(self,name, width, height): super().__init__( points=[ Point(20,20), Point(-10,10), Point(30,15), Point(-20,-20) ] ) <file_sep>import sys import random import pygame from pygame.locals import * from game import Game from ship import Ship from bullet import Bullet from star import Star from spacerock import Spacerock from spacerock2 import Spacerock2 from spacerock3 import Spacerock3 #from enemyship import Enemyship class Asteroids( Game ): """ Asteroids extends the base class Game to provide logic for the specifics of the game """ def __init__(self, name, width, height): super().__init__( name, width, height ) self.ship = Ship( 320, 200, 0) # TODO: should create a Ship object here self.asteroids=[] # TODO: should create asteroids for i in range(8): self.asteroids.append(Spacerock(random.randrange(800), random.randrange(600),random.randrange(4,8))) for i in range(6): self.asteroids.append(Spacerock2(random.randrange(640), random.randrange(480),random.randrange(4,8))) for i in range(4): self.asteroids.append(Spacerock3(random.randrange(320), random.randrange(480),random.randrange(4,8))) self.stars=[] # TODO: should create stars for i in range(30): self.stars.append(Star(random.randrange(800), random.randrange(600),random.randrange(1,3), 0)) self.bullets =[] self.enemyship=[] # self.enemyship = Enemyship(640, 360, 0) def handle_input(self): super().handle_input() keys_pressed = pygame.key.get_pressed() if keys_pressed[K_LEFT] and self.ship: self.ship.rotate(-2) if keys_pressed[K_RIGHT] and self.ship: self.ship.rotate(2) if keys_pressed[K_UP] and self.ship: self.ship.accelerate(0.1) if keys_pressed[K_DOWN] and self.ship: self.ship.accelerate(0) if keys_pressed[K_SPACE] and self.ship: self.bullets.append(Bullet(self.ship.position.x,self.ship.position.y,self.ship.rotation)) # TODO: should create a bullet when the user fires def update_simulation(self): """ update_simulation() causes all objects in the game to update themselves """ super().update_simulation() if self.ship: self.ship.update( self.width, self.height ) for asteroid in self.asteroids: asteroid.update( self.width, self.height ) for star in self.stars: star.update( self.width, self.height ) for bullet in self.bullets: bullet.update_bullet(self.width, self.height) # TODO: should probably call update on our bullet/bullets here # TODO: should probably work out how to remove a bullet when it gets old self.handle_collisions() def render_objects(self): """ render_objects() causes all objects in the game to draw themselves onto the screen """ super().render_objects() # Render the ship: if self.ship: self.ship.draw( self.screen ) # Render all the stars, if any: for star in self.stars: star.draw( self.screen ) # Render all the asteroids, if any: for asteroid in self.asteroids: asteroid.draw( self.screen ) # Render all the bullet, if any: for bullet in self.bullets: bullet.draw( self.screen ) def handle_collisions(self): for bullet in self.bullets: for spacerock in self.asteroids: if spacerock.contains(bullet.position): print("Target Destroyed") self.asteroids.remove(spacerock) for spacerock in self.asteroids: if isinstance( spacerock, Spacerock ): if self.ship and self.ship.collide(spacerock): print("Ship Hit") self.ship.health = self.ship.health - 25 self.asteroids.remove(spacerock) if self.ship and self.ship.health <= 0: self.ship = None for spacerock2 in self.asteroids: if isinstance( spacerock2, Spacerock2 ): if self.ship and self.ship.collide(spacerock2): print("Ship Critical Hit") self.ship.health = self.ship.health - 50 self.asteroids.remove(spacerock2) if self.ship and self.ship.health <= 0: self.ship = None for spacerock3 in self.asteroids: if isinstance( spacerock3, Spacerock3 ): if self.ship and self.ship.collide(spacerock3): print("Ship Destroyed") self.ship.health = self.ship.health - 100 self.asteroids.remove(spacerock3) if self.ship and self.ship.health <= 0: self.ship = None """ handle_collisions() should check: - if our ship has crashed into an asteroid (the ship gets destroyed - game over!) - if a bullet has hit an asteroid (the asteroid gets destroyed) :return: """ # TODO: implement collission detection, # using the collission detection methods in all of the shapes pass <file_sep>from circle import Circle from polygon import Polygon class Bullet(Circle): def __init__(self, x, y, rotation): super().__init__(x, y, r=2,rotation=rotation) self.accelerate(5.0) def update_bullet(self, width, height): # Update the position and orientation of the shape # position is modified by "pull" - how much it should move each frame # rotation is modified by "angular_velocity" - how much it should rotate each frame self.position += self.pull self.rotation += self.angular_velocity
5d835374028a6015f73543999ae3143ab33251cb
[ "Markdown", "Python" ]
10
Python
Shogun616/Asteroid-Python-
74c8333d9e17295bb61e33c17837304d04e2a036
63943b4038e59d602344fcbe3c47e9aea1d21dd6
refs/heads/master
<file_sep># Tapper- A super cool tapping game! <file_sep>// // ViewController.swift // Tapper! // // Created by Dishank on 12/21/15. // Copyright © 2015 Dishank. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { //Variables var maxTaps = 0 var currentTaps = 0 var currentTaps2 = 0 var btnSound : AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() let path = NSBundle.mainBundle().pathForResource("btn", ofType: "wav") let soundUrl = NSURL(fileURLWithPath: path!) do{ try btnSound = AVAudioPlayer(contentsOfURL: soundUrl) //Use 'try' in a do loop when throw error is shown btnSound.prepareToPlay() } catch let err as NSError{ print(err.debugDescription) } } @IBOutlet weak var logoImg: UIImageView! @IBOutlet weak var howManyTapstxt: UITextField! @IBOutlet weak var playBtn: UIButton! @IBOutlet weak var tapBtn: UIButton! @IBOutlet weak var tapsToGo: UILabel! @IBOutlet weak var tapBtn2: UIButton! func updateTaplbl(){ if currentTaps2 >= currentTaps{ tapsToGo.text = "Player 2 wins!!" } else { tapsToGo.text = "Player 1 wins!!" } } @IBAction func dismissKeypad(sender: AnyObject) { self.resignFirstResponder() } @IBAction func onPlayBtnPressed(sender: UIButton){ playSound() if howManyTapstxt.text != nil && howManyTapstxt.text != "" { logoImg.hidden = true howManyTapstxt.hidden = true playBtn.hidden = true tapBtn.hidden = false tapBtn2.hidden = false tapsToGo.hidden = true maxTaps = Int(howManyTapstxt.text!)! currentTaps = 0 currentTaps2 = 0 //updateTaplbl() } } @IBAction func coinTap(sender: UIButton){ playSound() currentTaps++ //updateTaplbl() if currentTaps >= maxTaps{ restartGame() } } func restartGame(){ maxTaps = 0 howManyTapstxt.text = nil logoImg.hidden = false howManyTapstxt.hidden = false playBtn.hidden = false tapBtn.hidden = true tapBtn2.hidden = true tapsToGo.hidden = false updateTaplbl() } @IBAction func coinTap2(sender: UIButton) { playSound() currentTaps2++ if currentTaps2 >= maxTaps{ restartGame() } } func playSound(){ if btnSound.playing{ btnSound.stop() } btnSound.play() } }
c0ebecd7dee1ed826fc4efbf60f8b4e83ef6109d
[ "Markdown", "Swift" ]
2
Markdown
dishankng/Tapper
f2890f3f17ac43a459c1afb1009c83cbc337140e
35c30bbc832d87f138ed01c60732e8d18525824e
refs/heads/master
<file_sep>package br.com.testeandroid.feature; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import br.com.testeandroid.R; import br.com.testeandroid.adapter.InvestimentoAdapter; import br.com.testeandroid.model.DownInfo; import br.com.testeandroid.model.Info; import br.com.testeandroid.model.MoreInfo; import br.com.testeandroid.model.Screen; public class InvestimentoFragment extends Fragment implements InvestimentoView { TextView tvSubTitulo, tvInvestiment, tvNomePessoa, tvpergunta, tvResposta, tvGrauInvest, tvInfoInvestimento, tvMes, tvMesCdi, tvMesFundo, tvAno, tvAnoFundo, tvAnoCdi, tvDozeMes, tvDozeMesFundo, tvDozeMesCdi; RecyclerView recycleViewDadosArray; private InvestimentoPresenter presenter; private View view; public InvestimentoFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_investimento, container, false); presenter = new InvestimentoPresenterImpl(this); presenter.getInvestimentoArrayList(); inicializador(); iniciarRecycleView(); return view; } public void inicializador(){ tvSubTitulo = (TextView) view.findViewById(R.id.txtSubTitulo); tvInvestiment = (TextView) view.findViewById(R.id.txtInvestiment); tvNomePessoa = (TextView) view.findViewById(R.id.txtNomePessoa); tvpergunta = (TextView) view.findViewById(R.id.txtpergunta); tvResposta = (TextView) view.findViewById(R.id.txtResposta); tvGrauInvest = (TextView) view.findViewById(R.id.txtGrauInvest); tvInfoInvestimento = (TextView) view.findViewById(R.id.txtInfoInvestimento); tvMes = (TextView) view.findViewById(R.id.txtMes); tvMesCdi = (TextView) view.findViewById(R.id.txtMesCdi); tvMesFundo = (TextView) view.findViewById(R.id.txtMesFundo); tvAno = (TextView) view.findViewById(R.id.txtAno); tvAnoFundo = (TextView) view.findViewById(R.id.txtAnoFundo); tvAnoCdi = (TextView) view.findViewById(R.id.txtAnoCdi); tvDozeMes = (TextView) view.findViewById(R.id.txtDozeMes); tvDozeMesFundo = (TextView) view.findViewById(R.id.txtDozeMesFundo); tvDozeMesCdi = (TextView) view.findViewById(R.id.txtDozeMesCdi); tvDozeMes = (TextView) view.findViewById(R.id.txtDozeMes); tvDozeMes = (TextView) view.findViewById(R.id.txtDozeMes); } public void iniciarRecycleView(){ recycleViewDadosArray = (RecyclerView)view.findViewById(R.id.recycleViewDadosArray); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recycleViewDadosArray.setLayoutManager(layoutManager); } @Override public void setScreen(Screen screen) { Log.e("CHEGO", screen.getTitle()); tvSubTitulo.setText(screen.getTitle()); // Typeface font = Typeface.createFromAsset(getContext().getAssets(),"fonts/dipro_light.otf"); // tvSubTitulo.setTypeface(font); tvNomePessoa.setText(screen.getFundName()); tvpergunta.setText(screen.getWhatIs()); tvResposta.setText(screen.getDefinition()); tvGrauInvest.setText(screen.getRiskTitle()); tvInfoInvestimento.setText(screen.getInfoTitle()); setRiskInfo(screen.getRisk()); } @Override public void setInfoInvestimento(MoreInfo moreInfo) { tvMes.setText("No mês"); tvMesCdi.setText(String.valueOf(moreInfo.getMonth().getCdi())+"%"); tvMesFundo.setText(String.valueOf(moreInfo.getMonth().getFund())+"%"); tvAno.setText("No Ano"); tvAnoCdi.setText(String.valueOf(moreInfo.getYear().getCdi())+"%"); tvAnoFundo.setText(String.valueOf(moreInfo.getYear().getFund())+"%"); tvDozeMes.setText("12 meses"); tvDozeMesCdi.setText(String.valueOf(moreInfo.getMonths().getCdi())+"%"); tvDozeMesFundo.setText(String.valueOf(moreInfo.getMonths().getFund())+"%"); } @Override public void setRiskInfo(Integer risk) { View viewIndicator = null; ImageView imgIndicator = null; switch (risk) { case 1: viewIndicator = view.findViewById(R.id.viewUm); imgIndicator = view.findViewById(R.id.imgUm); break; case 2: viewIndicator = view.findViewById(R.id.viewDois); imgIndicator = view.findViewById(R.id.imgDois); break; case 3: viewIndicator = view.findViewById(R.id.viewTres); imgIndicator = view.findViewById(R.id.imgTres); break; case 4: viewIndicator = view.findViewById(R.id.viewQuatro); imgIndicator = view.findViewById(R.id.imgQuatro); break; case 5: viewIndicator = view.findViewById(R.id.viewCinco); imgIndicator = view.findViewById(R.id.imgCinco); break; } if (viewIndicator != null && imgIndicator != null) { viewIndicator.setLayoutParams(getLayoutParams(viewIndicator)); imgIndicator.setImageResource(R.drawable.ic_down); } } private LinearLayout.LayoutParams getLayoutParams(View colorIndicator) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) colorIndicator.getLayoutParams(); params.height = 40; return params; } @Override public void setRecycleViewAdapter(ArrayList<Info> infos, ArrayList<DownInfo> downInfos) { InvestimentoAdapter adapter = new InvestimentoAdapter(infos , downInfos); recycleViewDadosArray.setAdapter(adapter); } @Override public void showProgress() { view.findViewById(R.id.viewLoading).setVisibility(View.VISIBLE); } @Override public void finishProgress() { view.findViewById(R.id.viewLoading).setVisibility(View.GONE); } @Override public void ErroLoading() { view.findViewById(R.id.viewErroLoading).setVisibility(View.VISIBLE); } } <file_sep>package br.com.testeandroid.network; import br.com.testeandroid.model.CellsResponse; import br.com.testeandroid.model.Screen; import br.com.testeandroid.model.Tela; import retrofit2.Call; import retrofit2.http.GET; public interface NetworkUrl { @GET("fund.json") Call<Tela> getTelaInvestimento(); @GET("cells.json") Call<CellsResponse> getCells(); } <file_sep>package br.com.testeandroid.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import br.com.testeandroid.R; import br.com.testeandroid.model.DownInfo; import br.com.testeandroid.model.Info; public class InvestimentoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { final int VIEW_TYPE_INFO = 0; final int VIEW_TYPE_DOWNINFO = 1; private ArrayList<Info> infos; private ArrayList<DownInfo> downInfos; public InvestimentoAdapter(ArrayList<Info> infos , ArrayList<DownInfo> downInfos) { this.infos = infos; this.downInfos = downInfos; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){ if(viewType == VIEW_TYPE_INFO){ LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.itens_info_inventimento, parent, false); return new InvestimentoAdapter.InfoViewHolder(view); } if(viewType == VIEW_TYPE_DOWNINFO){ LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.itens_info_inventimento, parent, false); return new InvestimentoAdapter.DownInfoViewHolder(view); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, @SuppressLint("RecyclerView") final int position) { if(viewHolder instanceof InvestimentoAdapter.InfoViewHolder){ ((InvestimentoAdapter.InfoViewHolder) viewHolder).populate(infos.get(position)); } if(viewHolder instanceof InvestimentoAdapter.DownInfoViewHolder){ ((InvestimentoAdapter.DownInfoViewHolder) viewHolder).populate(downInfos.get(position - infos.size())); } } @Override public int getItemCount(){ return infos.size() + downInfos.size(); } @Override public int getItemViewType(int position){ if(position < infos.size()){ return VIEW_TYPE_INFO; } if(position - infos.size() < downInfos.size()){ return VIEW_TYPE_DOWNINFO; } return -1; } public class InfoViewHolder extends RecyclerView.ViewHolder { TextView tvTitulo, tvDescricao; public InfoViewHolder(View itemView){ super(itemView); tvTitulo = (TextView) itemView.findViewById(R.id.txtTituloItem); tvDescricao = (TextView) itemView.findViewById(R.id.txtDescricaoItem); } public void populate(Info info){ tvTitulo.setText(info.getName()); tvDescricao.setText(info.getData()); } } public class DownInfoViewHolder extends RecyclerView.ViewHolder { TextView tvTitulo, tvDescricao; ImageView imgDownload; public DownInfoViewHolder(View itemView){ super(itemView); tvTitulo = (TextView) itemView.findViewById(R.id.txtTituloItem); tvDescricao = (TextView) itemView.findViewById(R.id.txtDescricaoItem); imgDownload = (ImageView) itemView.findViewById(R.id.imgDownload); } public void populate(DownInfo downInfow){ tvTitulo.setText(downInfow.getName()); if (TextUtils.isEmpty(downInfow.getData())){ tvDescricao.setText("Baixar"); tvDescricao.setTextColor(Color.RED); imgDownload.setVisibility(View.VISIBLE); }else { tvDescricao.setText(downInfow.getData()); } } } }<file_sep>package br.com.testeandroid.utils.dinamico.elementos; import android.content.Context; import android.support.constraint.ConstraintLayout; import android.view.View; import android.widget.TextView; import br.com.testeandroid.model.Cells; import br.com.testeandroid.utils.dinamico.CellDinamico; public class TextViewDin extends BaseDin implements CellDinamico { public TextViewDin(Context context) { super(context); } @Override public View crearCell(Cells cell) { ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout .LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT); TextView view = new TextView(getContext()); view.setText(cell.getMessage()); view.setId(cell.getId()); view.setLayoutParams(params); return view; } } <file_sep>package br.com.testeandroid.utils.dinamico.elementos; import android.content.Context; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.view.View; import android.widget.Button; import br.com.testeandroid.R; import br.com.testeandroid.model.Cells; import br.com.testeandroid.utils.dinamico.CellDinamico; public class ButtonDin extends BaseDin implements CellDinamico { private View.OnClickListener listener; public ButtonDin(Context context, @Nullable View.OnClickListener l) { super(context); setListener(l); } @Override public View crearCell(Cells cell) { ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout .LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT); Button view = new Button(getContext()); view.setText(cell.getMessage()); view.setId(cell.getId()); view.setBackgroundResource(R.drawable.button_backgroud); view.setTextAppearance(getContext(), R.style.ButtonConfig); view.setAllCaps(false); view.setLayoutParams(params); view.setOnClickListener(listener); return view; } public void setListener(View.OnClickListener listener) { this.listener = listener; } public View.OnClickListener getListener() { return listener; } } <file_sep>package br.com.testeandroid.model; import com.google.gson.annotations.SerializedName; public class MoreInfo { @SerializedName("month") private Month month; @SerializedName("year") private Year Year; @SerializedName("12months") private Months months; public Month getMonth() { return month; } public void setMonth(Month month) { this.month = month; } public MoreInfo.Year getYear() { return Year; } public void setYear(MoreInfo.Year year) { Year = year; } public Months getMonths() { return months; } public void setMonths(Months months) { this.months = months; } public class Month{ @SerializedName("fund") public double fund; @SerializedName("CDI") public double cdi; public double getFund() { return fund; } public void setFund(double fund) { this.fund = fund; } public double getCdi() { return cdi; } public void setCdi(double cdi) { this.cdi = cdi; } } public class Year{ @SerializedName("fund") private double fund; @SerializedName("CDI") private double cdi; public double getFund() { return fund; } public void setFund(double fund) { this.fund = fund; } public double getCdi() { return cdi; } public void setCdi(double cdi) { this.cdi = cdi; } } public class Months{ @SerializedName("fund") private double fund; @SerializedName("CDI") private double cdi; public double getFund() { return fund; } public void setFund(double fund) { this.fund = fund; } public double getCdi() { return cdi; } public void setCdi(double cdi) { this.cdi = cdi; } } } <file_sep>package br.com.testeandroid.utils; import android.support.annotation.ColorInt; public class Constants { public final static int TYPE_FIELD = 1; public final static int TYPE_TEXT = 2; public final static int TYPE_CHECKBOX = 4; public final static int TYPE_SEND = 5; public final static String INPUT_TYPE_TEXT = "1"; public final static String INPUT_TYPE_TEL_NUMBER = "telnumber"; public final static String INPUT_TYPE_EMAIL = "3"; public final static String INVALID_FIELD = "Campo inválido"; @ColorInt public static final int BLACK = 0xFF000000; } <file_sep>package br.com.testeandroid.utils; import android.text.Editable; import android.text.TextWatcher; public class MaskFone implements TextWatcher { private int length = 0; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { length = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (length < s.length()) { if (s.length() == 1) { if (Character.isDigit(s.charAt(0))) { s.insert(0, "("); } } else if (s.length() == 3) { s.append(")"); } else if (s.length() == 8) { s.append("-"); } else if (s.length() > 13) { if (Character.isDigit(s.charAt(9))) { s.replace(8, 9, s.charAt(9) + ""); } s.replace(9, 10, "-"); } } } }<file_sep>package br.com.testeandroid.feature.contato; import java.util.ArrayList; import br.com.testeandroid.model.Cells; public interface ContatoView { void ConfigureCells(ArrayList<Cells> cells); void showProgress(); void finishProgress(); void showSucesso(); void finishSucesso(); void ErroLoading(); } <file_sep># Teste para desenvolvedor android Desenvolvido conforme as instruções. <file_sep>package br.com.testeandroid.feature.contato; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.v4.app.Fragment; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.EditText; import java.util.ArrayList; import java.util.List; import br.com.testeandroid.R; import br.com.testeandroid.feature.InvestimentoPresenter; import br.com.testeandroid.model.Cells; import br.com.testeandroid.utils.Constants; import br.com.testeandroid.utils.Validador; import br.com.testeandroid.utils.dinamico.CellDinamico; import br.com.testeandroid.utils.dinamico.CellGeradorDin; import br.com.testeandroid.utils.dinamico.DefinirConstraints; import br.com.testeandroid.utils.dinamico.elementos.ButtonDin; import br.com.testeandroid.utils.dinamico.elementos.CheckBoxDin; import br.com.testeandroid.utils.dinamico.elementos.EditTextDin; import br.com.testeandroid.utils.dinamico.elementos.TextViewDin; public class ContatoFragment extends Fragment implements ContatoView{ private ContatoPresenterImpl presenter; private View view; private ConstraintLayout constraintLayout; public ContatoFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_contato, container, false); presenter = new ContatoPresenterImpl(this); presenter.getCellArrayList(); clickFecharMsgSucesso(); return view; } private void clickFecharMsgSucesso() { view.findViewById(R.id.txtFechar) .setOnClickListener(new ClickFecharSucesso()); } private class ClickFecharSucesso implements View.OnClickListener { @Override public void onClick(final View view) { finishSucesso(); } } @Override public void ConfigureCells(ArrayList<Cells> cells) { for (Cells cell : cells) { int i = cells.indexOf(cell); int inicioID = cell.getId(); int fimID = getFormLayoutContainer().getId(); boolean isFirstElement = true; if (i > 0) { Cells cellanterior = cells.get(i - 1); fimID = cellanterior.getId(); isFirstElement = false; } addField(cell); DefinirConstraints.definirConstraints(getFormLayoutContainer(), cell, inicioID, fimID, isFirstElement); } } @Override public void showProgress() { view.findViewById(R.id.show).setVisibility(View.VISIBLE); view.findViewById(R.id.viewLoading).setVisibility(View.VISIBLE); } @Override public void finishProgress() { view.findViewById(R.id.show).setVisibility(View.GONE); view.findViewById(R.id.viewLoading).setVisibility(View.GONE); } @Override public void showSucesso() { view.findViewById(R.id.viewSucesso).setVisibility(View.VISIBLE); view.findViewById(R.id.show).setVisibility(View.VISIBLE); } @Override public void finishSucesso() { view.findViewById(R.id.viewSucesso).setVisibility(View.GONE); view.findViewById(R.id.show).setVisibility(View.GONE); } @Override public void ErroLoading() { view.findViewById(R.id.show).setVisibility(View.VISIBLE); view.findViewById(R.id.viewErroLoading).setVisibility(View.VISIBLE); } private ConstraintLayout getFormLayoutContainer() { if (constraintLayout == null) { constraintLayout = (ConstraintLayout) view.findViewById(R.id.formLayoutContainer); } return constraintLayout; } private void addField(Cells cell) { CellDinamico cellDinamico = null; switch (cell.getType()) { case Constants.TYPE_FIELD: cellDinamico = new EditTextDin(getContext()); break; case Constants.TYPE_TEXT: cellDinamico = new TextViewDin(getContext()); break; case Constants.TYPE_CHECKBOX: cellDinamico = new CheckBoxDin(getContext(), new ExibirEmail()); break; case Constants.TYPE_SEND: cellDinamico = new ButtonDin(getContext(), new OnClickButton()); break; } if (cellDinamico != null) { CellGeradorDin generator = new CellGeradorDin(cellDinamico); View view = generator.createCell(cell); getFormLayoutContainer().addView(view); } } private class ExibirEmail implements CompoundButton.OnCheckedChangeListener { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { setvisivilEdit(View.VISIBLE); } else { setvisivilEdit(View.GONE); } } } private void setvisivilEdit(int visibility) { int childCount = getFormLayoutContainer().getChildCount(); for (int i = 0; i < childCount; i++) { View view = getFormLayoutContainer().getChildAt(i); if (view instanceof EditText) { EditText editText = (EditText) view; if (editText.getInputType() == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) { editText.setVisibility(visibility); } } } } private class OnClickButton implements View.OnClickListener { @Override public void onClick(final View view) { if (Validador.validadeForm(getViews())) { showSucesso(); clear(); } } } public void clear() { List<EditText> textList = getViews(); for (EditText editText : textList) { editText.setText(""); } } private List<EditText> getViews() { int childCount = getFormLayoutContainer().getChildCount(); List<EditText> editTexts = new ArrayList<>(); for (int i = 0; i < childCount; i++) { View v = getFormLayoutContainer().getChildAt(i); if (v instanceof EditText) { editTexts.add((EditText) v); } } return editTexts; } }
7754844df393a6ca5ca47a6f614ffcca568c21c6
[ "Markdown", "Java" ]
11
Java
GuilhermeMFresca/TesteAndroid
f9298a6ce57c49d5c8be1d894e01ce4ff39fc679
581d5c8ce704f9ebe838a317af8793a4f4e38057
refs/heads/master
<file_sep>$(document).ready(function() { var player = []; var opponent = []; var population = []; var graveyard = []; var active = 0; var atk = 0; var cAtk = 0; var playerHp = 0; var opponentHp = 0; var multiplier = 0; var alive = true; var luke = { name: "<NAME>", pid: 1, ap: 7, cap: 5, hp: 100 }; var obi = { name: "<NAME>", pid: 2, ap: 6, cap: 10, hp: 100 }; var maul = { name: "<NAME>", pid: 3, ap: 5, cap: 13, hp: 100 }; var vader = { name: "<NAME>", pid: 4, ap: 4, cap: 18, hp: 100 }; population = [luke, obi, maul, vader]; var kills = population.length-1; // $(".img-thumbnail").on("click", function() { // if (active == 0) { // console.log(this.longdesc); // console.log(population[this.value]); // player.push(population[this.value]); // active = 1; // $(this).appendTo($("#player")); // console.log(player); // console.log(playerHp); // return; // } // if (active == 1) { // opponent.push(population[this.value]); // active = 2; // $(this).appendTo($("#opponent")); // return; // } // }); $(".number").on("click", function() { if (active == 0) { console.log(this.value); console.log(population[this.value]); player.push(population[this.value]); active = 1; $(this).appendTo($("#player")); playerHp = player[0].hp; atk = player[0].ap; multiplier = atk; var div = $("<div></div>"); div.text(playerHp); div.addClass("text-center"); div.attr("id", "plHp"); $("#player").append(div); return; } if (active == 1 && alive) { opponent.push(population[this.value]); active = 2; $(this).appendTo($("#opponent")); $(this).attr("id", "currentOp"); cAtk = opponent[0].cap; opponentHp = opponent[0].hp; var div = $("<div></div>"); div.text(opponentHp); div.addClass("text-center"); div.attr("id", "opHp"); $("#opponent").append(div); return; } }); $("#attack").on("click", function() { if (active == 2 && alive) { opponentHp -= atk; $("#cm1").text( player[0].name + " did " + atk + " dmg to " + opponent[0].name ); if (active == 2) { $("#cm2").text("You defeated your current enemy! pick another guy!"); } atk += multiplier; $("#opHp").text(opponentHp); if (opponentHp <= 0) { active = 1; $("#currentOp").remove(); $("#opHp").remove(); opponent = []; kills--; if (kills == 0) { active = 3; $("#cm2").text("You defeated everyone! You are the champion!"); setTimeout(_ => { location.reload(true); }, 4000); } return; } playerHp -= cAtk; $("#cm2").text( opponent[0].name + " did " + cAtk + " dmg to " + player[0].name ); $("#plHp").text(playerHp); if (playerHp <= 0) { $("#cm2").text( opponent[0].name + " did " + cAtk + " dmg to " + player[0].name + ", you died!" ); alive = false; setTimeout(_ => { document.write("GAME OVER"); }, 2000); setTimeout(_ => { location.reload(true); }, 3500); } } }); });
1916eafffdecc5fc0e19c1ad00ae1c88bc513419
[ "JavaScript" ]
1
JavaScript
fongl/sw-game
0f3c9b5156c15f60c1e8dad8c23928bcd2ca65d7
22216b109942c36975f32cddbc393ef8e897f58a
refs/heads/master
<file_sep> <!-- start banner Area --> <section class="banner-area relative" id="home"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row d-flex align-items-center justify-content-center"> <div class="about-content col-lg-12"> <h1 class="text-white"> User's Current Posted Job List </h1> <p class="text-white link-nav"><a href="index.php">Home </a> <span class="lnr lnr-arrow-right"></span> <a href="listjobuser.php"> User's Current Posted Job List</a></p> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start post Area --> <!-- First Job --> <section class="post-area section-gap"> <div class="container"> <?php foreach($_SESSION['user']->posted_jobs as $item){ echo " <div class='row justify-content-center d-flex'> <div class='col-lg-8 post-list'> <div class='single-post d-flex flex-row'> <div class='thumb'> <img src='img/creative_art_designer.png' alt='' width='80' height='80'> </div> <div class='details'> <div class='title d-flex flex-row justify-content-between'> <div class='titles'> <a href='#'><h4>$item->category</h4></a> </div> <ul class='btns'> <li><a href='#'><span class='lnr lnr-heart'></span></a></li> <li><a href='controller.php?action=finishjob&id-$item->id'>Finish Job</a></li> </ul> </div> <br> <br> <p> $item->description </p> <h5>Job Nature: Full time</h5> <!-- <p class='address'><span class='lnr lnr-map'></span> 56/8, Panthapath Dhanmondi Dhaka</p> --> <p class='address'><span class='lnr lnr-database'></span>$item->budget</p> </div> "; } ?> <file_sep>User Requirements: 1. User dapat melihat penawaran jasa apa saja yang tersedia di dalam platform yang telah dibuat 2. User hanya dapat menyewa jasa yang telah tersedia jika sudah merupakan member 3. User dapat melakukan sign up jika belum mempunyai akun platform 4. User dapat melakukan sign in jika sudah mempunyai akun platform 5. User hanya dapat memasang iklan jasa yang diperlukan di dalam platform 6. User tidak dapat mencari jasa dari user lain dan memulai proyek 7. Freelancer hanya dapat mencari job pemasangan iklan dari user 8. Freelancer tidak dapat memasang iklan jasa yang diperlukan di dalam platform 9. Setelah user memasang iklan jasa, freelancer dalam platform dapat mencari dan menyesuaikan jasa yang mereka tawarkan jika menemukan ada user yang sudah memasang iklan jasa yang diperlukan 10. User dapat berkomunikasi dengan freelancer yang berhubungan dengan jasa yang dicari, mendeskripsikan jasa yang diperlukan secara keseluruhan dan detil, penawaran harga dan tanggal yang diperlukan untuk diserahkan 11. Jika user dan freelancer sudah menyelesaikan proyek yang sedang berjalan maka user dapat melakukan transaksi dengan freelancer yang kemudian mengakhiri proyek. <file_sep> <!-- start banner Area --> <section class="banner-area relative" id="home"> <div class="overlay overlay-bg"></div> <div class="container"> <div class="row fullscreen d-flex align-items-center justify-content-center"> <div class="banner-content col-lg-12"> <h1 class="text-white"> <br><br><br> <span>1500+</span> Jobs posted last week </h1> <form action="search.php" class="serach-form-area"> <div class="row justify-content-center form-wrap"> <div class="col-lg-4 form-cols"> <input type="text" class="form-control" name="search" placeholder="what are you looging for?"> </div> <div class="col-lg-3 form-cols"> <div class="default-select" id="default-selects""> <select> <option value="1">Select area</option> <option value="2">Dhaka</option> <option value="3">Rajshahi</option> <option value="4">Barishal</option> <option value="5">Noakhali</option> </select> </div> </div> <div class="col-lg-3 form-cols"> <div class="default-select" id="default-selects2"> <select> <option value="1">All Category</option> <option value="2">Medical</option> <option value="3">Technology</option> <option value="4">Goverment</option> <option value="5">Development</option> </select> </div> </div> <div class="col-lg-2 form-cols"> <button type="button" class="btn btn-info"> <span class="lnr lnr-magnifier"></span> Search </button> </div> </div> </form> <p class="text-white"> <span>Search by tags:</span> Tecnology, Business, Consulting, IT Company, Design, Development</p> </div> </div> </div> </section> <!-- End banner Area --> <!-- Start feature-cat Area --> <section class="feature-cat-area pt-100" id="category"> <div class="container"> <div class="row d-flex justify-content-center"> <div class="menu-content pb-60 col-lg-10"> <div class="title text-center"> <h1 class="mb-10">Featured Job Categories</h1> <p>Who are in extremely love with eco friendly system.</p> </div> </div> </div> <div class="row"> <div class="col-lg-2 col-md-4 col-sm-6"> <div class="single-fcat"> <a href="controller.php?param=home&topic=graphic"> <img src="img/o1.png" alt=""> </a> <p>Graphic Designer</p> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6"> <div class="single-fcat"> <a href="controller.php?param=home&topic=director"> <img src="img/o3.png" alt=""> </a> <p>Creative/Art Director</p> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6"> <div class="single-fcat"> <a href="controller.php?param=home&topic=scriptwriter"> <img src="img/o4.png" alt=""> </a> <p>Scriptwriter</p> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6"> <div class="single-fcat"> <a href="controller.php?param=home&topic=screenwriter"> <img src="img/o5.png" alt=""> </a> <p>Screenwriter</p> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6"> <div class="single-fcat"> <a href="controller.php?param=home&topic=website"> <img src="img/o6.png" alt=""> </a> <p>Website Developer</p> </div> </div> <div class="col-lg-2 col-md-4 col-sm-6"> <div class="single-fcat"> <a href="controller.php?param=home&topic=software"> <img src="img/o6.png" alt=""> </a> <p>Software Developer</p> </div> </div> </div> </div> <br><br><br><br> </section> <!-- End feature-cat Area --> <section class="post-area section-gap"> <div class="container"> <div class="row justify-content-left d-flex"> <?php if(isset($_GET['topic'])){ if(isset($_SESSION['user'])) $jobs = $_SESSION['user']->getAllJobs(); if(isset($_SESSION['fl'])) $jobs = $_SESSION['fl']->getAllJobs(); $filter = array(); switch($_GET['topic']){ case "graphic" : foreach($jobs as $item){ if($item->category == "Graphic Designer") array_push($filter,$item); } break; case "director" : foreach($jobs as $item){ if($item->category == "Creative/Art Director") array_push($filter,$item); } break; case "scriptwriter" : foreach($jobs as $item){ if($item->category == "Scriptwriter") array_push($filter,$item); } break; case "screenwriter" : foreach($jobs as $item){ if($item->category == "Screenwriter") array_push($filter,$item); } break; case "website" : foreach($jobs as $item){ if($item->category == "Website Developer") array_push($filter,$item); } break; case "software" : foreach($jobs as $item){ if($item->category == "Software Developer") array_push($filter,$item); } break; } foreach($filter as $item){ echo " <div class='col-lg-12 post-list'> <div class='single-post d-flex flex-row'> <div class='thumb'> <img src='img/creative_art_designer.png' alt='' width='80' height='80'> </div> <div class='details'> <div class='title d-flex flex-row justify-content-between'> <div class='titles'> <a href='#'><h4>$item->category</h4></a> </div> <ul class='btns' style='text-align:left;'> <li><a href='#'><span class='lnr lnr-heart'></span></a></li> <li><a href='controller.php?param=home&action=takejob&job_id=$item->id'>Take Job</a></li> </ul> </div> <br> <br> <p> $item->description </p> <h5>Job By: $item->user_id</h5> <h5>Taken/Accepted By: $item->fl_id</h5> <!-- <p class='address'><span class='lnr lnr-map'></span> 56/8, Panthapath Dhanmondi Dhaka</p> --> <p class='address'><span class='lnr lnr-database'></span>$item->budget</p> </div> </div> "; } } ?> </div> </div> </section> <file_sep>Pemodelan Berbasis Objek Nama Projek : Fulcrum (Berbasis Web) Deskripsi program : Pencari designer (freelancer) Nama anggota : - <NAME> (03082170004) - <NAME> (03082170008)<file_sep><?php include("objects.php"); session_start(); if(!isset($_GET['param'])) $_GET['param'] = "login"; ?> <!DOCTYPE html> <html lang="zxx" class="no-js"> <head> <!-- Mobile Specific Meta --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Favicon--> <link rel="shortcut icon" href="img/fav.png"> <!-- Author Meta --> <meta name="author" content="codepixer"> <!-- Meta Description --> <meta name="description" content=""> <!-- Meta Keyword --> <meta name="keywords" content=""> <!-- meta character set --> <meta charset="UTF-8"> <!-- Site Title --> <title>FULCRUM - Log In</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Poppins:100,200,400,300,500,600,700" rel="stylesheet"> <!-- CSS ============================================= --> <link rel="stylesheet" href="css/linearicons.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/bootstrap.css"> <link rel="stylesheet" href="css/magnific-popup.css"> <link rel="stylesheet" href="css/nice-select.css"> <link rel="stylesheet" href="css/animate.min.css"> <link rel="stylesheet" href="css/owl.carousel.css"> <link rel="stylesheet" href="css/main.css"> </head> <body> <header id="header" id="home"> <div class="container"> <div class="row align-items-center justify-content-between d-flex"> <div id="logo"> <a href="index.php"><img src="img/Logo/Logo-02.png" width="270" height="45" alt="" title="" /></a> </div> <nav id="nav-menu-container"> <ul class="nav-menu"> <?php if(isset($_SESSION['user']) || isset($_SESSION['fl'])){ echo "<li class='menu-active'><a href='controller.php?param=home'>Home</a></li>"; echo " <li><a href='controller.php?param=listjob'>Jobs List</a></li>"; } if(isset($_SESSION['user'])){ echo " <li><a href='controller.php?param=postjob'>Post Job</a></li>"; } ?> <?php if($_GET['param'] == "login"){ ?> <li><a class="ticker-btn" href="controller.php?param=signup">Signup</a></li> <?php } else if($_GET['param'] == "signup") { ?> <li><a class="ticker-btn" href="controller.php?param=login">Login</a></li> <?php } else { if(isset($_SESSION['user'])){ echo "<li><a class='ticker-btn' href='controller.php?param=login'>Log Out : ".$_SESSION['user']->username."</a></li>"; } else if(isset($_SESSION['fl'])){ echo "<li><a class='ticker-btn' href='controller.php?param=login'>Log Out : ".$_SESSION['fl']->username."</a></li>"; } }?> </ul> </nav><!-- #nav-menu-container --> </div> </div> </header> <?php // echo "<script>alert(\"User\");</script>"; if($_GET['param'] == "login") { session_destroy(); session_start(); REQUIRE("login.html"); } else if($_GET['param'] == "signup") REQUIRE("signup.html"); else if($_GET['param'] == "home" && isset($_SESSION['fl'])) REQUIRE("index.php"); else if($_GET['param'] == "home" && isset($_SESSION['user'])) REQUIRE("index(user).php"); else if($_GET['param'] == "listjob" && isset($_SESSION['fl'])) REQUIRE("listjobfreelancer.php"); else if($_GET['param'] == "listjob" && isset($_SESSION['user'])) REQUIRE("listjobuser.php"); else if($_GET['param'] == "postjob") REQUIRE("postjob.php"); if(isset($_POST['login'])){ $user = new User(); $fl = new Freelancer(); if($user->fetchUser($_POST['username'],$_POST['password'])) { $_SESSION['user'] = $user; header('Location: controller.php?param=home'); } else if($fl->fetchFL($_POST['username'],$_POST['password'])){ echo"<script>alert(\"".$_POST['username'].$_POST['password']."\");</script>"; $_SESSION['fl'] = $fl; header('Location: controller.php?param=home'); } else { echo"<script>alert(\"Username or Password wrong ! Probably not registered yet !\");</script>"; } } if(isset($_POST['signup'])){ if($_POST['check'] == "User") { $user = new User($_POST['username'], $_POST['name'], $_POST['password'],$_POST['email'],$_POST['institution']); if($user->createUser()) { echo"<script>alert(\"User Created!\");</script>"; } else echo"<script>alert(\"Username taken !\");</script>"; } else if($_POST['check'] == "Freelancer") { $fl = new Freelancer($_POST['username'], $_POST['name'], $_POST['password'],$_POST['email'],$_POST['experience']); if($fl->createFL()) { echo"<script>alert(\"FreeLancer Created!\");</script>"; } else echo"<script>alert(\"Username taken !\");</script>"; } } if(isset($_POST['postjob'])){ //echo "<script>alert(\"Masok !\");</script>"; // echo "<script>alert(\"".$_POST['category'].$_POST['desc'].$_POST['budget'].$_SESSION['user']->username."\");</script>"; $newjob = new Job("",$_POST['category'],$_POST['desc'],$_POST['budget'],$_SESSION['user']->username,""); $user = $_SESSION['user']; if($user->createJob($newjob)){ echo "<script>alert(\"Job posted !\");</script>"; } } if(isset($_GET['action']) && isset($_GET['id'])){ if($_GET['action'] == "takejob") { $_SESSION['fl']->takeJob($_GET['id']); echo "<script>alert(\"Job taken!\");</script>"; } } ?> <script src="js/vendor/jquery-2.2.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="js/vendor/bootstrap.min.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBhOdIF3Y9382fqJYt5I_sswSrEw5eihAA"></script> <script src="js/easing.min.js"></script> <script src="js/hoverIntent.js"></script> <script src="js/superfish.min.js"></script> <script src="js/jquery.ajaxchimp.min.js"></script> <script src="js/jquery.magnific-popup.min.js"></script> <script src="js/owl.carousel.min.js"></script> <script src="js/jquery.sticky.js"></script> <script src="js/jquery.nice-select.min.js"></script> <script src="js/parallax.min.js"></script> <script src="js/mail-script.js"></script> <script src="js/main.js"></script> </body> </html> <file_sep><?php function conn(){ $server = "localhost"; $user = "root"; $password = ""; $dbname = "pbo_db"; $conn = mysqli_connect($server,$user,$password, $dbname); return $conn; } class User{ var $username; var $name; var $password; var $email; var $institution; var $posted_jobs = array(); function __construct($par1="",$par2="",$par3="",$par4="",$par5=""){ $this->username = $par1; $this->name = $par2; $this->password = $<PASSWORD>; $this->email = $par4; $this->institution = $par5; } function fetchUser($un, $pass){ $conn = conn(); $this->getAllPostedJobs(); $sql = "SELECT * FROM userr where username = '$un'"; if($result = mysqli_query($conn,$sql) ){ $row = $result->fetch_assoc(); if( $pass == $row['password']){ $this->username = $row['username']; $this->name = $row['name']; $this->password = $row['<PASSWORD>']; $this->email = $row['email']; $this->institution = $row['institution']; return true; } } return false; } function createUser(){ $conn = conn(); $sql = "SELECT * FROM userr where username = '$this->username'"; if(mysqli_query($conn,$sql)->num_rows > 0) return false; $sql = "INSERT INTO userr VALUES ('$this->username','$this->name', '$this->password','$this->email','$this->institution')"; if(mysqli_query($conn, $sql)) return true; } function editUser($edited){ $conn = conn(); $this->name = $edited->name; $this->password = $<PASSWORD>; $this->email = $edited->email; $this->institution = $edited->institution; $sql = "UPDATE userr SET name = '$this->name', password = '$<PASSWORD>', email = '$this->email', institution = '$this->institution' WHERE username='$this->username'"; if(mysqli_query($conn, $sql)) return true; return false; } function deleteUser(){ $conn = conn(); $sql = "DELETE FROM userr where username ='$this->username'"; if(mysqli_query($conn,$sql)) return true; return false; } function createJob(&$job){ $conn =conn(); $sql = "INSERT INTO job VALUES ('id','$job->category','$job->description','$job->budget','$job->user_id','')"; if(mysqli_query($conn, $sql)) { $this->getAllPostedJobs(); return true; } return false; } function deleteJob($id){ $conn = conn(); $sql = "DELETE FROM job where id ='$id'"; if(mysqli_query($conn,$sql)) { $this->getAllPostedJobs(); return true; } return false; } function getAllPostedJobs(){ $conn = conn(); $sql = "SELECT * FROM job where user_id = '$this->username'"; if($result = mysqli_query($conn,$sql)) { for($i = 0; $row = $result->fetch_assoc(); $i++){ $posted_jobs[$i] = new Job($row['id'], $row['category'],$row['desc'], $row['budget'], $row['user_id'],$row['fl_id']); } } } function getAllJobs(){ $conn = conn(); $arr=array(); $sql = "SELECT * FROM job"; if($result = mysqli_query($conn,$sql)) { for($i = 0; $row = $result->fetch_assoc(); $i++){ $arr[$i] = new Job($row['id'], $row['category'],$row['desc'], $row['budget'], $row['user_id'],$row['fl_id']); } } return $arr; } } class Job{ var $id; var $category; var $description; var $budget; var $user_id; var $fl_id; function __construct($par1,$par2,$par3,$par4,$par5,$par6){ $this->id = $par1; $this->category = $par2; $this->description = $par3; $this->budget = $par4; $this->user_id = $par5; $this->fl_id = $par6; } } class Freelancer{ var $username; var $name; var $password; var $email; var $experience; var $taken_jobs = array(); function __construct($par1="",$par2="",$par3="",$par4="",$par5=""){ $this->username = $par1; $this->name = $par2; $this->password = $<PASSWORD>; $this->email = $par4; $this->experience = $par5; } function fetchFL($un, $pass){ $conn = conn(); $this->getAllTakenJobs(); $sql = "SELECT * FROM freelancer where username = '$un'"; if($result = mysqli_query($conn,$sql) ){ $row = $result->fetch_assoc(); if( $pass == $row['password']){ $this->username = $row['username']; $this->name = $row['name']; $this->password = $row['<PASSWORD>']; $this->email = $row['email']; $this->experience = $row['experience']; return true; } } return false; } function createFL(){ $conn = conn(); $sql = "SELECT * FROM freelancer where username = '$this->username'"; if(mysqli_query($conn,$sql)->num_rows > 0) return false; $sql = "INSERT INTO freelancer VALUES ('$this->username','$this->name', '$this->password','$this->email','$this->experience')"; if(mysqli_query($conn, $sql)) return true; } function editFL($edited){ $conn = conn(); $this->name = $edited->name; $this->password = $edited->password; $this->email = $edited->email; $this->experience = $edited->experience; $sql = "UPDATE freelancer SET name = '$this->name', password = '$<PASSWORD>', email = '$this->email', experience = '$this->experience' WHERE username='$this->username'"; if(mysqli_query($conn, $sql)) return true; return false; } function deleteFL(){ $conn = conn(); $sql = "DELETE FROM freelancer where username ='$this->username'"; if(mysqli_query($conn,$sql)) return true; return false; } function takeJob($id){ $conn =conn(); $sql = "UPDATE job SET fl_id = '$this->username' where id = '$id'"; if(mysqli_query($conn, $sql)) { $this->getAllTakenJobs(); return true; } return false; } function releaseJob($id){ $conn = conn(); $sql = "UPDATE job SET fl_id = '' where id = '$id'"; if(mysqli_query($conn,$sql)) { $this->getAllTakenJobs(); return true; } return false; } private function getAllTakenJobs(){ $conn = conn(); $sql = "SELECT * FROM job where fl_id = '$this->username'"; if($result = mysqli_query($conn,$sql)) { for($i = 0; $row = $result->fetch_assoc(); $i++){ $taken_jobs[$i] = new Job($row['id'], $row['category'],$row['desc'], $row['budget'], $row['user_id'],$row['fl_id']); } } } function getAllJobs(){ $conn = conn(); $arr=array(); $sql = "SELECT * FROM job"; if($result = mysqli_query($conn,$sql)) { for($i = 0; $row = $result->fetch_assoc(); $i++){ $arr[$i] = new Job($row['id'], $row['category'],$row['desc'], $row['budget'], $row['user_id'],$row['fl_id']); } } return $arr; } } ?>
ad6f07932379241346fe4e76cb6b3b1c54d2011e
[ "Markdown", "Text", "PHP" ]
6
PHP
WeYaTa/Pemodelan-Berbasis-Objek
cacb9ca1041b4a480a396121ab8968f81f164c44
d065143813b6a8d9bdaa757bd7057d05564b3de4
refs/heads/master
<repo_name>TopFuel/popcorn-site<file_sep>/README.md Popcorn Time Website ====================== ### The site is [get-popcorn.com](http://get-popcorn.com) <file_sep>/inc/lang/pt-br.php <?php $langsite = Array( // Site description in the title bar "TITLE_INDEX" => "Veja filmes por torrent instantaneamente", "TITLE_FAQ" => "Perguntas Frequentes", "TITLE_TOS" => "Termos de Serviço", "TITLE_DL" => "Download", "SITE_DESC" => "Pule os downloads! Veja os melhores filmes instantaneamente em HD, com legendas, de graça! Disponível para Windows, Mac e Linux.", "HEADER" => "Veja filmes por torrent instantaneamente", "SUBHEADER" => "Atualmente em beta, mas vá em frente e experimente!", // %s replaced with version number "BTN_DOWNLOAD" => "Baixar Beta %s", "DL_DESC_WIN" => "Para Windows 7 e acima", "DL_DESC_MAC" => "Para Mac OSX 10.6 e acima", "DL_DESC_LIN32" => "Para usuários 32-bit Linux", "DL_DESC_LIN64" => "Para usuários 64-bit Linux", "DL_THANKYOU" => "Obrigado por usar o Popcorn Time", "DL_STARTING_1" => "Seu download está para começar.", "DL_STARTING_2" => "Clique aqui", "DL_STARTING_3" => "se o download não começou.", "MAIL_SUBSCRIBE" => "Inscreva-se em nossa lista de correspondência oficial", "MAIL_EMAIL" => "Endereço de e-mail", "MAIL_SUBSCRIBE_BTN" => "Inscreva-se", "DISCLAIMER_TITLE" => "Popcorn Time transmite filmes a partir Torrents", "DISCLAIMER_DESC" => "Baixar material protegido por direitos autorais pode ser ilegal em seu pais. Use por sua conta e risco.", "FEAT_MOVIES" => "Excelentes filmes", "FEAT_MOVIES_DESC" => "Nos estamos constantemente procurando por toda a internet pelos melhores torrents dos mais importantes sites.", "FEAT_NORESTRICTION" => "Sem restrições", "FEAT_NORESTRICTION_DESC"=> "Veja qualquer filme quantas vezes você quiser. Tudo que precisa para começar é uma conexão com a internet adequada.", "FEAT_CATALOGUE" => "Catálogo incrível", "FEAT_CATALOGUE_DESC" => "Se o filme esta por ai, Popcorn Time vai encontrar a melhor versão possível e iniciar a transmissão imediatamente.", "FEAT_QUALITY" => "A melhor qualidade", "FEAT_QUALITY_DESC" => "Veja seu filme instantaneamente em HD e com legendas. E depois continue assistindo.", "FEAT_BEST" => "O melhor de tudo... é grátis!", "HOW_TITLE" => "Difícil de acreditar?", "HOW_DESC" => "Veja como funciona...", "HOW_1" => "Abra o PT & Selecione um filme", "HOW_2" => "Selecione HD & Legendas", "HOW_3" => "Clique em iniciar & divirta-se!", "GET_TITLE" => "Um jeito totalmente novo de assistir filmes", "GET_DESC" => "Apenas cuide do popcorn & deixe o resto por nossa conta.", "FOOTER" => "Feito com <span>&lt;3</span> por um bando de geeks de Todo o Mundo" ); $langfaq = Array( "WARNING_1" => "To enjoy a great experience, always make sure you're running", "WARNING_2" => "the latest Popcorn Time version.", "WARNING_3" => "Our only official site is", "WARNING_4" => "(for now). Do not get the app from anywhere else, as there's a few fake sites going around.", "TITLE" => "Frequently Asked Questions", "DESC_1" => "Popcorn Time! is the result of many developers and designers putting a bunch of APIs together to make the experience of watching torrent movies as simple as possible.", "DESC_2" => "We are an open source project. We are from all over the world. We love our movies. And boy, do we love popcorn.", "LEGAL_Q" => "Is this legal?", "LEGAL_A" => "Depends on where you're from, really. Once again: we're using torrents, so if you really care, you'd better google what the legal situation around these protocol is where you live.", "SEED_Q" => "Popcorn Time works using torrents, fair enough. Am I seeding while watching a movie?", "SEED_A" => "Indeed, you are. You're going to be uploading bits and bits of the movie for as long as you're watching it on Popcorn Time.", "STORAGE_Q" => "What happens to the movies after I'm done?", "STORAGE_A" => "Your movies will stay buried in a secret folder somewhere in your drive until you restart your computer. Then it will be gone for good.", "UPDATE_Q" => "Will there be a new version?", "UPDATE_A" => "Most definitely. You're going to have to download it manually though. But fear not! If you're on version Beta 2, you'll be notified within the app. Other than that, we'll let you know through Twitter.", "MOVIES_Q" => "How come you've got the latest movies?", "MOVIES_A" => "We search for movies uploaded by YIFY. Better ask them how they are handling this!", "LANG_Q" => "Will you be adding movies in my language?", "LANG_A" => "Chances are that most (if not all) of the movies available in Popcorn Time will be in English. However, languages for subtitles and the app itself are constantly being added by our lovely contributors.", "LAUNCH_Q" => "Why can't I launch Popcorn Time?", "LAUNCH_Q1" => "Your system may prevent unsigned apps from being run", "LAUNCH_A1" => "Go to <span class=\"code\">System Preferences > Security > Allow Apps downloaded from > Anywhere</span> and try to launch Popcorn Time! again.", "LAUNCH_Q2" => "You may have not have enough User Priviliges", "LAUNCH_A2" => "Open a Terminal, and type:", "STUCK_Q" => "I can't get past the initial \"Please wait...\" screen", "STUCK_A" => "It is possible that your internet provider block the API used by this app. <a href=\"http://en.wikipedia.org/wiki/Websites_blocked_in_the_United_Kingdom\">Like this Black list in UK</a>.", "SUBS_Q" => "Why can't I select subtitles?", "SUBS_A" => "You may have to wait until all of the movie data (cover, summary, length, etc...) is retrieved. Sometimes it may be something else!", "BUILDS_Q" => "Thinking about launching for Android/iOS/Chromecast/Smart TVs/Commodore 64?", "BUILDS_A" => "Our efforts are currently towards making the best desktop app for watching torrent movies. So launching versions for other devices is not in our inmediate roadmap.", "DEVICES_Q" => "Is the app works on Raspberry Pi/ChomeBook/BeagleBone?", "DEVICES_A" => "Currently the App compiled only for Win/Linux32/Linux64/Mac but if you want to try it on ARM go for it!", "SITE_Q" => "You are changing site/repo more often than some underwear, which is the best place to start with?", "SITE_A" => "Well yes, the App had difficult times, the best place for the latest info yet is the IRC channel." ); ?>
df59d9646637400966ecd3eed024de2e2ec9e520
[ "Markdown", "PHP" ]
2
Markdown
TopFuel/popcorn-site
d9f2cbd13928a3b17153bef4baa2cefafe7219e2
9872c086f55477af5ebca57fc2185e7c78498fb7
refs/heads/master
<file_sep>-- cleanup drop table Agenda drop table Conference drop table Venue -- not necessary --drop database test1<file_sep>use test1 select * from Venue select * from Conference select * from Agenda<file_sep>------------------------------------------------ /* * Uzywanie danych z bazy ExampleData: * Tworzymy sobie zapytanie * select 'insert into tabela ([kolumna1], [kolumna2], ...) values (''' + wartosc_typu_varchar +''', '+ wartosc_int +', ...); from GeneralData ' * wybierajac w nim dane jakie nam sa potrzebne * to tworzy nam polecenia które wystarczy przekopiować do edytora i wykonać (F5) * trzeba tylko pamiętać aby zaznaczyć "Results to text" na pasku * przyklad */ use ExampleData select 'insert into tabela ([id], [City], [ZipCode], [Street], [Phone]) values (' + cast(id as varchar(10)) +', '''+ City+''', '''+ ZipCode+''', '''+ Street+''', '''+ Phone+''');' from GeneralData ------------------------------------------------ use test1 -- venue insert into Venue (Name, City, ZipCode, Street, Phone) values('Budynek1', 'NYC', '43-300', 'Wall', '509111111'); insert into Venue (Name, City, ZipCode, Street, Phone) values('Budynek 2', 'Bielsko-Biala', '38-364', 'Warszawska', '+48509144555'); -- conference insert into Conference (Name, VenueID, [Date]) values ('Moja konferencja', 1, GETDATE())
c07a922d119497b947b5050d3404ca17c83a9d33
[ "SQL" ]
3
SQL
slonka/projekt1_db
84ee8f2650d6423bb361838f6b4ce2058112b560
75ef60d1d3bc74ace3925d15f1d84e03974a2750
refs/heads/master
<file_sep>class CowsController < ApplicationController #before_action :set_cow, only: [:show, :edit, :update, :destroy] # GET /cows # GET /cows.json def index @cows = HTTParty.get("http://172.16.58.3:8080/measurements/?id=1") #@cows = [{"cow_id"=>"2", "timestamp"=>"2015-02-21T17:46:59.000Z", "ph"=>0.1, "imp"=>0.2, "nir"=>0.2, "dfd_0"=>0, "score"=>0.5}, {"cow_id"=>"2", "timestamp"=>"2015-03-01T10:41:32.000Z", "ph"=>0.1, "imp"=>0.2, "nir"=>0.2, "dfd_0"=>0, "score"=>0.5}, {"cow_id"=>"2", "timestamp"=>"2015-03-17T19:47:59.000Z", "ph"=>0, "imp"=>0.2, "nir"=>0.2, "dfd_0"=>1, "score"=>0.4}, {"cow_id"=>"2", "timestamp"=>"2015-02-23T08:06:55.000Z", "ph"=>0.25, "imp"=>0.2, "nir"=>0.2, "dfd_0"=>0, "score"=>0.65}] #@graphs = HTTParty.get("http://172.16.58.3:8080") end # GET /cows/1 # GET /cows/1.json def show end def display end # GET /cows/new def new @cow = Cow.new end # GET /cows/1/edit def edit end # POST /cows # POST /cows.json def create @cow = Cow.new(cow_params) respond_to do |format| if @cow.save format.html { redirect_to @cow, notice: 'Cow was successfully created.' } format.json { render :show, status: :created, location: @cow } else format.html { render :new } format.json { render json: @cow.errors, status: :unprocessable_entity } end end end # PATCH/PUT /cows/1 # PATCH/PUT /cows/1.json def update respond_to do |format| if @cow.update(cow_params) format.html { redirect_to @cow, notice: 'Cow was successfully updated.' } format.json { render :show, status: :ok, location: @cow } else format.html { render :edit } format.json { render json: @cow.errors, status: :unprocessable_entity } end end end # DELETE /cows/1 # DELETE /cows/1.json def destroy @cow.destroy respond_to do |format| format.html { redirect_to cows_url, notice: 'Cow was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_cow @cow = Cow.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def cow_params params[:cow] end end <file_sep>Rails.application.routes.draw do resources :measurements resources :cows root to: 'cows#index' devise_for :users resources :users get 'cows/display', to: "cows#display" end <file_sep>json.extract! @measurement, :id, :created_at, :updated_at <file_sep>class AddAttributesToMeasurements < ActiveRecord::Migration def change add_column :measurements, :cow_id, :integer add_column :measurements, :ph, :integer add_column :measurements, :imp, :integer add_column :measurements, :nir, :integer add_column :measurements, :dfd_0, :integer add_column :measurements, :score, :integer end end <file_sep>FactoryGirl.define do factory :cow do end end <file_sep>setInterval(function () { var previousData = null; $.ajax({ url: "http://192.168.127.12:8080/measurements/?id=1", context: document.body }).done(function(data) { console.log(data); if(data != previousData){ // reload window.reload(); } else { } previousData = data; }); }, 1000); <file_sep>json.extract! @cow, :id, :created_at, :updated_at <file_sep>class Cow < ActiveRecord::Base end <file_sep>json.array!(@cows) do |cow| json.extract! cow, :id json.url cow_url(cow, format: :json) end <file_sep>$(function () { if ($('#measurements').length > 0) { setTimeout(updateMeasurements, 10000); } }); function updateMeasurements() { $.getScript('/measurements.js'); setTimeout(updateMeasurements, 10000); } <file_sep>class Measurement < ActiveRecord::Base end
d98d914d316516c08676d5be84e4f3df90d5b1be
[ "JavaScript", "Ruby" ]
11
Ruby
lyonsv/tenderscan
be3be6fdd4df874bd0571e5933502b886dc7ef33
4b66ee8c7a82181efae43956a47fc8f836c1e2e2
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; @Injectable() export class UnshiftService { person = []; constructor() { } sums = 0; persons() { return this.person = [{ name: 'Kevin', salary: 123 }, { name: 'AB', salary: 234 }, { name: 'Yuvaraj', salary: 345 }] } sum () { for (let i in this.person) { this.sums += this.person[i].salary; } return this.sums; } } <file_sep>import { Component } from '@angular/core'; import { UnshiftService } from './unshift.service'; import { DropdownService } from './dropdown.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [UnshiftService] }) export class AppComponent { title = 'app works!'; persons = []; sums = 0; combos = []; constructor(public unshiftService: UnshiftService, public dropdownService: DropdownService) { } ngOnInit() { this.persons = this.unshiftService.persons(); this.sums = this.unshiftService.sum(); this.combos = this.dropdownService.dropdown(); } }
b43c311d2e0f15812618c1f80043f9dda956e0ba
[ "TypeScript" ]
2
TypeScript
rajmaravanthe/dropdown-service
4175452ec34eca3b26b392cfa63b6b650cba8e20
7e3b1dab46be1f0a8cc2bad6694497e1c2e89da8
refs/heads/master
<file_sep># tfe_passwd.py This tool is designed to change a users password for terraform enterprise ## Installation pip3 install -r requirments.txt ## example usage ### Change joe_user's password to a specific string $ tfe_passwd.py joe_user update joes_old_pass --newpass jo<PASSWORD>_pass Changing password for username: joe_user at https://app.terraform.io SUCCESS: Changed password for user: joe_user to <PASSWORD> ### Change joe_user's password to a random string $ tfe_passwd.py joe_user update joes_old_pass --random Changing password for username: joe_user at https://app.terraform.io SUCCESS: Changed password for user: <PASSWORD>user to <PASSWORD> ### Validate joes_user's password $ tfe_passwd.py validate joe_user <PASSWORD> SUCCESS: Login for: joe_user Succeeded ## Get help output $ tfe_passwd.py -h $ tfe_passwd.py update -h $ tfe_passwd.py validate -h <file_sep>#!/usr/bin/env python3 from bs4 import BeautifulSoup import begin, logging, requests, sys, json, random, string default_tfe_url='https://app.terraform.io' def _random_password(): return ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) def _login(username, password, base_url): """ helper function to make requests to TFE Web Page :param username: TFE username string :param password: <PASSWORD> :param base_url: TFE base url (i.e. https://app.terraform.io) :return: If successful, returns a logged in requests.session() object, else false """ login_url = base_url + '/session' # Create a session object client = requests.Session() # Get the login page logging.debug(f"Requesting login page via GET: {login_url}") try: response = client.get(login_url) except: logging.error(f"Unable to open login URL: {login_url}") return False if response.status_code != 200: logging.error(f"Request GET to login URL: {login_url}. Returned non 200 code: {response.status_code}") return False # Get the csrf token from html soup = BeautifulSoup(response.content, "html.parser") csrf = soup.find("meta", {"name":"csrf-token"})['content'] logging.debug(f"Login Page csrf token: {csrf}") # Build the login form payload payload = { #"csrf": csrf, "utf8":"%E2%9C%93", "authenticity_token": csrf, "user[login]": username, "user[password]": <PASSWORD>, "commit": "Sign in", } # Now log in logging.debug(f"Logging in with POST: {login_url}") response = client.post( login_url, data = payload, headers = dict(referer=login_url)) if response.status_code != 200: logging.error(f"Unable to login to {login_url} with username: {username}. Got Status code: {response.status_code}") return False # We got a valid response... If we failed to login, we should get redirected back to /session # with an html notification includes "Invalid login or password." if response.url == login_url: # uh oh, looks like we were redirected back to the login page. Probably bad username or password logging.debug(f"got url: {response.url}") soup = BeautifulSoup(response.content, "html.parser") # Look for the first tag like <div class:"row alert-error">xxxx</a> error = soup.find('div', {'class':'row alert-error'}) if error: # Found the tag, print the error logging.error(f"Page returned error: {error.text.strip()}") else: # Formatting of the page must have changed. Assume the error logging.error("Unable to log in, probably due to an invalid login or password.") return False elif response.url == base_url + '/app': logging.debug(f"Successfully logged in to {response.url}") return client @begin.subcommand def validate(username, password, tfe_url=default_tfe_url): logging.debug(f"Validating password for username: {username} at url: {tfe_url}") logging.debug(f"Password: {password}") client = _login(username, password, tfe_url) if client: logging.info(f"SUCCESS: Login for: {username} Succeeded") sys.exit(0) else: logging.error(f"ERROR: Login for: {username} Failed") sys.exit(1) @begin.subcommand def update(username, oldpass, newpass='', random=False, tfe_url=default_tfe_url): password_api = tfe_url + '/api/v2/account/password' password_url = tfe_url + '/app/settings/password' logging.info(f"Changing password for username: {username} at {tfe_url}") logging.debug(f"Old password: {oldpass}") logging.debug(f"New password: {newpass}") if newpass == '' and random: newpass = _random_password() client = _login(username, oldpass, tfe_url) if not client: logging.error(f"ERROR: Login for: {username} Failed") sys.exit(1) logging.debug(f"GET password page: {password_url}") headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } response = client.get(password_url, headers=headers) if response.status_code != 200: logging.error(f"Unable to access password page: {password_url}, got status_code:{response.status_code}") sys.exit(1) soup = BeautifulSoup(response.content, "html.parser") csrf = soup.find("meta", {"name":"csrf-token"})['content'] logging.debug(f"Csrf token: {csrf}") payload = json.dumps({ "data": { "attributes": { "current_password": <PASSWORD>, "password": <PASSWORD>, "password_confirmation": <PASSWORD>, } } }) headers['content-type'] = 'application/vnd.api+json' headers['x-csrf-token'] = csrf logging.debug(f"Calling password change api: {password_api}") response = client.patch(password_api, data=payload, headers=headers) if response.status_code == 200: logging.info(f"SUCCESS: Changed password for user: {username} to {newpass}") sys.exit(0) else: logging.debug(f"ERROR: Password change request at {password_api} returned status_code: {response.status_code}") sys.exit(1) @begin.start @begin.logging def run(): "Manages a Terraform Enterprise user's password"
47312be7728b50fbee7e04cefde167a1e31cb6d8
[ "Markdown", "Python" ]
2
Markdown
DheerajJoshi/tfe_passwd_reset
b2758f0194f0683ab2a0847afb51f00c5a137fd0
1712b41fc96641ee913704bfff8956fe2791aee5
refs/heads/master
<repo_name>akameco/first-path<file_sep>/readme.md # first-path [![Build Status](https://travis-ci.org/akameco/first-path.svg?branch=master)](https://travis-ci.org/akameco/first-path) [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) [![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors) > get first path ## Install ``` $ npm install first-path ``` ## Usage ```js const firstPath = require('first-path') firstPath('src/path/to/file') //=> 'src' ``` ## API ### `firstPath(filePath: string): string` #### filePath Type: `string` ## Contributors Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore --> | [<img src="https://avatars2.githubusercontent.com/u/4002137?v=4" width="100px;"/><br /><sub>akameco</sub>](http://akameco.github.io)<br />[💻](https://github.com/akameco/first-path/commits?author=akameco "Code") [📖](https://github.com/akameco/first-path/commits?author=akameco "Documentation") [⚠️](https://github.com/akameco/first-path/commits?author=akameco "Tests") [🚇](#infra-akameco "Infrastructure (Hosting, Build-Tools, etc)") | | :---: | <!-- ALL-CONTRIBUTORS-LIST:END --> This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome! ## License MIT © [akameco](http://akameco.github.io) <file_sep>/test.js // @flow const path = require('path') const firstPath = require('.') test('throw errors', () => { // $FlowFixMe expect(() => firstPath(1)).toThrowErrorMatchingSnapshot() }) test('return first path', () => { const file = path.join('src', 'nest', 'file') expect(firstPath(file)).toBe('src') }) test('return first path with string', () => { const file = 'nest/nest1/nest2/nest3' expect(firstPath(file)).toBe('nest') })
6154752875e49cd0548fe8bc9e23104dfd728789
[ "Markdown", "JavaScript" ]
2
Markdown
akameco/first-path
d088d9ad6ddceb37a29a7336231850473871742a
2baa0ce51136a2d3002947bb1f06a9c62910bcbd
refs/heads/master
<file_sep>var ToolRect = function() { this.l = 10; this.t = 10; this.w = 10; this.h = 10; } ToolRect.prototype.setLeftTop = function(x, y) { this.l = x; this.t = y; } ToolRect.prototype.setRightButtom = function(x, y) { this.w = x - this.l; this.h = y - this.t; } ToolRect.prototype.draw = function(context) { context.beginPath(); context.rect(this.l, this.t, this.w, this.h); context.stroke(); } <file_sep>var ToolCircle = function() { this.center_x = 10; this.center_y = 10; this.radius = 10; } ToolCircle.prototype.setCenterPoint = function(x, y) { this.center_x = x; this.center_y = y; } ToolCircle.prototype.setRadiusByEndPoint = function(x, y) { var diff_x = x - this.center_x; var diff_y = y - this.center_y; //console.log([diff_x, diff_y]); this.radius = Math.sqrt(diff_x*diff_x + diff_y*diff_y); } ToolCircle.prototype.draw = function(context) { context.beginPath(); context.arc(this.center_x, this.center_y, this.radius, 0, Math.PI*2, false); //context.strokeStyle = "red"; //context.lineWidth = 3; //context.fillStyle = color; //context.fill(); context.stroke(); } <file_sep> var ToolText = function(t) { this.text = t; this.center_x = 10; this.center_y = 10; } ToolText.prototype.setCenterPoint = function(x, y) { this.center_x = x; this.center_y = y; } ToolText.prototype.draw = function(context) { context.fillText(this.text, this.center_x, this.center_y); } <file_sep> var ToolLine = function() { this.start_x = 0; this.start_y = 0; this.end_x = 10; this.end_y = 10; } ToolLine.prototype.setStartPoint = function(x, y) { this.start_x = x; this.start_y = y; } ToolLine.prototype.setEndPoint = function(x, y) { this.end_x = x; this.end_y = y; } ToolLine.prototype.draw = function(context) { context.beginPath(); //context.fillStyle = color; //context.lineWidth = 3; context.moveTo(this.start_x, this.start_y); context.lineTo(this.end_x, this.end_y); context.stroke(); }
d3f1fe6b02dc564159212b2105705c8a87275e91
[ "JavaScript" ]
4
JavaScript
HsuBokai/PaintJS
07d55851304c773ca4fd501e858998e0e28cb56f
230d42ccaaba2c0856cc599a5369a42af13f436f