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>hazemosman/germanizer<file_sep>/db_base.rb # TODO Change into active record require 'sqlite3' require_relative 'verb' class DBBase def initialize @db = SQLite3::Database.new('dbfile') @db.results_as_hash = true end def drop_tables puts 'Dropping pronouns table...' @db.execute 'Drop table if exists pronouns' @db.execute 'Drop table if exists tenses' @db.execute 'Drop table if exists verbs' end def create_tables create_pronouns_table create_tenses_table create_verbs_table end def get_pronouns @db.execute('Select * from pronouns') end def insert_veb(verb) @db.execute(%q{Insert into verbs(tense_id, infinitive, ich, du, er, sie_she, es, wir, ihr, sie, sie_formal) values(?,?,?,?,?,?,?,?,?,?,?)}, verb.tense_id, verb.infinitive, verb.ich, verb.du, verb.er, verb.sie_she, verb.es, verb.wir, verb.ihr, verb.sie, verb.sie_formal) end def get_tenses return @db.execute %q{ Select * from tenses } end # Private Methods private def create_pronouns_table puts 'Creating pronouns table...' @db.execute %q{ Create table pronouns ( id integer primary key Autoincrement, description varchar(50), nominative varchar(10), accusative varchar(10), dative varchar(10) ) } i = 0 sql = 'Insert into pronouns(description,nominative,accusative,dative) values(' puts 'Inserting pronouns...' @db.execute"#{sql}'I','ich','mich','mir')" @db.execute"#{sql}'you (informal)','du','dich','dir')" @db.execute"#{sql}'he','er','ihn','ihm')" @db.execute"#{sql}'she','sie','sie','ihr')" @db.execute"#{sql}'it','es','es','ihm')" @db.execute"#{sql}'we','wir','uns','uns')" @db.execute"#{sql}'you (all)','ihr','euch','euch')" @db.execute"#{sql}'they','sie','sie','ihnen')" @db.execute"#{sql}'you (formal)','Sie','Sie','Ihnen')" end def create_tenses_table puts 'Creating tenses table...' @db.execute %q{ Create table tenses ( id integer primary key Autoincrement, description varchar(10), tense varchar(10) ) } i = 0 sql = "Insert into tenses(description,tense) values(" puts 'Inserting tenses...' @db.execute"#{sql}'present','Präsens')" @db.execute"#{sql}'preterite', 'Imperfekt, Präteritum')" @db.execute"#{sql}'perfect','Perfekt')" @db.execute"#{sql}'past perfect','Plusquamperfekt')" @db.execute"#{sql}'future','Futur I')" @db.execute"#{sql}'future perfect','Futur II')" end def create_verbs_table puts 'Creating verbs table...' @db.execute %q{ Create table verbs ( id integer primary key Autoincrement, tense_id integer, infinitive varchar(20), ich varchar(20), du varchar(20), er varchar(20), sie_she varchar(20), es varchar(20), wir varchar(20), ihr varchar(20), sie varchar(20), sie_formal varchar(20), foreign key(tense_id) references tenses(id) ) } end end<file_sep>/tests/test_verb.rb require 'minitest/autorun' require_relative '../verb' class TestVerb < Minitest::Test def test_present_conjugate_irregular v = Verb.new('sein') assert_equal(['ich bin', 'du bist', 'er,sie, es ist', 'wir sind', 'ihr seid', 'sie,Sie sind'], v.present_conjugate, 'Wrong conjugation for sein in present') v = Verb.new('haben') assert_equal(['ich habe', 'du hast', 'er,sie, es hat', 'wir haben', 'ihr habt', 'sie,Sie haben'], v.present_conjugate, 'Wrong conjugation for haben in present') end def test_present_conjugate_regular end end<file_sep>/regular_verb.rb # This class handles regular verbs class RegularVerb attr_accessor :infinitive, :tense_id, :tense, :ich, :du, :er, :sie_she, :es, :wir, :ihr, :sie, :sie_formal def initialize (infinitive) @infinitive = infinitive.downcase set_stem(@infinitive) end # A method to conjugate a regular verb in present tense def present_conjugate if defined?(@stem) ["ich #{@stem}e", "du #{@stem}st", "er,sie, es #{@stem}t", "wir #{@stem}en", "ihr #{@stem}t", "sie,Sie #{@stem}en"] else puts "Could not work with the verb: #{@infinitive}" end end # Returns the verb in infinitive form def to_s "Verb: #{@infinitive}" end private def set_stem(infinitive) @stem = infinitive.slice(0,infinitive.length - 2) if infinitive.end_with?('en') @stem = infinitive.slice(0,infinitive.length - 1) if infinitive.end_with?('n') && ! infinitive.end_with?('en') end end<file_sep>/README.md # germanizer Learning ruby the German way.<file_sep>/verb.rb require_relative 'regular_verb' require_relative 'db_base' #==Part of Germanizer project # This class extends RegularVerb to handle irregular verbs too class Verb < RegularVerb $irregular_verbs = %w(sein haben) # Supported irregular verbs def self.each $irregular_verbs.each {|verb| yield verb} end # A method to conjugate a verb in present tense def present_conjugate if defined?(@stem) # TODO Get irregular verbs from DB case @infinitive when 'sein' present_conjugate_sein when 'haben' present_conjugate_haben else super end else puts "Could not work with the verb: #{@infinitive}" end end def self.add_verb mydb = DBBase.new puts 'This will add a new irregular verb' infinitive = '' #TODO validate user input print "\nEnter verb infinitve:" infinitive = gets.chomp.downcase verb = Verb.new(infinitive) puts '' mydb.get_tenses.each { |tense| puts "#{tense['id']}: #{tense['tense']} (#{tense['description']})"} print "Enter the number of the tense of your verb (e.g. 1):" verb.tense_id = gets.chomp puts "\nNow enter verb conjugation with each pronoun in the selected tense" print "\nich:" verb.ich = gets.chomp.downcase print "du:" verb.du = gets.chomp.downcase print "er:" verb.er = gets.chomp.downcase print "se (she):" verb.sie_she = gets.chomp.downcase print "es:" verb.es = gets.chomp.downcase print "wir:" verb.wir = gets.chomp.downcase print "ihr:" verb.ihr = gets.chomp.downcase print "sie (they):" verb.sie = gets.chomp.downcase print "Sie (formal):" verb.sie_formal = gets.chomp.downcase mydb.insert_veb(verb) end private # TODO Get and save irregular verbs from/to DB def present_conjugate_sein ['ich bin', 'du bist', 'er,sie, es ist', 'wir sind', 'ihr seid', 'sie,Sie sind'] end def present_conjugate_haben ['ich habe', 'du hast', 'er,sie, es hat', 'wir haben', 'ihr habt', 'sie,Sie haben', ] end end<file_sep>/germanizer.rb require_relative 'verb' require 'colorize' catch :finish do 100.times do |x| #throw :finish if x == 2 break if x == 2 puts x + 1 end end 40.times {print'-'} # Print out supported irregular verbs print "\nSupported irregular verbs: " Verb.each {|v| print "#{v} "} print "\n" # Conjugate supported irregular verbs in present tense Verb.each do |inf| v = Verb.new(inf) puts "\n#{v.to_s}".colorize(:blue) puts v.present_conjugate end # An example of conjugating a regular verb print "\nRegular verbs:" v = Verb.new('kaufen') puts "\n#{v.to_s}".colorize(:green) puts v.present_conjugate<file_sep>/test.rb require_relative 'db_base.rb' require_relative 'verb' #mydb = DBBase.new #mydb.drop_tables #mydb.create_tables #Verb.add_verb
3701c08e0e8516180b7146862b1bc912cccf858e
[ "Markdown", "Ruby" ]
7
Ruby
hazemosman/germanizer
b1f5cdd5f22f4f086f34fb33e30d05059f45f535
d44d0453715cb079e2b838d85208d031d819df15
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //Data class that will be saved. It needs the System.Serializable attribute to be used by the Binary Formatter [System.Serializable] public class EnemyDataArray { public EnemyData[] enemyDatas; public EnemyDataArray() { enemyDatas = new EnemyData[0]; } public void Add(EnemyData e) { EnemyData[] temp = new EnemyData[enemyDatas.Length+1]; enemyDatas.CopyTo(temp, 0); temp[enemyDatas.Length] = e; enemyDatas = temp; } public void Remove(EnemyData e) { for (int i = 0; i < enemyDatas.Length; i++) { } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class NPCHealth : Killable { public float _health; public Vector3 enemyCurrentPosition; private void Start() { MaxHealth = 100; Health = 100; } // Update is called once per frame void Update() { _health = Health; enemyCurrentPosition = transform.position; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Assets.Code { public class SmartWaypoint : Waypoint { [SerializeField] protected float connectedRadius = 100f; List<SmartWaypoint> connections; // Start is called before the first frame update void Start() { //Locate all waypoints in scene GameObject[] allWaypoints = GameObject.FindGameObjectsWithTag("Waypoint"); //Create a list of waypoints to reference connections = new List<SmartWaypoint>(); //Check To see if Waypoint is connected for(int i = 0; i < allWaypoints.Length; i++) { SmartWaypoint nextWaypoint = allWaypoints[i].GetComponent<SmartWaypoint>(); //If Waypoint Found if(nextWaypoint != null) { if(Vector3.Distance(this.transform.position, nextWaypoint.transform.position) <= connectedRadius && nextWaypoint != this) { connections.Add(nextWaypoint); } } } } //Draw the Gizmo to see in engine public override void OnDrawGizmo() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, debugDrawRadius); Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(transform.position, connectedRadius); } public SmartWaypoint NextWaypoint(SmartWaypoint previousWaypoint) { if(connections.Count == 0) { //No Waypoints available Debug.LogError("Not Enough Waypoints, you absolute darling of a man you ;) "); return null; } else if(connections.Count == 1 && connections.Contains(previousWaypoint)) { //Only Waypoint in range is the previous one so backtrack / Dead End return previousWaypoint; } else { SmartWaypoint nextWaypoint; int nextIndex = 0; do { nextIndex = UnityEngine.Random.Range(0, connections.Count); nextWaypoint = connections[nextIndex]; } while (nextWaypoint == previousWaypoint); return nextWaypoint; } } // Update is called once per frame void Update() { } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; namespace Assets.Code { public class NPC_SmartPatrol : MonoBehaviour { //Waiting at Node [SerializeField] bool patrolWaiting; //Time waiting at Node [SerializeField] float totalWaitTime = 3f; //Chance that NPC will alter direction [SerializeField] float probabilitySwitch = .2f; //Time to sit at Node [SerializeField] float sitThere = 2f; //Base Behaviors NavMeshAgent navMeshAgent; SmartWaypoint currentWaypoint; SmartWaypoint previousWaypoint; bool travelling; bool waiting; float waitTimer; int wayPointsVisited; // Start is called before the first frame update void Start() { navMeshAgent = this.GetComponent<NavMeshAgent>(); if(navMeshAgent == null) { Debug.LogError("There is no SMARTPATROL NavMeshAgent on the object " + gameObject.name + " you DOLT!!!"); } else { if(currentWaypoint == null) { //Set Random Waypoint //Get all Waypoints GameObject[] allWaypoints = GameObject.FindGameObjectsWithTag("Waypoint"); if(allWaypoints.Length > 0) { while (currentWaypoint == null) { int random = UnityEngine.Random.Range(0, allWaypoints.Length); SmartWaypoint startingWaypoint = allWaypoints[random].GetComponent<SmartWaypoint>(); //Waypoint Found if(startingWaypoint != null) { currentWaypoint = startingWaypoint; } } } else { Debug.LogError("We combed the beach sir, and we ain't found shit!! (no waypoints)"); } } SetDestination(); } } // Update is called once per frame void Update() { //Check to see if close to destination if(travelling && navMeshAgent.remainingDistance <= 1.0f) { travelling = false; wayPointsVisited++; //If we are waiting, wait if(patrolWaiting) { waiting = true; waitTimer = 0f; } else { SetDestination(); } } //If we are currently waiting if(waiting) { waitTimer += sitThere * Time.deltaTime; if(waitTimer >= totalWaitTime) { waiting = false; SetDestination(); } } } private void SetDestination() { if(wayPointsVisited > 0) { SmartWaypoint nextWaypoint = currentWaypoint.NextWaypoint(previousWaypoint); previousWaypoint = currentWaypoint; currentWaypoint = nextWaypoint; } Vector3 targetVector = currentWaypoint.transform.position; navMeshAgent.SetDestination(targetVector); travelling = true; //Set Animator to Travelling True Bool } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using System.Linq; public class GameManager : Singleton<GameManager> { //cache private AudioManager audioManager; private string ambienceAudioClip = "AmbientNoise"; private string winAudioClip = "Victory"; private string lossAudioClip = "Gameover"; private enum MusicState { None, Ambience, Loss, Win } MusicState _musicState; public List<GameObject> enemies = new List<GameObject>(); void Awake() { audioManager = AudioManager.instance; } private void Start() { if (audioManager == null) { Debug.Log("No Audiomanager found in scene"); } enemies = GameObject.FindGameObjectsWithTag("Enemy").ToList(); } private void Update() { Instance.PlayGameMusic(); } public void HideMouse() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } public void ShowMouse() { Cursor.lockState = CursorLockMode.Confined; Cursor.visible = true; } public void PlaySound(string soundName) { audioManager.PlaySound(soundName); } public void PlayMusic(string musicName) { audioManager.PlayMusic(musicName); } private void StopMusic(string musicName) { audioManager.StopMusic(musicName); } public void EnemyKilled() { } public void Died() { SceneManager.LoadScene("Loss"); } public void PlayGameMusic() { if(SceneManager.GetSceneByName("Alex's Level") == SceneManager.GetActiveScene() && _musicState != MusicState.Ambience) { PlayMusic(ambienceAudioClip); _musicState = MusicState.Ambience; StopMusic(winAudioClip); StopMusic(lossAudioClip); } if(SceneManager.GetSceneByName("Loss") == SceneManager.GetActiveScene() && _musicState != MusicState.Loss) { PlayMusic(lossAudioClip); _musicState = MusicState.Loss; StopMusic(ambienceAudioClip); StopMusic(winAudioClip); } if(SceneManager.GetSceneByName("Win") == SceneManager.GetActiveScene() && _musicState != MusicState.Win) { PlayMusic(winAudioClip); _musicState = MusicState.Win; StopMusic(ambienceAudioClip); StopMusic(lossAudioClip); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PlayerHealth : Killable { public Image healthBar; public MusicControl musicSystem; //MusicControl Script on the "MusicSystem" GameObject [FMODUnity.EventRef] public string playerHurtSound = ""; //place event path in "" [FMODUnity.EventRef] public string playerDeathSound = ""; //place event path in "" FMODUnity.StudioEventEmitter emitter; public void EndGame() { //TODO end the game. } public void Flash() { flashTimeRemaining = flashLength; StartCoroutine(FlashRoutine()); } private void Start() { MaxHealth = 100; Health = 100; } // Update is called once per frame void Update() { if (flashTimeRemaining > 0) { flashTimeRemaining -= Time.deltaTime;// Subtract Timer to break out of Co routine } } public override float Health { get { return base.Health; } set { base.Health = value; float ratio = Health / MaxHealth; float newRatio = ratio * 0.78f; healthBar.fillAmount = newRatio; } } void Respawn() { //Respawn when damage hits 0 } IEnumerator FlashRoutine() { while(flashTimeRemaining > 0) { if(flashActive) { flashActive = false; meshRenderer.material = primaryMat; } else { flashActive = true; meshRenderer.material = flashMat; } yield return new WaitForSeconds(.1f); } flashActive = false; meshRenderer.material = primaryMat; Invulnerable = false; } private void OnTriggerEnter(Collider other) { if(other.tag == "MeleeWeapon") { other.enabled = false; //TakeDamage(); Health -= 25; StartCoroutine("FlashRoutine"); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Assets.Code.NPCCode { public class NPCPatrolPoints : MonoBehaviour { [SerializeField] protected float debugDrawRadius = 1.0f; [SerializeField] protected float connectedRadius = 50f; List<NPCPatrolPoints> connections; // Start is called before the first frame update void Start() { //Locate all waypoints in scene GameObject[] allWaypoints = GameObject.FindGameObjectsWithTag("Waypoint"); //Create a list of waypoints to reference connections = new List<NPCPatrolPoints>(); //Check To see if Waypoint is connected for (int i = 0; i < allWaypoints.Length; i++) { NPCPatrolPoints nextWaypoint = allWaypoints[i].GetComponent<NPCPatrolPoints>(); //If Waypoint Found if (nextWaypoint != null) { if (Vector3.Distance(this.transform.position, nextWaypoint.transform.position) <= connectedRadius && nextWaypoint != this) { connections.Add(nextWaypoint); } } } } //Draw the Gizmo to see in engine //ASK BO WHY THEY ARE NOT APPEARING public void OnDrawGizmos() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, debugDrawRadius); Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(transform.position, connectedRadius); } public NPCPatrolPoints NextWaypoint(NPCPatrolPoints previousWaypoint) { if (connections.Count == 0) { //No Waypoints available Debug.LogError("Not Enough Waypoints, you absolute darling of a man you ;) "); return null; } else if (connections.Count == 1 && connections.Contains(previousWaypoint)) { //Only Waypoint in range is the previous one so backtrack / Dead End return previousWaypoint; } else { NPCPatrolPoints nextWaypoint; int nextIndex = 0; do { nextIndex = UnityEngine.Random.Range(0, connections.Count); nextWaypoint = connections[nextIndex]; } while (nextWaypoint == previousWaypoint); return nextWaypoint; } } // Update is called once per frame void Update() { } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IDamageable { float Health { get; set; } float MaxHealth { get; set; } } <file_sep>using UnityEngine; using UnityEngine.AI; using UnityEditor; public class BasicObjectSpawner : EditorWindow { #region Base Variables MonoScript scriptToAdd; GameObject objToSpawn; string objBaseName = ""; int objID = 0; int amountOfObjToSpawn = 1; float objScale = 1f; float spawnRadius = 5f; bool allowSceneObjects = false; Vector2 scrollPos; bool advancedMenu = false; #endregion Base Variables #region RigidBody bool addRigidBody; bool isKinematic; bool useGravity; float rbMass = 1; float rbDrag = 0; float rbAngularDrag = 0.05f; RigidBodyInterpolate rbInterpolate = RigidBodyInterpolate.None; RigidBodyCollsion rbCollisionType = RigidBodyCollsion.Discrete; enum RigidBodyInterpolate { None, Interpolate, Extrapolate, }; enum RigidBodyCollsion { Discrete, Continuous, ContinuousDynamic, ContinuousSpeculative, }; #endregion RigidBody #region Collider #region Box Collider bool addBoxCollider; bool isBoxTrigger; PhysicMaterial boxPhysicsMat; Vector3 boxCenter; Vector3 boxSize; int variableThatDoesNothing; // This makes my headaches go away #endregion Box Collider #region Sphere Collider bool addSphereCollider; bool isSphereTrigger; PhysicMaterial spherePhysMat; Vector3 sphereCenter; float sphereRadius; #endregion Sphere Collider #region Capsule Collider bool addCapsuleCollider; bool isCapsuleTrigger; PhysicMaterial capsulePhysMat; Vector3 capsuleCenter; float capsuleRadius; float capsuleHeight; int capsuleDirection; #endregion Capsule Collider #endregion Collider #region Navmesh #region Agent bool addNavMeshAgent; float navBaseOffset; #region steering float navSpeed; float navAngSpeed; float navAcceleration; float navStopDistance; bool navAutoBrake; #endregion Steering #region Obstacle Avoidance float navAvoidRadius; float navAvoidHeight; int navAvoidPriority; NavAvoidQualityEnum navAvoidQuality; #region Nav Avoidance Quality Enum enum NavAvoidQualityEnum { None, Low, Medium, Good, High } #endregion Nav Avoidance Quality Enum #endregion Obstacle Avoidance #endregion Agent #region Obstacle bool addNavMeshObstacle; ObsShapeEnum obsShape = ObsShapeEnum.Capsule; #region shapeEnum enum ObsShapeEnum { Capsule, Box }; #endregion Vector3 obsCenter; Vector3 obsSize; bool obsCarve; float obsMoveThreshhold; float obsTimeToStationary; bool obsCarveStationary; #endregion Obstacle #endregion Navmesh #region Animator bool addAnimator; RuntimeAnimatorController animController; Avatar animAvatar; bool animRootMotion; AnimatorUpdateModeEnum animUpdateMode; AnimatorCullingModeEnum animCullMode; enum AnimatorUpdateModeEnum { Normal, Animate, Unscaled }; enum AnimatorCullingModeEnum { AlwaysAnimate, CullUpdateTransforms, CullCompletely }; #endregion Animator #region Light bool addLight; LightTypeEnum lightType; float lightRange; Color lightColour; LightModeEnum lightMode; float lightIntensity; float lightIndirectMultiplier; LightShadowTypeEnum lightShadow; Flare lightFlare; #region Light Type Enum enum LightTypeEnum { Spot, Directional, Point, Area }; #endregion Light Type Enum #region Light Mode Enum enum LightModeEnum { Realtime, Mixed, Baked } #endregion Light Mode Enum #region Shadow Type Enum enum LightShadowTypeEnum { None, Hard, Soft } #endregion Shadow Type Enum #region Render Mode Enum enum LightRenderModeEnum { Auto, Important, NotImportant } #endregion Render Mode Enum #endregion Light [MenuItem("Tools/Basic Object Spawner")] public static void ShowWindow() { BasicObjectSpawner window = (BasicObjectSpawner)GetWindow(typeof(BasicObjectSpawner)); window.minSize = new Vector2(300, 400); window.maxSize = new Vector2(600, 800); window.Show(); } private void OnGUI() { #region Spawn Button EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Spawn Object")) { SpawnObject(); } EditorGUILayout.Space(); #endregion Spawn Button #region Object Container GUILayout.Label("Spawn A New Object", EditorStyles.boldLabel); objToSpawn = EditorGUILayout.ObjectField("Prefab To Spawn", objToSpawn, typeof(GameObject), allowSceneObjects) as GameObject; // scriptToAdd = EditorGUILayout.ObjectField("Script To Add", scriptToAdd, typeof(MonoScript), true) as MonoScript; EditorGUI.indentLevel++; allowSceneObjects = EditorGUILayout.Toggle("Allow Scene Objects?", allowSceneObjects); advancedMenu = EditorGUILayout.Toggle(new GUIContent("Advanced Settings", "Allows Modification Of Component Values"), advancedMenu); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUILayout.Space(); #endregion Object Container #region Scrollable Interface scrollPos = GUILayout.BeginScrollView(scrollPos, false, true); // begins scrollbar #region Object Null Check if (objToSpawn != null) { #region Base Object Values EditorGUILayout.BeginVertical(); EditorGUILayout.Space(); GUILayout.Label("Object: " + objBaseName, EditorStyles.boldLabel); objBaseName = EditorGUILayout.TextField("Object Name", objBaseName); objID = EditorGUILayout.IntSlider("Object ID", objID, 0, 2500); objScale = EditorGUILayout.Slider("Base Scale", objScale, 0.01f, 50f); spawnRadius = EditorGUILayout.Slider("Spawn Radius", spawnRadius, 0f, 500f); amountOfObjToSpawn = EditorGUILayout.IntSlider("Spawn Amount", amountOfObjToSpawn, 1, 2000); EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUILayout.Space(); #endregion Base Object Values #region Add Components GUILayout.Label("Add Collider Of Type(s)", EditorStyles.boldLabel); EditorGUI.indentLevel++; EditorGUILayout.BeginVertical(); #region Sphere Collider addSphereCollider = EditorGUILayout.Toggle("Sphere", addSphereCollider); if (addSphereCollider && advancedMenu) { EditorGUILayout.Space(); EditorGUI.indentLevel++; isSphereTrigger = EditorGUILayout.Toggle("isTrigger", isSphereTrigger); spherePhysMat = EditorGUILayout.ObjectField("Physics Material", spherePhysMat, typeof(PhysicMaterial), false) as PhysicMaterial; sphereCenter = EditorGUILayout.Vector3Field("Center", sphereCenter); sphereRadius = EditorGUILayout.Slider("Radius", sphereRadius, 0.01f, 25f); EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUI.indentLevel++; EditorGUILayout.Space(); } #endregion Sphere Collider #region Box Collider addBoxCollider = EditorGUILayout.Toggle(new GUIContent("Box", "Will Create A Box Type Collider"), addBoxCollider); if (addBoxCollider && advancedMenu) // Wrote == true to try and fix a viewport issue, auto resizing seems to be broken { EditorGUILayout.Space(); EditorGUI.indentLevel++; isBoxTrigger = EditorGUILayout.Toggle(new GUIContent("isTrigger", "Is this Collider A Trigger?"), isBoxTrigger); boxPhysicsMat = EditorGUILayout.ObjectField("Physics Material", boxPhysicsMat, typeof(PhysicMaterial), false) as PhysicMaterial; boxCenter = EditorGUILayout.Vector3Field(new GUIContent("Center", "Center Point On XYZ Axis"), boxCenter); boxSize = EditorGUILayout.Vector3Field(new GUIContent("Size", "This Is The Boxes Scale"), boxSize); variableThatDoesNothing = EditorGUILayout.IntSlider("", variableThatDoesNothing, 0, 1); EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUI.indentLevel++; } #endregion Box Collider #region Capsule Collider addCapsuleCollider = EditorGUILayout.Toggle("Capsule", addCapsuleCollider); if (addCapsuleCollider && advancedMenu) { EditorGUILayout.Space(); EditorGUI.indentLevel++; isCapsuleTrigger = EditorGUILayout.Toggle("isTrigger", isCapsuleTrigger); capsulePhysMat = EditorGUILayout.ObjectField("Physics Material", capsulePhysMat, typeof(PhysicMaterial), false) as PhysicMaterial; capsuleCenter = EditorGUILayout.Vector3Field("Center", capsuleCenter); capsuleRadius = EditorGUILayout.Slider("Radius", capsuleRadius, 0.01f, 25f); capsuleHeight = EditorGUILayout.Slider("Height", capsuleHeight, 0.01f, 25f); capsuleDirection = EditorGUILayout.IntSlider("Direction:X|Y|Z", capsuleDirection, 0, 2); EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUI.indentLevel++; EditorGUILayout.Space(); } EditorGUI.indentLevel--; EditorGUILayout.EndVertical(); if (!addCapsuleCollider) { EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; } else if (addCapsuleCollider && !advancedMenu) { EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; } #endregion Capsule Collider #region RigidBody EditorGUILayout.Space(); GUILayout.Label("RigidBody", EditorStyles.boldLabel); addRigidBody = EditorGUILayout.Toggle("Add Rigidbody", addRigidBody); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUILayout.Space(); EditorGUILayout.BeginVertical(); EditorGUI.indentLevel++; if (addRigidBody && advancedMenu) { EditorGUILayout.Space(); EditorGUI.indentLevel++; useGravity = EditorGUILayout.Toggle("useGravity", useGravity); isKinematic = EditorGUILayout.Toggle("isKinematic", isKinematic); rbMass = EditorGUILayout.Slider(new GUIContent("Mass", "Default = 1"), rbMass, 0, 10); // No object should weigh over 20, gravity will begin to break a bit after 10 through Unity default physics rbDrag = EditorGUILayout.Slider(new GUIContent("Drag", "Default = 0"), rbDrag, 0, 10); rbAngularDrag = EditorGUILayout.Slider(new GUIContent("Angular Drag", "Default = 0.05"), rbAngularDrag, 0, 1); // from what I can see angular drag is set to default at 0.05 meaning this value shouldnt increase too high rbInterpolate = (RigidBodyInterpolate)EditorGUILayout.EnumPopup("Interpolate", rbInterpolate); rbCollisionType = (RigidBodyCollsion)EditorGUILayout.EnumPopup("Collision Type", rbCollisionType); EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUI.indentLevel++; EditorGUILayout.Space(); } EditorGUI.indentLevel--; EditorGUILayout.EndVertical(); #endregion RigidBody #region NavMesh Obstacle GUILayout.Label("NavMesh Obstacle", EditorStyles.boldLabel); addNavMeshObstacle = EditorGUILayout.Toggle("Add NavMesh Obstacle", addNavMeshObstacle); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUILayout.Space(); EditorGUILayout.BeginVertical(); if (addNavMeshObstacle && advancedMenu) { GUILayout.Label("Shape", EditorStyles.boldLabel); obsShape = (ObsShapeEnum)EditorGUILayout.EnumPopup("", obsShape); GUILayout.Label("Center", EditorStyles.boldLabel); obsCenter = EditorGUILayout.Vector3Field("", obsCenter); GUILayout.Label("Size", EditorStyles.boldLabel); obsSize = EditorGUILayout.Vector3Field("", obsSize); if (obsSize == Vector3.zero) { obsSize = Vector3.one; } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Carve", EditorStyles.boldLabel); obsCarve = EditorGUILayout.Toggle(new GUIContent("", "Enable To Carve Object From NavMesh"), obsCarve); EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel++; if (obsCarve) { EditorGUILayout.Space(); obsMoveThreshhold = EditorGUILayout.Slider(new GUIContent("Move Threshold", "Default = 0.1"), obsMoveThreshhold, 0, 1); obsTimeToStationary = EditorGUILayout.Slider(new GUIContent("Time to Stationary", "Default = 0.5"), obsTimeToStationary, 0, 1); obsCarveStationary = EditorGUILayout.Toggle(new GUIContent("Carve Stationary", "Enable If This Object Is / Should Be Static"), obsCarveStationary); EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUI.indentLevel++; } } EditorGUILayout.EndVertical(); #endregion NavMesh Obstacle #region NavMesh Agent GUILayout.Label("NavMesh Agent", EditorStyles.boldLabel); EditorGUILayout.BeginVertical(); addNavMeshAgent = EditorGUILayout.Toggle("Add NavMesh Agent", addNavMeshAgent); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; if (addNavMeshAgent && advancedMenu) { GUILayout.Label("Agent Type Will Default To Humanoid", EditorStyles.boldLabel); EditorGUILayout.Space(); navBaseOffset = EditorGUILayout.Slider(new GUIContent("Base Offset", "Default = 0.5"), navBaseOffset, 0, 2); EditorGUILayout.Space(); #region innerSteering EditorGUILayout.Space(); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; GUILayout.Label("Steering", EditorStyles.label); navSpeed = EditorGUILayout.Slider(new GUIContent("Speed", "Default = 6"), navSpeed, 1f, 20f); navAngSpeed = EditorGUILayout.Slider(new GUIContent("Angular Speed", "Default = 120"), navAngSpeed, 1f, 360f); navAcceleration = EditorGUILayout.Slider(new GUIContent("Acceleration", "Default = 8"), navAcceleration, 1f, 20f); navStopDistance = EditorGUILayout.Slider(new GUIContent("Stop Distance", "Default = 6"), navStopDistance, 1f, 20f); navAutoBrake = EditorGUILayout.Toggle(new GUIContent("Auto Brake", "Will the agent automatically stop?"), navAutoBrake); EditorGUILayout.Space(); #endregion innerSteering EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; #region Obstacle Avoidance GUILayout.Label("Obstacle Avoidance", EditorStyles.label); navAvoidRadius = EditorGUILayout.Slider(new GUIContent("Radius", "Default = 0.5"), navAvoidRadius, 0.5f, 6f); navAvoidHeight = EditorGUILayout.Slider(new GUIContent("Height", "Default = 1"), navAvoidHeight, 1f, 6f); navAvoidQuality = (NavAvoidQualityEnum)EditorGUILayout.EnumPopup(new GUIContent("Avoidance Quality", "Quality Of The Navigation Avoidance"), navAvoidQuality); navAvoidPriority = EditorGUILayout.IntSlider(new GUIContent("Priority", "Default = 50"), navAvoidPriority, 50, 150); #endregion Obstacle Avoidance EditorGUILayout.Space(); } EditorGUILayout.EndVertical(); #endregion NavMesh Agent #region Animator GUILayout.Label("Animator", EditorStyles.boldLabel); addAnimator = EditorGUILayout.Toggle(new GUIContent("Add Animator", "Add An Animator Component To Instantiated Objects"), addAnimator); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUILayout.Space(); EditorGUILayout.BeginVertical(); if (addAnimator && advancedMenu) { EditorGUI.indentLevel++; EditorGUI.indentLevel++; animController = EditorGUILayout.ObjectField(new GUIContent("Controller", "Animator Controller Should Be Placed Here"), animController, typeof(RuntimeAnimatorController), false) as RuntimeAnimatorController; animAvatar = EditorGUILayout.ObjectField(new GUIContent("Avatar", "Model Avatar Should Be Placed Here"), animAvatar, typeof(Avatar), false) as Avatar; animRootMotion = EditorGUILayout.Toggle(new GUIContent("Apply Root Motion", "Automatically Move The Object Using The Root Motion From The Animations"), animRootMotion); animUpdateMode = (AnimatorUpdateModeEnum)EditorGUILayout.EnumPopup(new GUIContent("Update Mode", "This Controls How Often The Animator Is Updated"), animUpdateMode); animCullMode = (AnimatorCullingModeEnum)EditorGUILayout.EnumPopup(new GUIContent("Culling Mode", "Controls What Is Updated When The Object Is Culled"), animCullMode); EditorGUI.indentLevel--; EditorGUI.indentLevel--; } EditorGUILayout.EndVertical(); #endregion #region Light GUILayout.Label("Light", EditorStyles.boldLabel); addLight = EditorGUILayout.Toggle(new GUIContent("Add Light", "Add A Light Component To Instantiated Objects"), addLight); EditorGUI.indentLevel--; EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); EditorGUI.indentLevel++; EditorGUILayout.Space(); EditorGUILayout.BeginVertical(); if (addLight && advancedMenu) { lightType = (LightTypeEnum)EditorGUILayout.EnumPopup(new GUIContent("Type", "Select Which Type Of Light You Would Like"), lightType); EditorGUILayout.Space(); lightRange = EditorGUILayout.Slider(new GUIContent("Range", "The Range The Light Will Be Projected"), lightRange, 0f, 50f); lightColour = EditorGUILayout.ColorField(new GUIContent("Colour", "Colour Of The Light"), lightColour); EditorGUILayout.Space(); lightMode = (LightModeEnum)EditorGUILayout.EnumPopup(new GUIContent("Mode", "Used To Determine How The Light Will Be Rendered"), lightMode); lightIntensity = EditorGUILayout.Slider(new GUIContent("Intensity", "Intensity Level Of The Light"), lightIntensity, 0f, 50f); EditorGUILayout.Space(); lightIndirectMultiplier = EditorGUILayout.Slider(new GUIContent("Indirect Multiplier", "Controls The Intensity Of Indirect Light In The Scene"), lightIndirectMultiplier, 0f, 50f); lightShadow = (LightShadowTypeEnum)EditorGUILayout.EnumPopup(new GUIContent("Shadow Type", "Specifies What Shadows Will Be Cast By The Light"), lightShadow); EditorGUILayout.Space(); lightFlare = EditorGUILayout.ObjectField("Flare", lightFlare, typeof(Flare), false) as Flare; EditorGUILayout.Space(); } EditorGUILayout.EndVertical(); #endregion Light EditorGUILayout.Space(); EditorGUILayout.Space(); #endregion Add Components #region Update Window if (BasicObjectSpawner.focusedWindow || BasicObjectSpawner.mouseOverWindow) { Repaint(); } #endregion Update Window } #endregion Object Null Check GUILayout.EndScrollView(); //ends scrollbar #endregion Scrollable Interface #region Object Spawner Function void SpawnObject() { if (objToSpawn == null) { Debug.LogWarning("Warning: Object Must Be Assigned Before Instantiating"); return; } #region Component Instantiation Loop for (int i = 0; i < amountOfObjToSpawn; i++) { Vector2 spawnCircle = Random.insideUnitCircle * spawnRadius; Vector3 spawnPos = new Vector3(spawnCircle.x, 0f, spawnCircle.y); GameObject _newObject = Instantiate(objToSpawn, spawnPos, Quaternion.identity); _newObject.name = objBaseName + objID; _newObject.transform.localScale = Vector3.one * objScale; #region Add Box Collider if (addBoxCollider) { _newObject.AddComponent<BoxCollider>(); _newObject.GetComponent<BoxCollider>().sharedMaterial = boxPhysicsMat; _newObject.GetComponent<BoxCollider>().center = boxCenter; _newObject.GetComponent<BoxCollider>().size = boxSize; if (isBoxTrigger) { _newObject.GetComponent<BoxCollider>().isTrigger = true; } } #endregion Add Box Collider #region Add Sphere Collider if (addSphereCollider) { _newObject.AddComponent<SphereCollider>(); _newObject.GetComponent<SphereCollider>().sharedMaterial = spherePhysMat; _newObject.GetComponent<SphereCollider>().center = sphereCenter; _newObject.GetComponent<SphereCollider>().radius = sphereRadius; if (isSphereTrigger) { _newObject.GetComponent<SphereCollider>().isTrigger = true; } } #endregion Add Sphere Collider #region Add Capsule Collider if (addCapsuleCollider) { _newObject.AddComponent<CapsuleCollider>(); _newObject.GetComponent<CapsuleCollider>().sharedMaterial = capsulePhysMat; _newObject.GetComponent<CapsuleCollider>().center = capsuleCenter; _newObject.GetComponent<CapsuleCollider>().radius = capsuleRadius; _newObject.GetComponent<CapsuleCollider>().height = capsuleHeight; _newObject.GetComponent<CapsuleCollider>().direction = capsuleDirection; if (isCapsuleTrigger) { _newObject.GetComponent<CapsuleCollider>().isTrigger = true; } } #endregion Add Capsule Collider #region Add RigidBody if (addRigidBody) { if (_newObject.GetComponent<Rigidbody>() == null) { _newObject.AddComponent<Rigidbody>(); _newObject.GetComponent<Rigidbody>().mass = rbMass; _newObject.GetComponent<Rigidbody>().drag = rbDrag; _newObject.GetComponent<Rigidbody>().angularDrag = rbAngularDrag; _newObject.GetComponent<Rigidbody>().useGravity = useGravity; _newObject.GetComponent<Rigidbody>().isKinematic = isKinematic; #region rbInterpolate switch (rbInterpolate) { case RigidBodyInterpolate.None: _newObject.GetComponent<Rigidbody>().interpolation = RigidbodyInterpolation.None; break; case RigidBodyInterpolate.Interpolate: _newObject.GetComponent<Rigidbody>().interpolation = RigidbodyInterpolation.Interpolate; break; case RigidBodyInterpolate.Extrapolate: _newObject.GetComponent<Rigidbody>().interpolation = RigidbodyInterpolation.Extrapolate; break; default: break; } #endregion rbInterpolate #region rbCollisionType switch (rbCollisionType) { case RigidBodyCollsion.Discrete: _newObject.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Discrete; // Pretty much voids my collision enum butttt okay :/ break; case RigidBodyCollsion.Continuous: _newObject.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Continuous; break; case RigidBodyCollsion.ContinuousDynamic: _newObject.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; break; case RigidBodyCollsion.ContinuousSpeculative: _newObject.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; break; default: break; } #endregion rbCollisionType } else { Debug.LogError("Already A RigidBody Component Attached"); return; } } #endregion Add RigidBody #region Add Navmesh Agent if (addNavMeshAgent) { if (_newObject.GetComponent<NavMeshAgent>() == null && _newObject.GetComponent<NavMeshObstacle>() == null) { _newObject.AddComponent<NavMeshAgent>(); _newObject.GetComponent<NavMeshAgent>().baseOffset = navBaseOffset; _newObject.GetComponent<NavMeshAgent>().speed = navSpeed; _newObject.GetComponent<NavMeshAgent>().angularSpeed = navAngSpeed; _newObject.GetComponent<NavMeshAgent>().acceleration = navAcceleration; _newObject.GetComponent<NavMeshAgent>().stoppingDistance = navStopDistance; _newObject.GetComponent<NavMeshAgent>().autoBraking = navAutoBrake; _newObject.GetComponent<NavMeshAgent>().radius = navAvoidRadius; _newObject.GetComponent<NavMeshAgent>().height = navAvoidHeight; _newObject.GetComponent<NavMeshAgent>().avoidancePriority = navAvoidPriority; #region Avoidance Quality switch (navAvoidQuality) { case NavAvoidQualityEnum.None: _newObject.GetComponent<NavMeshAgent>().obstacleAvoidanceType = ObstacleAvoidanceType.NoObstacleAvoidance; break; case NavAvoidQualityEnum.Low: _newObject.GetComponent<NavMeshAgent>().obstacleAvoidanceType = ObstacleAvoidanceType.LowQualityObstacleAvoidance; break; case NavAvoidQualityEnum.Medium: _newObject.GetComponent<NavMeshAgent>().obstacleAvoidanceType = ObstacleAvoidanceType.MedQualityObstacleAvoidance; break; case NavAvoidQualityEnum.Good: _newObject.GetComponent<NavMeshAgent>().obstacleAvoidanceType = ObstacleAvoidanceType.GoodQualityObstacleAvoidance; break; case NavAvoidQualityEnum.High: _newObject.GetComponent<NavMeshAgent>().obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance; break; default: break; } #endregion Avoidance Quality } } #endregion #region Add Navmesh Obstacle if (addNavMeshObstacle) { if (_newObject.GetComponent<NavMeshAgent>() == null && _newObject.GetComponent<NavMeshObstacle>() == null) { _newObject.AddComponent<NavMeshObstacle>(); _newObject.GetComponent<NavMeshObstacle>().center = obsCenter; _newObject.GetComponent<NavMeshObstacle>().size = obsSize; _newObject.GetComponent<NavMeshObstacle>().carving = obsCarve; _newObject.GetComponent<NavMeshObstacle>().carvingMoveThreshold = obsMoveThreshhold; _newObject.GetComponent<NavMeshObstacle>().carvingTimeToStationary = obsTimeToStationary; _newObject.GetComponent<NavMeshObstacle>().carveOnlyStationary = obsCarveStationary; #region Shape Enum switch (obsShape) { case ObsShapeEnum.Capsule: _newObject.GetComponent<NavMeshObstacle>().shape = NavMeshObstacleShape.Capsule; break; case ObsShapeEnum.Box: _newObject.GetComponent<NavMeshObstacle>().shape = NavMeshObstacleShape.Box; break; default: break; } #endregion Shape Enum } } #endregion Add NavMesh Obstacle #region Add Animator if (addAnimator) { if (_newObject.GetComponent<Animator>() == null) { _newObject.AddComponent<Animator>(); _newObject.GetComponent<Animator>().runtimeAnimatorController = animController; _newObject.GetComponent<Animator>().avatar = animAvatar; _newObject.GetComponent<Animator>().applyRootMotion = animRootMotion; #region Aniamtor Enums switch (animUpdateMode) { case AnimatorUpdateModeEnum.Normal: _newObject.GetComponent<Animator>().updateMode = AnimatorUpdateMode.Normal; break; case AnimatorUpdateModeEnum.Animate: _newObject.GetComponent<Animator>().updateMode = AnimatorUpdateMode.AnimatePhysics; break; case AnimatorUpdateModeEnum.Unscaled: _newObject.GetComponent<Animator>().updateMode = AnimatorUpdateMode.UnscaledTime; break; default: Debug.LogError("Warning: Failed To Define Animator Update Mode"); break; } switch (animCullMode) { case AnimatorCullingModeEnum.AlwaysAnimate: _newObject.GetComponent<Animator>().cullingMode = AnimatorCullingMode.AlwaysAnimate; break; case AnimatorCullingModeEnum.CullUpdateTransforms: _newObject.GetComponent<Animator>().cullingMode = AnimatorCullingMode.CullUpdateTransforms; break; case AnimatorCullingModeEnum.CullCompletely: _newObject.GetComponent<Animator>().cullingMode = AnimatorCullingMode.CullCompletely; break; default: Debug.LogError("Warning: Failed To Define Animator Culling Mode"); break; } #endregion Animator Enums } } #endregion Add Animator #region Add Light if (addLight) { if (_newObject.GetComponent<Light>() == null) { _newObject.AddComponent<Light>(); _newObject.GetComponent<Light>().range = lightRange; _newObject.GetComponent<Light>().color = lightColour; _newObject.GetComponent<Light>().intensity = lightIntensity; _newObject.GetComponent<Light>().bounceIntensity = lightIndirectMultiplier; _newObject.GetComponent<Light>().flare = lightFlare; switch (lightType) { case LightTypeEnum.Spot: _newObject.GetComponent<Light>().type = LightType.Spot; break; case LightTypeEnum.Directional: _newObject.GetComponent<Light>().type = LightType.Directional; break; case LightTypeEnum.Point: _newObject.GetComponent<Light>().type = LightType.Point; break; case LightTypeEnum.Area: _newObject.GetComponent<Light>().type = LightType.Area; break; default: Debug.LogError("Warning: Failed To Define Light Type"); break; } switch (lightMode) { case LightModeEnum.Realtime: _newObject.GetComponent<Light>().lightmapBakeType = LightmapBakeType.Realtime; break; case LightModeEnum.Mixed: _newObject.GetComponent<Light>().lightmapBakeType = LightmapBakeType.Mixed; break; case LightModeEnum.Baked: _newObject.GetComponent<Light>().lightmapBakeType = LightmapBakeType.Baked; break; default: Debug.LogError("Warning: Failed To Define Lightmap Bake Type"); break; } switch (lightShadow) { case LightShadowTypeEnum.None: _newObject.GetComponent<Light>().shadows = LightShadows.None; break; case LightShadowTypeEnum.Hard: _newObject.GetComponent<Light>().shadows = LightShadows.Hard; break; case LightShadowTypeEnum.Soft: _newObject.GetComponent<Light>().shadows = LightShadows.Soft; break; default: Debug.LogError("Warning: Failed To Define Shadow Type"); break; } } } #endregion Add Light objID++; //Used to set Editor default ID +1 } #endregion Component Instantiation Loop } #endregion Object Spawner Function } } //EditorWindow.GetWindow(typeof(BasicObjectSpawner)); IF THE EDITOR WINDOW IS OPEN AND THIS IS ANYWHERE IN YOUR CODE BESIDES SHOWWINDOW() THIS WILL BREAK YOUR SHIT <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class NPC_SimplePatrol : MonoBehaviour { //Waiting at Node [SerializeField] bool patrolWaiting; //Time waiting at Node [SerializeField] float totalWaitTime = 3f; //Chance that NPC will alter direction [SerializeField] float probabilitySwitch = .2f; //Nodes [SerializeField] List<Waypoint> patrolPoints; //Base Behavior NavMeshAgent navMeshAgent; int currentPatrolPoint; bool travelling; bool waiting; bool patrolForward; float waitTimer; // Start is called before the first frame update void Start() { navMeshAgent = this.GetComponent<NavMeshAgent>(); if(navMeshAgent == null) { Debug.LogError("NO NAV MESH ON THIS COMPONENT YOU TWIT!!!: " + gameObject.name); } else { if(patrolPoints != null && patrolPoints.Count >= 2) { currentPatrolPoint = 0; SetDestination(); } else { Debug.Log("Not Enough Patrol Points to patrol you TWIT!!"); } } } // Update is called once per frame void Update() { //Check if close to destination if(travelling && navMeshAgent.remainingDistance <= 1.0f) { travelling = false; //Waiting Game if (patrolWaiting) { waiting = true; waitTimer = 0f; } else { ChangePatrolPoint(); SetDestination(); } } //If we are waiting if(waiting) { waitTimer += Time.deltaTime; if(waitTimer >= totalWaitTime) { waiting = false; ChangePatrolPoint(); SetDestination(); } } } //Setting The Destination private void SetDestination() { if(patrolPoints != null) { Vector3 targetVector = patrolPoints[currentPatrolPoint].transform.position; navMeshAgent.SetDestination(targetVector); travelling = true; //Set Anim travelling to true } } //Select Patrol Point from list //small chance to send NPC backwards in node path private void ChangePatrolPoint() { if(UnityEngine.Random.Range(0f, 1f) <= probabilitySwitch) { patrolForward = !patrolForward; } if(patrolForward) { /* USE MODULUS INSTEAD currentPatrolPoint++; if(currentPatrolPoint >= patrolPoints.Count) { currentPatrolPoint = 0; } */ //MODULUS currentPatrolPoint = (currentPatrolPoint + 1) % patrolPoints.Count; } else { /*Use Pre Process currentPatrolPoint--; if(currentPatrolPoint < 0) { currentPatrolPoint = patrolPoints.Count - 1; } */ //Pre Process Quick Decrement then check and - if(--currentPatrolPoint < 0) { currentPatrolPoint = patrolPoints.Count - 1; } } } } <file_sep>/*using System.Collections; using System.Collections.Generic; using UnityEngine; using Assets.Code.FSM; namespace Assets.Code.FSM { public enum FSMStateType { IDLE, PATROL, CHASE, ATTACK, RETREAT, }; public class NPC_Animate : MonoBehaviour { public FiniteStateMachine fsm; Animator anim; // Start is called before the first frame update void Start() { anim = this.GetComponent<Animator>(); } // Update is called once per frame void Update() { if(fsm._currentState = FSMStateType.PATROL) { anim.Se } if(fsm._currentState = FSMStateType.ATTACK) { anim.SetBool("isAttacking", true); } if(fsm._currentState = FSMStateType.) } } }*/<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class EnemyManager : MonoBehaviour { public void OnSave() { SerializationManager.Save("enemySave", SaveData.current); } public void Onload() { SaveData.current = (SaveData)SerializationManager.Load(Application.persistentDataPath + "/saves/enemysave.save"); for(int i=0; i<SaveData.current.enemyDatas.Count; i++) { EnemyData currentEnemy = SaveData.current.enemyDatas[i]; //GameObject obj = Instantiate(enemyDatas[(int)currentEnemy.enemyType]); //EnemyDataHandler enemyDataHandler = obj.GetComponent<EnemyDataHandler>(); //enemyDataHandler.enemyData = currentEnemy; //enemyDataHandler.transform.position = currentEnemy.position; //enemyDataHandler.transform.rotation = currentEnemy.rotation; } } } <file_sep>using Cinemachine; using UnityEngine; public class CameraFreeLookJoystickExtentsion : MonoBehaviour { private bool _freeLookActive; // Use this for initialization void Awake() { CinemachineCore.GetInputAxis = HandleAxisInputDelegate; } private void Update() { _freeLookActive = Input.GetMouseButton(1); } // Update is called once per frame float HandleAxisInputDelegate(string axisName) { Debug.Log(axisName); switch (axisName) { case "Right Stick X": return Input.GetAxis(axisName); case "Right Stick Y": return Input.GetAxis(axisName); default: Debug.LogError("Input <" + axisName + "> not recognyzed.", this); break; } return 0f; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IKillable : IDamageable { void Die(); } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyStatus : MonoBehaviour { [SerializeField] int enemyStatus; StunParticals stunParticalsScript; //RangedEnemyPatrol partrolScript; //EnemyContol enemyScript; bool tranquilized; // Start is called before the first frame update void Start() { stunParticalsScript = GetComponent<StunParticals>(); //partrolScript = GetComponent<RangedEnemyPatrol>(); //enemyScript = GetComponent<EnemyContol>(); } public enum statusEffects { //can't move or attack Stunned = 0, defaultStatus = 1 } //reference this script to use status effect; public void Effect(int e) { enemyStatus = e; switch (enemyStatus) { case 0: Debug.Log(statusEffects.Stunned); StartCoroutine(Stun()); break; case 1: Debug.Log("default Status"); break; } } IEnumerator Stun() { float effectTime = 2f; stunParticalsScript.startEmit(stunParticalsScript.stunParticalLauncher); yield return new WaitForSeconds(effectTime); stunParticalsScript.endEmit(stunParticalsScript.stunParticalLauncher); } private void Update() { //calling status effect (test) Effect(0); } // Update is called once per frame /* IEnumerator Stun() { float effectTime = 2f; stunParticalsScript.startEmit(stunParticalsScript.stunParticalLauncher); if (partrolScript != null) { partrolScript.enabled = false; } if (enemyScript != null) { enemyScript.enabled = false; } yield return new WaitForSeconds(effectTime); stunParticalsScript.endEmit(stunParticalsScript.stunParticalLauncher); if (partrolScript != null) { partrolScript.enabled = true; } if (enemyScript != null) { enemyScript.enabled = true; } }*/ } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public abstract class Killable : MonoBehaviour, IKillable { public virtual float Health { get { return _health; } set { if (Invulnerable) return; if (value > MaxHealth) _health = MaxHealth; else _health = value; Debug.Log(Health); if (_health <= 0) Die(); } } public bool Invulnerable { get; set; } = false; public bool isAlive { get { if (Health > 0) return true; return false; } private set { } } private float _health; public float MaxHealth { get; set; } = 100; public float flashLength; protected float flashTimeRemaining; protected bool flashActive; [SerializeField] public SkinnedMeshRenderer meshRenderer; Color originalColor; public Material primaryMat; public Material flashMat; public void Die() { if (gameObject.tag == "Enemy") { GameManager.Instance.EnemyKilled(); } if (gameObject.tag == "Player") { GameManager.Instance.Died(); } Destroy(gameObject); } IEnumerator FlashRoutine() { while (flashTimeRemaining > 0) { if (flashActive) { flashActive = false; meshRenderer.material = primaryMat; } else { flashActive = true; meshRenderer.material = flashMat; } yield return new WaitForSeconds(.1f); } flashActive = false; meshRenderer.material = primaryMat; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class StatusEffect : MonoBehaviour { /*[SerializeField] int playerStatus; PlayerMovement playerMovementScript; PlayerAttacks playerAttackScript; StunParticals stunParticalsScript; bool tranquilized; private void Start() { playerMovementScript = GetComponent<PlayerMovement>(); playerAttackScript = GetComponent<PlayerAttacks>(); stunParticalsScript = GetComponent<StunParticals>(); } //list of status effects public enum statusEffects { //can't move or attack Stunned = 0, //slow movement speed Slowed = 1, //can't move, can attack Rooted = 2, //slowed, and increase speed overtime Tranquilized = 3, //zap 3 times Zapped = 4, Engulfed = 5, defaultStatus = 6 } //weapon has status effect property will call this function public void Effect(int e) { playerStatus = e; switch (playerStatus) { case 0: Debug.Log(statusEffects.Stunned); StartCoroutine(Stun()); break; case 1: Debug.Log(statusEffects.Slowed); StartCoroutine(Slow()); break; case 2: Debug.Log(statusEffects.Rooted); StartCoroutine(Root()); break; case 3: Debug.Log(statusEffects.Tranquilized); tranquilized = true; playerMovementScript.currentSpeedMultiplier = 0.01f; StartCoroutine(Tranquilized()); break; case 4: Debug.Log(statusEffects.Zapped); StartCoroutine(Zapped()); break; case 5: Debug.Log(statusEffects.Engulfed); break; case 6: Debug.Log("default Status"); break; } } private void Update() { if(tranquilized) { if(playerMovementScript.currentSpeedMultiplier<playerMovementScript.moveSpeedMultiplier) { playerMovementScript.currentSpeedMultiplier += ((playerMovementScript.moveSpeedMultiplier - playerMovementScript.currentSpeedMultiplier) * Time.deltaTime) / 3; } } } private void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag=="stun") { Effect(0); } if (collision.gameObject.tag == "slow") { Effect(1); } if (collision.gameObject.tag == "root") { Effect(2); } if (collision.gameObject.tag == "tranquilized") { Effect(3); } if (collision.gameObject.tag == "zapped") { Effect(4); } } IEnumerator Stun() { float effectTime = 2f; playerMovementScript.canMove = false; playerAttackScript.canAttack = false; stunParticalsScript.startEmit(stunParticalsScript.stunParticalLauncher); yield return new WaitForSeconds(effectTime); playerMovementScript.canMove = true; playerAttackScript.canAttack = true; stunParticalsScript.endEmit(stunParticalsScript.stunParticalLauncher); } IEnumerator Slow() { float effectTime = 2f; playerMovementScript.currentSpeedMultiplier = 0.3f; stunParticalsScript.startEmit(stunParticalsScript.slowParticalLauncher); yield return new WaitForSeconds(effectTime); stunParticalsScript.endEmit(stunParticalsScript.slowParticalLauncher); playerMovementScript.currentSpeedMultiplier = 1f; } IEnumerator Root() { float effectTime = 2f; playerMovementScript.canMove = false; stunParticalsScript.startEmit(stunParticalsScript.rootParticalLauncher); yield return new WaitForSeconds(effectTime); stunParticalsScript.endEmit(stunParticalsScript.rootParticalLauncher); playerMovementScript.canMove = true; } //zap 3 times IEnumerator Zapped() { float zapCooldown = 0.3f; playerMovementScript.canMove = false; playerAttackScript.canAttack = false; stunParticalsScript.startEmit(stunParticalsScript.zapParticalLauncher); yield return new WaitForSeconds(zapCooldown); playerMovementScript.canMove = true; playerAttackScript.canAttack = true; yield return new WaitForSeconds(zapCooldown); playerMovementScript.canMove = false; playerAttackScript.canAttack = false; stunParticalsScript.startEmit(stunParticalsScript.zapParticalLauncher); yield return new WaitForSeconds(zapCooldown); playerMovementScript.canMove = true; playerAttackScript.canAttack = true; yield return new WaitForSeconds(zapCooldown); playerMovementScript.canMove = false; playerAttackScript.canAttack = false; stunParticalsScript.startEmit(stunParticalsScript.zapParticalLauncher); yield return new WaitForSeconds(zapCooldown); stunParticalsScript.endEmit(stunParticalsScript.zapParticalLauncher); playerMovementScript.canMove = true; playerAttackScript.canAttack = true; } IEnumerator Tranquilized() { float effectTime = 3f; stunParticalsScript.startEmit(stunParticalsScript.slowParticalLauncher); yield return new WaitForSeconds(effectTime); stunParticalsScript.endEmit(stunParticalsScript.slowParticalLauncher); }*/ } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.NPCCode; namespace Assets.Code.FSM.MyStates { [CreateAssetMenu(fileName = "RetreatState", menuName = "Unity-FSM/MyStates/Retreat", order = 5)]//Fifth in List public class RetreatState : FSMState { public float retreatLength; private float retreatTimeRemaining; public override void OnEnable() { base.OnEnable(); StateType = FSMStateType.RETREAT; } public override bool EnterState() { base.EnterState(); retreatTimeRemaining = retreatLength; navMeshAgent.destination = npc.transform.position; //Play animation taunt return true; } public override void UpdateState() { if (fsm.stunned) { fsm.EnterState(FSMStateType.STUN); } if((retreatTimeRemaining -= Time.deltaTime) <= 0) { fsm.EnterState(FSMStateType.PATROL); } } public override bool ExitState() { base.ExitState(); Debug.Log("Exiting Attack state"); return true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class StunParticals : MonoBehaviour { public ParticleSystem stunParticalLauncher; //public ParticleSystem rootParticalLauncher; //public ParticleSystem slowParticalLauncher; //public ParticleSystem zapParticalLauncher; public void startEmit(ParticleSystem launcher) { launcher.Play(); } public void endEmit(ParticleSystem launcher) { launcher.Stop(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class ChaseMovement : MonoBehaviour { public float speed = 10f; public float lookRadius = 10f; public NavMeshAgent agent; GameObject target; Rigidbody rb; public float runTimer = 1.2f; public Transform[] runLocations; private int pointIndex; // Start is called before the first frame update void Start() { target = GameObject.Find("Player"); rb = GetComponent<Rigidbody>(); agent = GetComponent<NavMeshAgent>(); } // Update is called once per frame void Update() { float distance = Vector3.Distance(target.transform.position, transform.position); if (distance <= lookRadius) { agent.speed = 10f; if (!agent.pathPending && agent.remainingDistance < 0.5f) { RunAway(); } } if(distance >= lookRadius) { agent.speed = 5f; } } private void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, lookRadius); } void RunAway() { if(runLocations.Length == 0) { return; } agent.destination = runLocations[pointIndex].position; pointIndex = (pointIndex + 1) % runLocations.Length; } private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Gate")) { Destroy(gameObject); } } IEnumerator IndexChange() { yield return new WaitForSeconds(runTimer); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace Assets.Code.FSM.MyStates { [CreateAssetMenu(fileName = "IdleState", menuName = "Unity-FSM/MyStates/Idle", order = 1)]//First in List public class IdleState : FSMState { [SerializeField] float idleDuration = 3f; float totalDuration; float speed = 0; [SerializeField] bool canScan; [SerializeField] float scanDegrees; [SerializeField] float scanDistance; public override void OnEnable() { base.OnEnable(); StateType = FSMStateType.IDLE; } public override bool EnterState() { EnteredState = base.EnterState(); if (EnteredState) { totalDuration = 0f; fsm.anim.SetFloat("speed", speed); } return EnteredState; } public bool Scan() { if (fsm.stunned) { fsm.EnterState(FSMStateType.STUN); } RaycastHit hit; //For Loop for Ray Cast for (int i = 0; i <= scanDegrees / 5; i++) { Vector3 rayDir = Quaternion.Euler(0, (i - scanDegrees / 10) * 5, 0) * npc.transform.forward; Debug.DrawRay(npc.transform.position, rayDir * scanDistance, Color.red); if (Physics.Raycast(npc.transform.position, rayDir, out hit, scanDistance)) { if (hit.transform.CompareTag("Player")) { npc.target = hit.transform; fsm.EnterState(FSMStateType.CHASE); return true; } } } //if raycast hits //if target is a player //set the target //start the chase state // return true; return false; } public override void UpdateState() { if (EnteredState) { totalDuration += Time.deltaTime; if (totalDuration >= idleDuration) { fsm.EnterState(FSMStateType.PATROL); } else { if (canScan) { Scan(); } } } } public override bool ExitState() { base.ExitState(); return true; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class PoolTest : MonoBehaviour { public GameObject prefab; public Transform[] spawnLocations; // public GameObject[] triggerBoxes = new GameObject[4]; int rand; int locationIndex = 3; private void Start() { PoolManager.instance.CreatePool(prefab, 3); /*Instantiate(spawnLocations[0], transform.position, Quaternion.identity); Instantiate(spawnLocations[1], transform.position, Quaternion.identity); Instantiate(spawnLocations[2], transform.position, Quaternion.identity); Instantiate(spawnLocations[3], transform.position, Quaternion.identity); System.Random rnd = new System.Random(); spawnLocations = spawnLocations.OrderBy(x => rnd.Next()).ToArray();*/ //Transform[] newSpawnLocations = spawnLocations.OrderBy(x => rnd.Next()).ToArray(); //for (int i = 0; i < newSpawnLocations.Length; i++) //{ // print(spawnLocations[i].position + " | " + newSpawnLocations[i].position); //} } private void Update() { if (Input.GetKeyDown(KeyCode.P)) { PoolManager.instance.AddToPool(prefab); } if(Input.GetKeyDown(KeyCode.O)) { RandomizeSpawnPositions(); for (int i = 0; i < spawnLocations.Length; i++) { PoolManager.instance.ReuseObject(prefab, spawnLocations[i].position, Quaternion.identity); } } } public void SpawnEnemyFromPool() { //Transform spawnLocation = spawnLocations[Array.IndexOf(triggerBoxes, triggerBox)]; RandomizeSpawnPositions(); for (int i = 0; i < spawnLocations.Length; i++) { Vector3 screenPoint = Camera.main.WorldToViewportPoint(spawnLocations[i].position); bool onScreen = screenPoint.z > 0 && screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1; if (!onScreen) { PoolManager.instance.ReuseObject(prefab, spawnLocations[i].position, Quaternion.identity); Debug.Log(spawnLocations[i].position); } } } void RandomizeSpawnPositions() { System.Random rnd = new System.Random(); spawnLocations = spawnLocations.OrderBy(x => rnd.Next()).ToArray(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.NPCCode; namespace Assets.Code.FSM.MyStates { [CreateAssetMenu(fileName = "AttackState", menuName = "Unity-FSM/MyStates/Attack", order = 4)]//Fourth in List public class AttackState : FSMState { [SerializeField] int attackDamage = 10; public bool ikActive = false; public Transform rightHandObj = null; public Transform lookObj = null; public override void OnEnable() { base.OnEnable(); StateType = FSMStateType.ATTACK; } public override bool EnterState() { EnteredState = true; Debug.Log("entered attack state"); fsm.anim.SetBool("isAttacking", true); ikActive = true; return EnteredState; } public override void UpdateState() { if(EnteredState) { PlayerHealth health = npc.target.GetComponent<PlayerHealth>(); if (fsm.stunned) { fsm.EnterState(FSMStateType.STUN); } if (health.isAlive) { fsm.EnterState(FSMStateType.RETREAT); } else { fsm.EnterState(FSMStateType.IDLE); } } } public override bool ExitState() { base.ExitState(); return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using Assets.Code.NPCCode; using System.Threading.Tasks; namespace Assets.Code.FSM { [RequireComponent(typeof(NPCHealth))] public class FiniteStateMachine : MonoBehaviour { [SerializeField] //FSMState startingState; FSMState currentState; [SerializeField] List<FSMState> validStates; [SerializeField] NPCHealth health; NPC npc; public Animator anim; public bool stunned = false; bool isDead; //Key //Value Dictionary<FSMStateType, FSMState> fsmStates; public void Awake() { currentState = null; fsmStates = new Dictionary<FSMStateType, FSMState>(); NavMeshAgent navMeshAgent = this.GetComponent<NavMeshAgent>(); npc = this.GetComponent<NPC>(); anim = this.GetComponent<Animator>(); //Iterate through each state in list foreach (FSMState validState in validStates) { FSMState state = Instantiate<FSMState>(validState); state.SetExecutingFSM(this); state.SetExecutingNPC(npc); state.SetNavMeshAgent(navMeshAgent); fsmStates.Add(state.StateType, state); } } public void Start() { /*if(startingState != null) { EnterState(startingState); }*/ EnterState(FSMStateType.IDLE); } public void Update() { if (health.Health == 0 && !isDead) { isDead = true; anim.SetBool("isDead", true); } if(npc.stunDuration > 0) { stunned = true; npc.stunDuration -= Time.deltaTime; } else { stunned = false; npc.stunDuration = 0; } if(currentState != null && !isDead) { currentState.UpdateState(); } } #region STATE MANAGEMENT public void EnterState(FSMState nextState) { if (nextState == null) { return; } if (currentState != null) { currentState.ExitState(); } currentState = nextState; currentState.EnterState(); } public void EnterState(FSMStateType stateType) { //Check for Key if(fsmStates.ContainsKey(stateType)) { //Grab next state from dictionary FSMState nextState = fsmStates[stateType]; if(currentState != null) { currentState.ExitState(); } EnterState(nextState); } } #endregion } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerSave : MonoBehaviour { PlayerHealth player; private void Start() { player = this.gameObject.GetComponent<PlayerHealth>(); } void Update() { //Call the Save System's Save Player function when you press 1. Pass it the current Player script component. if (Input.GetKeyDown(KeyCode.F5)) { Save(); } //Call the Save System's Load Player function else if (Input.GetKeyDown(KeyCode.F6)) { //Load player returns type PlayerData PlayerData data = SaveSystem.LoadPlayer(); if (data != null) { //player.Health = data.playerHealth; transform.position = new Vector3(data.playerPosition[0], data.playerPosition[1], data.playerPosition[2]); transform.rotation = new Quaternion(data.playerRotation[0], data.playerRotation[1], data.playerRotation[2], data.playerRotation[3]); transform.localScale = new Vector3(data.playerScale[0], data.playerScale[1], data.playerScale[2]); } } } public void Save() { SaveSystem.SavePlayer(player); } private void OnTriggerEnter(Collider other) { if(other.gameObject.tag == "CheckPoint") { Save(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.NPCCode; namespace Assets.Code.FSM.MyStates { [RequireComponent(typeof(IdleState))] [CreateAssetMenu(fileName = "PatrolState", menuName = "Unity-FSM/MyStates/Patrol", order = 2)]//Second In List public class PatrolState : FSMState { NPCPatrolPoints[] patrolPoints; int patrolPointIndex; [SerializeField] float scanDegrees; [SerializeField] float sneakScanDegrees; [SerializeField] float scanDistance; [SerializeField] float sneakScanDistance; private Vector3 lastPos; private float lastPosTime; float blendValue = 0.5f; public override void OnEnable() { base.OnEnable(); StateType = FSMStateType.PATROL; patrolPointIndex = -1; } public override bool EnterState() { lastPosTime = 0; lastPos = navMeshAgent.transform.position; EnteredState = false; if (base.EnterState())//Did it work correctly { //Grab and Store Patrol Points patrolPoints = npc.PatrolPoints; if (patrolPoints == null || patrolPoints.Length == 0) { Debug.LogError("PatrolState: Failed to retreive patrol points from the NPC"); } else { if (patrolPointIndex < 0) { patrolPointIndex = UnityEngine.Random.Range(0, patrolPoints.Length); } else { patrolPointIndex = (patrolPointIndex + 1) % patrolPoints.Length; } SetDestination(patrolPoints[patrolPointIndex]); fsm.anim.SetFloat("speed", blendValue); EnteredState = true; } } return EnteredState; } public override void UpdateState() { if (EnteredState) { if (fsm.stunned) { fsm.EnterState(FSMStateType.STUN); } if (npc.player.InvisBox == false) { if (Scan()) { return; } } if (lastPos == navMeshAgent.transform.position) { lastPosTime += Time.deltaTime; if (lastPosTime >= 3) { fsm.EnterState(FSMStateType.IDLE); } } lastPos = navMeshAgent.transform.position; //Logic if (Vector3.Distance(navMeshAgent.transform.position, patrolPoints[patrolPointIndex].transform.position) <= 1f) { if (fsm.stunned) { fsm.EnterState(FSMStateType.STUN); } fsm.EnterState(FSMStateType.IDLE); } } } public override bool ExitState() { base.ExitState(); return true; } private void SetDestination(NPCPatrolPoints destination) { if (navMeshAgent != null && destination != null) { //Position of patrol point navMeshAgent.SetDestination(destination.transform.position); } } public bool Scan() { if (npc.player.animState == AnimState.isSneaking) { RaycastHit hit; //For Loop for Ray Cast for (int i = 0; i <= sneakScanDegrees / 5; i++) { Vector3 rayDir = Quaternion.Euler(0, (i - sneakScanDegrees / 10) * 5, 0) * npc.transform.forward; Debug.DrawRay(npc.transform.position, rayDir * sneakScanDistance, Color.red); if (Physics.Raycast(npc.transform.position, rayDir, out hit, sneakScanDistance)) { if (hit.transform.CompareTag("Player")) { npc.target = hit.transform; fsm.EnterState(FSMStateType.CHASE); return true; } } } } RaycastHit hit2; //For Loop for Ray Cast for (int i = 0; i <= scanDegrees / 5; i++) { Vector3 rayDir = Quaternion.Euler(0, (i - scanDegrees / 10) * 5, 0) * npc.transform.forward; Debug.DrawRay(npc.transform.position, rayDir * scanDistance, Color.red); if (Physics.Raycast(npc.transform.position, rayDir, out hit2, scanDistance)) { if (hit2.transform.CompareTag("Player")) { npc.target = hit2.transform; fsm.EnterState(FSMStateType.CHASE); return true; } } } //if raycast hits //if target is a player //set the target //start the chase state // return true; return false; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class WolfSense : MonoBehaviour { [SerializeField] private float senseRadius; [SerializeField] private float senseStopRadius; [SerializeField] private float senseTimer; bool wolfSenseOn; public LayerMask enemyLayers; float shortesDistance; GameObject closestEnemy; public GameObject ClosestEnemy { get { return closestEnemy; } } public bool WolfSenseOn { get { return wolfSenseOn; } } // Start is called before the first frame update void Start() { senseRadius = 30.0f; senseStopRadius = 200.0f; senseTimer = 1.0f; wolfSenseOn = false; shortesDistance = Mathf.Infinity; } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.F)) { wolfSenseOn = !wolfSenseOn; } if (wolfSenseOn) { WolfSensing(); } else { if (closestEnemy != null) { closestEnemy.GetComponent<WolfSenseMaterial>().beingSensed = false; } } } void WolfSensing() { Collider[] colliders = Physics.OverlapSphere(transform.position, senseRadius, enemyLayers); foreach (Collider enemy in colliders) { float distance = Vector3.Distance(enemy.transform.position, transform.position); if (distance < shortesDistance) { shortesDistance = distance; closestEnemy = enemy.gameObject; } if (distance < senseRadius) { enemy.gameObject.GetComponent<WolfSenseMaterial>().beingSensed = true; } else { enemy.gameObject.GetComponent<WolfSenseMaterial>().beingSensed = false; } } } private void OnDrawGizmosSelected() { Gizmos.DrawWireSphere(transform.position, senseRadius); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //Data class that will be saved. It needs the System.Serializable attribute to be used by the Binary Formatter [System.Serializable] public class PlayerData { public float[] playerPosition; public float[] playerRotation; public float[] playerScale; public float playerHealth; //Constructor to create the default player data class public PlayerData(PlayerHealth player) { //get player health playerHealth = player.Health; //get player position playerPosition = new float[3]; playerPosition[0] = player.transform.position.x; playerPosition[1] = player.transform.position.y; playerPosition[2] = player.transform.position.z; //get player rotation playerRotation = new float[4]; playerRotation[0] = player.transform.rotation.x; playerRotation[1] = player.transform.rotation.y; playerRotation[2] = player.transform.rotation.z; playerRotation[3] = player.transform.rotation.w; //get player scale playerScale = new float[3]; playerScale[0] = player.transform.localScale.x; playerScale[1] = player.transform.localScale.y; playerScale[2] = player.transform.localScale.z; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.NPCCode; namespace Assets.Code.FSM.MyStates { [CreateAssetMenu(fileName = "RangedAttackState", menuName = "Unity-FSM/MyStates/Ranged Attack", order = 4)] public class RangedAttack : FSMState { [SerializeField] float attackDelay = 1f; float delayTimeRemaining; [SerializeField] float shootDistance; [SerializeField] public GameObject bullet; [SerializeField] private Transform muzzleEnd; [SerializeField] public AudioClip gunShot; private bool isShooting; private float shootForce; private float shootRate; private float shootRateTime; public override void OnEnable() { base.OnEnable(); StateType = FSMStateType.ATTACK; } public override bool EnterState() { EnteredState = true; navMeshAgent.isStopped = true; return EnteredState; } public override void UpdateState() { if (EnteredState) { if (fsm.stunned) { fsm.EnterState(FSMStateType.STUN); } delayTimeRemaining -= Time.deltaTime; if (delayTimeRemaining > 0) { return; } if (Vector3.Distance(npc.target.position, npc.transform.position) > shootDistance) { navMeshAgent.isStopped = false; fsm.EnterState(FSMStateType.CHASE); return; } PlayerHealth health = npc.target.GetComponent<PlayerHealth>(); if (health.isAlive) { delayTimeRemaining = attackDelay; } else { navMeshAgent.isStopped = false; fsm.EnterState(FSMStateType.PATROL); } } } public override bool ExitState() { base.ExitState(); Debug.Log("Exiting Attack state"); return true; } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerArea : MonoBehaviour { private void OnTriggerEnter(Collider other) { GameEvents.current.SpawnTriggerEnter(); // Destroy(gameObject); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestObject : PoolObject { void Update() { if (Input.GetKeyDown(KeyCode.Semicolon)) { Destroy(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //Data class that will be saved. It needs the System.Serializable attribute to be used by the Binary Formatter [System.Serializable] public class EnemyDatas { public EnemyData[] enemyDatasArray; //Constructor to create the default player data class public EnemyDatas(EnemyData[] enemyDatas) { this.enemyDatasArray = enemyDatas; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class CharacterHealth : MonoBehaviour { public float health; public float startHealth; public Image healthBar; public string whineSound = "WolfHurt"; void Start() { health = startHealth; } void Update() { if(health <= 0) { Die(); } //no over heal; else if(health > startHealth) { health = startHealth; } //updates health bar every frame healthBar.fillAmount = health / startHealth; } public void TakeDamage(float amount) { health -= amount; healthBar.fillAmount = health/startHealth; Debug.Log("Current Health: " + health); GameManager.Instance.PlaySound(whineSound); } //added a healing function public void Heal(float amount) { health += amount; healthBar.fillAmount = health / startHealth; Debug.Log("Current Health: " + health); } public void Die() { Destroy(gameObject); SceneManager.LoadScene("Loss"); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.NPCCode; namespace Assets.Code.FSM.MyStates { [CreateAssetMenu(fileName = "ChaseState", menuName = "Unity-FSM/MyStates/Chase", order = 3)]//Third in List public class ChaseState: FSMState { protected float direction; [SerializeField] private float angularSpeed; [SerializeField] private float speed; [SerializeField] private float catchDistance; [SerializeField] private float chaseDistance; float blendSpeed = 1f; public override void OnEnable() { base.OnEnable(); StateType = FSMStateType.CHASE; } public override bool EnterState() { EnteredState = false; direction = npc.transform.rotation.y; fsm.anim.SetFloat("speed", blendSpeed); return EnteredState; } public override void UpdateState() { if(npc.target == null) { fsm.EnterState(FSMStateType.PATROL); return; } if (fsm.stunned) { fsm.EnterState(FSMStateType.STUN); } if (navMeshAgent.isStopped) navMeshAgent.isStopped = false; float distance = (npc.transform.position - npc.target.position).magnitude; if(distance < catchDistance && npc.target.GetComponent<PlayerHealth>()) { fsm.EnterState(FSMStateType.ATTACK); return; } else if(distance > chaseDistance) { fsm.EnterState(FSMStateType.PATROL); return; } /*Vector3 origin = npc.transform.position; origin.y = npc.target.position.y; float angle = Vector3.Angle(origin, npc.target.position); Vector3 cross = Vector3.Cross(origin, npc.target.position);//Cross angle = Mathf.Min(angle, angularSpeed * Time.deltaTime); if (cross.y < 0) { angle = -angle; } direction += angle; npc.transform.rotation = Quaternion.Euler(0, direction, 0); */ Vector3 forward = npc.transform.forward; Vector3 target = npc.target.position - npc.transform.position; target.y = 0; forward = Vector3.RotateTowards(forward, target, angularSpeed * Time.deltaTime, 0); npc.transform.forward = forward; navMeshAgent.destination = npc.transform.position + forward;//Take one step forward avoid kinematic crossover //npc.transform.position += npc.transform.forward * Time.deltaTime * speed; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public enum EnemyType { Melee, Ranged } //Data class that will be saved. It needs the System.Serializable attribute to be used by the Binary Formatter [System.Serializable] public class EnemyData { //public string id; public int id; public EnemyType enemyType; public Vector3 Position; public Quaternion rotation; public float enemyHealth; NPCHealth enemy; public float[] enemyPosition; //Constructor to create the default player data class public EnemyData() { //get player health //enemyHealth = enemy.MaxHealth; //get player position //enemyPosition = new float[3]; //enemyPosition[0] = enemy.enemyCurrentPosition.x; //enemyPosition[1] = enemy.enemyCurrentPosition.y; //enemyPosition[2] = enemy.enemyCurrentPosition.z; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.NPCCode; namespace Assets.Code.FSM.MyStates { [RequireComponent(typeof(IdleState))] [CreateAssetMenu(fileName = "StunState", menuName = "Unity-FSM/MyStates/Stun", order = 6)]//Second In List // Start is called before the first frame update public class StunState : FSMState { public override void OnEnable() { base.OnEnable(); StateType = FSMStateType.STUN; } public override bool EnterState() { if (base.EnterState()) { EnteredState = true; } return EnteredState; } public override void UpdateState() { if (EnteredState) { Debug.Log("Entering Stun State"); if (!fsm.stunned) { fsm.EnterState(FSMStateType.CHASE); } else { navMeshAgent.isStopped = true; } } } public override bool ExitState() { base.ExitState(); Debug.Log("Exiting Stun state"); return true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class FMODMusicMenu : MonoBehaviour { public static FMOD.Studio.EventInstance MenuMusic; // Start is called before the first frame update void Start() { MenuMusic = FMODUnity.RuntimeManager.CreateInstance("event:/MenuMusic"); MenuMusic.start(); MenuMusic.release(); } // Update is called once per frame void Update() { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.FSM; using UnityEngine.Experimental.TerrainAPI; namespace Assets.Code.NPCCode { [RequireComponent(typeof(NavMeshAgent), (typeof(FiniteStateMachine)))] public class NPC : MonoBehaviour { public Transform target; public PlayerController player; [SerializeField] protected NPCPatrolPoints[] patrolPoints; NavMeshAgent navMeshAgent; FiniteStateMachine finiteStatemachine; public int attackDamage; public float stunDuration = 0f; public BoxCollider meleeWeapon; //Audio [FMODUnity.EventRefAttribute] public string hunterStepEventString = "event:/HunterSteps"; FMOD.Studio.EventInstance hunterStepEvent; FMOD.Studio.PARAMETER_ID groundQualityID; public void Awake() { navMeshAgent = this.GetComponent<NavMeshAgent>(); //this. is not neccessary but leaving for now finiteStatemachine = this.GetComponent<FiniteStateMachine>(); gameObject.layer = 9; if(target == null) { target = GameObject.FindGameObjectWithTag("Player").transform; } player = target.GetComponent<PlayerController>(); if(meleeWeapon == null) { meleeWeapon = GetComponentInChildren<BoxCollider>(); } if (meleeWeapon != null) { //meleeWeapon.enabled = false; } } public void Start() { } public void Update() { } public virtual void Attack(Transform attackTarget) { PlayerHealth health = attackTarget.GetComponent<PlayerHealth>(); health.Health -= attackDamage; //Set animation here } public NPCPatrolPoints[] PatrolPoints { get { return patrolPoints; } } public void HunterStepSound() { //Audio hunterStepEvent = FMODUnity.RuntimeManager.CreateInstance(hunterStepEventString); FMOD.Studio.PARAMETER_DESCRIPTION groundDesc; FMOD.Studio.EventDescription stepDesc; hunterStepEvent.getDescription(out stepDesc); stepDesc.getParameterDescriptionByName("Ground Quality", out groundDesc); groundQualityID = groundDesc.id; hunterStepEvent.set3DAttributes(FMODUnity.RuntimeUtils.To3DAttributes(transform)); hunterStepEvent.setParameterByID(groundQualityID, 50); hunterStepEvent.start(); hunterStepEvent.release(); } public void EnableWeaponCollider() { meleeWeapon.enabled = true; } public void DisableWeaponCollider() { meleeWeapon.enabled = false; } public void EndAttack() { finiteStatemachine.anim.SetBool("isAttacking", false); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class WolfSenseMaterial : MonoBehaviour { public Material[] material; public Renderer rend; public bool beingSensed; // Start is called before the first frame update void Start() { rend = GetComponent<Renderer>(); rend.enabled = true; rend.sharedMaterial = material[0]; beingSensed = false; } private void Update() { if(beingSensed == true && rend.sharedMaterial != material[1]) { rend.sharedMaterial = material[1]; } else if (beingSensed == false && rend.sharedMaterial != material[0]) { rend.sharedMaterial = material[0]; } } } <file_sep>using Assets.Code.FSM; using Assets.Code.NPCCode; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public enum ExecutionState { NONE, ACTIVE, COMPLETED, TERMINATED, }; public enum FSMStateType { IDLE, PATROL, CHASE, ATTACK, RETREAT, STUN, }; //Doesn't need to be attached to Game Object public abstract class FSMState : ScriptableObject { protected NavMeshAgent navMeshAgent; protected NPC npc; protected FiniteStateMachine fsm; public ExecutionState ExecutionState { get; protected set; }//Public get, protected Set - Inline property public FSMStateType StateType { get; protected set; } public bool EnteredState { get; protected set; } public virtual void OnEnable() { ExecutionState = ExecutionState.NONE; } public virtual bool EnterState() { bool successNavMesh = true; bool successNPC = true; ExecutionState = ExecutionState.ACTIVE; //Does NavMeshAgent exist? successNavMesh = (navMeshAgent != null); //Does The Executing Agent exist? successNPC = (npc != null); return successNavMesh & successNPC;//return boolean conjunction } public abstract void UpdateState(); public virtual bool ExitState() { ExecutionState = ExecutionState.COMPLETED; return true; } public virtual void SetNavMeshAgent(NavMeshAgent _navMeshAgent) { if(_navMeshAgent != null) { navMeshAgent = _navMeshAgent; } } public virtual void SetExecutingFSM(FiniteStateMachine _fsm) { if(_fsm != null) { fsm = _fsm; } } public virtual void SetExecutingNPC(NPC _npc) { if(_npc != null) { npc = _npc; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyDataHandler : MonoBehaviour { public EnemyType enemyType; public EnemyData enemyData; // Start is called before the first frame update void Start() { //if(string.IsNullOrEmpty(enemyData.id)) //{ // enemyData.id = System.DateTime.Now.ToLongDateString() + System.DateTime.Now.ToLongTimeString() + Random.Range(0, int.MaxValue).ToString(); // enemyData.enemyType = enemyType; // SaveData.current.enemyDatas.Add(enemyData); //} } // Update is called once per frame void Update() { enemyData.Position = transform.position; enemyData.rotation = transform.rotation; } } <file_sep>using Assets.Code.NPCCode; using JetBrains.Annotations; using System.Collections; using System.Collections.Generic; using System.Dynamic; using UnityEngine; using UnityEngine.UI; public enum AnimState { isIdle, isMoving, isAttacking, isJumping, isSneaking, isDashing, isHowling, isTailwhiping } public class PlayerController : MonoBehaviour { public Transform cam; public CharacterController controller; //Dash Particles public ParticleSystem dashParticles; public float rotationSpeed = 10f; public float turnSmoothTime = 0.05f; float turnSmoothVelocity; public float gravity = -12; float velocityY; public float jumpHeight = 1f; Rigidbody rb; Animator anim; //movement values private float currentSpeed; public float walkSpeed = 6f; public float runSpeed = 10f; public float stalkSpeed = 2.5f; public float jumpForce = 100.0f; private float t = 0;//this variable will be discontinued with animation events public float howlCooldownAmount = 5.0f; public float howlTimer = 0; public float howlRadius = 10f; public float howlStunDuration = 2.0f; private bool howlOnCooldown; private LayerMask enemies; public bool InvisBox = false; [Header("Attacks")] //**ATTACK**// //fury public Image furyBar; private float furyTimer; private float furyDamageModifier = 2.0f; private float fillAmount = 0.4f; //tail whip variables public float tailWhipCooldownAmount = 1.0f; public float tailWhipTimer = 0.0f; public float tailWhipRadius = 10.0f; public float tailWhipKnockBackDuration = 1.0f; private bool tailWhipOnCooldown; public float knockBackStrength = 10f; public float knockUpStrength = 5f; //attack variables public Transform attackPoint; public float attackDamage = 10f; public float heavyAttackDamage = 25f; public float attackRange = 0.5f; public float attackCooldown = 2.0f; public float heavyAttackCooldown = 10.0f; private float attackTimer = 0f; private float heavyAttackTimer = 0f; private bool heavyAttackOnCooldown; private bool attackOnCooldown; Vector3 moveDir = new Vector3(0, 0, 1); private AnimState _animState = AnimState.isIdle; public AnimState animState { get { return _animState; } } //dash variables private int dashesRemaining = 3; public float dashChargeTime = 3.0f; public float dashTimer = 0f; public float dashLength = 0.15f; public float dashSpeed = 100f; public BoxCollider collider; private Vector3 dashMove; private float dashing = 0f; private float dashingTime = 0f; private bool canDash = true; private bool dashReset = true; Collider[] dashCollider; Vector3 velocity; //Audio Variables //Paw Sounds [FMODUnity.EventRefAttribute] public string pawEventString = "event:/Music/Music"; FMOD.Studio.EventInstance pawEvent; FMOD.Studio.PARAMETER_ID groundQualityID; private void Start() { rb = GetComponent<Rigidbody>(); anim = GetComponent<Animator>(); enemies = LayerMask.GetMask("Enemies"); //furyBar.fillAmount = 0; Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; //set dash particles to inactive dashParticles.gameObject.SetActive(false); //controller = GetComponent<CharacterController>(); } // Update is called once per frame private void Update() { velocityY += Time.deltaTime * gravity; //if we're not moving we need to constantly check if we're groudned and if not fall if (_animState != AnimState.isMoving) { if (controller.isGrounded) { velocityY = 0; } else { velocity = Vector3.zero + Vector3.up * velocityY; controller.Move(velocity * Time.deltaTime); } } //basic movement if (_animState == AnimState.isIdle || _animState == AnimState.isMoving || _animState == AnimState.isSneaking) { float vertical = Input.GetAxisRaw("Vertical"); float horizontal = Input.GetAxisRaw("Horizontal"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; t = 0; if (Input.GetButtonDown("Jump")) Jump(); if (direction.magnitude >= 0.1f) { _animState = AnimState.isMoving; //get the angle we move and change the camera to match that angle float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); //transform.rotation = Quaternion.Euler(0f, targetAngle, 0f); bool running = Input.GetKey(KeyCode.LeftShift); bool sneaking = Input.GetKey(KeyCode.LeftControl); float currentSpeed = ((running) ? runSpeed : walkSpeed) * direction.magnitude; float sneakSpeed = ((sneaking) ? stalkSpeed : walkSpeed) * direction.magnitude; if (sneaking) { _animState = AnimState.isSneaking; currentSpeed = sneakSpeed; } velocityY += Time.deltaTime * gravity; velocity = transform.forward * currentSpeed + Vector3.up * velocityY; float blendValue = currentSpeed / runSpeed; Debug.Log(blendValue); anim.SetFloat("Speed", blendValue); controller.Move(velocity * Time.deltaTime); if (controller.isGrounded) { velocityY = 0; } } else { float blendValue = 0; anim.SetFloat("Speed", blendValue); } //anim.SetBool("isIdle", false); //anim.SetBool("isRunning", true); } //dash if (_animState == AnimState.isIdle || _animState == AnimState.isMoving || _animState == AnimState.isSneaking && dashesRemaining > 0) { //left ctrl or left mouse button if (Input.GetButtonDown("Fire3") && canDash && dashesRemaining >= 1) { dashMove = velocity.normalized; canDash = false; _animState = AnimState.isDashing; dashReset = false; dashesRemaining--; dashCollider = Physics.OverlapSphere(transform.position, tailWhipRadius, enemies); foreach (Collider col in dashCollider) { col.isTrigger = true; } //enable dash particles dashParticles.gameObject.SetActive(true); } } if (!canDash && dashing < dashLength) { controller.Move(dashMove * dashSpeed * Time.deltaTime); dashing += Time.deltaTime; } if (controller.isGrounded && canDash == false && dashing >= dashLength) { _animState = AnimState.isIdle; canDash = true; dashing = 0f; foreach (Collider col in dashCollider) { col.isTrigger = false; } StartCoroutine(DashParticleTimer()); } IEnumerator DashParticleTimer() { yield return new WaitForSeconds(0.3f); //disable dash particles dashParticles.gameObject.SetActive(false); } //recharge dashes if we don't currently have 3 if (dashesRemaining < 3) { dashTimer += Time.deltaTime; if (dashTimer > dashChargeTime) { dashTimer = 0; dashesRemaining++; } } //stop dashing after a second to set state back to idle //will happen in animation event later if (_animState == AnimState.isDashing) { t += Time.deltaTime; if (t > 1) { _animState = AnimState.isIdle; } } //if jumping check if we hit ground to go back to idle if (_animState == AnimState.isJumping) { if (isGrounded()) { _animState = AnimState.isIdle; } } //attacks if (_animState == AnimState.isIdle || _animState == AnimState.isMoving || _animState == AnimState.isSneaking) { if (Input.GetButtonDown("Fire1") && !attackOnCooldown) { _animState = AnimState.isAttacking; //anim.SetBool("isAttacking", true); attackOnCooldown = true; Attack(); } if (Input.GetButtonDown("Fire2") && !heavyAttackOnCooldown) { _animState = AnimState.isAttacking; //anim.SetBool("isAttacking", true); heavyAttackOnCooldown = true; HeavyAttack(); } } //set cooldown of attack and heavy attack if (attackOnCooldown) { attackTimer += Time.deltaTime; if (attackTimer >= 0.5f) { _animState = AnimState.isIdle; } if (attackTimer >= attackCooldown) { attackTimer = 0; attackOnCooldown = false; } } if (heavyAttackOnCooldown) { heavyAttackTimer += Time.deltaTime; if (heavyAttackTimer >= 0.5f) { _animState = AnimState.isIdle; } if (heavyAttackTimer >= heavyAttackCooldown) { heavyAttackTimer = 0; heavyAttackOnCooldown = false; } } //howl if (_animState == AnimState.isIdle || _animState == AnimState.isMoving || _animState == AnimState.isSneaking) { if (Input.GetButtonDown("Ability1") && !howlOnCooldown) { //grab all the enemies in howl radius and loop through setting them to stunned anim.SetBool("isHowling", true); _animState = AnimState.isHowling; Collider[] colliders = Physics.OverlapSphere(transform.position, howlRadius, enemies); howlOnCooldown = true; foreach (Collider enemy in colliders) { //enemy.GetComponent<EnemyStatus>().Effect(0); enemy.GetComponent<NPC>().stunDuration = howlStunDuration; } //TODO: start howling cooldown at end of animation } } //handles howl cooldown recharge if (howlOnCooldown) { howlTimer += Time.deltaTime; if (howlTimer >= howlCooldownAmount) { howlOnCooldown = false; howlTimer = 0f; } } //tailwhip if (_animState == AnimState.isIdle || _animState == AnimState.isMoving || _animState == AnimState.isSneaking) { if (Input.GetButtonDown("Ability2") && !tailWhipOnCooldown) { _animState = AnimState.isTailwhiping; Collider[] colliders = Physics.OverlapSphere(transform.position, tailWhipRadius, enemies); tailWhipOnCooldown = true; anim.SetBool("isSpinning", true); foreach (Collider enemy in colliders) { enemy.GetComponent<NPC>().stunDuration = tailWhipKnockBackDuration; enemy.GetComponent<Rigidbody>().isKinematic = false; } Knockback(colliders); } } if (tailWhipOnCooldown) { tailWhipTimer += Time.deltaTime; if (tailWhipTimer >= tailWhipCooldownAmount) { tailWhipTimer = 0; tailWhipOnCooldown = false; } } } private void Jump() { if (controller.isGrounded) { float jumpVelocity = Mathf.Sqrt(-2 * gravity * jumpHeight); velocityY = jumpVelocity; } } //basic ground check by raycast private bool isGrounded() { RaycastHit ray; LayerMask ground = LayerMask.GetMask("Ground"); if (Physics.Raycast(transform.position + new Vector3(0, 0.3f, 0), Vector3.down, out ray, .4f, ground)) { return true; } return false; } //basic attack public void Attack() { // Dectect Range of Enemy Collider[] hitEnemies = Physics.OverlapSphere(attackPoint.position, attackRange, enemies); // Damage the Enemy //TODO: make this only target one enemy foreach (Collider enemy in hitEnemies) { enemy.GetComponent<NPCHealth>().Health -= attackDamage; } } public void HeavyAttack() { Collider[] hitEnemies = Physics.OverlapSphere(attackPoint.position, attackRange, enemies); // Damage the Enemy foreach (Collider enemy in hitEnemies) { enemy.GetComponent<NPCHealth>().Health -= heavyAttackDamage; } } private void Knockback(Collider[] colliders) { foreach (Collider enemy in colliders) { Vector3 enemyKnockBackDirection = enemy.transform.position - transform.position; enemyKnockBackDirection.y = 0; enemyKnockBackDirection.Normalize(); enemy.GetComponent<Rigidbody>().AddForce(enemyKnockBackDirection * 15, ForceMode.Impulse); } StartCoroutine(ReAddKinematic(colliders)); } private IEnumerator ReAddKinematic(Collider[] colliders) { yield return new WaitForSeconds(1.0f); foreach (Collider enemy in colliders) { enemy.GetComponent<Rigidbody>().isKinematic = true; } } private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("InvisBox")) { InvisBox = true; // _animState = AnimState.isSneaking; } } private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("InvisBox")) { InvisBox = false; // _animState = AnimState.isIdle; } } public void AttackEvent() { //anim.SetBool("isAttacking", false); _animState = AnimState.isIdle; } public void HowlEvent() { anim.SetBool("isHowling", false); _animState = AnimState.isIdle; } public void SpinEvent() { anim.SetBool("isSpinning", false); _animState = AnimState.isIdle; } public void BiteEvent() { anim.SetBool("isBiting", false); _animState = AnimState.isAttacking; } public void PawStrikeSound() { //Audio pawEvent = FMODUnity.RuntimeManager.CreateInstance(pawEventString); FMOD.Studio.PARAMETER_DESCRIPTION groundDesc; FMOD.Studio.EventDescription pawDesc; pawEvent.getDescription(out pawDesc); pawDesc.getParameterDescriptionByName("Ground Quality", out groundDesc); groundQualityID = groundDesc.id; pawEvent.set3DAttributes(FMODUnity.RuntimeUtils.To3DAttributes(transform)); pawEvent.setParameterByID(groundQualityID, 50); pawEvent.start(); pawEvent.release(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MusicControl : MonoBehaviour { [FMODUnity.EventRefAttribute] public string music = "event:/GamePlayStart_Event"; FMOD.Studio.EventInstance musicEv; // Start is called before the first frame update void Start() { musicEv = FMODUnity.RuntimeManager.CreateInstance(music); musicEv.start(); } //Player has selected play Game from menu public void GameStartedMusic() { musicEv.setParameterByName("GameStarted", 1f); } //Player is less than 25% health public void isUnderHealthAmount() { musicEv.setParameterByName("IsUnderHealthAmount", 1f); } //Player is dead public void IsDeadMusic() { musicEv.setParameterByName("IsDead", 1f); } // Update is called once per frame void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemySave : MonoBehaviour { NPCHealth enemy; public EnemyData enemyData; int currentEnemiesLength; //find all the enemies in the scene, store in an array public GameObject[] enemies; public int[] enemyInstanceIDs; private void Start() { enemies = GameObject.FindGameObjectsWithTag("Enemy"); enemy = this.gameObject.GetComponent<NPCHealth>(); currentEnemiesLength = enemies.Length; enemyInstanceIDs = new int[enemies.Length]; //initial assigning instance IDs for (int i = 0; i < enemies.Length; i++) { //match Instance IDs with proper gameObjects enemyInstanceIDs[i] = enemies[i].GetInstanceID(); } //get instance ID enemyData.id = this.gameObject.GetInstanceID(); //Add enemyData to the list SaveData.current.enemyDatas.Add(enemyData); } void Update() { /* enemyData.enemyPosition[0] = transform.position.x; enemyData.enemyPosition[1] = transform.position.y; enemyData.enemyPosition[2] = transform.position.z; //if amount of enemies changes if (enemies.Length != currentEnemiesLength) { for (int i = 0; i < enemies.Length; i++) { //re-assign Instance IDs with proper gameObjects enemyInstanceIDs[i] = enemies[i].GetInstanceID(); } } //Call the Save System's Save Player function when you press 1. Pass it the current Player script component. if (Input.GetKeyDown(KeyCode.F5)) { Save(); } //Call the Save System's Load Player function else if (Input.GetKeyDown(KeyCode.F6)) { //Load player returns type PlayerData //EnemyData data = EnemySaveSystem.LoadEnemy(); for (int i = 0; i < SaveData.current.enemyDatas.Count; i++) { EnemyData currentData = SaveData.current.enemyDatas[i]; //enemy gets maxHP enemy.Health = enemy.MaxHealth; transform.position = new Vector3(currentData.enemyPosition[0], currentData.enemyPosition[1], currentData.enemyPosition[2]); } //if (enemyData != null) //{ // //enemy gets maxHP // enemy.Health = enemy.MaxHealth; // transform.position = new Vector3(enemyData.enemyPosition[0], enemyData.enemyPosition[1], enemyData.enemyPosition[2]); //} }*/ } public void Save() { EnemySaveSystem.SaveEnemy(enemyData); } } <file_sep>using UnityEngine; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Collections.Generic; public static class EnemySaveSystem { public static List<EnemyData> enemies; public static void SaveEnemy(EnemyData data) { //Create Binary Formatter to write to a file BinaryFormatter formatter = new BinaryFormatter(); //check if path exist if(!Directory.Exists(Application.persistentDataPath + "/enemydata.io")) { Directory.CreateDirectory(Application.persistentDataPath + "/enemydata.io"); } //Path to our file creation - Unity chooses the filepath based on operating system string path = Application.persistentDataPath + "/enemydata.io"; //Creating our stream to save the file FileStream stream = new FileStream(path, FileMode.Create); //PlayerData is now being created //EnemyData data = new EnemyData(); //Serializing the PlayerData formatter.Serialize(stream, data); //Closing the stream - VERY IMPORTANT STEP stream.Close(); } //public static void SaveEnemies(List<GameObject> enemyList) //{ // enemies = new List<EnemyData>(); // foreach (GameObject g in enemyList) // { // enemies.Add(new EnemyData(g.GetComponent<NPCHealth>())); // } //} public static EnemyData LoadEnemy() { //Path to our file - Unity chooses the filepath based on operating system string path = Application.persistentDataPath + "/enemydata.io"; //Check to make sure if the file exists if (File.Exists(path)) { //Create Binary Formatter to write to a file BinaryFormatter formatter = new BinaryFormatter(); //Creating our stream to open the file FileStream stream = new FileStream(path, FileMode.Open); //Deserializing our data - Deserialize function ouputs an object so we have to cast the object to our PlayerData class EnemyData data = formatter.Deserialize(stream) as EnemyData; //Closing the stream - VERY IMPORTANT STEP stream.Close(); //Return our PlayerData return data; } //if file doesn't exist, output an error. else { Debug.LogError("File does not exist"); return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnTrigger : MonoBehaviour { public PoolTest poolTest; private void Start() { GameEvents.current.OnSpawnTriggerEnter += OnSpawnTriggerEntered; } private void OnSpawnTriggerEntered() { poolTest.SpawnEnemyFromPool(); } private void OnDestroy() { GameEvents.current.OnSpawnTriggerEnter -= OnSpawnTriggerEntered; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.AI; using System.Threading.Tasks; using Assets.Code.FSM; namespace Assets.Code.NPCCode { [RequireComponent(typeof(NavMeshAgent), (typeof(FiniteStateMachine)))] //Inherited class public class NPC_Ranged : NPC { public Transform muzzleEnd; public override void Attack(Transform attackTarget) { //Particle burst muzzleEnd base.Attack(attackTarget); //Set animation here } } } <file_sep># ideal-octo-enigma Capstone Game For TFS <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class PathRenderer : MonoBehaviour { public LineRenderer line; //to hold the line Renderer [SerializeField] Transform targetTransform; //to hold the transform of the target GameObject closestEnemyGO; public WolfSense wolfSenseScript; GameObject Player; RaycastHit hit; public LayerMask enemyLayer; [SerializeField] NavMeshAgent playerAgent; void Awake() { line = GetComponent<LineRenderer>(); //get the line renderer line.startWidth = 0; Player = GameObject.FindGameObjectWithTag("Player"); playerAgent = Player.GetComponent<NavMeshAgent>(); } private void Update() { //aim and press V to choose target //if (wolfSenseScript.ClosestEnemy != null && Input.GetKeyDown(KeyCode.V)) //{ // if(Physics.Raycast(Player.transform.position, Player.transform.forward, out hit, enemyLayer)) // { // closestEnemyGO = hit.transform.gameObject; // } //} //chooses closest enemy every update if (wolfSenseScript.ClosestEnemy != null) { closestEnemyGO = wolfSenseScript.ClosestEnemy; getPath(); } } void getPath() { playerAgent.SetDestination(closestEnemyGO.transform.position); if (Player != null) { line.SetPosition(0, Player.transform.position); //set the line's origin } if (closestEnemyGO != null && wolfSenseScript.WolfSenseOn) { line.startWidth = 0.3f; DrawPath(playerAgent.path); playerAgent.isStopped = true; } else { line.startWidth = 0; } } void DrawPath(NavMeshPath path) { if (path.corners.Length < 2) //if the path has 1 or no corners, there is no need return; line.positionCount = path.corners.Length; //set the array of positions to the amount of corners for (var i = 1; i < path.corners.Length; i++) { line.SetPosition(i, path.corners[i]); //go through each corner and set that to the line renderer's position } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Cinemachine; public class LockOn : MonoBehaviour { [SerializeField] private float lockOnRadius; [SerializeField] private float lockOnStopRadius; public LayerMask enemyLayers; public bool wolfLockOn; GameObject closestEnemy; GameObject previousClosestEnemy; CinemachineTargetGroup CMGroup; GameObject CMObj; bool targetLocked; GameObject playerObj; [SerializeField] GameObject TPCamFreeLook; [SerializeField] GameObject lockOnCam; public GameObject ClosestEnemy { get { return closestEnemy; } } // Start is called before the first frame update void Start() { lockOnRadius = 15.0f; lockOnStopRadius = 10.0f; CMObj = GameObject.Find("CM TargetGroup1"); CMGroup = CMObj.GetComponent<CinemachineTargetGroup>(); targetLocked = false; playerObj = GameObject.Find("Player"); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.V)) { wolfLockOn = !wolfLockOn; } if (wolfLockOn) { WolfLockOn(); //turn this on and disable RotateToMatch extension from Cinemachine to work //playerObj.transform.LookAt(closestEnemy.transform); targetLocked = true; } else { targetLocked = false; if (previousClosestEnemy != null) { //lock off CMGroup.RemoveMember(previousClosestEnemy.transform); closestEnemy = null; previousClosestEnemy = null; } } if (TPCamFreeLook != null && lockOnCam != null) { if (targetLocked) { //TPCamFreeLook.SetActive(false); //lockOnCam.SetActive(true); //TPCamFreeLook.GetComponent<CinemachineFreeLook>().enabled = false; //TPCamFreeLook.GetComponent<CinemachineVirtualCamera>().enabled = true; TPCamFreeLook.GetComponent<CinemachineFreeLook>().m_Priority = 8; } else { //TPCamFreeLook.SetActive(true); //lockOnCam.SetActive(false); //TPCamFreeLook.GetComponent<CinemachineFreeLook>().enabled = true; //TPCamFreeLook.GetComponent<CinemachineVirtualCamera>().enabled = false; TPCamFreeLook.GetComponent<CinemachineFreeLook>().m_Priority = 10; } } } void WolfLockOn() { float shortestDistance = Mathf.Infinity; closestEnemy = null; Collider[] colliders = Physics.OverlapSphere(transform.position, lockOnRadius, enemyLayers); if (colliders.Length == 0) { wolfLockOn = false; return; } foreach (Collider enemy in colliders) { float distance = Vector3.Distance(enemy.transform.position, transform.position); if (distance < shortestDistance) { shortestDistance = distance; closestEnemy = enemy.gameObject; } } // first closest enemy if (!previousClosestEnemy) { CMGroup.AddMember(closestEnemy.transform, 100, 1); previousClosestEnemy = closestEnemy; } //Press a button to switch to different closest enemy else if (previousClosestEnemy != closestEnemy) { if (Input.GetKey(KeyCode.B)) { CMGroup.RemoveMember(previousClosestEnemy.transform); CMGroup.AddMember(closestEnemy.transform, 100, 1); previousClosestEnemy = closestEnemy; } } } private void OnDrawGizmosSelected() { Gizmos.DrawWireSphere(transform.position, lockOnRadius); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.VFX; public class VFXController : MonoBehaviour { [SerializeField] VisualEffect visualEffect; [SerializeField] Vector3 target; [SerializeField] Vector3 start; WolfSense wolfSenseScript; GameObject Player; private void Start() { Player = GameObject.FindGameObjectWithTag("Player"); wolfSenseScript = Player.GetComponent<WolfSense>(); } // Update is called once per frame void Update() { //follows the player this.gameObject.transform.position = Player.transform.position; //if wolf sense is on if(wolfSenseScript.WolfSenseOn) { start = Player.transform.position; target = wolfSenseScript.ClosestEnemy.transform.position; if(target != null && start != null) { //set target visualEffect.SetVector3("Target", target); //set start point visualEffect.SetVector3("Start", start); visualEffect.Play(); } } else { visualEffect.Stop(); } } }
e97a1bc7a5834f89609f24371a0d70e3855f579a
[ "Markdown", "C#" ]
51
C#
ademers1/moonrise-wolf-game
a5cae2f28b881b9e87533b4dd5e3f01cdcb42cf5
5a95d963d9e082d699be2465fe5c2a6528b38218
refs/heads/master
<repo_name>jkl071/network-attack-analysis<file_sep>/behavioral_QC_scripts/stop_signal_with_cued_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 19 15:29:04 2018 @author: jamie stop signal with two by two task switch: stay vs switch cue switch: stay vs switch stop: go go stop full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_with_cued_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice SS_stop__task_stay__cue_stay = 0 SS_stop__task_stay__cue_switch = 0 SS_stop__task_switch__cue_stay = 0 SS_stop__task_switch__cue_switch = 0 SS_go__task_stay__cue_stay = 0 SS_go__task_stay__cue_switch = 0 SS_go__task_switch__cue_stay = 0 SS_go__task_switch__cue_switch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].stop_signal_condition == "stop": SS_stop__task_stay__cue_stay += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].stop_signal_condition == "stop": SS_stop__task_stay__cue_switch += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].stop_signal_condition == "stop": SS_stop__task_switch__cue_stay += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].stop_signal_condition == "stop": SS_stop__task_switch__cue_switch += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].stop_signal_condition == "go": SS_go__task_stay__cue_stay += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].stop_signal_condition == "go": SS_go__task_stay__cue_switch += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].stop_signal_condition == "go": SS_go__task_switch__cue_stay += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].stop_signal_condition == "go": SS_go__task_switch__cue_switch += 1 print("SS_stop__task_stay__cue_stay = " + str(SS_stop__task_stay__cue_stay) + " / " + str(len(test_trials))) print("SS_stop__task_stay__cue_switch = " + str(SS_stop__task_stay__cue_switch) + " / " + str(len(test_trials))) print("SS_stop__task_switch__cue_stay = " + str(SS_stop__task_switch__cue_stay) + " / " + str(len(test_trials))) print("SS_stop__task_switch__cue_switch = " + str(SS_stop__task_switch__cue_switch) + " / " + str(len(test_trials))) print("SS_go__task_stay__cue_stay = " + str(SS_go__task_stay__cue_stay) + " / " + str(len(test_trials))) print("SS_go__task_stay__cue_switch = " + str(SS_go__task_stay__cue_switch) + " / " + str(len(test_trials))) print("SS_go__task_switch__cue_stay = " + str(SS_go__task_switch__cue_stay) + " / " + str(len(test_trials))) print("SS_go__task_switch__cue_switch = " + str(SS_go__task_switch__cue_switch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/predictable_task_switching_single_task_network.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 19 15:53:49 2018 @author: jamie predictable task switching single task task: switch vs stay task: magnitude vs parity full counterbalancing 1 throwaway trial per block of trials """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'predictable_task_switching_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice predictive_stay__dim_mag = 0 predictive_stay__dim_par = 0 predictive_switch__dim_mag = 0 predictive_switch__dim_par = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].predictive_dimension == "magnitude": predictive_stay__dim_mag += 1 elif test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].predictive_dimension == "parity": predictive_stay__dim_par += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].predictive_dimension == "magnitude": predictive_switch__dim_mag += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].predictive_dimension == "parity": predictive_switch__dim_par += 1 print("predictive_stay__dim_mag = " + str(predictive_stay__dim_mag) + " / " + str(len(test_trials))) print("predictive_stay__dim_par = " + str(predictive_stay__dim_par) + " / " + str(len(test_trials))) print("predictive_switch__dim_mag = " + str(predictive_switch__dim_mag) + " / " + str(len(test_trials))) print("predictive_switch__dim_par = " + str(predictive_switch__dim_par) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/predictable_task_switching_with_cued_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 5 22:01:24 2018 @author: jamie predictable task switching with two by two 5 blocks of 64 trials, 320 total task switch: stay vs switch cue switch: stay vs switch predictable: stay vs switch full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'predictable_task_switching_with_cued_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice predictable_stay__task_stay__cue_stay = 0 predictable_stay__task_stay__cue_switch = 0 predictable_stay__task_switch__cue_stay = 0 predictable_stay__task_switch__cue_switch = 0 predictable_switch__task_stay__cue_stay = 0 predictable_switch__task_stay__cue_switch = 0 predictable_switch__task_switch__cue_stay = 0 predictable_switch__task_switch__cue_switch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay": predictable_stay__task_stay__cue_stay += 1 elif test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch": predictable_stay__task_stay__cue_switch += 1 elif test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay": predictable_stay__task_switch__cue_stay += 1 elif test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch": predictable_stay__task_switch__cue_switch += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay": predictable_switch__task_stay__cue_stay += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch": predictable_switch__task_stay__cue_switch += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay": predictable_switch__task_switch__cue_stay += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch": predictable_switch__task_switch__cue_switch += 1 print("predictable_stay__task_stay__cue_stay = " + str(predictable_stay__task_stay__cue_stay) + " / " + str(len(test_trials))) print("predictable_stay__task_stay__cue_switch = " + str(predictable_stay__task_stay__cue_switch) + " / " + str(len(test_trials))) print("predictable_stay__task_switch__cue_stay = " + str(predictable_stay__task_switch__cue_stay) + " / " + str(len(test_trials))) print("preditable_stay__task_switch__cue_switch = " + str(predictable_stay__task_switch__cue_switch) + " / " + str(len(test_trials))) print("predictable_switch__task_stay__cue_stay = " + str(predictable_switch__task_stay__cue_stay) + " / " + str(len(test_trials))) print("predictable_switch__task_stay__cue_switch = " + str(predictable_switch__task_stay__cue_switch) + " / " + str(len(test_trials))) print("predictable_switch__task_switch__cue_stay = " + str(predictable_switch__task_switch__cue_stay) + " / " + str(len(test_trials))) print("predictable_switch__task_switch__cue_switch = " + str(predictable_switch__task_switch__cue_switch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/cued_task_switching_with_directed_forgetting.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 18:51:38 2018 @author: jamie two_by_two_with_directed_forgetting directed: pos pos con neg cued: task - switch vs stay cue - switch vs stay full counterbalancing 160 total trials, 32 trials per block, 5 blocks total """ A3NNB4LWIKA3BQ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'directed_forgetting_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice directed_neg__task_stay__cue_stay = 0 directed_neg__task_stay__cue_switch = 0 directed_neg__task_switch__cue_stay = 0 directed_neg__task_switch__cue_switch = 0 directed_pos__task_stay__cue_stay = 0 directed_pos__task_stay__cue_switch = 0 directed_pos__task_switch__cue_stay = 0 directed_pos__task_switch__cue_switch = 0 directed_con__task_stay__cue_stay = 0 directed_con__task_stay__cue_switch = 0 directed_con__task_switch__cue_stay = 0 directed_con__task_switch__cue_switch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].directed_forgetting_condition == 'neg': directed_neg__task_stay__cue_stay += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].directed_forgetting_condition == 'neg': directed_neg__task_stay__cue_switch += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].directed_forgetting_condition == 'neg': directed_neg__task_switch__cue_stay += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].directed_forgetting_condition == 'neg': directed_neg__task_switch__cue_switch += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].directed_forgetting_condition == 'pos': directed_pos__task_stay__cue_stay += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].directed_forgetting_condition == 'pos': directed_pos__task_stay__cue_switch += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].directed_forgetting_condition == 'pos': directed_pos__task_switch__cue_stay += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].directed_forgetting_condition == 'pos': directed_pos__task_switch__cue_switch += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].directed_forgetting_condition == 'con': directed_con__task_stay__cue_stay += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].directed_forgetting_condition == 'con': directed_con__task_stay__cue_switch += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].directed_forgetting_condition == 'con': directed_con__task_switch__cue_stay += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].directed_forgetting_condition == 'con': directed_con__task_switch__cue_switch += 1 print("directed_neg__task_stay__cue_stay = " + str(directed_neg__task_stay__cue_stay) + " / " + str(len(test_trials))) print("directed_neg__task_stay__cue_switch = " + str(directed_neg__task_stay__cue_switch) + " / " + str(len(test_trials))) print("directed_neg__task_switch__cue_stay = " + str(directed_neg__task_switch__cue_stay) + " / " + str(len(test_trials))) print("directed_neg__task_switch__cue_switch = " + str(directed_neg__task_switch__cue_switch) + " / " + str(len(test_trials))) print("directed_pos__task_stay__cue_stay = " + str(directed_pos__task_stay__cue_stay) + " / " + str(len(test_trials))) print("directed_pos__task_stay__cue_switch = " + str(directed_pos__task_stay__cue_switch) + " / " + str(len(test_trials))) print("directed_pos__task_switch__cue_stay = " + str(directed_pos__task_switch__cue_stay) + " / " + str(len(test_trials))) print("directed_pos__task_switch__cue_switch = " + str(directed_pos__task_switch__cue_switch) + " / " + str(len(test_trials))) print("directed_con__task_stay__cue_stay = " + str(directed_con__task_stay__cue_stay) + " / " + str(len(test_trials))) print("directed_con__task_stay__cue_switch = " + str(directed_con__task_stay__cue_switch) + " / " + str(len(test_trials))) print("directed_con__task_switch__cue_stay = " + str(directed_con__task_switch__cue_stay) + " / " + str(len(test_trials))) print("directed_con__task_switch__cue_switch = " + str(directed_con__task_switch__cue_switch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/stop_signal_single_task_network.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 19 17:36:25 2018 @author: jamie stop signal single task network 12 total conditions - 4 shapes by 3 SS type (go go stop) 144 total trials, 48/block, 3 blocks full counterbalance """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice stop_signal_conditions = ['go','stop'] #shapes = circle, square, triangle, pentagon go_shape1 = 0 go_shape2 = 0 go_shape3 = 0 go_shape4 = 0 stop_shape1 = 0 stop_shape2 = 0 stop_shape3 = 0 stop_shape4 = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].stop_signal_condition == 'go' and test_trials.iloc[row].stim == 'circle': go_shape1 += 1 elif test_trials.iloc[row].stop_signal_condition == 'go' and test_trials.iloc[row].stim == 'pentagon': go_shape2 += 1 elif test_trials.iloc[row].stop_signal_condition == 'go' and test_trials.iloc[row].stim == 'square': go_shape3 += 1 elif test_trials.iloc[row].stop_signal_condition == 'go' and test_trials.iloc[row].stim == 'triangle': go_shape4 += 1 elif test_trials.iloc[row].stop_signal_condition == 'stop' and test_trials.iloc[row].stim == 'circle': stop_shape1 += 1 elif test_trials.iloc[row].stop_signal_condition == 'stop' and test_trials.iloc[row].stim == 'pentagon': stop_shape2 += 1 elif test_trials.iloc[row].stop_signal_condition == 'stop' and test_trials.iloc[row].stim == 'square': stop_shape3 += 1 elif test_trials.iloc[row].stop_signal_condition == 'stop' and test_trials.iloc[row].stim == 'triangle': stop_shape4 += 1 print("go_shape1 = " + str(go_shape1) + " / " + str(len(test_trials))) print("go_shape2 = " + str(go_shape2) + " / " + str(len(test_trials))) print("go_shape3 = " + str(go_shape3) + " / " + str(len(test_trials))) print("go_shape4 = " + str(go_shape4) + " / " + str(len(test_trials))) print("stop_shape1 = " + str(stop_shape1) + " / " + str(len(test_trials))) print("stop_shape2 = " + str(stop_shape2) + " / " + str(len(test_trials))) print("stop_shape3 = " + str(stop_shape3) + " / " + str(len(test_trials))) print("stop_shape4 = " + str(stop_shape4) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/n_back_with_shape_matching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 21:38:29 2018 @author: jamie n_back_with_shape_matching shape: match vs mismatch nback: match match match match mismatch nback: 3 delays, 1,2,3 full counterbalancing 10 minimum trials 240 trials total, 40 trials each block, 6 blocks note: this nback needs to have block % 3 == 0 each delay has its own block, and there are three delays """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'n_back_with_shape_matching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice nback_conditions = ['match','mismatch'] delays = ['1','2','3'] shape_mismatch__nback_one_match = 0 shape_mismatch__nback_one_mismatch = 0 shape_mismatch__nback_two_match = 0 shape_mismatch__nback_two_mismatch = 0 shape_mismatch__nback_three_match = 0 shape_mismatch__nback_three_mismatch = 0 shape_match__nback_one_match = 0 shape_match__nback_one_mismatch = 0 shape_match__nback_two_match = 0 shape_match__nback_two_mismatch = 0 shape_match__nback_three_match = 0 shape_match__nback_three_mismatch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].shape_matching_condition == 'mismatch': shape_mismatch__nback_one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].shape_matching_condition == 'mismatch': shape_mismatch__nback_one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].shape_matching_condition == 'mismatch': shape_mismatch__nback_two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].shape_matching_condition == 'mismatch': shape_mismatch__nback_two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].shape_matching_condition == 'mismatch': shape_mismatch__nback_three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].shape_matching_condition == 'mismatch': shape_mismatch__nback_three_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].shape_matching_condition == 'match': shape_match__nback_one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].shape_matching_condition == 'match': shape_match__nback_one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].shape_matching_condition == 'match': shape_match__nback_two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].shape_matching_condition == 'match': shape_match__nback_two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].shape_matching_condition == 'match': shape_match__nback_three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].shape_matching_condition == 'match': shape_match__nback_three_mismatch += 1 print("shape_mismatch__nback_one_match = " + str(shape_mismatch__nback_one_match) + " / " + str(len(test_trials))) print("shape_mismatch__nback_one_mismatch = " + str(shape_mismatch__nback_one_mismatch) + " / " + str(len(test_trials))) print("shape_mismatch__nback_two_match = " + str(shape_mismatch__nback_two_match) + " / " + str(len(test_trials))) print("shape_mismatch__nback_two_mismatch = " + str(shape_mismatch__nback_two_mismatch) + " / " + str(len(test_trials))) print("shape_mismatch__nback_three_match = " + str(shape_mismatch__nback_three_match) + " / " + str(len(test_trials))) print("shape_mismatch__nback_three_mismatch = " + str(shape_mismatch__nback_three_mismatch) + " / " + str(len(test_trials))) print("shape_match__nback_one_match = " + str(shape_match__nback_one_match) + " / " + str(len(test_trials))) print("shape_match__nback_one_mismatch = " + str(shape_match__nback_one_mismatch) + " / " + str(len(test_trials))) print("shape_match__nback_two_match = " + str(shape_match__nback_two_match) + " / " + str(len(test_trials))) print("shape_match__nback_two_mismatch = " + str(shape_match__nback_two_mismatch) + " / " + str(len(test_trials))) print("shape_match__nback_three_match = " + str(shape_match__nback_three_match) + " / " + str(len(test_trials))) print("shape_match__nback_three_mismatch = " + str(shape_match__nback_three_mismatch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/go_nogo_with_n_back.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 14:47:55 2018 @author: jamie go_nogo_with_n_back GNG: ['go','go','go','go','nogo'] N-Back: ['match','mismatch','mismatch','mismatch','mismatch'] delay = 1,2,3 25 - minimum number of trials 300 total trials, 50 each block, 6 blocks note: this nback must have block % 2 == 0, since we want an equal number of blocks per delay each delay has 2 blocks, each block only has 1 delay """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'go_nogo_with_n_back_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice delay_1__gng_go__match = 0 delay_1__gng_go__mismatch = 0 delay_1__gng_nogo__match = 0 delay_1__gng_nogo__mismatch = 0 delay_2__gng_go__match = 0 delay_2__gng_go__mismatch = 0 delay_2__gng_nogo__match = 0 delay_2__gng_nogo__mismatch = 0 delay_3__gng_go__match = 0 delay_3__gng_go__mismatch = 0 delay_3__gng_nogo__match = 0 delay_3__gng_nogo__mismatch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].delay == 1: delay_1__gng_go__match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].delay == 1: delay_1__gng_go__mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].delay == 1: delay_1__gng_nogo__match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].delay == 1: delay_1__gng_nogo__mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].delay == 2: delay_2__gng_go__match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].delay == 2: delay_2__gng_go__mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].delay == 2: delay_2__gng_nogo__match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].delay == 2: delay_2__gng_nogo__mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].delay == 3: delay_3__gng_go__match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].delay == 3: delay_3__gng_go__mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].delay == 3: delay_3__gng_nogo__match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].delay == 3: delay_3__gng_nogo__mismatch += 1 print("delay_1__gng_go__match = " + str(delay_1__gng_go__match) + " / " + str(len(test_trials))) print("delay_1__gng_go__mismatch = " + str(delay_1__gng_go__mismatch) + " / " + str(len(test_trials))) print("delay_1__gng_nogo__match = " + str(delay_1__gng_nogo__match) + " / " + str(len(test_trials))) print("delay_1__gng_nogo__mismatch = " + str(delay_1__gng_nogo__mismatch) + " / " + str(len(test_trials))) print("delay_2__gng_go__match = " + str(delay_2__gng_go__match) + " / " + str(len(test_trials))) print("delay_2__gng_go__mismatch = " + str(delay_2__gng_go__mismatch) + " / " + str(len(test_trials))) print("delay_2__gng_nogo__match = " + str(delay_2__gng_nogo__match) + " / " + str(len(test_trials))) print("delay_2__gng_nogo__mismatch = " + str(delay_2__gng_nogo__mismatch) + " / " + str(len(test_trials))) print("delay_3__gng_go__match = " + str(delay_3__gng_go__match) + " / " + str(len(test_trials))) print("delay_3__gng_go__mismatch = " + str(delay_3__gng_go__mismatch) + " / " + str(len(test_trials))) print("delay_3__gng_nogo__match = " + str(delay_3__gng_nogo__match) + " / " + str(len(test_trials))) print("delay_3__gng_nogo__mismatch = " + str(delay_3__gng_nogo__mismatch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array') <file_sep>/behavioral_QC_scripts/go_nogo_with_directed_forgetting.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 14:26:29 2018 @author: jamie go_nogo_with_directed_forgetting GNG: ['go','go','go','go','stop'] Directed: ['pos', 'pos', 'neg', 'con'] 20 minimum trials full counterbalancing 180 total trials, 20 trials per block, 9 blocks total """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'go_nogo_with_directed_forgetting_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice directed_forgetting_conditions = ['pos','pos','con','neg'] gng_go__pos = 0 gng_go__con = 0 gng_go__neg = 0 gng_nogo__pos = 0 gng_nogo__con = 0 gng_nogo__neg = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__neg += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__neg += 1 print("gng_go__pos = " + str(gng_go__pos) + " / " + str(len(test_trials))) print("gng_go__con = " + str(gng_go__con) + " / " + str(len(test_trials))) print("gng_go__neg = " + str(gng_go__neg) + " / " + str(len(test_trials))) print("gng_nogo__pos = " + str(gng_nogo__pos) + " / " + str(len(test_trials))) print("gng_nogo__con = " + str(gng_nogo__con) + " / " + str(len(test_trials))) print("gng_nogo__neg = " + str(gng_nogo__neg) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array') <file_sep>/behavioral_QC_scripts/flanker_with_shape_matching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 17:39:18 2018 @author: jamie flanker with shape matching 280 total trials, 56 trials per block, 5 blocks flanker: congruent vs incongruent shape matching : ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] full counterbalancing 14 = lowest number of trials """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'flanker_with_shape_matching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] congruent__DDD = 0 congruent__SDD = 0 congruent__DSD = 0 congruent__DDS = 0 congruent__SSS = 0 congruent__SNN = 0 congruent__DNN = 0 incongruent__DDD = 0 incongruent__SDD = 0 incongruent__DSD = 0 incongruent__DDS = 0 incongruent__SSS = 0 incongruent__SNN = 0 incongruent__DNN = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].flanker_condition == 'congruent' : congruent__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__DNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__DNN += 1 print("congruent__DDD = " + str(congruent__DDD) + " / " + str(len(test_trials))) print("congruent__SDD = " + str(congruent__SDD) + " / " + str(len(test_trials))) print("congruent__DSD = " + str(congruent__DSD) + " / " + str(len(test_trials))) print("congruent__DDS = " + str(congruent__DDS) + " / " + str(len(test_trials))) print("congruent__SSS = " + str(congruent__SSS) + " / " + str(len(test_trials))) print("congruent__SNN = " + str(congruent__SNN) + " / " + str(len(test_trials))) print("congruent__DNN = " + str(congruent__DNN) + " / " + str(len(test_trials))) print("incongruent__DDD = " + str(incongruent__DDD) + " / " + str(len(test_trials))) print("incongruent__SDD = " + str(incongruent__SDD) + " / " + str(len(test_trials))) print("incongruent__DSD = " + str(incongruent__DSD) + " / " + str(len(test_trials))) print("incongruent__DDS = " + str(incongruent__DDS) + " / " + str(len(test_trials))) print("incongruent__SSS = " + str(incongruent__SSS) + " / " + str(len(test_trials))) print("incongruent__SNN = " + str(incongruent__SNN) + " / " + str(len(test_trials))) print("incongruent__DNN = " + str(incongruent__DNN) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/directed_forgetting_with_shape_matching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 20:18:57 2018 @author: jamie directed_forgetting_with_shape_matching directed: pos pos neg con shape matching: match mismatch 8 = lowest number of trials full counterbalancing 160 trials total, 32 per block, 5 blocks """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'directed_forgetting_with_shape_matching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice directed_forgetting_conditions = ['pos','pos','con','neg'] match__pos = 0 match__con = 0 match__neg = 0 mismatch__pos = 0 mismatch__con = 0 mismatch__neg = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].shape_matching_condition == 'match': match__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].shape_matching_condition == 'match': match__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].shape_matching_condition == 'match': match__neg += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].shape_matching_condition == 'mismatch': mismatch__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].shape_matching_condition == 'mismatch': mismatch__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].shape_matching_condition == 'mismatch': mismatch__neg += 1 print("match__pos = " + str(match__pos) + " / " + str(len(test_trials))) print("match__con = " + str(match__con) + " / " + str(len(test_trials))) print("match__neg = " + str(match__neg) + " / " + str(len(test_trials))) print("mismatch__pos = " + str(mismatch__pos) + " / " + str(len(test_trials))) print("mismatch__con = " + str(mismatch__con) + " / " + str(len(test_trials))) print("mismatch__neg = " + str(mismatch__neg) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/go_nogo_single_task_network.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 19 17:18:49 2018 @author: jamie go nogo single task network go go go go nogo 5 trial types """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'go_nogo_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice go_nogo_conditions = ['go','nogo'] go = 0 nogo = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].go_nogo_condition == 'go': go += 1 elif test_trials.iloc[row].go_nogo_condition == 'nogo': nogo += 1 print("go = " + str(go) + " / " + str(len(test_trials))) print("nogo = " + str(nogo) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/flanker_with_predictable_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 2 13:20:20 2018 @author: jamie checks trial types for flanker with predictive task switching exp calls for 40 trials per block, 200 trials total, 5 blocks. Due to the nature of the predictive_task, I added 1 throwaway trial at the beginning, to have full set of switch vs stay trials. conditions: Flanker: ['congruent','incongruent'] Predictive: 2 (switch or stay) full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'flanker_with_predictable_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice congruent_switch = 0 congruent_stay = 0 incongruent_switch = 0 incongruent_stay = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].flanker_condition == "congruent": congruent_stay += 1 elif test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].flanker_condition == "incongruent": incongruent_stay += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].flanker_condition == "incongruent": incongruent_switch += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].flanker_condition == "congruent": congruent_switch += 1 print("congruent_switch = " + str(congruent_switch) + " / " + str(len(test_trials))) print("incongruent_switch = " + str(incongruent_switch) + " / " + str(len(test_trials))) print("incongruent_stay = " + str(incongruent_stay) + " / " + str(len(test_trials))) print("congruent_stay = " + str(congruent_stay) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array - this exp has been fixed')<file_sep>/behavioral_QC_scripts/n_back_with_flanker.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 22:06:44 2018 @author: jamie n_back_with_flanker flanker: congruent vs incongruent nback: match match match match mismatch nback: 3 delays, 1,2,3 full counterbalancing 10 minimum trials 240 trials total, 40 trials each block, 6 blocks note: this nback needs to have block % 3 == 0 each delay has its own block, and there are three delays """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'n_back_with_flanker_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice nback_conditions = ['match','mismatch'] delays = ['1','2','3'] flanker_congruent__nback_one_match = 0 flanker_congruent__nback_one_mismatch = 0 flanker_congruent__nback_two_match = 0 flanker_congruent__nback_two_mismatch = 0 flanker_congruent__nback_three_match = 0 flanker_congruent__nback_three_mismatch = 0 flanker_incongruent__nback_one_match = 0 flanker_incongruent__nback_one_mismatch = 0 flanker_incongruent__nback_two_match = 0 flanker_incongruent__nback_two_mismatch = 0 flanker_incongruent__nback_three_match = 0 flanker_incongruent__nback_three_mismatch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].flanker_condition == 'congruent': flanker_congruent__nback_one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].flanker_condition == 'congruent': flanker_congruent__nback_one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].flanker_condition == 'congruent': flanker_congruent__nback_two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].flanker_condition == 'congruent': flanker_congruent__nback_two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].flanker_condition == 'congruent': flanker_congruent__nback_three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].flanker_condition == 'congruent': flanker_congruent__nback_three_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].flanker_condition == 'incongruent': flanker_incongruent__nback_one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].flanker_condition == 'incongruent': flanker_incongruent__nback_one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].flanker_condition == 'incongruent': flanker_incongruent__nback_two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].flanker_condition == 'incongruent': flanker_incongruent__nback_two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].flanker_condition == 'incongruent': flanker_incongruent__nback_three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].flanker_condition == 'incongruent': flanker_incongruent__nback_three_mismatch += 1 print("flanker_congruent__nback_one_match = " + str(flanker_congruent__nback_one_match) + " / " + str(len(test_trials))) print("flanker_congruent__nback_one_mismatch = " + str(flanker_congruent__nback_one_mismatch) + " / " + str(len(test_trials))) print("flanker_congruent__nback_two_match = " + str(flanker_congruent__nback_two_match) + " / " + str(len(test_trials))) print("flanker_congruent__nback_two_mismatch = " + str(flanker_congruent__nback_two_mismatch) + " / " + str(len(test_trials))) print("flanker_congruent__nback_three_match = " + str(flanker_congruent__nback_three_match) + " / " + str(len(test_trials))) print("flanker_congruent__nback_three_mismatch = " + str(flanker_congruent__nback_three_mismatch) + " / " + str(len(test_trials))) print("flanker_incongruent__nback_one_match = " + str(flanker_incongruent__nback_one_match) + " / " + str(len(test_trials))) print("flanker_incongruent__nback_one_mismatch = " + str(flanker_incongruent__nback_one_mismatch) + " / " + str(len(test_trials))) print("flanker_incongruent__nback_two_match = " + str(flanker_incongruent__nback_two_match) + " / " + str(len(test_trials))) print("flanker_incongruent__nback_two_mismatch = " + str(flanker_incongruent__nback_two_mismatch) + " / " + str(len(test_trials))) print("flanker_incongruent__nback_three_match = " + str(flanker_incongruent__nback_three_match) + " / " + str(len(test_trials))) print("flanker_incongruent__nback_three_mismatch = " + str(flanker_incongruent__nback_three_mismatch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/README.md # network-attack-analysis Repository for analyzing network-attack battery of experiments <file_sep>/behavioral_QC_scripts/n_back_single_task_network.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 16:32:44 2018 @author: jamie nback single task network condition (match match match match mismatch) delay (1,2,3) 15 trials - full counterbalancing 150 total trials, 50/block, 3 blocks note: nback tasks must have multiples of 3 blocks, 1 for each delay (1,2,3) """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'n_back_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice nback_conditions = ['match','mismatch'] delays = ['1','2','3'] one_match = 0 one_mismatch = 0 two_match = 0 two_mismatch = 0 three_match = 0 three_mismatch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1: one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1: one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2: two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2: two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3: three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3: three_mismatch += 1 print("one_match = " + str(one_match) + " / " + str(len(test_trials))) print("one_mismatch = " + str(one_mismatch) + " / " + str(len(test_trials))) print("two_match = " + str(two_match) + " / " + str(len(test_trials))) print("two_mismatch = " + str(two_mismatch) + " / " + str(len(test_trials))) print("three_match = " + str(three_match) + " / " + str(len(test_trials))) print("three_mismatch = " + str(three_mismatch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/go_nogo_with_flanker.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 12:21:14 2018 @author: jamie go_nogo_with_flanker GNG: ['go','go','go','go','stop'] Flanker: ['H_congruent','H_incongruent','F_congruent','F_incongruent'] 20 minimum trials 240 total trials, 60 per block, 4 blocks total full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'go_nogo_with_flanker_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice gng_go__F_congruent = 0 gng_go__H_congruent = 0 gng_go__F_incongruent = 0 gng_go__H_incongruent = 0 gng_nogo__F_congruent = 0 gng_nogo__H_congruent = 0 gng_nogo__F_incongruent= 0 gng_nogo__H_incongruent = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].flanker_condition == 'F_congruent' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__F_congruent += 1 elif test_trials.iloc[row].flanker_condition == 'H_congruent' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__H_congruent += 1 elif test_trials.iloc[row].flanker_condition == 'F_incongruent' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__F_incongruent += 1 elif test_trials.iloc[row].flanker_condition == 'H_incongruent' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__H_incongruent += 1 elif test_trials.iloc[row].flanker_condition == 'F_congruent' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__F_congruent += 1 elif test_trials.iloc[row].flanker_condition == 'H_congruent' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__H_congruent += 1 elif test_trials.iloc[row].flanker_condition == 'F_incongruent' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__F_incongruent += 1 elif test_trials.iloc[row].flanker_condition == 'H_incongruent' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__H_incongruent += 1 print("gng_go__F_congruent = " + str(gng_go__F_congruent) + " / " + str(len(test_trials))) print("gng_go__H_congruent = " + str(gng_go__H_congruent) + " / " + str(len(test_trials))) print("gng_go__F_incongruent = " + str(gng_go__F_incongruent) + " / " + str(len(test_trials))) print("gng_go__H_incongruent = " + str(gng_go__H_incongruent) + " / " + str(len(test_trials))) print("gng_nogo__F_congruent = " + str(gng_nogo__F_congruent) + " / " + str(len(test_trials))) print("gng_nogo__H_congruent = " + str(gng_nogo__H_congruent) + " / " + str(len(test_trials))) print("gng_nogo__F_incongruent = " + str(gng_nogo__F_incongruent) + " / " + str(len(test_trials))) print("gng_nogo__H_incongruent = " + str(gng_nogo__H_incongruent) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array') <file_sep>/behavioral_QC_scripts/stop_signal_with_flanker.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 16:22:16 2018 @author: jamie stop_signal_with_flanker SS: go, go, stop Flanker: ['H_congruent','H_incongruent','F_congruent','F_incongruent'] 240 total trials, 48 trials per block, 5 blocks 12 minimum trials full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_with_flanker_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice SS_stop__H_congruent = 0 SS_stop__H_incongruent = 0 SS_stop__F_congruent = 0 SS_stop__F_incongruent = 0 SS_go__H_congruent = 0 SS_go__H_incongruent = 0 SS_go__F_congruent = 0 SS_go__F_incongruent = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].flanker_condition == "H_congruent" and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__H_congruent += 1 elif test_trials.iloc[row].flanker_condition == "H_congruent" and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__H_congruent += 1 elif test_trials.iloc[row].flanker_condition == "H_incongruent" and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__H_incongruent += 1 elif test_trials.iloc[row].flanker_condition == "H_incongruent" and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__H_incongruent += 1 elif test_trials.iloc[row].flanker_condition == "F_congruent" and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__F_congruent += 1 elif test_trials.iloc[row].flanker_condition == "F_congruent" and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__F_congruent += 1 elif test_trials.iloc[row].flanker_condition == "F_incongruent" and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__F_incongruent += 1 elif test_trials.iloc[row].flanker_condition == "F_incongruent" and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__F_incongruent += 1 print("SS_stop__H_congruent = " + str(SS_stop__H_congruent) + " / " + str(len(test_trials))) print("SS_stop__H_incongruent = " + str(SS_stop__H_incongruent) + " / " + str(len(test_trials))) print("SS_stop__F_congruent = " + str(SS_stop__F_congruent) + " / " + str(len(test_trials))) print("SS_stop__F_incongruent = " + str(SS_stop__F_incongruent) + " / " + str(len(test_trials))) print("SS_go__H_congruent = " + str(SS_go__H_congruent) + " / " + str(len(test_trials))) print("SS_go__H_incongruent = " + str(SS_go__H_incongruent) + " / " + str(len(test_trials))) print("SS_go__F_congruent = " + str(SS_go__F_congruent) + " / " + str(len(test_trials))) print("SS_go__F_incongruent = " + str(SS_go__F_incongruent) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/n_back_with_predictable_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 21:19:54 2018 @author: jamie n_back_with_predictable_task_switching predictive: task - switch vs stay task: 1back or 2back n_back: ['match','mismatch','mismatch','mismatch','mismatch'] delays: 1back or 2back 240 trials total, 40 trials per block, 6 blocks note: each block has both 1 and 2-back trials. """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'n_back_with_predictable_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice predictive_stay__mismatch = 0 predictive_stay__match = 0 predictive_switch__mismatch = 0 predictive_switch__match = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].n_back_condition == "mismatch": predictive_stay__mismatch += 1 elif test_trials.iloc[row].predictive_condition == "stay" and test_trials.iloc[row].n_back_condition == "match": predictive_stay__match += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].n_back_condition == "mismatch": predictive_switch__mismatch += 1 elif test_trials.iloc[row].predictive_condition == "switch" and test_trials.iloc[row].n_back_condition == "match": predictive_switch__match += 1 print("predictive_stay__mismatch = " + str(predictive_stay__mismatch) + " / " + str(len(test_trials))) print("predictive_stay__match = " + str(predictive_stay__match) + " / " + str(len(test_trials))) print("predictive_switch__mismatch = " + str(predictive_switch__mismatch) + " / " + str(len(test_trials))) print("predictive_switch__match = " + str(predictive_switch__match) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/stop_signal_with_shape_matching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 16:07:55 2018 @author: jamie stop_signal_with_shape_matching SS: go, go, stop Shape: ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] 420 total trials, 84 per block, 5 blocks total 21 minimum trials full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_with_shape_matching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice SS_go__DDD = 0 SS_go__SDD = 0 SS_go__DSD = 0 SS_go__DDS = 0 SS_go__SSS = 0 SS_go__SNN = 0 SS_go__DNN = 0 SS_stop__DDD = 0 SS_stop__SDD = 0 SS_stop__DSD = 0 SS_stop__DDS = 0 SS_stop__SSS = 0 SS_stop__SNN = 0 SS_stop__DNN = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__DNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__DNN += 1 print("SS_go__DDD = " + str(SS_go__DDD) + " / " + str(len(test_trials))) print("SS_go__SDD = " + str(SS_go__SDD) + " / " + str(len(test_trials))) print("SS_go__DSD = " + str(SS_go__DSD) + " / " + str(len(test_trials))) print("SS_go__DDS = " + str(SS_go__DDS) + " / " + str(len(test_trials))) print("SS_go__SSS = " + str(SS_go__SSS) + " / " + str(len(test_trials))) print("SS_go__SNN = " + str(SS_go__SNN) + " / " + str(len(test_trials))) print("SS_go__DNN = " + str(SS_go__DNN) + " / " + str(len(test_trials))) print("SS_stop__DDD = " + str(SS_stop__DDD) + " / " + str(len(test_trials))) print("SS_stop__SDD = " + str(SS_stop__SDD) + " / " + str(len(test_trials))) print("SS_stop__DSD = " + str(SS_stop__DSD) + " / " + str(len(test_trials))) print("SS_stop__DDS = " + str(SS_stop__DDS) + " / " + str(len(test_trials))) print("SS_stop__SSS = " + str(SS_stop__SSS) + " / " + str(len(test_trials))) print("SS_stop__SNN = " + str(SS_stop__SNN) + " / " + str(len(test_trials))) print("SS_stop__DNN = " + str(SS_stop__DNN) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/shape_matching_with_cued_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 4 10:41:31 2018 @author: jamie shape_matching_with_two_by_two shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] task_conditions = switch vs stay cue_conditions = switch vs stay 5 blocks of 112 trials, 560 total. lowest counterbalance = 28 full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'shape_matching_with_cued_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] task_stay__cue_stay_DDD = 0 task_stay__cue_stay_SDD = 0 task_stay__cue_stay_DSD = 0 task_stay__cue_stay_DDS = 0 task_stay__cue_stay_SSS = 0 task_stay__cue_stay_SNN = 0 task_stay__cue_stay_DNN = 0 task_stay__cue_switch_DDD = 0 task_stay__cue_switch_SDD = 0 task_stay__cue_switch_DSD = 0 task_stay__cue_switch_DDS = 0 task_stay__cue_switch_SSS = 0 task_stay__cue_switch_SNN = 0 task_stay__cue_switch_DNN = 0 task_switch__cue_stay_DDD = 0 task_switch__cue_stay_SDD = 0 task_switch__cue_stay_DSD = 0 task_switch__cue_stay_DDS = 0 task_switch__cue_stay_SSS = 0 task_switch__cue_stay_SNN = 0 task_switch__cue_stay_DNN = 0 task_switch__cue_switch_DDD = 0 task_switch__cue_switch_SDD = 0 task_switch__cue_switch_DSD = 0 task_switch__cue_switch_DDS = 0 task_switch__cue_switch_SSS = 0 task_switch__cue_switch_SNN = 0 task_switch__cue_switch_DNN = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DDD': task_stay__cue_stay_DDD += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'SDD': task_stay__cue_stay_SDD += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DSD': task_stay__cue_stay_DSD += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DDS': task_stay__cue_stay_DDS += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'SSS': task_stay__cue_stay_SSS += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'SNN': task_stay__cue_stay_SNN += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DNN': task_stay__cue_stay_DNN += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DDD': task_stay__cue_switch_DDD += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'SDD': task_stay__cue_switch_SDD += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DSD': task_stay__cue_switch_DSD += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DDS': task_stay__cue_switch_DDS += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'SSS': task_stay__cue_switch_SSS += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'SNN': task_stay__cue_switch_SNN += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DNN': task_stay__cue_switch_DNN += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DDD': task_switch__cue_stay_DDD += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'SDD': task_switch__cue_stay_SDD += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DSD': task_switch__cue_stay_DSD += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DDS': task_switch__cue_stay_DDS += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'SSS': task_switch__cue_stay_SSS += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'SNN': task_switch__cue_stay_SNN += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].shape_matching_condition == 'DNN': task_switch__cue_stay_DNN += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DDD': task_switch__cue_switch_DDD += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'SDD': task_switch__cue_switch_SDD += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DSD': task_switch__cue_switch_DSD += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DDS': task_switch__cue_switch_DDS += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'SSS': task_switch__cue_switch_SSS += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'SNN': task_switch__cue_switch_SNN += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].shape_matching_condition == 'DNN': task_switch__cue_switch_DNN += 1 print("task_stay__cue_stay_DDD = " + str(task_stay__cue_stay_DDD) + " / " + str(len(test_trials))) print("task_stay__cue_stay_SDD = " + str(task_stay__cue_stay_SDD) + " / " + str(len(test_trials))) print("task_stay__cue_stay_DSD = " + str(task_stay__cue_stay_DSD) + " / " + str(len(test_trials))) print("task_stay__cue_stay_DDS = " + str(task_stay__cue_stay_DDS) + " / " + str(len(test_trials))) print("task_stay__cue_stay_SSS = " + str(task_stay__cue_stay_SSS) + " / " + str(len(test_trials))) print("task_stay__cue_stay_SNN = " + str(task_stay__cue_stay_SNN) + " / " + str(len(test_trials))) print("task_stay__cue_stay_DNN = " + str(task_stay__cue_stay_DNN) + " / " + str(len(test_trials))) print("task_stay__cue_switch_DDD = " + str(task_stay__cue_switch_DDD) + " / " + str(len(test_trials))) print("task_stay__cue_switch_SDD = " + str(task_stay__cue_switch_SDD) + " / " + str(len(test_trials))) print("task_stay__cue_switch_DSD = " + str(task_stay__cue_switch_DSD) + " / " + str(len(test_trials))) print("task_stay__cue_switch_DDS = " + str(task_stay__cue_switch_DDS) + " / " + str(len(test_trials))) print("task_stay__cue_switch_SSS = " + str(task_stay__cue_switch_SSS) + " / " + str(len(test_trials))) print("task_stay__cue_switch_SNN = " + str(task_stay__cue_switch_SNN) + " / " + str(len(test_trials))) print("task_stay__cue_switch_DNN = " + str(task_stay__cue_switch_DNN) + " / " + str(len(test_trials))) print("task_switch__cue_stay_DDD = " + str(task_switch__cue_stay_DDD) + " / " + str(len(test_trials))) print("task_switch__cue_stay_SDD = " + str(task_switch__cue_stay_SDD) + " / " + str(len(test_trials))) print("task_switch__cue_stay_DSD = " + str(task_switch__cue_stay_DSD) + " / " + str(len(test_trials))) print("task_switch__cue_stay_DDS = " + str(task_switch__cue_stay_DDS) + " / " + str(len(test_trials))) print("task_switch__cue_stay_SSS = " + str(task_switch__cue_stay_SSS) + " / " + str(len(test_trials))) print("task_switch__cue_stay_SNN = " + str(task_switch__cue_stay_SNN) + " / " + str(len(test_trials))) print("task_switch__cue_stay_DNN = " + str(task_switch__cue_stay_DNN) + " / " + str(len(test_trials))) print("task_switch__cue_switch_DDD = " + str(task_switch__cue_switch_DDD) + " / " + str(len(test_trials))) print("task_switch__cue_switch_SDD = " + str(task_switch__cue_switch_SDD) + " / " + str(len(test_trials))) print("task_switch__cue_switch_DSD = " + str(task_switch__cue_switch_DSD) + " / " + str(len(test_trials))) print("task_switch__cue_switch_DDS = " + str(task_switch__cue_switch_DDS) + " / " + str(len(test_trials))) print("task_switch__cue_switch_SSS = " + str(task_switch__cue_switch_SSS) + " / " + str(len(test_trials))) print("task_switch__cue_switch_SNN = " + str(task_switch__cue_switch_SNN) + " / " + str(len(test_trials))) print("task_switch__cue_switch_DNN = " + str(task_switch__cue_switch_DNN) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/shape_matching_single_task_network.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 19 16:12:34 2018 @author: jamie shape_matching_single_task_network shape_matching_with_two_by_two shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] 5 blocks of 49 trials, 245 total. lowest counterbalance = 7 full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'shape_matching_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] DDD = 0 SDD = 0 DSD = 0 DDS = 0 SSS = 0 SNN = 0 DNN = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].shape_matching_condition == 'DDD': DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD': SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD': DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS': DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS': SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN': SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN': DNN += 1 print("DDD = " + str(DDD) + " / " + str(len(test_trials))) print("SDD = " + str(SDD) + " / " + str(len(test_trials))) print("DSD = " + str(DSD) + " / " + str(len(test_trials))) print("DDS = " + str(DDS) + " / " + str(len(test_trials))) print("SSS = " + str(SSS) + " / " + str(len(test_trials))) print("SNN = " + str(SNN) + " / " + str(len(test_trials))) print("DNN = " + str(DNN) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/flanker_with_cued_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 2 13:44:46 2018 @author: jamie checks trial types and timing for: flanker with two by two exp calls for 40 trials per block, 240 trials total, 6 blocks. conditions: Flanker: ['congruent','incongruent'] two by two: 2 task (switch or stay) two by two: 2 cue (switch or stay) full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'flanker_with_cued_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice task_stay__cue_stay__congruent = 0 task_stay__cue_stay__incongruent = 0 task_stay__cue_switch__congruent = 0 task_stay__cue_switch__incongruent = 0 task_switch__cue_stay__congruent = 0 task_switch__cue_stay__incongruent = 0 task_switch__cue_switch__congruent = 0 task_switch__cue_switch__incongruent = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].flanker_condition == "congruent": task_stay__cue_stay__congruent += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].flanker_condition == "incongruent": task_stay__cue_stay__incongruent += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].flanker_condition == "congruent": task_stay__cue_switch__congruent += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].flanker_condition == "incongruent": task_stay__cue_switch__incongruent += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].flanker_condition == "congruent": task_switch__cue_stay__congruent += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "stay" and test_trials.iloc[row].flanker_condition == "incongruent": task_switch__cue_stay__incongruent += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].flanker_condition == "congruent": task_switch__cue_switch__congruent += 1 elif test_trials.iloc[row].task_condition == "switch_new" and test_trials.iloc[row].cue_condition == "switch" and test_trials.iloc[row].flanker_condition == "incongruent": task_switch__cue_switch__incongruent += 1 print("task_stay__cue_stay__congruent = " + str(task_stay__cue_stay__congruent) + " / " + str(len(test_trials))) print("task_stay__cue_stay__incongruent = " + str(task_stay__cue_stay__incongruent) + " / " + str(len(test_trials))) print("task_stay__cue_switch__congruent = " + str(task_stay__cue_switch__congruent) + " / " + str(len(test_trials))) print("task_stay__cue_switch__incongruent = " + str(task_stay__cue_switch__incongruent) + " / " + str(len(test_trials))) print("task_switch__cue_stay__congruent = " + str(task_switch__cue_stay__congruent) + " / " + str(len(test_trials))) print("task_switch__cue_stay__incongruent = " + str(task_switch__cue_stay__incongruent) + " / " + str(len(test_trials))) print("task_switch__cue_switch__congruent = " + str(task_switch__cue_switch__congruent) + " / " + str(len(test_trials))) print("task_switch__cue_switch__incongruent = " + str(task_switch__cue_switch__incongruent) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/shape_matching_with_predictable_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 17:07:51 2018 @author: jamie shape_matching_with_predictable_task_switching shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] predictable_task_switching_conditions = ['congruent','incongruent'] 280 trials total, 56 trials per block, 5 blocks lowest counterbalance = 14 full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'shape_matching_with_predictable_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] switch__DDD = 0 switch__SDD = 0 switch__DSD = 0 switch__DDS = 0 switch__SSS = 0 switch__SNN = 0 switch__DNN = 0 stay__DDD = 0 stay__SDD = 0 stay__DSD = 0 stay__DDS = 0 stay__SSS = 0 stay__SNN = 0 stay__DNN = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].predictive_condition == 'switch' : switch__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].predictive_condition == 'switch': switch__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].predictive_condition == 'switch': switch__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].predictive_condition == 'switch': switch__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].predictive_condition == 'switch': switch__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].predictive_condition == 'switch': switch__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].predictive_condition == 'switch': switch__DNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].predictive_condition == 'stay': stay__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].predictive_condition == 'stay': stay__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].predictive_condition == 'stay': stay__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].predictive_condition == 'stay': stay__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].predictive_condition == 'stay': stay__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].predictive_condition == 'stay': stay__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].predictive_condition == 'stay': stay__DNN += 1 print("switch__DDD = " + str(switch__DDD) + " / " + str(len(test_trials))) print("switch__SDD = " + str(switch__SDD) + " / " + str(len(test_trials))) print("switch__DSD = " + str(switch__DSD) + " / " + str(len(test_trials))) print("switch__DDS = " + str(switch__DDS) + " / " + str(len(test_trials))) print("switch__SSS = " + str(switch__SSS) + " / " + str(len(test_trials))) print("switch__SNN = " + str(switch__SNN) + " / " + str(len(test_trials))) print("switch__DNN = " + str(switch__DNN) + " / " + str(len(test_trials))) print("stay__DDD = " + str(stay__DDD) + " / " + str(len(test_trials))) print("stay__SDD = " + str(stay__SDD) + " / " + str(len(test_trials))) print("stay__DSD = " + str(stay__DSD) + " / " + str(len(test_trials))) print("stay__DDS = " + str(stay__DDS) + " / " + str(len(test_trials))) print("stay__SSS = " + str(stay__SSS) + " / " + str(len(test_trials))) print("stay__SNN = " + str(stay__SNN) + " / " + str(len(test_trials))) print("stay__DNN = " + str(stay__DNN) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/flanker_single_task_network.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 2 12:53:40 2018 @author: jamie checks trial types for flanker single task network exp calls for 48 trials per block, 96 trials total. Half should be incompatible half should be compatible """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'flanker_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice incompatible = 0 compatible = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].condition == "compatible": compatible += 1 elif test_trials.iloc[row].condition == "incompatible": incompatible += 1 print("compatible = " + str(compatible) + " / " + str(len(test_trials))) print("incompatible = " + str(incompatible) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/directed_forgetting_single_task_network.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 15:43:22 2018 @author: jamie directed forgetting single task pos pos neg con - four conditions full counterbalancing pos - probe was in memory set neg - probe was in forget set con - probe was not in either memory or forget 80 trials total, 20/block, 4 blocks """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'directed_forgetting_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice directed_forgetting_conditions = ['pos','pos','con','neg'] pos = 0 con = 0 neg = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].directed_forgetting_condition == 'pos': pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con': con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg': neg += 1 print("pos = " + str(pos) + " / " + str(len(test_trials))) print("con = " + str(con) + " / " + str(len(test_trials))) print("neg = " + str(neg) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/stop_signal_with_go_no_go.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 17:47:39 2018 @author: jamie stop_signal_with_go_no_go SS: go, go, stop GNG: go, go, go, go, nogo 300 total trials, 60 trials per block, 5 blocks tota 15 trials minimum full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_with_go_no_go_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice SS_go__go = 0 SS_go__nogo = 0 SS_nogo__go = 0 SS_nogo__nogo = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__go += 1 elif test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__nogo += 1 elif test_trials.iloc[row].go_nogo_condition == 'go' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_nogo__go += 1 elif test_trials.iloc[row].go_nogo_condition == 'nogo' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_nogo__nogo += 1 print("SS_go__go = " + str(SS_go__go) + " / " + str(len(test_trials))) print("SS_go__nogo = " + str(SS_go__nogo) + " / " + str(len(test_trials))) print("SS_nogo__go = " + str(SS_nogo__go) + " / " + str(len(test_trials))) print("SS_nogo__nogo = " + str(SS_nogo__nogo) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/n_back_with_cued_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 16 18:12:42 2018 @author: jamie n back with two by two nback : 1back vs 2back two by two - task: stay vs switch task - 1back vs 2 back cues: stay vs switch cues - one-ago & 1-back vs two-ago & 2-back full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'n_back_with_cued_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice nback_match__task_stay__cue_stay = 0 nback_match__task_stay__cue_switch = 0 nback_match__task_switch__cue_stay = 0 nback_match__task_switch__cue_switch = 0 nback_mismatch__task_stay__cue_stay = 0 nback_mismatch__task_stay__cue_switch = 0 nback_mismatch__task_switch__cue_stay = 0 nback_mismatch__task_switch__cue_switch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].n_back_condition == "mismatch" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay": nback_mismatch__task_stay__cue_stay += 1 elif test_trials.iloc[row].n_back_condition == "mismatch" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch": nback_mismatch__task_stay__cue_switch += 1 elif test_trials.iloc[row].n_back_condition == "mismatch" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay": nback_mismatch__task_switch__cue_stay += 1 elif test_trials.iloc[row].n_back_condition == "mismatch" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch": nback_mismatch__task_switch__cue_switch += 1 elif test_trials.iloc[row].n_back_condition == "match" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay": nback_match__task_stay__cue_stay += 1 elif test_trials.iloc[row].n_back_condition == "match" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch": nback_match__task_stay__cue_switch += 1 elif test_trials.iloc[row].n_back_condition == "match" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay": nback_match__task_switch__cue_stay += 1 elif test_trials.iloc[row].n_back_condition == "match" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch": nback_match__task_switch__cue_switch += 1 print("nback_match__task_stay__cue_stay = " + str(nback_match__task_stay__cue_stay) + " / " + str(len(test_trials))) print("nback_match__task_stay__cue_switch = " + str(nback_match__task_stay__cue_switch) + " / " + str(len(test_trials))) print("nback_match__task_switch__cue_stay = " + str(nback_match__task_switch__cue_stay) + " / " + str(len(test_trials))) print("nback_match__task_switch__cue_switch = " + str(nback_match__task_switch__cue_switch) + " / " + str(len(test_trials))) print("nback_mismatch__task_stay__cue_stay = " + str(nback_mismatch__task_stay__cue_stay) + " / " + str(len(test_trials))) print("nback_mismatch__task_stay__cue_switch = " + str(nback_mismatch__task_stay__cue_switch) + " / " + str(len(test_trials))) print("nback_mismatch__task_switch__cue_stay = " + str(nback_mismatch__task_switch__cue_stay) + " / " + str(len(test_trials))) print("nback_mismatch__task_switch__cue_switch = " + str(nback_mismatch__task_switch__cue_switch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/cued_task_switching_single_task.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 4 10:10:39 2018 @author: jamie two by two single task for network grant 4 blocks of 48 trials, 192 total task switch: stay vs switch cue switch: stay vs switch full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'cued_task_switching_single_task_network_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice task_stay__cue_stay = 0 task_stay__cue_switch = 0 task_switch__cue_stay = 0 task_switch__cue_switch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay": task_stay__cue_stay += 1 elif test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch": task_stay__cue_switch += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay": task_switch__cue_stay += 1 elif test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch": task_switch__cue_switch += 1 print("task_stay__cue_stay = " + str(task_stay__cue_stay) + " / " + str(len(test_trials))) print("task_stay__cue_switch = " + str(task_stay__cue_switch) + " / " + str(len(test_trials))) print("task_switch__cue_stay = " + str(task_switch__cue_stay) + " / " + str(len(test_trials))) print("task_switch__cue_switch = " + str(task_switch__cue_switch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/go_nogo_with_cued_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 16 19:18:55 2018 @author: jamie go_nogo_with_two_by_two go-nogo: go, go, go, go, stop two by two: task: stay vs switch cues: stay vs switch full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'go_nogo_with_cued_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice gng_go__task_stay__cue_stay = 0 gng_go__task_stay__cue_switch = 0 gng_go__task_switch__cue_stay = 0 gng_go__task_switch__cue_switch = 0 gng_nogo__task_stay__cue_stay = 0 gng_nogo__task_stay__cue_switch = 0 gng_nogo__task_switch__cue_stay = 0 gng_nogo__task_switch__cue_switch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].go_no_go_condition == "go" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay": gng_go__task_stay__cue_stay += 1 elif test_trials.iloc[row].go_no_go_condition == "go" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch": gng_go__task_stay__cue_switch += 1 elif test_trials.iloc[row].go_no_go_condition == "go" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay": gng_go__task_switch__cue_stay += 1 elif test_trials.iloc[row].go_no_go_condition == "go" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch": gng_go__task_switch__cue_switch += 1 elif test_trials.iloc[row].go_no_go_condition == "nogo" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "stay": gng_nogo__task_stay__cue_stay += 1 elif test_trials.iloc[row].go_no_go_condition == "nogo" and test_trials.iloc[row].task_condition == "stay" and test_trials.iloc[row].cue_condition == "switch": gng_nogo__task_stay__cue_switch += 1 elif test_trials.iloc[row].go_no_go_condition == "nogo" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "stay": gng_nogo__task_switch__cue_stay += 1 elif test_trials.iloc[row].go_no_go_condition == "nogo" and test_trials.iloc[row].task_condition == "switch" and test_trials.iloc[row].cue_condition == "switch": gng_nogo__task_switch__cue_switch += 1 print("gng_go__task_stay__cue_stay = " + str(gng_go__task_stay__cue_stay) + " / " + str(len(test_trials))) print("gng_go__task_stay__cue_switch = " + str(gng_go__task_stay__cue_switch) + " / " + str(len(test_trials))) print("gng_go__task_switch__cue_stay = " + str(gng_go__task_switch__cue_stay) + " / " + str(len(test_trials))) print("gng_go__task_switch__cue_switch = " + str(gng_go__task_switch__cue_switch) + " / " + str(len(test_trials))) print("gng_nogo__task_stay__cue_stay = " + str(gng_nogo__task_stay__cue_stay) + " / " + str(len(test_trials))) print("gng_nogo__task_stay__cue_switch = " + str(gng_nogo__task_stay__cue_switch) + " / " + str(len(test_trials))) print("gng_nogo__task_switch__cue_stay = " + str(gng_nogo__task_switch__cue_stay) + " / " + str(len(test_trials))) print("gng_nogo__task_switch__cue_switch = " + str(gng_nogo__task_switch__cue_switch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/go_nogo_with_shape_matching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 11:58:46 2018 @author: jamie go_nogo_with_shape_matching GNG: ['go','go','go','go','nogo'] Shape: ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] 700 total trials, 140 per block, 5 blocks total 35 minimum trials full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'go_nogo_with_shape_matching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice shape_matching_conditions = ['DDD','SDD','DSD','DDS','SSS','SNN','DNN'] gng_go__DDD = 0 gng_go__SDD = 0 gng_go__DSD = 0 gng_go__DDS = 0 gng_go__SSS = 0 gng_go__SNN = 0 gng_go__DNN = 0 gng_nogo__DDD = 0 gng_nogo__SDD = 0 gng_nogo__DSD = 0 gng_nogo__DDS = 0 gng_nogo__SSS = 0 gng_nogo__SNN = 0 gng_nogo__DNN = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].go_nogo_condition == 'go': gng_go__DNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDD' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__DDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'SDD' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__SDD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DSD' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__DSD += 1 elif test_trials.iloc[row].shape_matching_condition == 'DDS' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__DDS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SSS' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__SSS += 1 elif test_trials.iloc[row].shape_matching_condition == 'SNN' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__SNN += 1 elif test_trials.iloc[row].shape_matching_condition == 'DNN' and test_trials.iloc[row].go_nogo_condition == 'nogo': gng_nogo__DNN += 1 print("gng_go__DDD = " + str(gng_go__DDD) + " / " + str(len(test_trials))) print("gng_go__SDD = " + str(gng_go__SDD) + " / " + str(len(test_trials))) print("gng_go__DSD = " + str(gng_go__DSD) + " / " + str(len(test_trials))) print("gng_go__DDS = " + str(gng_go__DDS) + " / " + str(len(test_trials))) print("gng_go__SSS = " + str(gng_go__SSS) + " / " + str(len(test_trials))) print("gng_go__SNN = " + str(gng_go__SNN) + " / " + str(len(test_trials))) print("gng_go__DNN = " + str(gng_go__DNN) + " / " + str(len(test_trials))) print("gng_nogo__DDD = " + str(gng_nogo__DDD) + " / " + str(len(test_trials))) print("gng_nogo__SDD = " + str(gng_nogo__SDD) + " / " + str(len(test_trials))) print("gng_nogo__DSD = " + str(gng_nogo__DSD) + " / " + str(len(test_trials))) print("gng_nogo__DDS = " + str(gng_nogo__DDS) + " / " + str(len(test_trials))) print("gng_nogo__SSS = " + str(gng_nogo__SSS) + " / " + str(len(test_trials))) print("gng_nogo__SNN = " + str(gng_nogo__SNN) + " / " + str(len(test_trials))) print("gng_nogo__DNN = " + str(gng_nogo__DNN) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/directed_forgetting_with_flanker.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 20:44:48 2018 @author: jamie directed_forgetting_with_flanker directed: pos pos neg con shape matching: congruent incongruent 8 = lowest number of trials full counterbalancing 160 trials total, 32 per block, 5 blocks """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'directed_forgetting_with_flanker_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice directed_conditions = ['pos','pos','con','neg'] congruent__pos = 0 congruent__con = 0 congruent__neg = 0 incongruent__pos = 0 incongruent__con = 0 incongruent__neg = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].flanker_condition == 'congruent': congruent__neg += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].flanker_condition == 'incongruent': incongruent__neg += 1 print("congruent__pos = " + str(congruent__pos) + " / " + str(len(test_trials))) print("congruent__con = " + str(congruent__con) + " / " + str(len(test_trials))) print("congruent__neg = " + str(congruent__neg) + " / " + str(len(test_trials))) print("incongruent__pos = " + str(incongruent__pos) + " / " + str(len(test_trials))) print("incongruent__con = " + str(incongruent__con) + " / " + str(len(test_trials))) print("incongruent__neg = " + str(incongruent__neg) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/stop_signal_with_predictable_task_switching.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 15:47:18 2018 @author: jamie stop_signal_with_predictable_task_switching SS: go, go, stop Predictive: 2 (switch or stay) by 2 (mag or parity) 240 trials tota, 48 trials per block, 5 blocks 12 minimum trials full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_with_predictable_task_switching_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_with_stop for practice stop_signal_conditions = ['go','stop'] #shapes = circle, square, triangle, pentagon go_stay = 0 go_switch = 0 stop_stay = 0 stop_switch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].stop_signal_condition == 'go' and test_trials.iloc[row].predictive_condition == 'stay': go_stay += 1 elif test_trials.iloc[row].stop_signal_condition == 'go' and test_trials.iloc[row].predictive_condition == 'switch': go_switch += 1 elif test_trials.iloc[row].stop_signal_condition == 'stop' and test_trials.iloc[row].predictive_condition == 'stay': stop_stay += 1 elif test_trials.iloc[row].stop_signal_condition == 'stop' and test_trials.iloc[row].predictive_condition == 'switch': stop_switch += 1 print("go_stay = " + str(go_stay) + " / " + str(len(test_trials))) print("go_switch = " + str(go_switch) + " / " + str(len(test_trials))) print("stop_stay = " + str(stop_stay) + " / " + str(len(test_trials))) print("stop_switch = " + str(stop_switch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array') <file_sep>/behavioral_QC_scripts/stop_signal_with_n_back.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 17:02:47 2018 @author: jamie stop_signal_with_n_back SS: go, go, stop N-Back: mismatch, mismatch, mismatch, mismatch, match delays - 1,2,3 270 total trials, 45 trials per block, 6 blocks 15 minimum trials full counterbalancing note: this nback must have blocks % 3 == 0, need equal amount of blocks per delay """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_with_n_back_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice nback_conditions = ['match','mismatch'] delays = ['1','2','3'] SS_stop__one_match = 0 SS_stop__one_mismatch = 0 SS_stop__two_match = 0 SS_stop__two_mismatch = 0 SS_stop__three_match = 0 SS_stop__three_mismatch = 0 SS_go__one_match = 0 SS_go__one_mismatch = 0 SS_go__two_match = 0 SS_go__two_mismatch = 0 SS_go__three_match = 0 SS_go__three_mismatch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__three_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__three_mismatch += 1 print("SS_stop__one_match = " + str(SS_stop__one_match) + " / " + str(len(test_trials))) print("SS_stop__one_mismatch = " + str(SS_stop__one_mismatch) + " / " + str(len(test_trials))) print("SS_stop__two_match = " + str(SS_stop__two_match) + " / " + str(len(test_trials))) print("SS_stop__two_mismatch = " + str(SS_stop__two_mismatch) + " / " + str(len(test_trials))) print("SS_stop__three_match = " + str(SS_stop__three_match) + " / " + str(len(test_trials))) print("SS_stop__three_mismatch = " + str(SS_stop__three_mismatch) + " / " + str(len(test_trials))) print("SS_go__one_match = " + str(SS_go__one_match) + " / " + str(len(test_trials))) print("SS_go__one_mismatch = " + str(SS_go__one_mismatch) + " / " + str(len(test_trials))) print("SS_go__two_match = " + str(SS_go__two_match) + " / " + str(len(test_trials))) print("SS_go__two_mismatch = " + str(SS_go__two_mismatch) + " / " + str(len(test_trials))) print("SS_go__three_match = " + str(SS_go__three_match) + " / " + str(len(test_trials))) print("SS_go__three_mismatch = " + str(SS_go__three_mismatch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/n_back_with_directed_forgetting.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 22:27:26 2018 @author: jamie n_back_with_directed_forgetting N-Back: ['match','mismatch','mismatch','mismatch','mismatch'] Directed Forgetting: ['forget','remember'] 10 minimum trials full counterbalancing 240 total trials, 40 trials per block, 6 blocks total """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'n_back_with_directed_forgetting_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice nback_conditions = ['match','mismatch'] delays = ['1','2','3'] directed_rememember__one_match = 0 directed_rememember__one_mismatch = 0 directed_rememember__two_match = 0 directed_rememember__two_mismatch = 0 directed_rememember__three_match = 0 directed_rememember__three_mismatch = 0 directed_forget__one_match = 0 directed_forget__one_mismatch = 0 directed_forget__two_match = 0 directed_forget__two_mismatch = 0 directed_forget__three_match = 0 directed_forget__three_mismatch = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].directed_forgetting_condition == 'remember': directed_rememember__one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].directed_forgetting_condition == 'remember': directed_rememember__one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].directed_forgetting_condition == 'remember': directed_rememember__two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].directed_forgetting_condition == 'remember': directed_rememember__two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].directed_forgetting_condition == 'remember': directed_rememember__three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].directed_forgetting_condition == 'remember': directed_rememember__three_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].directed_forgetting_condition == 'forget': directed_forget__one_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 1 and test_trials.iloc[row].directed_forgetting_condition == 'forget': directed_forget__one_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].directed_forgetting_condition == 'forget': directed_forget__two_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 2 and test_trials.iloc[row].directed_forgetting_condition == 'forget': directed_forget__two_mismatch += 1 elif test_trials.iloc[row].n_back_condition == 'match' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].directed_forgetting_condition == 'forget': directed_forget__three_match += 1 elif test_trials.iloc[row].n_back_condition == 'mismatch' and test_trials.iloc[row].delay == 3 and test_trials.iloc[row].directed_forgetting_condition == 'forget': directed_forget__three_mismatch += 1 print("directed_rememember__one_match = " + str(directed_rememember__one_match) + " / " + str(len(test_trials))) print("directed_rememember__one_mismatch = " + str(directed_rememember__one_mismatch) + " / " + str(len(test_trials))) print("directed_rememember__two_match = " + str(directed_rememember__two_match) + " / " + str(len(test_trials))) print("directed_rememember__two_mismatch = " + str(directed_rememember__two_mismatch) + " / " + str(len(test_trials))) print("directed_rememember__three_match = " + str(directed_rememember__three_match) + " / " + str(len(test_trials))) print("directed_rememember__three_mismatch = " + str(directed_rememember__three_mismatch) + " / " + str(len(test_trials))) print("directed_forget__one_match = " + str(directed_forget__one_match) + " / " + str(len(test_trials))) print("directed_forget__one_mismatch = " + str(directed_forget__one_mismatch) + " / " + str(len(test_trials))) print("directed_forget__two_match = " + str(directed_forget__two_match) + " / " + str(len(test_trials))) print("directed_forget__two_mismatch = " + str(directed_forget__two_mismatch) + " / " + str(len(test_trials))) print("directed_forget__three_match = " + str(directed_forget__three_match) + " / " + str(len(test_trials))) print("directed_forget__three_mismatch = " + str(directed_forget__three_mismatch) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/behavioral_QC_scripts/stop_signal_with_directed_forgetting.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 21 16:53:37 2018 @author: jamie stop_signal_with_directed_forgetting SS: go, go, stop Directed: ['pos', 'pos', 'neg', 'con'] 180 total trials, 36 trials per block, 5 blocks full counterbalancing 12 minimum trials """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'stop_signal_with_directed_forgetting_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice directed_forgetting_conditions = ['pos','pos','con','neg'] SS_stop__pos = 0 SS_stop__con = 0 SS_stop__neg = 0 SS_go__pos = 0 SS_go__con = 0 SS_go__neg = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].stop_signal_condition == 'stop': SS_stop__neg += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].stop_signal_condition == 'go': SS_go__neg += 1 print("SS_stop__pos = " + str(SS_stop__pos) + " / " + str(len(test_trials))) print("SS_stop__con = " + str(SS_stop__con) + " / " + str(len(test_trials))) print("SS_stop__neg = " + str(SS_stop__neg) + " / " + str(len(test_trials))) print("SS_go__pos = " + str(SS_go__pos) + " / " + str(len(test_trials))) print("SS_go__con = " + str(SS_go__con) + " / " + str(len(test_trials))) print("SS_go__neg = " + str(SS_go__neg) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')<file_sep>/utils.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 8 17:46:28 2019 @author: jamie Intended to be a script where all functions that are utilized in 36 experiments are """ import pandas as pd path = '/Users/jamie/Desktop/network_output/second_round_of_subs_9assignment_HIT/' worker_id = 'A17MUS17DFQZ4P' task = 'n_back_with_predictable_task_switching' full_path = path + worker_id + '/' + task + '_' + worker_id + '.csv' df = pd.read_csv(full_path) def getAvgRT(): <file_sep>/behavioral_QC_scripts/predictable_task_switching_with_directed_forgetting.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 20 18:20:44 2018 @author: jamie predictable_task_switching_with_directed_forgetting 160 total trials, 32 trials per block, 5 blocks predictive: switch or stay directed: pos pos neg con full counterbalancing """ import pandas as pd input_path = "/Users/jamie/Desktop/network_output/final/A3NNB4LWIKA3BQ/modified_for_analysis/" task = 'predictable_task_switching_with_directed_forgetting_A3NNB4LWIKA3BQ.csv' df = pd.read_csv(input_path + task) test_trials = df[(df.trial_id == "test_trial")] #practice_trial for practice directed_forgetting_conditions = ['pos','pos','con','neg'] switch__pos = 0 switch__con = 0 switch__neg = 0 stay__pos = 0 stay__con = 0 stay__neg = 0 for row in range(0,len(test_trials)): if test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].predictive_condition == 'switch': switch__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].predictive_condition == 'switch': switch__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].predictive_condition == 'switch': switch__neg += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'pos' and test_trials.iloc[row].predictive_condition == 'stay': stay__pos += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'con' and test_trials.iloc[row].predictive_condition == 'stay': stay__con += 1 elif test_trials.iloc[row].directed_forgetting_condition == 'neg' and test_trials.iloc[row].predictive_condition == 'stay': stay__neg += 1 print("switch__pos = " + str(switch__pos) + " / " + str(len(test_trials))) print("switch__con = " + str(switch__con) + " / " + str(len(test_trials))) print("switch__neg = " + str(switch__neg) + " / " + str(len(test_trials))) print("stay__pos = " + str(stay__pos) + " / " + str(len(test_trials))) print("stay__con = " + str(stay__con) + " / " + str(len(test_trials))) print("stay__neg = " + str(stay__neg) + " / " + str(len(test_trials))) suspect_trial_timing = [] for row in range(0,len(df)-1): actual_duration = df.iloc[row + 1].time_elapsed - df.iloc[row].time_elapsed expected_duration = df.iloc[row + 1].block_duration + df.iloc[row].timing_post_trial if df.iloc[row + 1].trial_type == 'poldrack-categorize': expected_duration += 500 if abs(expected_duration - actual_duration) > 50: suspect_trial_timing.append(str(df.iloc[row + 1].trial_index) + '_' + task + '_' + str(abs(expected_duration - actual_duration)) + '_' + str(actual_duration) + '_' + df.iloc[row + 1].trial_id + '_' + df.iloc[row + 1].trial_type) if len(suspect_trial_timing) == 0: print('no suspect timing issues') else: print('check suspect_trial_timing array')
6292d9b85c357a5e7752e8f58e9518d319254877
[ "Markdown", "Python" ]
37
Python
jkl071/network-attack-analysis
5e8cf93243cb5a7dab21a823577f0c9db36fd15d
a4142aef44abb01f7163cc25dd7cca35eb94ee53
refs/heads/main
<repo_name>simrit1/CLA<file_sep>/compress/pca.py ''' Implementation of Principal Component Analysis. ''' import numpy as np #Principal Component Analysis based on Eigenvector and Eigenvalues def compute_PCs(X): #Step 1: Center Data arround 0 X_centered = (X - np.mean(X, axis=0)) #Step 2: Compute Covariance Matrix covariance_matrix = np.cov(X_centered.T) #Step 3: Compute eigenvector and eigenvalues for the Covariance Matrix eig_vals, eig_vecs = np.linalg.eig(covariance_matrix) #Step 4: Sort Eigenvalues based on highest inforamtion gain fraction_variance_explained = eig_vals / np.sum(eig_vals) idx = np.argsort(-fraction_variance_explained) principal_components = eig_vecs[:, idx].T return principal_components, fraction_variance_explained #Select Principal Components based on percentage of information explained def select_PCs(principal_components, variance_explained, percent_variance=0.9): #Computing the amount of Components necessary to explain the desired percent i = 0 var_expl = 0 while(var_expl < percent_variance): var_expl += variance_explained[i] i+=1 variance_explained_kept = np.array(variance_explained[0:i]) principal_components_kept = np.array(principal_components[0:i]) return principal_components_kept, variance_explained_kept #Compute PCA scores based on principal Components def compute_PCA(X, principal_components): pc_scores = np.dot(principal_components, X.T) return pc_scores #Complete PCA projection for Data def PCA(X, information_explained=0.9): principal_components, variance_explained = compute_PCs(X) selected_pcs, information = select_PCs(principal_components, variance_explained) pc_scores = compute_PCA(X, selected_pcs) return pc_scores <file_sep>/compress/test_vq.py """ Simple test for Vector Qunatization. """ import vector_quantization as vq import numpy as np def vq_clustering_test(): sample_data = [[25,34,22,27,33,33,31,22,35,34,67,54,57,43,50,57,59,52,65,47,49,48,35,33,44,45,38,43,51,46],[79,51,53,78,59,74,73,57,69,75,51,32,40,47,53,36,35,58,59,50,25,20,14,12,20,5,29,27,8,7]] sample_data_transformed = np.array(sample_data).T clustering, vector_values = vq.vector_quantization(sample_data_transformed, vectors=3) j = 2 k = 0 for i in range(len(clustering)-1): if(clustering[i] != clustering[i+1]): j -= 1 else: k+=1 assert(j == 0 and k == 27), ('Vector Quantization fails for simple clustering task.') if __name__ == '__main__': vq_clustering_test() <file_sep>/README.txt # Compression Algorithms This source code offers tools for simple string compression. Mainly suitable for ilustrative purposes and experiments. 1) For Entropy type: - includes Huffman encoding scheme for binary encoding - includes Shannon-Fano-Elias encoding 2) For Dictionary type: - includes plain LZ77 encoding - includes LZW coding based on LZ78 3) For Transforms: - includes plain Burrows Wheeler Transform - includes bijective Burrows Wheeler Transform based on Lyndon Words - includes Move-To-Front encoding 4) For Pattern Recognition: - includes Decision Tree based on entropy of information - includes Vector Quantization based on K-Means - includes Principal Component Analysis based on Eigenvectors and Eigenvalues - includes Boosting based on Decision Tree stumps - includes Random Forest and Bagged Trees based on Decision Trees To get started have a look at the test files to see how to use compression and pattern recognition. <file_sep>/compress/random_forest.py ''' Implementation of Random Forest Algorithm based on Decision Trees and giving option of simple Bagged Trees. ''' import decisiontree as dt import random as rdm import numpy as np import math import cla_util as util #Sample from the given set data points def boots_trap(X, y, sample_size=None): samples = len(X) if(sample_size is None): sample_size = int(samples/2) + 1 set = [] target = [] for i in range(sample_size): pick = rdm.randrange(samples) set.append(X[pick]) target.append(y[pick]) return set, target #Create a forest of boots trap samples def bagged_trees(X, y, tree_number=10, tree_depth=2, sample_size=None, split=util.entropy, random_forest_mode=False, boots_trapping = True): forest = [] for tree in range(tree_number): if(boots_trapping): sample_set, target_set = boots_trap(X, y, sample_size) else: sample_set, target_set = X, y dtree = dt.build_tree(np.array(sample_set), target_set, 0, max_depth=tree_depth, split=split, random_forest=random_forest_mode) forest.append(dtree) return forest #Use forest of decision trees to predict data via majority vote def forest_predict(X, forest): y_prediction = [] for x in X: vote = [None]*len(forest) for tree in range(len(forest)): vote[tree] = dt.predict_tree(forest[tree], x) decision = np.argmax(np.bincount(vote)) y_prediction.append(decision) return y_prediction #Create random forest using limited size of features for each split def random_forest(X, y, tree_number=10, tree_depth=2, sample_size=None, split=util.entropy, random_forest_mode=True, boots_trapping=True): forest = bagged_trees(X, y, tree_number=tree_number, tree_depth=tree_depth, sample_size=None, split=util.entropy, random_forest_mode=False, boots_trapping=boots_trapping) return forest <file_sep>/compress/vector_quantization.py """ Implementation of Vector Quantization based on simple K-Means Clustering. """ import numpy as np import random import cla_util as util MAX = 9999999999999999 #Vector Quantization algorithm for clustering def vector_quantization(X, vectors=5, epsilon=1E-4, max_iteration=100, distance=util.euclidean): X = np.array(X) n = len(X[0]) m = len(X) min, max = [], [] #Setup 1: Get min and max values for all attributes for i in range(n): min.append(np.amin(X[:,i])) max.append(np.amax(X[:,i])) means = [] #Setup 2: Initialize random starting points based on random samples for i in range(vectors): mean = [] for j in range(n): mean.append(random.uniform(min[j], max[j])) means.append(mean) clusters = [0]*m iterations = 0 eps = MAX #Start main process of clustering points while(iterations < max_iteration and eps > epsilon): #Step 1: Cluster points to closest vector for i in range(m): min = MAX for j in range(vectors): dist = distance(X[i],means[j]) if(dist < min): min = dist clusters[i] = j #Step 2: Optimize distance of vector to clustered points eps = 0 for i in range(vectors): epsilon_diff = 0 indices = [j for j, x in enumerate(clusters) if x == i] sum = [0]*n for j in range(len(indices)): sum += X[indices[j]] if(len(indices) > 0): means_old = means[i] means[i] = [x / len(indices) for x in sum] epsilon_diff = distance(means[i], means_old) eps += epsilon_diff iterations += 1 return clusters, means <file_sep>/compress/arirthmetic.py ''' Implementation of the Shannon-Fano-Elias Coding and Real Arithmetic Coding. ''' import math import cla_util as util import datastructures as ds #Plain Shannon Fano Elias coding, less efficient than Huffman def shannon_fano_elias_coding(omega): n = len(omega) alphabet = util.word_alphabet(omega) m = len(alphabet) dict = util.dictionary(alphabet) bits = "" word_count = util.letter_count(omega, dict, alphabet) word_prob = [count / n for count in word_count] sum = 0 notebook = ds.CodeBook() for i in range(m): prob = word_prob[i] sum += prob Fx = sum - 0.5*prob bits = util.decimal2binary(Fx) bits = bits[2:len(bits)] encoding_length = math.ceil(math.log(1/prob, 2)) + 1 while(len(bits) < encoding_length): bits += '0' if(len(bits) > encoding_length): bits = bits[0:encoding_length] notebook.insert(alphabet[i], bits) return notebook def real_arithmetic_coding(omega, word): n = len(omega) alphabet = util.word_alphabet(omega) m = len(alphabet) dict = util.dictionary(alphabet) word_count = util.letter_count(omega, dict, alphabet) word_prob = [count / n for count in word_count] prob_ranges = [] prob_sum = 0 for i in range(m): start = prob_sum prob_sum += word_prob[i] prob_ranges.append([start, prob_sum]) for j in range(len(word)-1): index = dict[word[j]] low = prob_ranges[index][0] high = prob_ranges[index][1] prob = high - low prob_sum = low prob_ranges = [] for i in range(m): start = prob_sum prob_sum += word_prob[i] * prob prob_ranges.append([start, prob_sum]) last_letter = word[len(word)-1] last_letter_index = dict[last_letter] final_range = prob_ranges[last_letter_index] bits_low = util.decimal2binary(final_range[0]) bits_high = util.decimal2binary(final_range[1]) return bits_low, bits_high low, high = (real_arithmetic_coding("aabbbbbccc", "bac")) print(low, high) <file_sep>/compress/huffman.py ''' Implementation of the Huffman coding. ''' import cla_util as util import datastructures as ds #Encoding procedure for binary huffman codes def huffman_coding(omega): n = len(omega) q = ds.Heap() alphabet = util.word_alphabet(omega) dict = util.dictionary(alphabet) bits = [""]*len(alphabet) word_count = util.letter_count(omega, dict, alphabet) word_prob = [count / n for count in word_count] for i in range(len(word_prob)): q.insert([word_prob[i], i]) #Encode least probable characters with one further bit while(q.size > 1): min1 = q.getMin() q.extractMin() min2 = q.getMin() q.extractMin() min2[0] += min1[0] #Add 0 to characters in set 2 for i in range(1, len(min2)): bits[min2[i]] += "0" #ADD 1 to characters in set 1 for i in range(1, len(min1)): min2.append(min1[i]) bits[min1[i]] += "1" q.insert(min2) #Create code book based on encoding code_words = ds.CodeBook() for i in range (len(bits)): code = bits[i][::-1] code_words.insert(i, code) return(code_words) #Compress word based on codebook def huffman_compress(omega, code_book): binary_code = "" for letter in omega: binary_code += code_book.getBinary(letter) return(binary_code) #Decompress code based on codebook def huffman_decompress(eta, code_book): n = len(eta) current_word = "" omega = [] for bit in eta: current_word += bit if(code_book.hasBinary(current_word)): omega.append(code_book.getWord(current_word)) current_word = "" return(omega) <file_sep>/README.md # CLA **C**ompression and **L**earning **A**lgorithms offers compression and learning algorithms. The implementation is mainly suitable for ilustrative purposes of the interconection of the two topics. The source code offers the following: 1) For Entropy type compression: - includes Huffman encoding scheme for binary coding - includes Shannon-Fano-Elias coding 2) For Dictionary type compression: - includes plain LZ77 encoding - includes LZW coding based on LZ78 3) For Transforms: - includes plain Burrows Wheeler Transform - includes bijective Burrows Wheeler Transform based on Lyndon Words - includes Move-To-Front encoding 4) For Pattern Recognition: - includes Decision Tree based on entropy of information - includes Vector Quantization based on K-Means - includes Principal Component Analysis based on Eigenvectors and Eigenvalues - includes Boosting based on Decision Tree stumps - includes Random Forest and Bagged Trees based on Decision Trees To **get started** have a look at the test files to see how to use compression and pattern recognition. <file_sep>/compress/svm.py ''' Implementation of Support Vector Machine ''' <file_sep>/compress/bwt.py """ An implementation of the plain Burrows Wheeler Transform and a bijective variant using Lyndon Factors of the word. """ import cla_util as util import datastructures as ds #Computes the Burrows Wheeler Transform based on a Suffix Array def BWT(omega): alpha = omega + "$" + omega sa = ds.SuffixArray(omega + "$") eta = "" i = 0 n = len(omega) #Compute the preceding letters of the sorted letters while(i <= n): eta += alpha[sa[i] + n] i+=1 return eta #Computes Permutation Table to reverse the Burrows Wheeler Transform def Permutation(eta): n = len(eta) pi = [0]*n alphabet = util.word_alphabet(eta) Lambda = [0]*len(alphabet) alphabet = sorted(alphabet) sigma = util.dictionary(alphabet) Lambda = util.letter_count(eta, sigma, alphabet) theta = [0]*len(Lambda) i = 1 #Compute how many letters occure before in the sorted list while(i < len(theta)): theta[i] = theta[i-1] + Lambda[i-1] i += 1 #Compute the final Permutation for i in range(n): letter = sigma[eta[i]] pi[i] = theta[letter] theta[letter] += 1 return(pi) #Retrive the original word from the transformed word def BWT_inv(eta): pi = Permutation(eta) omega = "" n = len(eta) k = 0 i = 0 #Backtrack the original word with help of the permutation table for i in range(n-1): omega += eta[k] k = pi[k] return omega[::-1] #Implementation of Duval's Algorithm for Lyndon Factors def duval(w): i = 0 n = len(w) factors = [] while(i < n): j = i + 1 k = i while(j < n and w[k] <= w[j]): if(w[k] < w[j]): k = i else: k += 1 j += 1 while(i <= k): factors.append(w[i:i+j-k]) i += j-k return(factors) #Computes the bijective Wheeler Transform with Lyndon factors def BBWT(omega): #Compute all Lyndon factors factors = duval(omega) chi = util.cyclic_shifts(factors) #Sorting based on comparing infinite periodic repetitions tau = util.ipr_sort(chi) eta = "" #Strip last Characters of all sorted shiffted factors for i in range(len(tau)): eta += tau[i][-1] return(eta) #Retrive the original word of the bijective transformed string def BBWT_inv(eta): pi = Permutation(eta) omega = "" n = len(eta) nu = [False]*n k = 0 j = 0 #Backtrack the original word with help of the permutation table for i in range(n): #If letter has been used proceed to the next factor while(nu[k] != False): j += 1 k = j omega += eta[k] nu[k] = True k = pi[k] return omega[::-1] <file_sep>/compress/test_ensemble.py ''' Test for ensemble methods. ''' import decisiontree as dt import boosting as boost import cla_util as util import random_forest as rf from sklearn.datasets import load_wine from sklearn import tree #Assert that the decision tree classifier achieves comparable results sk learn tree def test_decisiontree_accuracy(): X, t = load_wine(return_X_y=True) X_train, X_test, t_train, t_test = util.split_data(X, t) dtree = dt.build_tree(X_train, t_train, 0, max_depth=3, n_labels=3) count = 0 for i in range(len(X_test)): if(t_test[i] == dt.predict_tree(dtree, X_test[i])): count += 1 dt_score = count/len(t_test) clf = tree.DecisionTreeClassifier(criterion="entropy", max_depth=3) clf = clf.fit(X_train, t_train) predsk = clf.predict(X_test) skcounter = 0 for i in range(len(predsk)): if(predsk[i] == t_test[i]): skcounter += 1 sk_score = skcounter/len(t_test) assert(sk_score-0.1 <= dt_score), ('Prediction of decision tree score ', dt_score, ' has to be at least int the target score ', sk_score-0.1) #Assert that boosted classifier achieves fine results def test_boosting_accuracy(): X, t = load_wine(return_X_y=True) X_train, X_test, t_train, t_test = util.split_data(X, t, seed=0) classifier = boost.train_boosting(X_train, t_train, n_learner=25) y_predictions = boost.predict_boosting(X_test, classifier) count = 0 for i in range(len(t_test)): if(y_predictions[i] == t_test[i]): count +=1 boost_score = count/len(t_test) assert(boost_score > 0.9), ('Prediction of boosted classifier not good enough with ', boost_score, ' accuracy.') #Assert that bagged trees classifier achieves fine results def test_bagged_trees_accuracy(): X, t = load_wine(return_X_y=True) X_train, X_test, t_train, t_test = util.split_data(X, t, seed=0) forest = rf.bagged_trees(X_train,t_train) predictions = rf.forest_predict(X_test, forest) count = 0 for i in range(len(t_test)): if(predictions[i] == t_test[i]): count += 1 bagged_score = count/len(t_test) assert(bagged_score > 0.8), ('Prediction of bagged trees not good enough with ', bagged_score, ' accuracy.') #Assert that random_forest classifier achieves fine results def test_random_forest_accuracy(): X, t = load_wine(return_X_y=True) X_train, X_test, t_train, t_test = util.split_data(X, t, seed=0) forest = rf.random_forest(X_train,t_train) predictions = rf.forest_predict(X_test, forest) count = 0 for i in range(len(t_test)): if(predictions[i] == t_test[i]): count += 1 rf_score = count/len(t_test) assert(rf_score > 0.8), ('Prediction of bagged trees not good enough with ', rf_score, ' accuracy.') #Assert that random_forest classifier achieves fine results via cross validation def test_random_forest_cv_accuracy(): X, t = load_wine(return_X_y=True) cv_data = util.crossvalidate_data(X, t, seed=0) K = len(cv_data) rf_score = 0 for i in range(K): X_train = cv_data[i][0] t_train = cv_data[i][1] X_test = cv_data[i][2] t_test = cv_data[i][3] forest = rf.random_forest(X_train,t_train) predictions = rf.forest_predict(X_test, forest) count = 0 for i in range(len(t_test)): if(predictions[i] == t_test[i]): count += 1 rf_score += count/len(t_test) rf_score = rf_score/5 assert(rf_score > 0.8), ('Prediction of bagged trees not good enough with ', rf_score, ' accuracy.') if __name__ == '__main__': test_decisiontree_accuracy() test_boosting_accuracy() test_bagged_trees_accuracy() test_random_forest_accuracy() test_random_forest_cv_accuracy() <file_sep>/compress/tutorial_bwt.py ''' Example of using the implemented Burrows Wheeler Transform. ''' import bwt #Read in the book Ulysses of <NAME> as a string file = open("sample_data/ulysses.txt") string = file.read().replace("\n", " ") file.close() #Use the first 50000 characters of the complete book string = string[0:50000] #Transform string based on bijective Burrows Wheeler Transform enc = bwt.BBWT(string) #Recover original string using the transformed string dec = bwt.BBWT_inv(enc) #write transformed string as text file text_file = open("sample_data/encoded.txt", "wt") n = text_file.write(enc) text_file.close() #write recovered string as text file text_file = open("sample_data/decoded.txt", "wt") n = text_file.write(dec) text_file.close() <file_sep>/compress/decisiontree.py ''' Implementation of decision tree with splitting based on entropy. ''' import numpy as np import cla_util as util import math import random as rdm MAX = 999999999999999999999999999 #Node of decision tree indicating which subset to consider in next level class Node: def __init__(self, left, right, n_feat, threshold): self.left = left self.right = right self.n_feat = n_feat self.threshold = threshold def getInfo(self): return(self.n_feat, self.threshold) def hasChild(self): return True def predict_tree(self, x): if(self.hasChild()): feat_n, thresh = self.getInfo() feat_x = x[feat_n] if(feat_x < thresh): return self.left.predict_tree(x) else: return self.right.predict_tree(x) else: return self.getInfo() #Leaf at the end of the tree making the decision class Leaf: def __init__(self, label): self.label = label def getInfo(self): return(self.label) def hasChild(sef): return False #Build decision tree based on dataset def build_tree(X, y, y_inv=None, depth=0, max_depth=3, n_labels=2, split=util.entropy, random_forest=False): if len(y) < 1: return Leaf(np.argmin(np.bincount(y_inv))) if depth == max_depth: return Leaf(np.argmax(np.bincount(y))) best_information = MAX best_feat= -1 best_split = 0.0 feature_number = X.shape[1] if(random_forest): features = [] feature_check = {} while(len(features) < int(math.sqrt(feature_number) + 1)): pick = rdm.randrange(samples) if(not(pick in feature_check)): features.append(pick) feature_check[pick] = pick else: features = list(range(0, feature_number)) #Iterate threw all features for n_feat in features: x_candidates = define_candidates(X.T[n_feat]) n = X.shape[0] #Find best candidate value for i in range(len(x_candidates)): # split column into left and right row = X.T[n_feat] left, right = left_right_split(value = x_candidates[i], row=row, y=y) # calculate entropy coeficients for left and right left_entropy, right_entropy = split(left), split(right) # calculate wighted entropy information_gain = (len(left)/n)*left_entropy + (len(right)/n)*right_entropy # save split with best information gain if information_gain < best_information: best_information = information_gain best_split = x_candidates[i] best_left = left best_right = right best_feat = n_feat left_X = [] right_X = [] #Based on best candidate and feature split set for j in range(X.shape[0]): row = X.T[best_feat] if row[j] < best_split: left_X.append(X[j]) else: right_X.append(X[j]) node = Node(None,None,best_feat,best_split) node.left = build_tree(np.array(left_X), best_left, best_right, depth+1, max_depth, n_labels) node.right = build_tree(np.array(right_X), best_right, best_left, depth+1, max_depth, n_labels) return node #Split data based on on threshold value def left_right_split(value, row, y): left, right = list(), list() n = len(row) for i in range(n): if row[i] < value: left.append(int(y[i])) else: right.append(int(y[i])) return np.array(left), np.array(right) #Traverse tree to make a decision for x def predict_tree(node, x): if(node.hasChild()): feat_n, thresh = node.getInfo() feat_x = x[feat_n] if(feat_x < thresh): return predict_tree(node.left, x) else: return predict_tree(node.right, x) else: return node.getInfo() #Defines candidates for possible splitts def define_candidates(X): X_sorted = sorted(X) x_candidates = [] cmp1 = X_sorted[0] #find suitable candidates for i in range(1, len(X)): cmp2 = X_sorted[i] candidate = (cmp1 + cmp2)/2 x_candidates.append(candidate) cmp1 = X_sorted[i] return x_candidates <file_sep>/compress/compressors.py ''' Using the implemented algorithms for compression procedures ''' import bwt import mtf import huffman as huf #Compression based on Bijective BWT, MTF and Huffman encoding def bijective_huffman_compress(omega): string_bwt = bwt.BBWT(omega) string_mtf, alphabet = mtf.MTF_encode(string_bwt) code_book = huf.huffman_coding(string_mtf) binary = huf.huffman_compress(string_mtf, code_book) return(binary, code_book, alphabet) #Decompression for algorithm based on Bijective BWT, MTF and Huffman encoding def bijective_huffman_decompress(binary, notebook, alphabet): string_mtf = huf.huffman_decompress(binary, notebook) string_bwt = mtf.MTF_decode(string_mtf, alphabet) omega = bwt.BBWT_inv(string_bwt) return(omega) #Compression based on plain BWT, MTF and Huffman encoding def bwt_huffman_compress(omega): string_bwt = bwt.BWT(omega) string_mtf, alphabet = mtf.MTF_encode(string_bwt) code_book = huf.huffman_coding(string_mtf) binary = huf.huffman_compress(string_mtf, code_book) return(binary, code_book, alphabet) #Decompression for algorithm based on Bijective BWT, MTF and Huffman encoding def bwt_huffman_decompress(binary, notebook, alphabet): string_mtf = huf.huffman_decompress(binary, notebook) string_bwt = mtf.MTF_decode(string_mtf, alphabet) omega = bwt.BWT_inv(string_bwt) return(omega) <file_sep>/compress/boosting.py ''' Implementation of Boosting via Decision Tree Stumps ''' import decisiontree as dt import math import cla_util as util import numpy as np MAX = 999999999999999999999999999 #Weak classifier with decision strenght based on weight class weak_learner(): """Weak learner classifier to for boosted algorithm. Args: n_feat : int or string feature on which classifier takes decision threshold : double the value on which classifier takes decision left : array classes with feature value lower than threshold right : array classes with feature value greater than threshold weight : double weight decicdes strength of classifier Attributes: n_feat : int or string feature on which classifier takes decision threshold : double the value on which classifier takes decision left : array classes with feature value lower than threshold right : array classes with feature value greater than threshold weight : double weight decicdes strength of classifier """ def __init__(self,n_feat, threshold, left, right, weight): self.n_feat = n_feat self.threshold = threshold self.left_class = np.argmax(np.bincount(left)) self.right_class = np.argmax(np.bincount(right)) self.weight = weight def weak_prediction(self, X): feat = self.n_feat if(X[feat] < self.threshold): return self.left_class else: return self.right_class #Iteration of n_learner classifiers creating n weak learners def weak_learners(X, y, n_learner): labels = len(np.unique(y)) learners = [] n = len(X) weights = [1/n]*n for t in range(n_learner): best_feat= -1 best_split = 0.0 smallest_error = MAX for n_feat in range(X.shape[1]): x_candidates = dt.define_candidates(X.T[n_feat]) n = X.shape[0] #Find best candidate value for i in range(len(x_candidates)): # split column into left and right row = X.T[n_feat] left, right = dt.left_right_split(value = x_candidates[i], row=row, y=y) if(len(left) == 0): left_decision = np.argmin(np.bincount(right)) else: left_decision = np.argmax(np.bincount(left)) if(len(right) == 0): right_decision = np.argmin(np.bincount(left)) else: right_decision = np.argmax(np.bincount(right)) weighted_error, miss = compute_weighted_error(left, right, left_decision, right_decision, y, weights) if(weighted_error < smallest_error): smallest_error = weighted_error misses = miss best_feat = n_feat best_split = x_candidates[i] best_left = left best_right = right frac = (1-weighted_error)/weighted_error classifier_weight = 0.5*math.log(frac) + math.log(labels-1) for i in range(n): if(misses[i] == True): weights[i] = weights[i]*math.exp(classifier_weight) normalize = sum(weights) weights = [weight / normalize for weight in weights] learners.append(weak_learner(best_feat, best_split, best_left, best_right, classifier_weight)) return learners #Compute Error based on weights def compute_weighted_error(left, right, left_decision, right_decision, y, weights): weighted_error = 0 miss = [False]*len(weights) for i in range(len(left)+len(right)): if(i < len(left)): if(left_decision == y[i]): miss[i] = False else: weighted_error += weights[i] miss[i] = True else: if(right_decision == y[i]): miss[i] = False else: weighted_error += weights[i] miss[i] = True return weighted_error, miss #Train boosted clasifieres on Data def train_boosting(X, y, n_learner=25): experts = weak_learners(X, y, n_learner) return experts #Predict with voting based on boosted learners def predict_boosting(X, learner): y_prediction = [] for x in X: dict = {} for i in range(len(learner)): weak_predictor = learner[i].weak_prediction(x) if(not(weak_predictor in dict)): dict[weak_predictor] = learner[i].weight else: dict[weak_predictor] += learner[i].weight max_value = max(dict.values()) ensemble_prediction = [k for k, v in dict.items() if v == max_value] y_prediction.append(ensemble_prediction[0]) return y_prediction <file_sep>/compress/test_lempelziv.py ''' Tests for the Lempel Ziv Encodings ''' import lz778 as lz import random import string #Tests if LZ77 can decode a random encoded string correctly def test_lzw(string): enc = lz.lzw_encoding(string) dec = lz.lzw_decoding(enc) assert(string == dec), ('LZW does decode encoded string not correctly') #Tests if LZ77 can decode a random encoded string correctly def test_77(string): enc = lz.lz77_encoding(string) dec = lz.lz77_decoding(enc) assert(string == dec), ('LZ77 does decode encoded string not correctly') if __name__ == '__main__': n = random.randrange(10000) string =''.join(random.choices(string.ascii_uppercase + string.digits, k = n)) test_lzw(string) test_77(string) <file_sep>/compress/mtf.py ''' An implementation of the move to front algorithm. ''' import copy import cla_util as util #Move to front encoding algorithm def MTF_encode(omega, Lambda=None): n = len(omega) eta = [] #If there exists no alphabet for the word compute it on the fly if(Lambda==None): Lambda = util.word_alphabet(omega) Lambda = sorted(Lambda) alphabet = copy.deepcopy(Lambda) #encode next character based on alphabet for w in omega: i = alphabet.index(w) eta.append(i) k = w #update alphabet in moving last character to the front of the alphabet for j in range(i+1): l = alphabet[j] alphabet[j] = k k = l return eta, Lambda #Move to front decoding algorithm def MTF_decode(eta, Lambda): n = len(eta) omega = "" alphabet = copy.deepcopy(Lambda) #decode next character based on alphabet for i in range(n): omega += alphabet[eta[i]] k = alphabet[eta[i]] #update alphabet in moving last character to the front of the alphabet for j in range(eta[i]+1): l = alphabet[j] alphabet[j] = k k = l return omega <file_sep>/compress/lz778.py ''' Implementation of the Lempel Ziv Encodings. ''' import datastructures as ds import cla_util as util #Computes LZ77 standard encoding def lz77_encoding(omega): jump_length = [] m = 0 n = len(omega) jump_length.append([0, 0, omega[0]]) i = 0 while(i < n-1): search = True pattern = "" matches = [] i += 1 j = i #look up the largest string in preceding substring while(search == True): pattern += omega[i] substring = omega[0:i] final_matching = matches matches = util.knuth_morris_pratt(substring, pattern) if(matches == []): search = False if(len(pattern) == 1): jump_length.append([0, 0, omega[i]]) else: jumps = j - max(final_matching) l = len(pattern)-1 jump_length.append([jumps, l, omega[i]]) else: i += 1 return jump_length #Decodes code word encoded with LZ77 def lz77_decoding(jump_length): omega = "" for tripple in jump_length: j = tripple[0] l = tripple[1] c = tripple[2] n = len(omega) for i in range(l): omega += omega[n-j] n += 1 omega += c return omega #Computes encoded string based on Lempel-Ziv-Welch coding notebook def lzw_encoding(omega): omega += '$' code_book = ds.CodeBook() j = 256 for i in range(j): code_book.insert(chr(i), i) string = "" enc_string = [] n = len(omega) i = 0 while(i < n): string += omega[i] msg_byte = omega[i+1] if(msg_byte == '$'): enc_string.append(code_book.getBinary(string)) break look_up = string + msg_byte if(code_book.hasWord(look_up)): i += 1 else: code_book.insert(look_up, j) j += 1 enc_string.append(code_book.getBinary(string)) string = "" i += 1 return enc_string #Decodes encoded word based on Lempel-Ziv-Welch coding def lzw_decoding(eta): omega = "" code_book = ds.CodeBook() j = 256 for i in range(j): code_book.insert(chr(i), i) n = len(eta) code = eta[0] string = code_book.getWord(code) omega += string i = 1 while(i < n): code = eta[i] if(not(code_book.hasBinary(code))): entry = string + string[0] else: entry = code_book.getWord(code) omega += entry code_book.insert(string + entry[0],j) string = entry j += 1 i += 1 return omega <file_sep>/compress/test_bwt.py ''' Testing of the Burrows Wheeler Transform ''' import bwt #check if string does not change after transform and inversion def BWT_test(): string = "ananasibananamamissisipi" assert(bwt.BWT_inv(bwt.BWT(string)) == string), ('Plain BWT does not recover original string') assert(bwt.BBWT_inv(bwt.BBWT(string)) == string), ('Bijective BWT does not recover original string') if __name__ == '__main__': BWT_test() <file_sep>/compress/test_compressors.py ''' Test file for compressing algorithms ''' import compressors as cp import random import string #Check if original string does not change after being compressed and decompressed by bwt huffman compression def test_bwt_huffman_compress(string): bin, note, alph = cp.bwt_huffman_compress(string) string_re = cp.bwt_huffman_decompress(bin, note, alph) assert(string == string_re) #Check if original string does not change after being compressed and decompressed by bijective huffman compression def test_bijective_huffman_compress(string): bin, note, alph = cp.bijective_huffman_compress(string) string_re = cp.bijective_huffman_decompress(bin, note, alph) assert(string == string_re) if __name__ == '__main__': n = random.randrange(100000) string =''.join(random.choices(string.ascii_uppercase + string.digits, k = n)) test_bwt_huffman_compress(string) test_bijective_huffman_compress(string)
dc697634ddea3f37b74ee5d23eaf17fa88c98ae5
[ "Markdown", "Python", "Text" ]
20
Python
simrit1/CLA
c44a83312e8761ba41dba33e87c07c83629202ac
69c006b7a050dc1d2c190877751b5df2ce503641
refs/heads/master
<repo_name>onestepsero/navertv-remocon<file_sep>/app.js global.CHANNEL_LIST = ['secretjuju', 'ted','tobot']; var express = require('express') , request = require('request') , http = require('http') , app = express() , cp = require('child_process') , path = require('path') , server = http.createServer(app) , db = require('./db.js'); var tvoutChild = cp.fork('naverTv.js'); var naverTvIndex = 1; var contents = [{}]; app.configure(function(){ app.set('port', process.env.PORT || 8080); app.set('view', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.urlencoded()); app.use('/public',express.static(path.join(__dirname, '/public'))); }) //main app.get('/', function(req, res){ res.render("index", {channelList: CHANNEL_LIST, host : req.host }) db.naverTvUrlParse(); }); //list app.get('/tvlist/:id', function(req, res){ contents = db.getData(req.params.id) ; if(contents) { res.format({ html: function() { res.render("list", {id: req.params.id, contents:contents});}, json: function() { res.json(JSON.stringify(contents));} }); } else { res.send('Not found'); } }); app.get('/test/:id', function(req, res){ contents = db.getData(req.params.id) ; res.json(JSON.stringify(contents)); }); //detail app.get('/detail/:id', function(req, res){ tvoutChild.send({naverTvIndex : req.params.id, tvInfo:contents[req.params.id]}); db.makeJsonFile(req.params.id); res.render('detail', {script:contents[req.params.id].script, naverTvIndex:req.params.id}); }); server.listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });<file_sep>/README.md # NaverTvCast TvOut ## Run * clone this repo. * `$ npm install`. * `$ node app.js`. * visit 'localhost:8080' on your favorite browser. * visit 'localhost:9002' on your favorite browser. * connect tv out ## See Demo <file_sep>/naverTv.js var express = require('express') , http = require('http') , app = express() , server = http.createServer(app) , path = require('path'); var tvInfo ; var naverTvIndex ; app.configure(function(){ app.set('port', process.env.TV_PORT || 9002); app.set('view', __dirname + '/views'); app.set('view engine', 'jade'); app.use('/public',express.static(path.join(__dirname, '/public'))); }); process.on('message', function(m) { naverTvIndex = m.naverTvIndex; tvInfo = m.tvInfo; // console.log('CHILD got message:', m ); }); app.get('/', function(req, res){ if(naverTvIndex == undefined) { res.sendfile("views/noindex.html"); } else { res.render('view', {script:tvInfo.script.s, tvInfo:tvInfo}); } }); server.listen(app.get('port'), function(){ console.log("TVCast server listening on port " + app.get('port')); }); <file_sep>/db.js var request = require('request') , cheerio = require('cheerio') , S = require('string') , fs = require('fs'); var contents = new Array(CHANNEL_LIST.length); var ipadUseragent = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25"; /* contents[channle][{text: , title:, href: }] */ // Array init for(var i =0; i< CHANNEL_LIST.length; i++) { contents[i] =[{}]; } exports.getData = function(id) { var keyIndex = CHANNEL_LIST.indexOf(id); return contents[keyIndex]; }; exports.naverTvUrlParse = function(){ for(var i =0; i<CHANNEL_LIST.length; i++) { urlParseToDb(CHANNEL_LIST[i]); } } urlParseToDb = function(channel){ var keyIndex = CHANNEL_LIST.indexOf(channel); request( { uri: "http://tvcast.naver.com/" + channel }, function(error, response, body){ var $ = cheerio.load(body); var index = 0; $(".lst_obj .conts > a").each(function(){ var link = $(this); var text = link.text(); var title = link.attr("title"); var href = link.attr("href"); contents[keyIndex][index] = { id: index, title:title, href: href } tvInfoscript(index); index++; }); makeImageThumb(body); }); var makeImageThumb = function(body) { var $ = cheerio.load(body); var index = 0; $(".lst_obj .conts .thumb > img").each(function(){ var link = $(this); contents[keyIndex][index].img = link.attr('src'); index++; }); }; var tvInfoscript = function(index) { request({ uri: contents[keyIndex][index].href, headers: { 'user-agent' : ipadUseragent } }, function(error, response, body){ var $ = cheerio.load(body); //TODO $("#player").each(function(){ var link = $(this).children().text(); var replaceContent = S(link).replaceAll('"', "'"); contents[keyIndex][index].script = replaceContent; }); }); }; }; exports.makeJsonFile = function(param) { var data = { index: param}; var outputFile = 'public/api.json'; fs.writeFile(outputFile, JSON.stringify(data), function(err){ if(err){ console.log(err); } else { console.log("JSON saved to"); } }); };
b6ecba9eab95accb440830711c3516abb512b0e9
[ "JavaScript", "Markdown" ]
4
JavaScript
onestepsero/navertv-remocon
5cf021e7bf5d7b5a9e9bd1081ee1a21b9e2ea428
c653a289ad75a71e2754231b3b40bf22aa9e86cb
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace pacmanVTwo { class OverLay { Font drawFont = new Font("Arial", 16); Brush drawBrush = Brushes.Red; Brush RedBrush = Brushes.White; Brush GreenBrush = Brushes.Green; Image LifeIcon = (Image)new Bitmap("C:\\Users\\Student\\source\\repos\\PROG2200-700-4032-NSCC-FALL2019\\Anthony_Healy\\pacman\\pacmanVTwo\\pacmanVTwo\\sprites\\pacman\\pac_left.bmp"); bool isDead = false; int X; int Y; /// <summary> /// Constructor /// </summary> /// <param name="Map"></param> public OverLay(Rectangle Map) { this.X = Map.X + Map.Width+5; this.Y = Map.Y; } /// <summary> /// Draw function /// </summary> /// <param name="g"></param> public void Draw(Graphics g,int Life,int Score) { DrawLifeBar(X,Y,Life,g); DrawScore(X, Y + LifeIcon.Height,Score, g); } /// <summary> /// Lose OverLay /// </summary> /// <param name="g"></param> public void Draw(Graphics g, String msg) { DrawGameOver(g); g.DrawString(msg,drawFont,drawBrush,X,Y+20); } public void Draw(Graphics g, int Life, int Score, String msg) { DrawLifeBar(X, Y, Life, g); DrawScore(X, Y + LifeIcon.Height, Score, g); g.DrawString("YOU WON\n"+msg, drawFont, GreenBrush, X, Y+75); } /// <summary> /// Draws the Lose screen /// </summary> /// <param name="g"></param> private void DrawGameOver(Graphics g) { g.DrawString("Game Over", drawFont, drawBrush, X, Y); } /// <summary> /// Draws the Life Bar And Handles Logic /// </summary> /// <param name="X"></param> /// <param name="Y"></param> /// <param name="Lifes"></param> /// <param name="g"></param> private void DrawLifeBar(int X, int Y, int Lifes, Graphics g) { switch (Lifes) { case 0: break; case 1: g.DrawImage(LifeIcon, X, Y); break; case 2: g.DrawImage(LifeIcon, X, Y); g.DrawImage(LifeIcon, X+LifeIcon.Width, Y); break; case 3: g.DrawImage(LifeIcon, X, Y); g.DrawImage(LifeIcon, X + LifeIcon.Width, Y); g.DrawImage(LifeIcon, X +( LifeIcon.Width*2), Y); break; } } /// <summary> /// Draws Score /// </summary> /// <param name="X"></param> /// <param name="Y"></param> /// <param name="Score"></param> /// <param name="g"></param> private void DrawScore(int X,int Y,int Score , Graphics g) { g.DrawString("Score: "+Score.ToString(),drawFont,RedBrush,X,Y); } } } <file_sep>using System.Collections.Generic; using System.Drawing; namespace pacmanVTwo { internal class list<T> : List<Rectangle> { } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace pacmanVTwo { /// <summary> /// Its your boy PacMan /// </summary> public class Player { int Score=0; public bool hasWon=false; int Life = 3; bool isDead = false; public enum Direction { Up, Down, Left, Right, Still } //this direction serves the porpose of determin clipping Direction LastMove = Direction.Still; //Images List<Image> sprites = new List<Image>(); //active Sprite //0=Up //1=Down //2=Left //3=right //4=full Image ActiveSprite; //loacation from the top left int X; int Y; private static int Height =39, Width=39; //hit box public Rectangle HitBox; //speed int Speed= 2; //canvas private Rectangle Canvas; //Map Map CurrMap; List<bool> AD = new List<bool>(); public int GetLifes() { return Life; } /// <summary> /// Gets Score /// </summary> /// <returns></returns> public int GetScore() { return Score; } /// <summary> /// Adds Score /// </summary> public void AddScore() { Score++; } /// <summary> /// Adds Extra Life /// </summary> public void AddLife() { if (Life<3) { Life++; } } /// <summary> /// This gets the map to help with colistions /// </summary> /// <param name="map"></param> public void SetMap(Map map) { this.CurrMap = map; } /// <summary> /// creating Empty PacMan Class /// </summary> public Player() { setDefualtDirections(); } /// <summary> /// creating full PacMan Class /// </summary> public Player(int X, int Y,Rectangle canvas) { this.X = X; this.Y = Y; HitBox=new Rectangle(X-2, Y-2, Height,Width); this.Canvas = canvas; //getting the important stuff readyy setDefualtDirections(); GetSprites(); ActiveSprite=sprites[4]; } public Player(Rectangle canvas) { this.X = (canvas.Width / 2); this.Y = (canvas.Height / 2) ; HitBox = new Rectangle(X-2, Y-2, Height, Width); this.Canvas = canvas; //getting the sprites setDefualtDirections(); GetSprites(); ActiveSprite = sprites[4]; } /// <summary> /// /Returns if wall was hit /// </summary> /// <returns></returns> public bool WallCollision() { if (CurrMap.HasHitWall(HitBox)) { return true; } else { return false; } } /// <summary> /// This Draws/ Spawns PacMan /// </summary> /// <param name="graphics"></param> public void Draw(Graphics graphics) { //draw pacman graphics.DrawImage(ActiveSprite,this.X,this.Y); } /// <summary> /// This gets the sprites /// </summary> private void GetSprites() { Image PacUp= (Image) new Bitmap("C:\\Users\\Student\\source\\repos\\PROG2200-700-4032-NSCC-FALL2019\\Anthony_Healy\\pacman\\pacmanVTwo\\pacmanVTwo\\sprites\\pacman\\pac_up.bmp"); this.sprites.Add(PacUp); Image PacDown = (Image)new Bitmap("C:\\Users\\Student\\source\\repos\\PROG2200-700-4032-NSCC-FALL2019\\Anthony_Healy\\pacman\\pacmanVTwo\\pacmanVTwo\\sprites\\pacman\\pac_down.bmp"); this.sprites.Add(PacDown); Image PacLeft = (Image)new Bitmap("C:\\Users\\Student\\source\\repos\\PROG2200-700-4032-NSCC-FALL2019\\Anthony_Healy\\pacman\\pacmanVTwo\\pacmanVTwo\\sprites\\pacman\\pac_left.bmp"); this.sprites.Add(PacLeft); Image PacRight = (Image)new Bitmap("C:\\Users\\Student\\source\\repos\\PROG2200-700-4032-NSCC-FALL2019\\Anthony_Healy\\pacman\\pacmanVTwo\\pacmanVTwo\\sprites\\pacman\\pac_right.bmp"); this.sprites.Add(PacRight); Image PacFull = (Image)new Bitmap("C:\\Users\\Student\\source\\repos\\PROG2200-700-4032-NSCC-FALL2019\\Anthony_Healy\\pacman\\pacmanVTwo\\pacmanVTwo/sprites/pacman/pac_full.bmp"); this.sprites.Add(PacFull); } /// <summary> /// This sets active sprite /// </summary> /// <param name="index"></param> public void SetActiveSprite(int index) { ActiveSprite = sprites[index]; } /// <summary> /// This moves Player(Big Function) /// </summary> /// <param name="direction"></param> public void Move(Direction direction) { switch (direction) { case Direction.Still: MoveStill(); break; case Direction.Up: MoveUp(); break; case Direction.Down: MoveDown(); break; case Direction.Left: MoveLeft(); break; case Direction.Right: MoveRight(); break; } } //mover Functions /// <summary> /// Moves Player Up /// </summary> private void MoveUp() { this.Y -= this.Speed; ActiveSprite = sprites[0]; HitBox.Y -= this.Speed; } /// <summary> /// Moves Player Down /// </summary> private void MoveDown() { this.Y += this.Speed; ActiveSprite = this.sprites[1]; HitBox.Y += this.Speed; } /// <summary> /// Moves Player Left /// </summary> private void MoveLeft() { this.X -= this.Speed; ActiveSprite = this.sprites[2]; HitBox.X -= this.Speed; } /// <summary> /// Moves Player Right /// </summary> private void MoveRight() { this.X += this.Speed; this.ActiveSprite = this.sprites[3]; HitBox.X += this.Speed; } //Destroyes System32 public void MoveStill() { this.ActiveSprite = this.sprites[4]; } //Colision detection /// <summary> /// 0=up /// 1=down /// 2=left /// 3=right /// </summary> public void setDefualtDirections() { //I know Naming Conventions but this will do alot of the heavy work //This will help with walls AD.Add(false); AD.Add(false); AD.Add(false); AD.Add(false); } /// <summary> /// Resets the directions /// </summary> public void ResetDirections() { //I know Naming Conventions but this will do alot of the heavy work //This will help with walls for (int i = 0; i <3 ; i++) { AD[i] = false; } } /// <summary> /// This will Change the The Directions Permission /// </summary> /// <param name="IndexOfDirection"></param> /// <param name="Permission"></param> public void ChangeDirectionPermission(int IndexOfDirection, bool Permission) { try { AD[IndexOfDirection] = Permission; } catch(IndexOutOfRangeException e) { } } //check if colided /// <summary> /// This will check if wall was hit then determine what way the was the player headed /// </summary> /// <returns></returns> public bool HasContactedWall(Rectangle Side) { if (CurrMap.HasHitWall(Side)) { return true; } else { return false; } } //Reset Player public void Reset() { if (Life <= 0 && isDead) { //varReseting Life = 3; Score = 0; this.X = 312; this.Y = 258; HitBox.X = X; HitBox.Y = Y; Die(); } else if (hasWon ) { //varReseting Life = 3; Score = 0; this.X = 312; this.Y = 258; HitBox.X = X; HitBox.Y = Y; Win(); } else { Life--; this.X = 312; this.Y = 258; HitBox.X = X; HitBox.Y = Y; } } public bool IsDead() { return isDead; } public void IsDead(bool isDead) { this.isDead = isDead; } //die public void Die() { isDead = true; } public void Win() { hasWon = true; } public void EatDot(List<DotSmall> dots) { foreach (DotSmall dot in dots) { if (HitBox.IntersectsWith(dot.HitBox)&& !dot.GetIsEaten()) { dot.SetEaten(); AddScore(); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace pacmanVTwo { public class DotSmall { public Rectangle HitBox; bool IsEaten= false; int X; int Y; static int Height=4, Width = 4; public DotSmall(int X, int Y) { this.X=X; this.Y = Y; HitBox = new Rectangle(X, Y, Width, Height); } //Draw public void Draw(Graphics graphics) { if (HitBox!=null) { if (!IsEaten) { graphics.FillRectangle(Brushes.AntiqueWhite, HitBox); } } } //Eaten public void SetEaten() { IsEaten = true; } public void UnsetEaten() { IsEaten = false; } public bool GetIsEaten() { return IsEaten; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace pacmanVTwo { public class Map { //Variables const int Scale = 2; int X = 0; int Y = 0; static int Height = 744; static int Width = 672; List<Rectangle> Walls = new list<Rectangle>(); public Rectangle screen; PointF location; Image MapBase =(Image)( new Bitmap("C:\\Users\\Student\\source\\repos\\PROG2200-700-4032-NSCC-FALL2019\\Anthony_Healy\\pacman\\pacmanVTwo\\pacmanVTwo\\sprites\\map_pink.bmp")); /// <summary> /// Default /// </summary> public Map() { } /// <summary> /// Takes map and sets X and Y /// </summary> /// <param name="X"></param> /// <param name="Y"></param> public Map(int X,int Y) { this.X = X; this.Y = Y; screen = new Rectangle(X,Y,Width,Height); location = new PointF(this.X, this.Y); AssignMapWalls(); } /// <summary> /// Creating the Rectangle Walls /// </summary> private void AssignMapWalls() { // Top And bottom Walls //Top and Bottom Rectangle WallTop = new Rectangle(X,Y, 675, 15); Walls.Add(WallTop); Rectangle WallBot = new Rectangle(X, Y+Height-15, 675, 15); Walls.Add(WallBot); // Side Walls //Left Side Rectangle WallSideTopLeft = new Rectangle(WallTop.X+3,WallTop.Y+15,15,210); Walls.Add(WallSideTopLeft); Rectangle WallSideAboveRightTP = new Rectangle(WallSideTopLeft.X,WallSideTopLeft.Y+WallSideTopLeft.Height,133,99); Walls.Add(WallSideAboveRightTP); Rectangle WallSBelowLTP = new Rectangle(WallSideAboveRightTP.X,WallSideAboveRightTP.Y+WallSideAboveRightTP.Height+48,132,96); Walls.Add(WallSBelowLTP); Rectangle WallSLowLeft = new Rectangle(WallSBelowLTP.X,WallSBelowLTP.Y+WallSBelowLTP.Height,15,261); Walls.Add(WallSLowLeft); //Right Side Rectangle WallSTR = new Rectangle((WallTop.X + WallTop.Width)-15, WallTop.Y + 15, 15, 210); Walls.Add(WallSTR); Rectangle WallSAboveRTP = new Rectangle(WallSTR.X-133+15, WallSTR.Y + WallSTR.Height, 133, 99); Walls.Add(WallSAboveRTP); Rectangle WallSBelowRTP = new Rectangle(WallSideAboveRightTP.X+screen.Width-133, WallSideAboveRightTP.Y + WallSideAboveRightTP.Height + 48, 132, 96); Walls.Add(WallSBelowRTP); Rectangle WallSLowRTP = new Rectangle(WallSBelowLTP.X+screen.Width-15, WallSBelowLTP.Y + WallSBelowLTP.Height, 15, 261); Walls.Add(WallSLowRTP); // Middle Areas Rectangle GhostBox = new Rectangle(this.X+255,this.Y+300,168,96); Walls.Add(GhostBox); Rectangle IslandOne = new Rectangle(this.X + 63, this.Y + 60, 72, 48); Walls.Add(IslandOne); Rectangle IslandTwo = new Rectangle(this.X + 183, this.Y + 60, 96, 48); Walls.Add(IslandTwo); Rectangle IslandThree = new Rectangle(this.X + 327, this.Y + 15, 24, 93); Walls.Add(IslandThree); Rectangle IsleFour = new Rectangle(this.X + 399, this.Y +60 , 96, 48); Walls.Add(IsleFour); Rectangle IsleFive = new Rectangle(this.X + 543, this.Y + 60, 72, 48); Walls.Add(IsleFive); Rectangle IsleSix = new Rectangle(this.X + 63, this.Y + 156, 72, 24); Walls.Add(IsleSix); Rectangle IsleSeven = new Rectangle(this.X + 183, this.Y + 156, 27, 168); Walls.Add(IsleSeven); Rectangle IsleEight = new Rectangle(this.X + 255, this.Y + 156, 168, 24); Walls.Add(IsleEight); Rectangle IsleNine = new Rectangle(this.X + 324, this.Y + 180, 30, 72); Walls.Add(IsleNine); Rectangle IsleTen = new Rectangle(this.X + 207, this.Y + 225, 72, 30); Walls.Add(IsleTen); Rectangle Isle11 = new Rectangle(this.X + 399, this.Y + 225, 72, 30); Walls.Add(Isle11); Rectangle Isle12 = new Rectangle(this.X + 471, this.Y + 156, 24, 168); Walls.Add(Isle12); Rectangle Isle13 = new Rectangle(this.X + 543, this.Y + 156, 72, 24); Walls.Add(Isle13); Rectangle Isle14 = new Rectangle(this.X + 183, this.Y + 372, 24, 96); Walls.Add(Isle14); Rectangle Isle15 = new Rectangle(this.X + 471, this.Y + 372, 24, 96); Walls.Add(Isle15); Rectangle Isle16 = new Rectangle(this.X + 255, this.Y + 444, 168, 24); Walls.Add(Isle16); Rectangle Isle17 = new Rectangle(this.X + 324, this.Y + 468, 30, 72); Walls.Add(Isle17); Rectangle Isle18 = new Rectangle(this.X + 63, this.Y+516, 72, 27); Walls.Add(Isle18); Rectangle Isle19 = new Rectangle(this.X + 183, this.Y + 516, 96 ,24); Walls.Add(Isle19); Rectangle Isle20= new Rectangle(this.X + 399, this.Y + 516, 96, 24); Walls.Add(Isle20); Rectangle Isle21 = new Rectangle(this.X + 543, this.Y + 516, 72, 27); Walls.Add(Isle21); Rectangle Isle22 = new Rectangle(this.X + 111, this.Y + 543, 24 ,69); Walls.Add(Isle22); Rectangle Isle23 = new Rectangle(this.X + 18, this.Y + 588, 45, 24); Walls.Add(Isle23); Rectangle Isle24 = new Rectangle(this.X + 63, this.Y + 657, 216, 27); Walls.Add(Isle24); Rectangle Isle25 = new Rectangle(this.X + 183, this.Y + 588, 24, 69); Walls.Add(Isle25); Rectangle Isle26 = new Rectangle(this.X + 255, this.Y + 588, 168, 27); Walls.Add(Isle26); Rectangle Isle27 = new Rectangle(this.X + 327, this.Y + 615, 24, 68); Walls.Add(Isle27); Rectangle Isle28 = new Rectangle(this.X + 399, this.Y + 657, 216, 27); Walls.Add(Isle28); Rectangle Isle29 = new Rectangle(this.X + 615, this.Y + 588, 45, 24); Walls.Add(Isle29); Rectangle Isle30 = new Rectangle(this.X + 471, this.Y + 588, 24, 69); Walls.Add(Isle30); Rectangle Isle31 = new Rectangle(this.X + 543, this.Y + 543, 24, 69); Walls.Add(Isle31); } /// <summary> /// This is where we Draw Things Kiddo /// </summary> /// <param name="graphics"></param> public void Draw(Graphics graphics) { graphics.DrawImage(MapBase,location); //gotta put the walls up DrawWalls(graphics); } /// <summary> /// Draws the walls DEV /// </summary> /// <param name="g"></param> public void DrawWalls(Graphics g) { foreach (Rectangle Wall in Walls) { g.DrawRectangle(new Pen(Brushes.Red),Wall); } } /// <summary> /// Colision Detection /// </summary> /// <param name="player">Player Object</param> /// <param name="mode">For Colision detection</param> /// <returns></returns> public bool HasHitWall(Rectangle rectangle) { foreach (Rectangle wall in Walls) { if (rectangle.IntersectsWith(wall)) { return true; } } return false; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace pacmanVTwo { public partial class gameForm : Form { int oldScore = 0; bool hasWon=false; //Active Objects Map map; Player PacMan; Player.Direction LastInput=Player.Direction.Still; List<DotSmall> Dots = new List<DotSmall>(); OverLay overlay; //Utility bool Up = false; bool Down = false; bool Left = false; bool Right = false; bool hasStarted = false; /// <summary> /// Checks on the Walls /// </summary> public void CheckWallDetection() { Up = map.HasHitWall(PacMan.HitBox); Down = map.HasHitWall(PacMan.HitBox); Left = map.HasHitWall(PacMan.HitBox); Right = map.HasHitWall(PacMan.HitBox); if (PacMan.WallCollision()) { if (LastInput==Player.Direction.Up) { LastInput = Player.Direction.Still; } else if (LastInput == Player.Direction.Down) { LastInput = Player.Direction.Still; } else if (LastInput == Player.Direction.Left) { LastInput = Player.Direction.Still; } else if (LastInput == Player.Direction.Right) { LastInput = Player.Direction.Still; } } } /// <summary> /// Constructor /// </summary> public gameForm() { InitializeComponent(); } /// <summary> /// Sets the timer /// </summary> public void SetTimer() { aTimer.Interval = (6); aTimer.Enabled = true; } /// <summary> /// Stops Timer /// </summary> public void StopTimer() { aTimer.Stop(); hasStarted = false; } /// <summary> /// Starts Timer /// </summary> public void StartTimer() { aTimer.Start(); hasStarted = true; } /// <summary> /// on Load /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { this.WindowState = FormWindowState.Maximized; map = new Map(0,0); PacMan = new Player(312, 258 ,this.map.screen); PacMan.SetMap(map); SetAllDots(); overlay = new OverLay(map.screen); } /// <summary> /// Setting All Dots /// </summary> private void SetAllDots() { Dots.Add(new DotSmall(290, 275)); Dots.Add(new DotSmall(260, 275)); Dots.Add(new DotSmall(230, 275)); Dots.Add(new DotSmall(230, 305)); Dots.Add(new DotSmall(230, 305)); } private void DrawAllDots(Graphics g) { foreach (DotSmall dot in Dots) { if (!dot.GetIsEaten()) { dot.Draw(g); } } } /// <summary> /// Timer /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { //checlk if dead bool PacManAlive=CheckIfDead(); bool win =CheckForWin(); CheckWallDetection(); PacMan.EatDot(Dots); if (win) { PacMan.Reset(); ResetDetectors(); } else if (!PacMan.WallCollision()) { PacMan.Move(LastInput); } else { PacMan.Reset(); ResetDetectors(); } Invalidate(); } /// <summary> /// Checks if has won /// </summary> /// <returns></returns> private bool CheckIfDead() { if (PacMan.IsDead()) { PacMan.IsDead(true); return true ; } else { return false; } } /// <summary> /// draws /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void gameForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; //take a break from this for now oldScore = Dots.Count(); //map.Draw(graphics); map.Draw(g); if (PacMan.IsDead()) {overlay.Draw(g,"Please Hit Space to Play Again \n Or Hit ESC to Quit"); } else if (CheckForWin()) { overlay.Draw(g,PacMan.GetLifes(),PacMan.GetScore(), "Please Hit Space to Play Again \n Or Hit ESC to Quit"); } else { overlay.Draw(g,PacMan.GetLifes(),PacMan.GetScore()); } PacMan.Draw(g); DrawAllDots(g); } private void HasHitAWall(KeyEventArgs e) { if (!PacMan.IsDead()) { switch (e.KeyCode) { case Keys.Up: if (!Up) { LastInput = Player.Direction.Up; } break; case Keys.Down: if (!Down) { LastInput = (Player.Direction.Down); } break; case Keys.Left: if (!Left) { LastInput = (Player.Direction.Left); } break; case Keys.Right: if (!Right) { LastInput = (Player.Direction.Right); } break; } } } /// <summary> /// Key Down /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void gameForm_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Space: if (PacMan.IsDead()) { PacMan.IsDead(false); ResetDots(); } else if (hasWon) { hasWon = false; ResetDots(); } break; case Keys.Escape: Application.Exit(); break; default: HasHitAWall(e); break; } } /// <summary> /// Key Up /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void gameForm_KeyUp(object sender, KeyEventArgs e) { } /// <summary> /// Resets Detectors /// </summary> private void ResetDetectors() { Up = false; Down = false; Left = false; Right = false; } /// <summary> /// Checks for to see if you win /// </summary> private bool CheckForWin() { if (PacMan.GetScore()==Dots.Count() && !PacMan.IsDead()) { hasWon = true; return true; } else { hasWon = false; return false; } } /// <summary> /// Resets Dots /// </summary> private void ResetDots() { foreach (DotSmall Dot in Dots) { Dot.UnsetEaten(); } } } }
0812b3dcbc6470a268e10c614436a7176f275c32
[ "C#" ]
6
C#
MadHatter1999/PacMan
ca4e96a6c62e9cdfa9cb615de7e710acb23866ea
23250888c273224f0732684a4712258f22fba80f
refs/heads/master
<repo_name>SAREhub/service-builder-recipe<file_sep>/README.md # Service Builder Recipe Example recipe for SAREhub Service Builder. ## How to use it? Install SAREhub Service Builder composer plugin and use **inject** command inside terminal ### Example usage: ``` composer inject github SAREhub/service-builder-recipe Project/Namespace ``` This command should extract source files to _src/Project/Namespace_ directory in your working dir. Additional files from recipe will be extracted in directories where have been placed before. In this case this will be _bin/init.sh_ folder in your working dir. <file_sep>/src/Service/TestCommand.php <?php namespace Service; class TestCommand { public function execute() { print("Executing Test Command..."); } }
e89d8fb222cc3626c1d429c0086d02095e712259
[ "Markdown", "PHP" ]
2
Markdown
SAREhub/service-builder-recipe
c067c92dbe23550fc6920394300269e3ddb4c445
c8fddb2129144662f7aada0165f9a1ed826a5e9f
refs/heads/master
<repo_name>wenbin-liu/FDU-Xuanke<file_sep>/xuanke.py import time from selenium import webdriver import selenium from selenium.webdriver.chrome.options import Options import subprocess def tryPick(className, driver): try: ele = driver.find_element_by_xpath( "//td[contains(.,'{0}')]".format(className)) except selenium.common.exceptions.NoSuchElementException: try: ele = driver.find_element_by_link_text(className) ele = ele.find_element_by_xpath("./..") except selenium.common.exceptions.NoSuchElementException: print("Can't find class: " + className) time.sleep(3) return False # ele = driver.find_element_by_xpath( # "//td[contains(.,'{0}')]".format(className)) pare = ele.find_element_by_xpath(".//..") try: # pare.find_element_by_xpath("//span[contains(.,'已满')]") ele = pare.find_element_by_link_text("选课") ele.click() ele = driver.find_element_by_xpath("//button[contains(.,'确定')]") ele.click() except Exception as e: print(className) print(e) return False print(className+" picked!") time.sleep(2) return True # Start chrome subprocess.Popen(["google-chrome-stable", "--remote-debugging-port=9222", "--user-data-dir=.config/google-chrome/", "--disk-cache-dir=.cache/google-chrome/Default"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Connect to chrome chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "localhost:9222") chrome_driver = "chrome_driver" driver = webdriver.Chrome(options=chrome_options) driver.get("http://yjsxk.fudan.edu.cn/wsxk/") while input("If you finished entering you account, please press enter!"): pass print(driver.title) # ii=1 # while(ii): # driver.refresh() # time.sleep(2) # ii=ii-1 # #学科专业课 # ele = driver.find_element_by_link_text("学科专业课") # ele.click() # # ele = driver.find_element_by_tag_nam("专业选修课") # # ele.click() # ele = driver.find_element_by_link_text("微电子材料") ii = 0 政治理论课 = [] 第一外国语 = [] 专业外语 = [] 学位基础课 = [] 学位专业课 = ["系统级可编程芯片设计2021202201INFO630047.01"] 专业选修课 = [] # 专业选修课 = ["计算微电子学2020202102INFO830033.01"] while True: if ii % 20 == 0: driver.refresh() time.sleep(1) if ii % 100 == 0: time.sleep(3) try: # 学位公共课 if 政治理论课 != [] or 第一外国语 != [] or 专业外语 != []: ele = driver.find_element_by_link_text("学位公共课") ele.click() time.sleep(1) for cls in 政治理论课: if tryPick(cls, driver): 政治理论课.remove(cls) if 第一外国语 != []: ele = driver.find_element_by_xpath("//li[contains(.,'第一外国语')]") ele.click() time.sleep(1) for cls in 第一外国语: if tryPick(cls, driver): 第一外国语.remove(cls) if 专业外语 != []: ele = driver.find_element_by_xpath("//li[contains(.,'专业外语')]") ele.click() time.sleep(1) for cls in 专业外语: if tryPick(cls, driver): 专业外语.remove(cls) # 专业课选课 ele = driver.find_element_by_link_text("学科专业课") ele.click() time.sleep(1) for cls in 学位基础课: if tryPick(cls, driver): 学位基础课.remove(cls) ele = driver.find_element_by_xpath("//li[contains(.,'学位专业课')]") ele.click() time.sleep(1) for cls in 学位专业课: if tryPick(cls, driver): 学位专业课.remove(cls) ele = driver.find_element_by_xpath("//li[contains(.,'专业选修课')]") ele.click() time.sleep(1) for cls in 专业选修课: if tryPick(cls, driver): 专业选修课.remove(cls) except selenium.common.exceptions.NoSuchElementException as e: print(e) ii = 0 continue ii = ii+1 def isFull(className, driver): ele = driver.find_element_by_link_text(className) pare = ele.find_element_by_xpath("./..") try: # pare.find_element_by_xpath("//span[contains(.,'已满')]") ele = pare.find_element_by_link_text("选课") except Exception: return False time.sleep(1) return True
c3c12afb59b2235dc80e4f41feb97919f7afe0e2
[ "Python" ]
1
Python
wenbin-liu/FDU-Xuanke
b379cd634e96ecb10d1bf7cccb581ed6e488df92
c00b5a00118b4cfdd9de292fda0e609cf6a8205d
refs/heads/master
<repo_name>jlehnert/tasks<file_sep>/tasks/src/main/java/net/lehnert/tasks/jpa/Task.java package net.lehnert.tasks.jpa; import java.util.*; import javax.persistence.*; @Entity public class Task { @GeneratedValue(strategy=GenerationType.SEQUENCE) @Id private long id; private String title; private String description; @Temporal(TemporalType.TIMESTAMP) private Date dueDate; @ManyToOne private Swimlane swimlane; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public void setSwimlane(Swimlane swimlane) { this.swimlane =swimlane; } public Swimlane getSwimlane() { return swimlane; } } <file_sep>/tasks/src/main/java/net/lehnert/tasks/jpa/Swimlane.java package net.lehnert.tasks.jpa; import java.util.*; import javax.persistence.*; @Entity public class Swimlane { @GeneratedValue(strategy=GenerationType.SEQUENCE) @Id private long id; private String name; @OneToMany(cascade=CascadeType.ALL) private List<Task> tasks; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Task> getTasks() { return tasks; } public void setTasks(List<Task> tasks) { this.tasks = tasks; } public void addTask(Task task) { if (this.tasks == null) { this.tasks = new ArrayList<Task>(); } this.tasks.add(task); } } <file_sep>/tasks/src/main/java/net/lehnert/tasks/wicket/OpenEntityManager.java package net.lehnert.tasks.wicket; import java.util.*; import javax.persistence.*; import org.apache.wicket.request.cycle.*; public class OpenEntityManager { public static EntityManager getEntityManager() { Iterator<IRequestCycleListener> listenerIterator = RequestCycle.get().getListeners().iterator(); while (listenerIterator.hasNext()) { IRequestCycleListener listener = listenerIterator.next(); if (listener instanceof RequestCycleListenerCollection) { Iterator<IRequestCycleListener> iterator = ((RequestCycleListenerCollection) listener).iterator(); while (iterator.hasNext()) { IRequestCycleListener appListener = iterator.next(); if (appListener instanceof OpenEntityManagerListener) { return ((OpenEntityManagerListener) appListener).getEntityManager(); } } } } return null; } }<file_sep>/tasks/src/main/java/net/lehnert/tasks/wicket/OpenEntityManagerListener.java package net.lehnert.tasks.wicket; import javax.persistence.*; import org.apache.wicket.*; import org.apache.wicket.request.*; import org.apache.wicket.request.cycle.*; public class OpenEntityManagerListener implements IRequestCycleListener { private ThreadLocal<EntityManager> entityManagerThreadLocal = new ThreadLocal<EntityManager>(); @Override public void onBeginRequest(RequestCycle cycle) { EntityManagerFactory entityManagerFactory = ((WicketApplication) Application.get()).getEntityManagerFactory(); entityManagerThreadLocal.set(entityManagerFactory.createEntityManager()); getEntityManager().getTransaction().begin(); } @Override public void onEndRequest(RequestCycle cycle) { EntityManager entityManager = entityManagerThreadLocal.get(); if (entityManager != null && entityManager.isOpen()) { entityManager.getTransaction().commit(); entityManager.close(); } } @Override public void onDetach(RequestCycle cycle) { entityManagerThreadLocal.remove(); } public EntityManager getEntityManager() { synchronized (entityManagerThreadLocal) { if (entityManagerThreadLocal.get() == null) { EntityManagerFactory entityManagerFactory = ((WicketApplication) Application.get()).getEntityManagerFactory(); entityManagerThreadLocal.set(entityManagerFactory.createEntityManager()); getEntityManager().getTransaction().begin(); } return entityManagerThreadLocal.get(); } } @Override public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler) { // TODO Auto-generated method stub } @Override public void onRequestHandlerScheduled(RequestCycle cycle, IRequestHandler handler) { // TODO Auto-generated method stub } @Override public IRequestHandler onException(RequestCycle cycle, Exception ex) { // TODO Auto-generated method stub return null; } @Override public void onExceptionRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler, Exception exception) { // TODO Auto-generated method stub } @Override public void onRequestHandlerExecuted(RequestCycle cycle, IRequestHandler handler) { // TODO Auto-generated method stub } @Override public void onUrlMapped(RequestCycle cycle, IRequestHandler handler, Url url) { // TODO Auto-generated method stub } }
7973e35808764b01fb1bfd6c62bb35f340c18db0
[ "Java" ]
4
Java
jlehnert/tasks
bdeba1dc0e47915f43161413dabe7690b7d4e77d
76e55221189580f0c1f9cbf0217b0c15aaea7594
refs/heads/master
<file_sep>## Read source file and only extract Feb 1 and 2 of 2007 library(sqldf) library(lubridate) library(graphics) library(grDevices) subdata <- read.csv.sql("household_power_consumption.txt", sql = "select * from file where Date = '2/2/2007' or Date = '1/2/2007'", header=TRUE, sep = ";") closeAllConnections() ## Paste and format Date/Time columns subdata$datetime <- paste(subdata$Date, subdata$Time, sep=' ') subdata$datetime <- strptime(subdata$datetime, "%d/%m/%Y %H:%M:%S") ## Set PNG device and margins png("plot4.png", width=480, height=480) par(mfcol=c(2,2), mar = c(4,4,2,1), oma=c(0,0,2,0)) ##Graph 1, in upper left plot(subdata$datetime, subdata$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="") ##Graph 2, in lower left with(subdata, plot(datetime, Global_active_power, type="n", ylab="Energy sub metering", xlab="", ylim=c(0,38))) with(subdata, points(datetime, Sub_metering_1, type="l", col="black")) with(subdata, points(datetime, Sub_metering_2, type="l", col="red")) with(subdata, points(datetime, Sub_metering_3, type="l", col="blue")) legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col = c("black", "red", "blue"), lty=1, cex=0.8, bty="n") ##Graph 3, in upper right plot(subdata$datetime, subdata$Voltage, type="l", xlab="datetime", ylab="Voltage") ##Graph 4, in lower right plot(subdata$datetime, subdata$Global_reactive_power, type="l", xlab="datetime", ylab="Global_reactive_power") dev.off() <file_sep>## Read source file and only extract Feb 1 and 2 of 2007 library(sqldf) library(lubridate) library(graphics) library(grDevices) subdata <- read.csv.sql("household_power_consumption.txt", sql = "select * from file where Date = '2/2/2007' or Date = '1/2/2007'", header=TRUE, sep = ";") closeAllConnections() ## Paste and format Date/Time columns subdata$datetime <- paste(subdata$Date, subdata$Time, sep=' ') subdata$datetime <- strptime(subdata$datetime, "%d/%m/%Y %H:%M:%S") ## Plot Line graph by series and with legend, then save as PNG file png("plot3.png", width=480, height=480) with(subdata, plot(datetime, Global_active_power, type="n", ylab="Energy sub metering", xlab="", ylim=c(0,38))) with (subdata, points(datetime, Sub_metering_1, type="l", col="black")) with (subdata, points(datetime, Sub_metering_2, type="l", col="red")) with (subdata, points(datetime, Sub_metering_3, type="l", col="blue")) legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col = c("black", "red", "blue"), lty=1, cex=0.8) dev.off() <file_sep>## Read source file and only extract Feb 1 and 2 of 2007 library(sqldf) library(lubridate) library(graphics) library(grDevices) subdata <- read.csv.sql("household_power_consumption.txt", sql = "select * from file where Date = '2/2/2007' or Date = '1/2/2007'", header=TRUE, sep = ";") closeAllConnections() ## Paste and format Date/Time columns subdata$datetime <- paste(subdata$Date, subdata$Time, sep=' ') subdata$datetime <- strptime(subdata$datetime, "%d/%m/%Y %H:%M:%S") ## Plot histogram and save as PNG file png("plot2.png", width=480, height=480) hist(subdata$Global_active_power, xlab="Global Active Power (kilowatts)", ylab="Frequency", main="Global Active Power", col="red") dev.off()
837dd14a4db823119bdf54840ed31c35f32ad1e7
[ "R" ]
3
R
edieg2000/ExData_Plotting1
ace5d45b333ddd3c0ad607d1d556dc1833827e6b
58a50e91009940ff68eacabe799e821dde3cb100
refs/heads/master
<file_sep># iic3585-memeticame-g4 Proyecto del curso IIC3585 para construcción de una Applicacion Nativa en Android <file_sep>package com.retekne.iic3380g4memeticame.tasks; import android.content.ContentResolver; import android.content.Context; import android.os.AsyncTask; import com.retekne.iic3380g4memeticame.domains.Contact; import java.util.ArrayList; /** * Created by quelves on 14/09/2016. */ public class ContactTask extends AsyncTask<String, Void, ArrayList<Contact>> { private Context context; private ContentResolver mResolver; @Override protected ArrayList<Contact> doInBackground(String... params) { return null; } }
6153ca66afb7c50d8eabc4b04e66362096bffdc0
[ "Markdown", "Java" ]
2
Markdown
retekne/iic3585-memeticame-g4
184d29bd65b788a117697f145162450ce5f34859
b68702b7322ce01815b0b4c39e633e60cb6ca0cf
refs/heads/main
<repo_name>yangzi33/kmeans-stitch<file_sep>/vignette.Rmd --- title: "Creating Cross-Stitch Patterns of Images Using K-Means Clustering" subtitle: "STA314H1 - Fall 2020" author: "<NAME>" date: "November 3^rd^, 2020" output: pdf_document --- ```{r knitsetup, include = FALSE} knitr::opts_chunk$set(warning = FALSE) ``` # Introduction This article demonstrates how to make a cross-stitch pattern of images, based on the k-means clustering algorithm. ## Setup It is required for you to use the following libraries. Note that if you don't have any of these, undo the commenting before you run: ```{r libraries, message=FALSE} # Uncomment the following if need to install libraries # install.packages("imager") # install.packages("tidyverse") # install.packages("tidymodels") # install.packages("sp") # install.packages("scales") # install.packages("cowplot") # devtools::install_github("sharlagelfand/dmc") library(imager) library(tidyverse) library(tidymodels) library(sp) library(scales) library(cowplot) library(dmc) ``` In addition, we load the script `functions.R`, which will provide us the functions we are going to demonstrate: ```{r loadfunctions} source('functions.R') ``` The script `functions.R` contains the following functions: a. `process_image()` b. `scree_plot()` c. `colour_strips()` d. `make_pattern()` For demonstration, let's make a cross-stitch pattern of a Warhol screenprint of Elizabeth Taylor: ```{r} plot(imager::load.image('sakura.jpg')) ``` ## Workflow Our work flow can be briefly described as: $$\text{Get Cluster Data for Multiple }K's \rightarrow \text{Choose Ideal }K\rightarrow \text{Make Cross-Stitch Pattern with Chosen $K$.} $$ # Generating Cross-Stitch Patterns Before we begin, let's go over the functions we need to make a cross-stitch pattern. ## `process_image()` Function `process_image()` allows us to retrieve the cluster information based on a list of k's. This function takes two inputs: - `image_file_name`: the path of the image you want to cluster; - `k_list`: a list of numbers of centers in the clustering. For instance, if we want to cluster the image with 2, 3, 7 cluster centers respectively, then `k_list` takes `c(2, 3, 7)` as the input. Calling the function as shown below allows us to retrieve the clustering information of the Warhol picture, from 1 to 10 cluster centers. We want to choose the best number of cluster centers later: ```{r} cluster_info <- process_image('sakura.jpg', c(5:6)) ``` The output of `process_image()` stores information in variable `cluster_info`, for every k in `k_list`. For each k, the output contains - `kclust`: the output of calling `kmeans(x = select(image_dat, c(-x, -y)), centers = .x, nstart = 5)`; - `tidied`: the tidied data of `kclust`, i.e. `tidy(kclust)`; - `glanced`: the `glance` of `kclust`. Let's check the output of each of the above, for `k = 2`: ```{r} cluster_info$kclust[[2]] cluster_info$tidied[[2]] cluster_info$glanced[[2]] ``` **Note**: From now on, `cluster_info` will store all the clustering information of the Warhol image, which will be used as the input for the following functions. ## `scree_plot` This function takes the input `cluster_info`, as produces a scree plot based on `glanced`: and returns a scree plot, with respect to the maximum numbers of cluster centers in `k_list` we inputted for `process_image()` (10 in this case): ```{r} scree_plot(cluster_info) ``` Note that it's hard to tell what number of centers to choose based on scree plot. Let's try the ratio version: ```{r} clusterings <- cluster_info %>% unnest(cols = c(glanced)) nclust = length(clusterings$k) ratio = rep(NA, nclust-1) for (kk in 2:nclust) { ratio[kk-1] = clusterings$tot.withinss[kk]/clusterings$tot.withinss[kk-1] } plot_data <- data.frame(k = clusterings$k[2:nclust],ratio) ggplot(plot_data, aes(x = k, y = ratio)) + geom_line() ``` From which we can tell that the number of clusters seems to be 5. ## `colour_strips()` This function takes the input `cluster_info`, and produces the DMC colour strips that are closest to the RGB colours of cluster centers, for each k in `k_list`. ```{r} colour_strips(cluster_info) ``` Looks like 5 is a good option. Let's use 5 centers to make our cross-stitch pattern! ## `make_pattern()` Finally, this function allows us to plot the cross-stitch of our image. This function takes several inputs: - `cluster_info`: The output of `process_image`. - `k`: The number of cluster centers. - `x_size`: The total number of possible stitches in the horizontal direction. - `black_white`: The logical value indicating whether the cross-sitch will be plotted in black and white. Default is `FALSE`, such that we have a cross-stitch where the i^th cluster has the DMC colour that is closest to the RGB colour of the i^th^ cluster center. - `background_colour`: The colour of the background. Default is `NULL`, such that we have a transparent background. Here is where things are getting exciting. Let's make a $60\times 60$ colourful cross-stitch of Elizabeth Taylor's picture, with 4 cluster centers: ```{r} make_pattern(cluster_info, 6, 100) ``` or, if we prefer a black-and-white version: ```{r} make_pattern(cluster_info, 5, 60, black_white = TRUE) ``` Furthermore, we can make a colourful one with light green blackground: ```{r} make_pattern(cluster_info, 5, 60, background_colour = "light green") ``` # Session Information ```{r, echo = FALSE} sessionInfo() ``` <file_sep>/README.md # K Means Image Cross-Stitch [See here](https://github.com/yangzi33/kmeans-stitch/blob/main/vignette.pdf) for usage.<file_sep>/functions.R ### STA314 Assignment 1: Cross-Stitch ### # Author: <NAME> # # Student Number: 1004804759 # # Contact: <EMAIL> # ######################################### # Install the required libraries # Uncomment the following if you don't have them # install.packages("imager") # install.packages("tidyverse") # install.packages("tidymodels") # install.packages("sp") # install.packages("scales") # install.packages("cowplot") # devtools::install_github("sharlagelfand/dmc") # Loading libraries library(imager) library(tidyverse) library(tidymodels) library(sp) library(scales) library(cowplot) library(dmc) # From change_solution.R change_resolution <- function(image_df, x_size) { ## change_resolution(image_df, x_size) subsamples an image to produce ## a lower resolution image. Any non-coordinate columns in the data ## frame are summarized with their most common value in the larger ## grid cell. ## ## Input: ## - image_df: A data frame in wide format. The x-coordinate column MUST ## be named 'x' and the y-coordinate column MUST be named 'y'. ## Further columns have no naming restrictions. ## - x_size: The number of cells in the x-direction. The number of cells ## in the vertical direction will be computed to maintain the ## perspective. There is no guarantee that the exact number ## of cells in the x-direction is x_size ## ## Output: ## - A data frame with the same column names as image_df, but with fewer ## entries that corresponds to the reduced resolution image. ## ## Example: ## library(imager) ## library(dplyr) ## fpath <- system.file('extdata/Leonardo_Birds.jpg',package='imager') ## im <- load.image(fpath) ## im_dat<- as.data.frame(im,wide = "c") %>% rename(R = c.1, G = c.2, B = c.3) %>% ## select(x,y,R,G,B) ## agg_image <- change_resolution(im_dat, 50) if(!require(sp)) { stop("The sp packages must be installed. Run install.packages(\"sp\") and then try again.") } if(!require(dplyr)) { stop("The dplyr packages must be installed. Run install.packages(\"dplyr\") and then try again.") } sp_dat <- image_df gridded(sp_dat) = ~x+y persp = (gridparameters(sp_dat)$cells.dim[2]/gridparameters(sp_dat)$cells.dim[1]) y_size = floor(x_size*persp) orig_x_size = gridparameters(sp_dat)$cells.dim[1] orig_y_size = gridparameters(sp_dat)$cells.dim[2] x_res = ceiling(orig_x_size/x_size) y_res = ceiling(orig_y_size/y_size) gt = GridTopology(c(0.5,0.5), c(x_res, y_res), c(floor(orig_x_size/x_res), floor(orig_y_size/y_res))) SG = SpatialGrid(gt) agg = aggregate(sp_dat, SG, function(x) names(which.max(table(x)))[1] ) agg@grid@cellsize <- c(1,1) df <- agg %>% as.data.frame %>% rename(x = s1, y = s2) %>% select(colnames(image_df)) return(df) } # Function a process_image <- function(image_file_name, k_list) { ########################################################################### ## process_image gets k-cluster info of input image, where k is the ## numbers of cluster centers in input list k_list ## Input: ## - image_file_name: path of the image to cluster as a string ## ## - k_list: list of cluster centers. For instance, if we want ## to cluster the image with 1, 2, 3 centers respec- ## tively, then k_list will be the list c(1:3). ## ## Output: A tibble `cluster_info` containing cluster information for ## each k in k_list. For each k, cluster_info[[k]] contains the ## following info: ## ## - k_clust: the original output of the kmeans() call on image with k. ## ## - glanced: the glance of cluster_info[[k]], which will be used to ## produce the scree plot. ## ## - tidied: tidied clusters info, with their associated RGB value and ## the DMC value closest to the RGB color. ## ########################################################################### # Loading image and store color info as data frame image_dat img <- imager::load.image(image_file_name) image_dat <- as.data.frame(img, wide = "c") %>% rename(R = c.1, G = c.2, B = c.3) kclusts <- tibble(k = k_list) %>% mutate( kclust = map(k, ~kmeans(x = select(image_dat, c(-x, -y)), centers = .x, nstart = 5)), glanced = map(kclust, glance), tidied = map(k, ~( tidy(kclust[[.x]]) %>% mutate(RGB = rgb(R, G, B), # Initialize the DMC column with null entries DMC = vector("character", length = .x))) ) ) # Adding DMC for (k in k_list) { for (cen in 1:length(kclusts$tidied[[k]]$RGB)) { kclusts$tidied[[k]]$DMC[cen] <- dmc(kclusts$tidied[[k]]$RGB[cen])$hex } kclusts$kclust[[k]] <- augment(kclusts$kclust[[k]], image_dat) } return(kclusts) } # Function b scree_plot <- function(cluster_info) { ########################################################################### ## Produces the scree plot of cluster_info - the output of `process_image`. ## Input: ## - cluster_info: the output of `process_image`. Details can be found ## in documentation of function A: process_image(). ## ## Output: ## -A scree plot based on `glanced` for each k in cluster_info. ## ########################################################################### ggplot(cluster_info %>% unnest(cols = c(glanced)), aes(x = k, y = tot.withinss)) + geom_line() + geom_point() } # Function C colour_strips <- function(cluster_info) { ########################################################################### ## For each k in cluster_info$k, produces a DMC colour strip. ## Input: ## - cluster_info: the output of `process_image`. Details can be found ## in documentation of function A: process_image(). ## ## Output: ## - k colour strips. ## The i^th colour strip ( where 1 <= i <= length(k_list)) contains ## the closest DMC colour of centers ## ########################################################################### for (k in cluster_info$k) { n_col = length(cluster_info$tidied[[k]]$DMC) rect_dat <- tibble(x1 = c(0: (n_col - 1)), x2 = c(1: n_col), y1 = rep(0, n_col), y2 = rep(1, n_col), colour = cluster_info$tidied[[k]]$DMC) k_strip <- ggplot(rect_dat) + coord_fixed() + geom_rect(aes(xmin = x1, xmax = x2, ymin = y1, ymax = y2, fill = colour)) + geom_text(aes(x = x1 + (x2 - x1) / 2, y = y1 + (y2 - y1) / 2, label = colour), size = 24 / n_col, colour = "white") + scale_fill_manual(values = rect_dat$colour) + theme_void() + theme(legend.position = "none") } plot_grid(k_strip) } # Function D make_pattern <- function(cluster_info, k, x_size, black_white = FALSE, background_colour = NULL) { ########################################################################### ## Make a cross-stitch pattern based on image inputted to `process_image` ## Inputs: ## - cluster_info: Output of `process_image()` ## ## - k: The chosen number of clusters ## ## - x_size: The approximate total number of possible stitches in the ## horizontal direction. ## ## - black_white: Logical (or boolean) value that indicates whether ## the cross-stitch produced is colourful (FALSE) or ## black-and-white (TRUE). Default is set to FALSE. ## ## - background_colour: Background colour of the cross-stitch plot. ## Default is set to NULL, which produces a ## transparent background. Input takes colour ## names such as "blue", or colour codes such ## as "#0000FF". ## ## Output: The cross-stitch pattern of image input with k centers. The pattern ## is "stitched" on surface with colour of input `background_colour`. ## ########################################################################### # Resize the image resize_image_info <- cluster_info$kclust[[k]] %>% select(x, y, R, G, B, .cluster) resized_image <- change_resolution(resize_image_info, x_size) dmc_names <- c() for (i in 1:k) { dmc_names <- append(dmc_names, dmc(cluster_info$tidied[[k]]$RGB[i])$name) } if (!black_white) { # Colourful resized_image %>% ggplot(aes(x = x, y = y)) + geom_point(aes(shape = .cluster, col = .cluster)) + scale_y_reverse() + theme_void() + scale_colour_manual(values = cluster_info$tidied[[k]] %>% select(DMC) %>% deframe, label = cluster_info$kclust[[k]] %>% select(.cluster) %>% deframe,) + theme(panel.background = element_rect(fill = background_colour, colour = background_colour)) + labs(shape = "Cluster", col = "DMC Colour") } else { # Black and white resized_image %>% ggplot(aes(x = x, y = y)) + geom_point(aes(shape = .cluster)) + scale_y_reverse() + theme_void() + theme(panel.background = element_rect(fill = background_colour, colour = background_colour)) + labs(shape = "Cluster") } } <file_sep>/playground.Rmd --- title: "R Notebook" output: html_notebook --- ```{r} library(imager) library(tidyverse) library(tidymodels) library(sp) library(scales) library(cowplot) #devtools::install_github("sharlagelfand/dmc") library(dmc) ``` ```{r} process_image <- function(image_file_name, k_list) { img <- imager::load.image('warhol.jpeg') # Getting RGB info and store as data frame rgb_df <- as.data.frame(img, wide = "c") %>% rename(R = c.1, G = c.2, B = c.3) %>% select(c(-x, -y)) kclust <- kmeans(rgb_df, centers = k_list, nstart = 5) ret_tb <- tidy(kclust) %>% mutate(RGB = rgb(R, G, B), # Storing RGB in a column DMC = map(RGB, ~ dmc(.x))) # Storing DMC info based on corresponding RGB return(ret_tb) } # Using k = 4 cluster_info <- process_image('warhol.jpeg', 4) head(cluster_info) ``` ```{r} img <- imager::load.image('warhol.jpeg') # Getting RGB info and store as data frame image_dat <- as.data.frame(img, wide = "c") %>% rename(R = c.1, G = c.2, B = c.3) # select(-c(x, y)) km <- tidy(kmeans(x = image_dat, centers = 2, nstart = 5)) k_list = c(2) kclusts <- tibble(k = k_list) %>% mutate( kclust = map(k, ~kmeans(x = select(image_dat, c(-x, -y)), centers = .x, nstart = 5)), # # tidy_with_dmc = map(k, ~(tidy(kmeans(x = rgb_dat, centers = .x, nstart = 5)) %>% # mutate(DMC = map(rgb(R, G, B), ~dmc(.x))))), tidied = map(kclust, ~(tidy(.x) %>% mutate(RGB = rgb(R, G, B), DMC = map(RGB, ~dmc(.x)$hex))) ), glanced = map(kclust, glance), ) f <- kclusts$centers f$x ff <- kclusts$kclust ############################### kclusts <- tibble(k = k_list) %>% mutate( k_clust = map(k, ~kmeans(x = select(image_dat, c(-x, -y)), centers = .x, nstart = 5)), ) kclusts$k_clust[[1]]$centers[1] for (k in k_list) { curr_clust <- kclusts$k_clust[[k]] # for (cen in 1:nrow(curr_clust$centers)) { curr_clust$DMC[cen] <- dmc(rgb(curr_clust$centers[1], curr_clust$centers[2], curr_clust$centers[3]))$hex # } } kclusts <- kclusts %>% mutate( tidied = map(k, ~( augment(kclusts$k_clust[[.x]], image_dat) %>% rename(cluster = .cluster) %>% mutate(RGB = rgb(R, G, B)) ))) kclusts <- tibble(k = k_list) %>% mutate( kclust = map(k, ~kmeans(x = select(image_dat, c(-x, -y)), centers = .x, nstart = 5)), glanced = map(kclust, glance), tidied = map(k, ~( tidy(kclust[[.x]]) %>% mutate(RGB = rgb(R, G, B), DMC = c("")) # augment(kclusts$kclust[[.x]], image_dat) %>% # rename(cluster = .cluster) %>% # mutate(RGB = rgb(R, G, B)) )) ) for (k in k_list) { curr_tidied <- kclusts$tidied[[k]] for (cen in 1:length(curr_tidied$RGB)) { curr_tidied$DMC[cen] <- dmc(curr_tidied$RGB[cen])$hex } } single_clust <- kmeans(x = image_dat, centers = 2, nstart = 5) ################################################ for (cen in 1:nrow(single_clust$centers)) { single_clust$DMC[cen] <- dmc(rgb(single_clust$centers[cen, 3], single_clust$centers[cen, 4], single_clust$centers[cen, 5]))$hex } tidied <- augment(single_clust, image_dat) %>% rename(cluster = .cluster) %>% mutate(RGB = rgb(R, G, B)) ############################### k = 3 cluster_info$kclust[[k]] %>% ggplot(aes(x = x, y = y)) + geom_point(aes(shape = .cluster, col = .cluster)) + scale_y_reverse() + theme_void() + scale_colour_manual(values = cluster_info$tidied[[k]] %>% select(DMC) %>% deframe, label = cluster_info$kclust[[k]] %>% select(.cluster) %>% deframe) + theme(panel.background = element_rect(fill = NULL, colour = NULL)) cluster_info$tidied[[k]]$cluster ############################### SINGLE CLUSTER single_clust <- kmeans(x = image_dat, centers = 2, nstart = 5) for (cen in 1:nrow(single_clust$centers)) { single_clust$DMC[cen] <- dmc(rgb(single_clust$centers[cen, 3], single_clust$centers[cen, 4], single_clust$centers[cen, 5]))$hex } tidied <- augment(single_clust, image_dat) %>% rename(cluster = .cluster) %>% mutate(RGB = rgb(R, G, B)) ############################### rgb(single_clust$centers[1, 3], single_clust$centers[1, 4]) nrow(single_clust$centers) single_clust$centers[1,5] tidied <- augment(single_clust, image_dat) %>% rename(cluster = .cluster) %>% mutate(RGB = rgb(R, G, B)) center_col <- [cluster] tidied <- tidied %>% mutate(DMC = ) # for (i in c(1:nrow(tidied))) { # i_cluster <- tidied$cluster[i][1] # center_color <- rgb(single_clust$centers[i_cluster, 3], # single_clust$centers[i_cluster, 4], # single_clust$centers[i_cluster, 5]) # tidied$DMC[i] <- dmc(center_color)$hex # } dmc(tidied$RGB[1])$hex class(dmc("#FFFBBB")$hex) f <- single_clust$centers ##################################### # %>% unnest(cols = c(tidied)) ggplot(f, aes(x, y)) + geom_point() a <- head(kclusts[2]) kclust <- tibble(k_list) %>% kmeans(rgb_df, centers = k_list, nstart = 5) ret_tb <- tidy(kclust) %>% mutate(RGB = rgb(R, G, B), DMC = map(RGB, ~ dmc(.x))) head(tidy(kclust)) kclust show_col(ret_tb$RGB) head(centers) cluster_info <- process_image("warhol.jpeg", c(1:4)) ncol = length(cluster_info$DMC) cluster_info$RGB ``` ```{r} cluster_info$tidied[[2]]$DMC n_col = length(cluster_info$tidied[[2]]$DMC) n_col rect_dat <- tibble(x1 = c(0:(n_col-1)), x2 = c(1:n_col), y1 = rep(0,n_col), y2 =rep(1,n_col), colour = cluster_info$tidied[[1]]$DMC) rect_dat %>% ggplot() + coord_fixed() + geom_rect(aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill=colour), color=rect_dat$colour) + geom_text(aes(x=x1+(x2-x1)/2, y=y1+(y2-y1)/2, label=colour), size=24/n_col) + scale_fill_manual(values = rect_dat$colour)+ theme_void() + theme(legend.position = "none") ``` ```{r} for (k in c(1:3)){ n_col = length(cluster_info$tidied[[k]]$DMC) rect_dat <- tibble(x1 = c(0: (n_col - 1)), x2 = c(1: n_col), y1 = rep(0, n_col), y2 = rep(1, n_col), colour = cluster_info$tidied[[k]]$DMC) ggplot(rect_dat) + coord_fixed() + geom_rect(aes(xmin = x1, xmax = x2, ymin = y1, ymax = y2, fill = colour)) + geom_text(aes(x = x1 + (x2 - x1) / 2, y = y1 + (y2 - y1) / 2, label = colour), size = 24 / n_col, colour = "white") + scale_fill_manual(values = rect_dat$colour) + theme_void() + theme(legend.position = "none") } ```
7a791d910b52fd92b2260fb59552683b2952002a
[ "Markdown", "R", "RMarkdown" ]
4
RMarkdown
yangzi33/kmeans-stitch
1b1f1b28dabfece2d6c8d608b5926094714e91c3
814ad531d37dc0d3711892d84050bae6d3de1f9f
refs/heads/master
<repo_name>jwengelin/oop2019<file_sep>/BattleSim/BattleSim/Battlefield.cs using BattleSimEntities; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BattleSim { class Battlefield { private static Random random = new Random(); List<GameEntity> listOfPlayers = new List<GameEntity>(); public string Winner { get; set; } public Battlefield() { } public void AddPlayer(GameEntity entity) { listOfPlayers.Add(entity); } public void Battle() { GameEngine game = new GameEngine(); List<GameEntity> playersHasAttacked = new List<GameEntity>(); bool invalidEnemy = true; // Loops through so that every player attacks once. // How to account for dead players and figure out who wins? for (int i = 0; i<listOfPlayers.Count; i++) { var player = listOfPlayers[random.Next(listOfPlayers.Count)]; var secondPlayer = listOfPlayers[random.Next(listOfPlayers.Count)]; if (player.Dead is true || playersHasAttacked.Contains(player)) { continue; } while (invalidEnemy.Equals(true)) { if (secondPlayer.Dead) // If secondplayer is dead get a new target to attack { secondPlayer = listOfPlayers[random.Next(listOfPlayers.Count)]; continue; } if (player.Name.Equals(secondPlayer.Name)) // Checks if enemy is of same type as attacker { secondPlayer = listOfPlayers[random.Next(listOfPlayers.Count)]; // gets a new target if defender is same as attacker and continues loop continue; } break; } game.Attack(player, secondPlayer); playersHasAttacked.Add(player); } playersHasAttacked.Clear(); var listOfDead = listOfPlayers.Where(p => p.Dead == true).ToList(); } } } <file_sep>/BattleSim/BattleSimEntities/Human.cs using System; using System.Collections.Generic; using System.Text; namespace BattleSimEntities { public class Human : GameEntity { public override string Name => "Human"; public Human() : base (200, 50, 10) { } public override bool StrongAgainst(GameEntity entity) { if (entity is Monster || entity is Slime) { return true; } else { return false; } } public override bool WeakAgainst(GameEntity entity) { if (entity is Dragon) { return true; } else { return false; } } } } <file_sep>/BattleSim/BattleSimEntities/Monster.cs using System; using System.Collections.Generic; using System.Text; namespace BattleSimEntities { public class Monster : GameEntity { public override string Name => "Monster"; public Monster() : base(150, 100, 10) { } public override bool StrongAgainst(GameEntity entity) { if (entity is Slime || entity is Human) { return true; } else { return false; } } public override bool WeakAgainst(GameEntity entity) { if (entity is Human || entity is Dragon) { return true; } else { return false; } } } } <file_sep>/BattleSim/BattleSimEntities/Slime.cs using System; using System.Collections.Generic; using System.Text; namespace BattleSimEntities { public class Slime : GameEntity { public override string Name => "Slime"; public Slime() : base (50, 20, 5) { } public override bool StrongAgainst(GameEntity entity) { return false; } public override bool WeakAgainst(GameEntity entity) { return true; } } } <file_sep>/BattleSim/BattleSim/GameEngine.cs using BattleSimEntities; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace BattleSim { class GameEngine { private static Random random = new Random(); public int Attack(GameEntity attacker, GameEntity defender) { var damage = (double)random.Next(attacker.Damage / 10, attacker.Damage); if (attacker.StrongAgainst(defender)) damage *= 1.2; if (defender.WeakAgainst(attacker)) damage *= 1.2; defender.Health -= (int)damage; return (int)damage; } public (GameEntity First, GameEntity Second) RollForInitiative(GameEntity a, GameEntity b) { while (true) { int rollForA = random.Next(0, a.Agility); int rollForB = random.Next(0, b.Agility); if (rollForA > rollForB) { return (a, b); } if (rollForB > rollForA) { return (b, a); } } } public void Battle(GameEntity a, GameEntity b) { var initiative = RollForInitiative(a, b); int firstAttack = Attack(initiative.First, initiative.Second); int secondAttack = Attack(initiative.Second, initiative.First); } } } <file_sep>/BattleSim/BattleSim/Program.cs using System; using BattleSimEntities; namespace BattleSim { class Program { static void Main(string[] args) { var game = new GameEngine(); var human = new Human(); var monster = new Monster(); var dragon = new Dragon(); var slime = new Slime(); // EXERCISE 1 ------------------------------------------------------------ //------------------------------------------------------------------------ //EXERCISE 2 ---------------------------------------------------------------- //if(monster.WeakAgainst(human)) // Console.WriteLine("Monster has weak defense against Human"); //if (human.StrongAgainst(monster)) // Console.WriteLine("Human has strong attack against Monster"); //if (dragon.StrongAgainst(human) && dragon.StrongAgainst(monster)) // Console.WriteLine("Dragon is pretty bad ass..."); //Console.ReadKey(); //---------------------------------------------------------------------------- //EXERCISE 3 ----------------------------------------------------------------- //Console.WriteLine("Human attacks Monster!"); //var damage = game.Attack(human, monster); //Console.WriteLine($"{damage} points of damage, Monster has {monster.Health} health left!"); //Console.ReadKey(); //---------------------------------------------------------------------------- // EXERCISE 4 ---------------------------------------------------------------- //while (true) //{ // var initative = game.RollForInitiative(dragon, slime); // Console.WriteLine($"{initative.First.Name} would attack {initative.Second.Name} first"); // Console.ReadKey(); //} //---------------------------------------------------------------------------- // EXERCISE 5 ---------------------------------------------------------------- //var counter = 0; //while (!dragon.Dead) //{ // if (slime.Dead) // { // counter++; // slime = new Slime(); // } // game.Battle(slime, dragon); //} //Console.WriteLine($"Slime death counter: {counter}"); //Console.ReadKey(); //------------------------------------------------------------------------------ // EXERCISE 6 ------------------------------------------------------------------ //Not fully functioning yet.. var battlefield = new Battlefield(); // 4 slimes vs 1 monster vs 2 humans battlefield.AddPlayer(new Slime()); battlefield.AddPlayer(new Slime()); battlefield.AddPlayer(new Slime()); battlefield.AddPlayer(new Slime()); battlefield.AddPlayer(new Monster()); battlefield.AddPlayer(new Human()); battlefield.AddPlayer(new Human()); while (battlefield.Winner == null) { battlefield.Battle(); } Console.WriteLine($"{battlefield.Winner} is the winner!"); Console.ReadKey(); //------------------------------------------------------------------------------------ } } } <file_sep>/ProgrammingExercises/ProgrammingExercises/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProgrammingExercises { class Program { static void Main(string[] args) { //EXERCISE 1 - UNCOMMENT BELOW----------------------------- //int? y = ReadInt("Type a number: "); //int? x = ReadInt("Type another number: "); //Console.WriteLine($"{y}+{x} = {y + x}"); //Console.ReadLine(); //---------------------------------------- //EXERCISE 2 - UNCOMMENT BELOW ----------------------------- //List<string> yearList = new List<string>(); //for (int i = 0; i < 8; i++) //{ // string year = LeapYearCalculator("Write a year: "); // if (year.Equals("Year must be between 0 and 9999.") || year.Equals("Thats not a correct year input.")) // { // continue; // } // Console.WriteLine(year); // yearList.Add(year); //} //yearList.ForEach(i => Console.Write("{0}\n", i)); //Console.ReadLine(); //--------------------------------------------------------- //EXERCISE 3 - UNCOMMENT BELOW----------------------------- //Console.Write("Enter string to see if palindrome: "); //string input = Console.ReadLine(); //bool isPalindrome = IsPalindrome(input); //if (isPalindrome is true) //{ // Console.WriteLine($"{input} is palindrome!"); //} else //{ // Console.WriteLine($"{input} is not palindrome!"); //} //Console.ReadLine(); //--------------------------------------------------------- //EXERCISE 4 - UNCOMMENT BELOW----------------------------- //List<int> intList = new List<int>(); //for (int i = 0; i <=100; i++) //{ // intList.Add(i); //} //WriteFizz(intList); //Console.ReadLine(); //--------------------------------------------------------- //EXERCISE 5 - UNCOMMENT BELOW----------------------------- //Console.Write("Enter number between 0-100: "); //RandomGame(int.Parse(Console.ReadLine())); //--------------------------------------------------------- //EXERCISE 6 - UNCOMMENT BELOW----------------------------- //Console.Write("Enter number between 0-100: "); //RandomGameVsAi(int.Parse(Console.ReadLine())); //--------------------------------------------------------- } public static int? ReadInt(string input) { int? x = null; bool tryAgain = true; while (tryAgain is true) { try { Console.Write(input); x = int.Parse(Console.ReadLine()); tryAgain = false; } catch (Exception) { Console.WriteLine("Thats not a number, try again: "); } } return x; } public static string LeapYearCalculator (string input) { int x = 0; bool tryAgain = true; bool isLeapYear = false; string year = null; while (tryAgain is true) { try { Console.Write(input); x = int.Parse(Console.ReadLine()); isLeapYear = DateTime.IsLeapYear(x); tryAgain = false; if (x > 9999 && x < 0) { Console.WriteLine("Year must be between 0 and 9999."); tryAgain = true; } } catch (Exception) { Console.WriteLine("Thats not a correct year input, try again: "); } } year = x.ToString(); if (isLeapYear is true) { return year + "*"; } return year; } public static bool IsPalindrome(string input) { { bool isPalindrome = false; input = input.ToLower(); input = input.Replace(" ", string.Empty); char[] charArray = input.ToCharArray(); Array.Reverse(charArray); string reversedString= new string(charArray); if (input.Equals(reversedString)) { return isPalindrome = true; } return isPalindrome; } } public static void WriteFizz(List<int> intList) { foreach (int val in intList) { string fizz = IsDivisible(val, 3); string buzz = IsDivisible(val, 5); if (fizz.Equals("Fizz")) { Console.Write("{0}\n", fizz); fizz = String.Empty; } else if (buzz.Equals("Buzz")) { Console.Write("{0}\n", buzz); buzz = String.Empty; } else { Console.Write("{0}\n", val); } } } public static string IsDivisible(int x, int divideBy) { if ((x % divideBy) == 0 && divideBy == 3) { return "Fizz"; } else if ((x % divideBy) == 0 && divideBy == 5) { return "Buzz"; } else { return "Cannot divide!"; } } public static void RandomGame (int inputNbr) { bool numberIsCorrect = false; var random = new Random(); var number = random.Next(0, 100); while (numberIsCorrect is false) { if (inputNbr > number) { Console.Write("Too high, try again: "); inputNbr = int.Parse(Console.ReadLine()); } else if (inputNbr < number) { Console.Write("Too low, try again: "); inputNbr = int.Parse(Console.ReadLine()); } else { Console.Write($"{inputNbr} is correct!"); numberIsCorrect = true; } } Console.ReadLine(); } public static void RandomGameVsAi(int inputNbr) { bool numberIsCorrect = false; var random = new Random(); var number = random.Next(0, 100); while (numberIsCorrect is false) { var computerGuess = random.Next(0, 100); if (inputNbr > number) { Console.Write("Too high, try again: "); inputNbr = int.Parse(Console.ReadLine()); } else if (inputNbr < number) { Console.Write("Too low, try again: "); inputNbr = int.Parse(Console.ReadLine()); } else { Console.Write($"{inputNbr} is correct!"); numberIsCorrect = true; } Console.WriteLine($"Computer guesses {computerGuess}"); if (computerGuess == number) { Console.WriteLine($"Computer is correct!"); } } Console.ReadLine(); } } }
58db95a93835fcf8a8c2f788d212c65268556ec2
[ "C#" ]
7
C#
jwengelin/oop2019
467d91cae7823c0bef284ff20c7f2a0a0c1a1bca
f6372e7eec1879e07dc161910ede4b40d88740f2
refs/heads/master
<repo_name>Rhytah/Holdings<file_sep>/Holdings/investments/urls.py from django.conf.urls import url, include from django.conf import settings from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^$', views.items, name = 'items'), url(r'^$', views.services, name = 'services'), url(r'^$', views.look, name = 'gallery'), ]<file_sep>/Holdings/investments/models.py from django.db import models from django.db import models from django.utils import timezone import datetime now = timezone.now() class Item(models.Model): item_name= models.CharField(max_length=30) item_id= models.IntegerField(primary_key = True, default=0) item_category = models.CharField(max_length=20) item_description= models.CharField(max_length=200) release_date = models.DateTimeField( null=True, blank = True,default = '') hardware = models.CharField(max_length=30, default='') class Service(models.Model): service_name= models.CharField(max_length=20, default='') service_category = models.CharField(max_length=200) hardware = models.ForeignKey(Item, on_delete = models.CASCADE) description = models.TextField(null=True, blank = True) class Look(models.Model): item_name= models.ForeignKey(Item, on_delete = models.CASCADE) Service = models.ForeignKey(Service, on_delete = models.CASCADE) gallery_item = models.ImageField(upload_to='img/photo') particular = models.CharField(max_length=30) # Create your models here. <file_sep>/Holdings/investments/admin.py from django.contrib import admin from .models import Item from .models import Service from .models import Look admin.site.register(Item) admin.site.register(Service) admin.site.register(Look) # Register your models here. <file_sep>/Holdings/investments/templates/index.html <!DOCTYPE html> <html lang="en-US"> {% extends "index.html" %} {% block someblock %} <a href="={{index}}">Anchor</a> {% endblock someblock %} <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>KEVMARK INVESTMENTS LTD</title> <link rel="stylesheet" href="css/components.css"> <link rel="stylesheet" href="css/icons.css"> <link rel="stylesheet" href="css/responsee.css"> <link rel="stylesheet" href="owl-carousel/owl.carousel.css"> <link rel="stylesheet" href="owl-carousel/owl.theme.css"> <!-- CUSTOM STYLE --> <link rel="stylesheet" href="css/template-style.css"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript" src="js/jquery-ui.min.js"></script> </head> <body class="size-1140"> <!-- TOP NAV WITH LOGO --> <header> <nav> <div class="line"> <div class="top-nav"> <div class="logo hide-l"> <a href="index.html"> </a> </div> <p class="nav-text">Custom menu text</p> <div class="top-nav s-12 l-5"> <ul class="right top-ul chevron"> <li><a href="index.html">Home</a> </li> <li><a href="product.html">Product</a> </li> <li><a href="services.html">Services</a> </li> </ul> </div> <ul class="s-12 l-2"> <li class="logo hide-s hide-m"> <a href="index.html"><img src="img/Asset 1.png" alt=""></a> </li> </ul> <div class="top-nav s-12 l-5"> <ul class="top-ul chevron"> <li><a href="gallery.html">Gallery</a> </li> <li> <a>Company</a> <ul> <li><a>Company 1</a> </li> <li><a>Company 2</a> </li> <li> <a>Company 3</a> <ul> <li><a>Company 3-1</a> </li> <li><a>Company 3-2</a> </li> <li><a>Company 3-3</a> </li> </ul> </li> </ul> </li> <li><a href="contact.html">Contact</a> </li> </ul> </div> </div> </div> </nav> </header> <section> <!-- CAROUSEL --> <div id="carousel"> <div id="owl-demo" class="owl-carousel owl-theme" > <div class="item"> <img src="img/logoart.png" alt=""> <div class="carousel-text"> <div class="line"> <div class="s-12 l-9"> <h2>Namono</h2> </div> <div class="s-12 l-9"> <p>Rhytah </p> </div> </div> </div> </div> <div class="item"> <img src="img/p1010557-1.jpg" alt=""> <div class="carousel-text"> <div class="line"> <div class="s-12 l-9"> <h2>Quality assurance ensured</h2> </div> <div class="s-12 l-9"> <p>bla bla bla bla </p> </div> </div> </div> </div> <div class="item"> <img src="img/cb499216591638dece242e5f2a8f824b--computer-setup-desk-setup.jpg" alt=""> <div class="carousel-text"> <div class="line"> <div class="s-12 l-9"> <h2>Kevmark here</h2> </div> <div class="s-12 l-9"> <p>mambo jambo here </p> </div> </div> </div> </div> </div> </div> <!-- FIRST BLOCK --> <div id="first-block"> <div class="line"> <h2>wHAT WE PRIDE OURSELVES IN</h2> <p class="subtitile">what we are made of </p> <div class="margin"> <div class="s-12 m-6 l-3 margin-bottom"> <i class="icon-paperplane_ico icon2x"></i> <h3>About</h3> <p>We deal in general merchandise ranging from various office equipment to Computer software and hardware. </p> </div> <div class="s-12 m-6 l-3 margin-bottom"> <i class="icon-star icon2x"></i> <h3>Company</h3> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </p> </div> <div class="s-12 m-6 l-3 margin-bottom"> <i class="icon-message icon2x"></i> <h3>Services</h3> <p>We offer various office services that include but not limited to...... </p> </div> <div class="s-12 m-6 l-3 margin-bottom"> <i class="icon-mail icon2x"></i> <h3>Contact</h3> <p>Plot 14B Nkrumah Rd (Inside Loy Enterprises) TEl: 0752/0772/0701-551508 </p> </div> </div> </div> </div> <!-- SECOND BLOCK --> <div id="second-block"> <div class="line"> <div class="margin-bottom"> <div class="margin"> <article class="s-12 l-8 center"> <h1> title</h1> <p class="margin-bottom">dedicated to offering organizations the best of office printing technology, office furniture and office supplies. Your company will benefit from our outstanding service and our environmentally friendly, cost-saving technology solutions. </p> <a class="button s-12 l-4 center" href="product.html">Read more</a> </article> </div> </div> </div> </div> <!-- GALLERY --> <div id="third-block"> <div class="line"> <h2>Visuals</h2> <p class="subtitile">See for yourself. </p> <div class="margin"> <div class="s-12 m-6 l-3"> <img src="img/basic-office-stationery-2013_7_31.jpg" alt="alternative text"> <p class="subtitile">Stationery </p> </div> <div class="s-12 m-6 l-3"> <img src="img/Crossover_1_Download.jpg" alt="alternative text"> <p class="subtitile">Office equipment </p> </div> <div class="s-12 m-6 l-3"> <img src="img/gunners-office-equipment-computer-2.jpg" alt="alternative text"> <p class="subtitile">Computer hardware </p> </div> <div class="s-12 m-6 l-3"> <img src="img/foster-desk-accessories-3.jpg" alt="alternative text"> <p class="subtitile">Office accessories </p> </div> </div> </div> </div> <div id="fourth-block"> <div class="line"> <div id="owl-demo2" class="owl-carousel owl-theme"> <div class="item"> <h2>Corporate Office Solutions</h2> <p class="s-12 m-12 l-8 center">Corporate Office Solutions is a Full Technology, Software and System Management company with the flexibility to meet any needs or requirements your company may have. We offer your company complete support, supplies, maintenance and repair. </p> </div> <div class="item"> <h2>Responsive components</h2> <p class="s-12 m-12 l-8 center">The task of managing your printing fleet can be one of the biggest unmanaged expenses in your business—management that includes consideration of the combination of toner and supply ordering to routine maintenance and repair. Choose the right printer and easily manage the devices in your network. </p> </div> <div class="item"> <h2>Retina ready</h2> <p class="s-12 m-12 l-8 center">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. </p> </div> </div> </div> </div> </section> <!-- FOOTER --> <footer> <div class="line"> <div class="s-12 l-6"> <p>Copyright 2017, Risi '90 </p> </div> </div> </footer> <script type="text/javascript" src="js/responsee.js"></script> <script type="text/javascript" src="owl-carousel/owl.carousel.js"></script> <script type="text/javascript"> jQuery(document).ready(function($) { $("#owl-demo").owlCarousel({ slideSpeed : 300, autoPlay : true, navigation : false, pagination : false, singleItem:true }); $("#owl-demo2").owlCarousel({ slideSpeed : 300, autoPlay : true, navigation : false, pagination : true, singleItem:true }); }); </script> </body> </html><file_sep>/Holdings/investments/views.py from django.http import HttpResponse from django.template import loader from django.views import generic from .models import Item def index(request): template = loader.get_template('investments/index.html') # return HttpResponse ("Welcome to Investments.") return render(request,'investments/html') def items(request): response ="A few of the vendors" return HttpResponse(response) def services(request, ): response = "VArious services" return HttpResponse(response) def look(request): return HttpResponse("See for yourself") #def index(request): # return HttpResponse ("Welcome to Investments.") # Create your views here. <file_sep>/Holdings/investments/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-01 10:08 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Item', fields=[ ('item_name', models.CharField(max_length=30)), ('item_id', models.IntegerField(default=0, primary_key=True, serialize=False)), ('item_category', models.CharField(max_length=20)), ('item_description', models.CharField(max_length=200)), ('release_date', models.DateTimeField(blank=True, default='', null=True)), ('hardware', models.CharField(default='', max_length=30)), ], ), migrations.CreateModel( name='Look', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('gallery_item', models.ImageField(upload_to='img/photo')), ('particular', models.CharField(max_length=30)), ], ), migrations.CreateModel( name='Service', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('service_category', models.CharField(max_length=200)), ('description', models.TextField(blank=True, null=True)), ('hardware', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='investments.Item')), ], ), migrations.AddField( model_name='look', name='Service', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='investments.Service'), ), migrations.AddField( model_name='look', name='item_name', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='investments.Item'), ), ] <file_sep>/Holdings/investments/migrations/0002_service_service_name.py # -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-01 10:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('investments', '0001_initial'), ] operations = [ migrations.AddField( model_name='service', name='service_name', field=models.CharField(default='', max_length=20), ), ]
af2ed1aa91d712d05a4d875d7f557f2479a94dbb
[ "Python", "HTML" ]
7
Python
Rhytah/Holdings
a269b6618ce6e5dcee44f7bf51e1fea2eb8e8fe6
d565baaf592226555dcfa9821ff9ea1ae3f94566
refs/heads/master
<repo_name>BasManerino/rls-frontend<file_sep>/src/app/services/traincompositiondetails.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of, Subscription, Subject } from 'rxjs'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable({ providedIn: 'root' }) export class TraincompositiondetailsService { private component = new Subject<[]>(); component$ = this.component.asObservable(); private updateComponent = new Subject<[]>(); updateComponent$ = this.updateComponent.asObservable(); private compositionList = new Subject<[]>(); compositionList$ = this.compositionList.asObservable(); private toUpdateData; constructor(public http: HttpClient) { } async allLocomotives() { return await this.http.get('https://rls-backend.herokuapp.com/api/v1/tractions/', httpOptions).toPromise(); } async allWagons() { return await this.http.get('https://rls-backend.herokuapp.com/api/v1/wagons/', httpOptions).toPromise(); } async dangerousGoodLabels() { return await this.http.get('https://rls-backend.herokuapp.com/api/v1/dangerlabels/', httpOptions).toPromise(); } saveComponent(component) { this.component.next(component); } getSelectedDetails() { return this.toUpdateData; } setSelectedDetails(data) { this.toUpdateData = data; } updateDetails(data) { this.updateComponent.next(data); } editComponent(component) { this.updateComponent.next(component); } setSavedComposition(message) { this.compositionList.next(message); } } <file_sep>/src/app/components/dialog-locomotive/dialog-locomotive.component.ts import { Component, OnInit } from '@angular/core'; import { TraincompositiondetailsService } from 'src/app/services/traincompositiondetails.service'; import { MatDialogRef } from '@angular/material'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import { TrainServiceService } from 'src/app/services/train-service.service'; import { Observable } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper'; @Component({ selector: 'app-dialog-locomotive', templateUrl: './dialog-locomotive.component.html', styleUrls: ['./dialog-locomotive.component.css'], providers: [{ provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } }] }) export class DialogLocomotiveComponent implements OnInit { public compositionList; public locoId; public locoNumbers = []; public locomotiveList = []; public trainTypes = []; public tractionTypes = []; public driverIndication = []; locoTractionForm = new FormControl(); locoNumber = new FormControl(); locoDriver = new FormControl(); filteredOptions: Observable<string[]>; firstFormGroup: FormGroup; secondFormGroup: FormGroup; thirdFormGroup: FormGroup; public newLoco = [ { id: null, type: 'Locomotive', tractionType: null, driver: null, } ]; constructor(private tcService: TraincompositiondetailsService, private TrainService: TrainServiceService, public dialogLocoRef: MatDialogRef<DialogLocomotiveComponent>, private fb: FormBuilder) { tcService.allLocomotives().then((data: any) => { this.locomotiveList = data; this.getLoconumbers(); }); this.trainTypes = TrainService.getTrainTypes(); this.tractionTypes = TrainService.getTractionTypes(); this.driverIndication = TrainService.getDriverIndication(); } ngOnInit() { // Filter for the autocomplete for locomotiveNumber this.filteredOptions = this.locoNumber.valueChanges .pipe( startWith(''), map(value => this._filter(value)) ); // Validationcheck for Steps of stepper this.firstFormGroup = this.fb.group({ locoNumber: ['', Validators.required], }); this.secondFormGroup = this.fb.group({ locoTractionForm: ['', Validators.required] }); this.thirdFormGroup = this.fb.group({ locoDriver: ['', Validators.required] }); this.tcService.updateComponent$.subscribe(message => { this.compositionList = message; }); } private _filter(value: string): string[] { const filterValue = value.toLowerCase(); return this.locoNumbers.filter(option => option.toLowerCase().includes(filterValue)); } getLocoId() { this.locoId = (document.getElementById('locoInputId') as HTMLInputElement).value; } addLocomotive() { if (!this.checkDuplicates()) { this.newLoco.push({ id: this.locoId, type: 'Locomotive', tractionType: this.locoTractionForm.value, driver: this.locoDriver.value }); console.log(this.newLoco[1]); this.tcService.saveComponent(this.newLoco[1]); this.dialogLocoRef.close(); } else { alert('Locomotive: ' + this.locoId + ' already exists in this composition!'); } } checkDuplicates() { console.log(this.compositionList); let duplicate; // console.log(this.addedIds); // if (this.addedIds.length > 0) { // for (let id of this.addedIds) { // console.log(id); // if (this.locoId !== id) { // duplicate = false; // } else { // duplicate = true; // } // } // } else { // duplicate = false; // } console.log(this.locoId); console.log(duplicate); return duplicate; } getLoconumbers() { this.locomotiveList.forEach(locomotive => { this.locoNumbers.push(locomotive.locoNumber); }); } } <file_sep>/src/app/components/element-path/element-path.component.ts import { Component, OnInit } from "@angular/core"; import { TrainCompositionPathService } from "../../services/train-composition-path.service"; import { TrainCompositionService } from "src/app/services/train-composition.service"; import { ActivatedRoute } from "@angular/router"; import { DialogActivityPathComponent } from '../dialog-activity-path/dialog-activity-path.component'; import { MatDialog } from '@angular/material'; @Component({ selector: "app-element-path", templateUrl: "./element-path.component.html", styleUrls: ["./element-path.component.css"] }) export class ElementPathComponent implements OnInit { public locationsList = null; public allActivityTypes; public copyId = null; public allPathItems = []; public activityTypesPath = {}; public operationalTrainNumber = null; public tcmData = null; private sub: any; public pathItems = []; constructor( private pathService: TrainCompositionPathService, public tcmServie: TrainCompositionService, private route: ActivatedRoute, public dialog: MatDialog ) { pathService.allLocations().then((data: any) => { this.locationsList = data; }); pathService.allActivityTypes().then((data: any) => { this.allActivityTypes = data; }); tcmServie.loadTrain(this.route.snapshot.params.id).then((response: any) => { if (response.journeySections.length > 0) { response.journeySections.forEach(element => { const id = parseInt(element.id) const journeySectionOrigin = element.links.filter(item => item.rel === "journeySectionOrigin")[0];; const journeySectionDestination = element.links.filter(item => item.rel === "journeySectionDestination")[0];; this.allPathItems.push({ uId: Date.now() + id, id: id, start: parseInt( journeySectionOrigin.href.substring( journeySectionOrigin.href.lastIndexOf("/") + 1, journeySectionOrigin.href.length ) ), end: parseInt( journeySectionDestination.href.substring( journeySectionDestination.href.lastIndexOf("/") + 1, journeySectionDestination.href.length ) ), activityType: "0001" }); }); } else { const transferPoint = response.links.filter(item => item.rel === "transferPoint")[0]; this.allPathItems = [ { uId: Date.now(), id: null, start: parseInt( transferPoint.href.substring( transferPoint.href.lastIndexOf("/") + 1, transferPoint.href.length ) ), end: null, activityType: "0001" } ]; } }); } ngOnInit() { this.tcmServie.data$.subscribe(data => { this.tcmData = data; }); } addTraject() { const itemBefore = this.allPathItems[this.allPathItems.length - 1]; this.allPathItems.push({ uId: Date.now(), id: null, start: itemBefore.end, end: null, activityType: "0001" }); } deleteTraject(id) { const listIndex = this.allPathItems.findIndex(item => item.uId === id); if (this.allPathItems[listIndex + 1]) { this.allPathItems[listIndex + 1].start = this.allPathItems[ listIndex - 1 ].end; } this.allPathItems = this.allPathItems .slice(0, listIndex) .concat(this.allPathItems.slice(listIndex + 1, this.allPathItems.length)); } updateEndLocation(id) { const listIndex = this.allPathItems.findIndex(item => item.uId === id); if (listIndex !== this.allPathItems.length - 1) { this.allPathItems[listIndex + 1].start = this.allPathItems[listIndex].end; } if (this.allPathItems[listIndex].id === null) { this.tcmServie .addJourneysections( this.allPathItems[listIndex].start, this.allPathItems[listIndex].end, this.tcmServie.currentId ) .then((response: any) => { const journeyId = response.journeySections[response.journeySections.length - 1].id; this.allPathItems[listIndex].id = parseInt(journeyId); }); } else { this.tcmServie.updateJourneysections(this.allPathItems[listIndex].id, { journeySectionDestination: `https://rls-backend.herokuapp.com/api/v1/locationidents/${this.allPathItems[listIndex].end}` }) } } public copyComposition(id) { this.copyId = id; } public editComposition(id) { this.tcmServie.setActiveJourney(id); } public pasteComposition(id) { alert(`Paste composition ${this.copyId} to ${id}`); this.copyId = null; } setActivityType(id, value) { this.activityTypesPath[id] = value; } getLocation(locationPrimaryCode) { if (this.locationsList) { return this.locationsList.filter( item => locationPrimaryCode === item.locationPrimaryCode )[0]; } return; } openDialogActivity(id){ this.dialog.open(DialogActivityPathComponent); } } <file_sep>/src/app/services/train-composition.service.ts import { Injectable } from "@angular/core"; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { Subject } from "rxjs"; const httpOptions = { headers: new HttpHeaders({ "Content-Type": "application/json" }) }; @Injectable({ providedIn: "root" }) export class TrainCompositionService { public currentId; public currentStartLocation; private data = new Subject<[]>(); data$ = this.data.asObservable(); private activeJourney = new Subject<[]>(); activeJourney$ = this.activeJourney.asObservable(); constructor(public http: HttpClient) {} async allTcms() { return await this.http .get( "https://rls-backend.herokuapp.com/api/v1/traincompositionmessages/", httpOptions ) .toPromise(); } async allTrains() { return await this.http .get("https://rls-backend.herokuapp.com/api/v1/trains/", httpOptions) .toPromise(); } setCurrentId(id) { this.currentId = id; } setData(data) { this.data.next(data); } setCurrentStartLocation(startLocation) { this.currentStartLocation = startLocation; } setActiveJourney(id) { this.activeJourney.next(id); } async loadTcm(id) { return await this.http .get( `https://rls-backend.herokuapp.com/api/v1/traincompositionmessages/${id}/`, httpOptions ) .toPromise(); } async loadTrain(id) { return await this.http .get( `https://rls-backend.herokuapp.com/api/v1/trains/${id}/`, httpOptions ) .toPromise(); } async createTcm(train) { return await this.http .post( "https://rls-backend.herokuapp.com/api/v1/traincompositionmessages/", { train: `https://rls-backend.herokuapp.com/api/v1/trains/${train}`, }, httpOptions ) .toPromise(); } async createTrain(location, train) { return await this.http .post( "https://rls-backend.herokuapp.com/api/v1/trains/", { transferPoint: `https://rls-backend.herokuapp.com/api/v1/locations/${location}`, operationalTrainNumber: train, scheduledDateTimeAtTransfer: "2020-01-15T11:26:18.306Z", scheduledTimeAtHandover: "2020-01-15T11:26:18.306Z", "trainType": 2, }, httpOptions ) .toPromise(); } async addJourneysections(start, end, train) { return await this.http .post( `https://rls-backend.herokuapp.com/api/v1/trains/${train}/journeysections/`, { journeySectionDestinationUrl: `https://rls-backend.herokuapp.com/api/v1/locations/${end}`, journeySectionOriginUrl: `https://rls-backend.herokuapp.com/api/v1/locations/${start}`, livestockOrPeopleIndicator: 0, }, httpOptions ) .toPromise(); } async updateJourneysections(id, object) { return await this.http .put( `https://rls-backend.herokuapp.com/api/v1/traincompositionjourneysections/${id}/`, object, httpOptions ) .toPromise(); } } <file_sep>/src/app/services/train-composition-path.service.spec.ts import { TestBed } from '@angular/core/testing'; import { TrainCompositionPathService } from './train-composition-path.service'; describe('TrainCompositionPathService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: TrainCompositionPathService = TestBed.get(TrainCompositionPathService); expect(service).toBeTruthy(); }); }); <file_sep>/src/app/components/dialog-wagon/dialog-wagon.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormArray, Validators, FormBuilder, AbstractControl } from '@angular/forms'; import { TraincompositiondetailsService } from 'src/app/services/traincompositiondetails.service'; import { MatDialogRef } from '@angular/material'; import { map, startWith } from 'rxjs/operators'; import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper'; import { Observable } from 'rxjs'; @Component({ selector: 'app-dialog-wagon', templateUrl: './dialog-wagon.component.html', styleUrls: ['./dialog-wagon.component.css'], providers: [{ provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } }] }) export class DialogWagonComponent implements OnInit { public addedWagonIds = []; public totalWeight; public allWagonIds = []; public wagonList; public dangerIndex = 0; public dangerousGoodsList; public dangerousGoods = []; public wagonLoadIndex = -1; public wagonLoads = []; public wagonId; filteredOptions: Observable<string[]>; public newWagon = [ { id: null, wagonLoads: null, type: 'wagon' } ]; wagonNumber = new FormControl(); wagonLoadWeight = new FormControl(); wagonDangerousGood = new FormControl(); wagonIdControl: FormGroup; wagonLoadControl: FormGroup; constructor(private tcService: TraincompositiondetailsService, public dialogLocoRef: MatDialogRef<DialogWagonComponent>, private fb: FormBuilder) { tcService.allWagons().then(data => { this.wagonList = data; this.getWagonNumbers(); }); tcService.dangerousGoodLabels().then(data => { this.dangerousGoodsList = data; }); } ngOnInit() { // Filter for the autocomplete for wagonNumber this.filteredOptions = this.wagonNumber.valueChanges .pipe( startWith(''), map(value => this._filter(value)) ); this.wagonIdControl = this.fb.group({ wagonNumber: ['', [ Validators.required ]], }); this.wagonLoadControl = this.fb.group({ wagonLoads: this.fb.array([]) }); } private _filter(value: string): string[] { const filterValue = value; return this.allWagonIds.filter(option => option.toLowerCase().includes(filterValue)); } addWagon() { if (this.checkDuplicates()) { this.newWagon.push({ id: this.wagonId, wagonLoads: this.wagonLoads, type: 'Wagon', }); this.tcService.saveComponent(this.newWagon[1]); this.addedWagonIds.push(this.wagonId); this.dialogLocoRef.close(); } else { alert('Wagon: ' + this.wagonId + ' already exists in this composition!'); } } checkDuplicates() { let duplicate; for (let id of this.allWagonIds) { if (this.wagonId !== id) { duplicate = true; } else { duplicate = false; } } return duplicate; } get wagonLoadsForms() { return this.wagonLoadControl.get('wagonLoads') as FormArray; } addWagonLoad() { const wagonLoad = this.fb.group({ weight: [], dangerGoods: [], }); this.wagonLoadsForms.push(wagonLoad); } deleteWagonLoad(index) { this.wagonLoadsForms.removeAt(index); } showWagonLoads() { const list = this.wagonLoadControl.value; this.wagonLoads = list.wagonLoads; this.calcTotalWeight(this.wagonLoads); } calcTotalWeight(wagonLoads) { let emptyWagon; let loadWeight = 0; this.wagonList.forEach(wagon => { if (wagon.numberFreight === this.wagonId) { emptyWagon = wagon.wagonType.wagonWeightEmpty; } }); for (let load of wagonLoads) { loadWeight += load.weight; } this.totalWeight = emptyWagon + loadWeight; } getWagonNumbers() { this.wagonList.forEach(wagon => { this.allWagonIds.push(wagon.numberFreight); }); } getWagonId() { this.wagonId = ((document.getElementById('wagonInputId') as HTMLInputElement).value); } } <file_sep>/src/app/services/train-service.service.spec.ts import { TestBed } from '@angular/core/testing'; import { TrainServiceService } from './train-service.service'; describe('TrainServiceService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: TrainServiceService = TestBed.get(TrainServiceService); expect(service).toBeTruthy(); }); }); <file_sep>/src/app/components/edit-wagon-dialog/edit-wagon-dialog.component.ts import { Component, OnInit } from '@angular/core'; import { TraincompositiondetailsService } from 'src/app/services/traincompositiondetails.service'; import { FormControl, Validators, FormGroup, FormBuilder, FormArray } from '@angular/forms'; import { MatDialogRef } from '@angular/material'; @Component({ selector: 'app-edit-wagon-dialog', templateUrl: './edit-wagon-dialog.component.html', styleUrls: ['./edit-wagon-dialog.component.css'] }) export class EditWagonDialogComponent implements OnInit { public wagonId; public selectedWagon; public dangerousGoodsList; public wagonLoads = []; public dangerLabel; wagonLoadControl: FormGroup; existingWagonControl: FormGroup; public updatedWagon = [ { id: null, wagonLoads: null } ]; constructor(private tcService: TraincompositiondetailsService, public dialogEditWagon: MatDialogRef<EditWagonDialogComponent>, private fb: FormBuilder) { this.selectedWagon = tcService.getSelectedDetails(); tcService.dangerousGoodLabels().then((data: any) => { this.dangerousGoodsList = data; }); this.updatedWagon = this.selectedWagon; } ngOnInit() { for (let item of this.selectedWagon) { this.wagonId = item.id; } this.existingWagonControl = this.fb.group({ weight: [''], dangerGoods: [''] }) this.wagonLoadControl = this.fb.group({ wagonLoads: this.fb.array([]) }); } get wagonLoadsForms() { return this.wagonLoadControl.get('wagonLoads') as FormArray; } addWagonLoad() { const wagonLoad = this.fb.group({ weight: [], dangerGoods: [], }); this.wagonLoadsForms.push(wagonLoad); } deleteWagonLoad(index) { this.selectedWagon.forEach(wagon => { wagon.wagonLoads.splice(index, 1); }); } deleteNewWagonLoad(index) { this.wagonLoadsForms.removeAt(index); } updateWagon() { let loads; let existingLoad; this.updatedWagon.push({ id: this.wagonId, wagonLoads: null, }); loads = this.wagonLoadControl.value; existingLoad = this.updatedWagon[0]; if (loads.wagonLoads.length > 0) { for (let load of loads.wagonLoads) { existingLoad.wagonLoads.push(load); } this.tcService.updateDetails(existingLoad); } else { this.tcService.updateDetails(this.updatedWagon[0]); } this.selectedWagon = []; this.dialogEditWagon.close(); } } <file_sep>/src/app/services/train-service.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class TrainServiceService { private trainTypes = [ { id: 0, type: 'Goederenvervoer' }, { id: 1, type: 'Personenvervoer' } ]; private tractionTypes = [ { id: 0, type: 'Not specified' }, { id: 1, type: 'External electric power supply for traction' }, { id: 2, type: 'Onboard traction power supply for traction without external electrical or other power supply available' }, { id: 3, type: 'Hybrid traction (both onboard or electric traction)' } ]; private driverIndication = [ { id: 0, indication: 'No driver present' }, { id: 1, indication: 'Driver(s) is/are present' } ]; constructor(public http: HttpClient) { } getTrainTypes() { return this.trainTypes; } getTractionTypes() { return this.tractionTypes; } getDriverIndication() { return this.driverIndication; } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TrainCompositionListComponent } from './pages/train-composition-list/train-composition-list.component'; import { TrainCompositionComponent } from './pages/train-composition/train-composition.component'; const routes: Routes = [ { path: '', component: TrainCompositionListComponent }, { path: 'tcm/:id', component: TrainCompositionComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/services/train-composition-path.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable({ providedIn: 'root' }) export class TrainCompositionPathService { constructor(public http: HttpClient) {} async allLocations() { return await this.http.get('https://rls-backend.herokuapp.com/api/v1/locations', httpOptions).toPromise(); } async allActivityTypes() { return await this.http.get('https://rls-backend.herokuapp.com/api/v1/trainactivitytypes/', httpOptions).toPromise(); } } <file_sep>/src/app/pages/train-composition/train-composition.component.ts import { Component, OnInit } from "@angular/core"; import { ActivatedRoute } from '@angular/router'; import { TrainCompositionService } from 'src/app/services/train-composition.service'; @Component({ selector: "app-train-composition", templateUrl: "./train-composition.component.html", styleUrls: ["./train-composition.component.css"] }) export class TrainCompositionComponent implements OnInit { id: number; private sub: any; constructor(private route: ActivatedRoute, private tcmService : TrainCompositionService) { } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.id = params['id']; this.tcmService.setCurrentId(this.id); this.tcmService.loadTrain(this.id).then((data: any) => { this.tcmService.setData(data); }); }); } ngOnDestroy() { this.sub.unsubscribe(); } } <file_sep>/src/app/components/element-details/element-details.component.ts import { Component, OnInit, ElementRef } from '@angular/core'; import { TraincompositiondetailsService } from 'src/app/services/traincompositiondetails.service'; import { NgForm } from '@angular/forms'; import { MatDialog } from '@angular/material'; import { CdkDragDrop, moveItemInArray, CdkDragEnter } from '@angular/cdk/drag-drop'; import { DialogLocomotiveComponent } from '../dialog-locomotive/dialog-locomotive.component'; import { DialogWagonComponent } from '../dialog-wagon/dialog-wagon.component'; import { EditLocomotiveDialogComponent } from '../edit-locomotive-dialog/edit-locomotive-dialog.component'; import { EditWagonDialogComponent } from '../edit-wagon-dialog/edit-wagon-dialog.component'; import { TrainCompositionService } from 'src/app/services/train-composition.service'; @Component({ selector: 'app-element-details', templateUrl: './element-details.component.html', styleUrls: ['./element-details.component.css'] }) export class ElementDetailsComponent implements OnInit { public locomotiveList; public wagonList; public componentList; public activeJourney = []; public compositionList = []; public detailList = []; public updatedComponent = []; public dangerGoodIndicator; public totalWeightWagon; constructor(private TCDService: TraincompositiondetailsService, private TCService: TrainCompositionService, public dialog: MatDialog) { TCDService.allLocomotives().then((data: any) => { this.locomotiveList = data; }); TCDService.allWagons().then((data: any) => { this.wagonList = data; }); } entered(event: CdkDragEnter) { moveItemInArray(this.compositionList, event.item.data, event.container.data); } drop(event: CdkDragDrop<string[]>) { moveItemInArray(this.compositionList, event.previousIndex, event.currentIndex); } openLocoDialog() { this.dialog.open(DialogLocomotiveComponent, { height: '400px', width: '900px' } ); } openWagonDialog() { this.dialog.open(DialogWagonComponent, { height: '400px', width: '900px' }); } openEditDialog(type) { if (type === 'Locomotive') { for (let element of this.detailList) { let data = []; // ??? Beschrijving moet nog weggehaald worden ??? data.push({ id: element.id, description: element.description, trainType: element.trainType, tractionType: element.tractionType, driver: element.driver }); this.TCDService.setSelectedDetails(data); } this.dialog.open(EditLocomotiveDialogComponent, { height: '400px', width: '900px' }); } else { let wagonId; let wagonContent; for (let item of this.detailList) { wagonId = item.id; wagonContent = item.content; let data = []; data.push({ id: item.id, wagonLoads: item.wagonLoads, }); // ! Kan een goeie manier zijn om dit ook te doen met compositionList doorsturen bij aanmaken. this.TCDService.setSelectedDetails(data); } this.dialog.open(EditWagonDialogComponent, { height: '400px', width: '900px' }); } } addComponent(message) { if (message.type === 'Locomotive') { this.addLocomotive(); } else { this.addWagon(); } } addLocomotive() { let toAdd = {}; for (let item of this.locomotiveList) { if (this.componentList.id === item.locoNumber && this.componentList.id !== null && this.componentList.id !== '') { toAdd = { id: this.componentList.id, type: this.componentList.type, description: item.tractionMode.description, trainType: this.componentList.trainType, tractionType: this.componentList.tractionType, driver: this.componentList.driver }; this.compositionList.push(toAdd); this.TCDService.setSavedComposition(this.compositionList); } } // } // else { // this.dialog.closeAll(); // } } addWagon() { let toAdd = {}; if (this.componentList.id !== null && this.componentList.id !== '') { toAdd = { id: this.componentList.id, wagonLoads: this.componentList.wagonLoads, type: this.componentList.type }; } else { // this.dialog.closeAll(); } this.compositionList.push(toAdd); this.TCDService.setSavedComposition(this.compositionList); } update(data) { for (let i of this.compositionList) { if (i.type === 'Locomotive') { if (i.id === data[1].id) { // i.description = data[1].description; i.trainType = data[0].trainType; i.tractionType = data[0].tractionType; i.driver = data[0].driver; this.updateDetailList(data, i.type); } } else if (i.type === 'Wagon') { if (i.id === data.id) { this.updateDetailList(data[0], i.type); } } } } updateDetailList(data, type) { if (type === 'Locomotive') { this.detailList[0].description = data[1].description; this.detailList[0].trainType = data[0].trainType; this.detailList[0].tractionType = data[0].tractionType; this.detailList[0].driver = data[0].driver; } else if (type === 'Wagon') { if (this.detailList[0].wagonLoads.length > 0) { this.detailList[0].dangerousGoods = 'Yes'; this.dangerGoodIndicator = 'Yes'; } else { this.detailList[0].dangerousGoods = 'No'; this.dangerGoodIndicator = 'No'; } } } showDetails(itemId, itemType) { if (itemType === 'Locomotive') { let locoInfo = []; for (let element of this.compositionList) { if (element.id === itemId) { locoInfo.push({ id: itemId, description: element.description, type: element.type, trainType: element.trainType, tractionType: element.tractionType, driver: element.driver }); } this.detailList = locoInfo; } } else { let weightEmpty; let wagonLengthOverBuffers; let wagonNumberOfAxles; this.wagonList.forEach(element => { if (element.numberFreight === itemId) { weightEmpty = element.wagonType.wagonWeightEmpty; this.totalWeightWagon = weightEmpty; wagonLengthOverBuffers = element.wagonType.lengthOverBuffers; wagonNumberOfAxles = element.wagonType.wagonNumberOfAxles; } }); let wagonInfo = []; for (let element of this.compositionList) { if (element.id === itemId) { this.checkDangerousGoods(element); this.calcTotalWeightWagon(element); wagonInfo.push({ id: itemId, wagonLoads: element.wagonLoads, dangerousGoods: this.dangerGoodIndicator, type: element.type, wagonWeightEmpty: weightEmpty, lengthOverBuffers: wagonLengthOverBuffers, numberOfAxles: wagonNumberOfAxles }); } this.detailList = wagonInfo; } } } calcTotalWeightWagon(element) { let wagonLoadWeight; if (element.wagonLoads.length > 0) { for (let load of element.wagonLoads) { if (wagonLoadWeight) { wagonLoadWeight += load.weight; } else { wagonLoadWeight = load.weight; } } this.totalWeightWagon += wagonLoadWeight; } } checkDangerousGoods(element) { if (element.wagonLoads.length === 0) { this.dangerGoodIndicator = 'No'; } else { this.dangerGoodIndicator = 'Yes'; } } saveComposition() { this.TCDService.setSavedComposition(this.compositionList); } removeElement(id) { if (this.detailList[0].id === id) { this.detailList.splice(0, 1); } let index = 0; for (let item of this.compositionList) { let itemId = item.id; if (itemId === id) { this.compositionList.splice(index, 1); } index += 1; } } moveElementUp(index) { var temp = this.compositionList[index]; this.compositionList[index] = this.compositionList[index - 1]; this.compositionList[index - 1] = temp; } moveElementDown(index) { var temp = this.compositionList[index]; this.compositionList[index] = this.compositionList[index + 1]; this.compositionList[index + 1] = temp; } ngOnInit() { this.TCDService.component$.subscribe(message => { this.componentList = message; this.addComponent(message); }); this.TCDService.updateComponent$.subscribe(message => { this.updatedComponent = message; this.update(message); }); this.TCService.activeJourney$.subscribe(message => { this.activeJourney = message; }); } } <file_sep>/src/app/components/dialog-create-tcm/dialog-create-tcm.component.ts import { Component, OnInit } from "@angular/core"; import { MatDialogRef } from "@angular/material"; import { TrainCompositionPathService } from "src/app/services/train-composition-path.service"; import { TrainCompositionService } from "src/app/services/train-composition.service"; import { Router } from "@angular/router"; @Component({ selector: "app-dialog-create-tcm", templateUrl: "./dialog-create-tcm.component.html", styleUrls: ["./dialog-create-tcm.component.css"] }) export class DialogCreateTcmComponent implements OnInit { public trainId = null; public startLocation = null; public locationsList; constructor( private pathService: TrainCompositionPathService, private tcmService: TrainCompositionService, public dialogRef: MatDialogRef<DialogCreateTcmComponent>, private router: Router ) { pathService.allLocations().then((data: any) => { this.locationsList = data; }); } ngOnInit() {} public submitDialog() { if (this.trainId === null || this.startLocation === null) { alert("Niet alle velden zijn ingevuld"); } this.tcmService .createTrain(this.startLocation, this.trainId) .then((response: any) => { const id = response.id this.dialogRef.close(); this.router.navigate([`/tcm/${id}`]); }); } } <file_sep>/src/app/services/traincompositiondetails.service.spec.ts import { TestBed } from '@angular/core/testing'; import { TraincompositiondetailsService } from './traincompositiondetails.service'; describe('TraincompositiondetailsService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: TraincompositiondetailsService = TestBed.get(TraincompositiondetailsService); expect(service).toBeTruthy(); }); }); <file_sep>/src/app/components/edit-locomotive-dialog/edit-locomotive-dialog.component.ts import { Component, OnInit } from '@angular/core'; import { TraincompositiondetailsService } from 'src/app/services/traincompositiondetails.service'; import { FormControl, Validators, FormGroup } from '@angular/forms'; import { MatDialogRef } from '@angular/material'; import { TrainServiceService } from 'src/app/services/train-service.service'; @Component({ selector: 'app-edit-locomotive-dialog', templateUrl: './edit-locomotive-dialog.component.html', styleUrls: ['./edit-locomotive-dialog.component.css'] }) export class EditLocomotiveDialogComponent implements OnInit { locoDescFormControl = new FormControl('', [Validators.required]); locoTrainTypeFormControl = new FormControl('', [Validators.required]); locoTractionTypeFormControl = new FormControl('', [Validators.required]); locoDriverFormControl = new FormControl('', [Validators.required]); editLocomotiveForm: FormGroup = new FormGroup({ locoDescCheck: this.locoDescFormControl, locoTrainTypeCheck: this.locoTrainTypeFormControl, locoTractionTypeCheck: this.locoTractionTypeFormControl, locoDriverCheck: this.locoDriverFormControl }); public selectedData; public locoId; public trainTypes = []; public tractionTypes = []; public driverIndication = []; public updatedLoco = [ { id: null, // description: null, tractionType: null, driver: null } ]; constructor(private tcService: TraincompositiondetailsService, private TrainService: TrainServiceService, public dialogEditLoco: MatDialogRef<EditLocomotiveDialogComponent>) { this.selectedData = tcService.getSelectedDetails(); this.trainTypes = TrainService.getTrainTypes(); this.tractionTypes = TrainService.getTractionTypes(); this.driverIndication = TrainService.getDriverIndication(); this.updatedLoco = this.selectedData; } updateDetails() { // let locoDesc = (document.getElementById('description') as HTMLInputElement).value; this.updatedLoco.push({ id: this.locoId, // description: locoDesc, tractionType: null, driver: null }); this.tcService.updateDetails(this.updatedLoco); this.dialogEditLoco.close(); } ngOnInit() { for (let item of this.selectedData) { this.locoId = item.id; } } } <file_sep>/src/app/components/dialog-activity-path/dialog-activity-path.component.ts import { Component, OnInit } from "@angular/core"; import { MatDialogRef } from "@angular/material"; import { TrainCompositionPathService } from 'src/app/services/train-composition-path.service'; @Component({ selector: "app-dialog-activity-path", templateUrl: "./dialog-activity-path.component.html", styleUrls: ["./dialog-activity-path.component.css"] }) export class DialogActivityPathComponent implements OnInit { public allActivityTypes; constructor( public dialogRef: MatDialogRef<DialogActivityPathComponent>, private pathService: TrainCompositionPathService ) { pathService.allActivityTypes().then((data: any) => { this.allActivityTypes = data; }); } ngOnInit() {} } <file_sep>/src/app/pages/train-composition-list/train-composition-list.component.ts import { Component, OnInit } from "@angular/core"; import { TrainCompositionService } from "src/app/services/train-composition.service"; import { DialogCreateTcmComponent } from "../../components/dialog-create-tcm/dialog-create-tcm.component"; import { MatDialog } from "@angular/material"; import { Router } from "@angular/router"; @Component({ selector: "app-train-composition-list", templateUrl: "./train-composition-list.component.html", styleUrls: ["./train-composition-list.component.css"] }) export class TrainCompositionListComponent implements OnInit { public allTcms = []; constructor( private tcmService: TrainCompositionService, public dialog: MatDialog, private router: Router ) { tcmService.allTrains().then((data: any) => { this.allTcms = data; }); } ngOnInit() {} createTcm() { this.dialog.open(DialogCreateTcmComponent); } openTcm(tcm) { this.tcmService.setCurrentId(tcm.id); this.tcmService.setCurrentStartLocation(tcm.id); this.router.navigate([`/tcm/${tcm.id}`]); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; import { HttpClient, HttpClientModule } from "@angular/common/http"; import { AppRoutingModule } from "./app-routing.module"; import { AppComponent } from "./app.component"; import { ElementDetailsComponent } from "./components/element-details/element-details.component"; import { TrainCompositionComponent } from "./pages/train-composition/train-composition.component"; import { ElementPathComponent } from "./components/element-path/element-path.component"; import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { DialogWagonComponent } from "./components/dialog-wagon/dialog-wagon.component"; import { DialogLocomotiveComponent } from "./components/dialog-locomotive/dialog-locomotive.component"; import { MatCardModule, MatSelectModule, MatInputModule, MatAutocompleteModule, MatButtonModule, MatIconModule, MatMenuModule, MatDialogModule, MatGridListModule, MatListModule, MatFormFieldModule, MatSlideToggleModule, MatToolbarModule, MatCheckboxModule, MatStepperModule } from "@angular/material"; import { TextFieldModule } from "@angular/cdk/text-field"; import { DragDropModule } from "@angular/cdk/drag-drop"; import { FlexLayoutModule } from "@angular/flex-layout"; import { EditWagonDialogComponent } from "./components/edit-wagon-dialog/edit-wagon-dialog.component"; import { EditLocomotiveDialogComponent } from "./components/edit-locomotive-dialog/edit-locomotive-dialog.component"; import { DialogCreateTcmComponent } from "./components/dialog-create-tcm/dialog-create-tcm.component"; import { TrainCompositionListComponent } from "./pages/train-composition-list/train-composition-list.component"; import { DialogActivityPathComponent } from './components/dialog-activity-path/dialog-activity-path.component'; import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper'; @NgModule({ declarations: [ AppComponent, ElementDetailsComponent, TrainCompositionComponent, DialogWagonComponent, DialogLocomotiveComponent, ElementPathComponent, EditWagonDialogComponent, EditLocomotiveDialogComponent, TrainCompositionListComponent, DialogCreateTcmComponent, DialogActivityPathComponent, ], entryComponents: [ DialogLocomotiveComponent, DialogWagonComponent, EditLocomotiveDialogComponent, EditWagonDialogComponent, DialogCreateTcmComponent, DialogActivityPathComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, BrowserAnimationsModule, ReactiveFormsModule, FlexLayoutModule, MatCardModule, MatSelectModule, MatAutocompleteModule, MatInputModule, MatButtonModule, MatIconModule, MatDialogModule, MatMenuModule, MatGridListModule, MatListModule, MatFormFieldModule, MatSlideToggleModule, TextFieldModule, DragDropModule, MatToolbarModule, MatCheckboxModule, MatStepperModule ], providers: [ { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } }, HttpClient], bootstrap: [AppComponent] }) export class AppModule { }
f4fa203a69014e1d597c865f1e8778cabae5ad85
[ "TypeScript" ]
19
TypeScript
BasManerino/rls-frontend
0b6500404565b566820243d173798eb8651848ea
5e95909abaafbb7df6cbc3a22e0407c845f2216b
refs/heads/main
<repo_name>Z18Aplha/window_sensor_mysensors<file_sep>/README.md # window_sensor_mysensors Easy window sensor with MySensors library. Can be used for battery powered devices. ## Functionality - detects window state f.e. with a reed switch and provides it to the gateway immediately - sends battery voltage and percentage contemporaneous (and perdiodically, period can be set in the code) <file_sep>/src/main.cpp #include <Arduino.h> /* * The MySensors Arduino library handles the wireless radio link and protocol * between your home built sensors/actuators and HA controller of choice. * The sensors forms a self healing radio network with optional repeaters. Each * repeater and gateway builds a routing tables in EEPROM which keeps track of the * network topology allowing messages to be routed to nodes. * * Created by <NAME> <<EMAIL>> * Copyright (C) 2013-2018 Sensnology AB * Full contributor list: https://github.com/mysensors/MySensors/graphs/contributors * * Documentation: http://www.mysensors.org * Support Forum: http://forum.mysensors.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * ******************************* * * REVISION HISTORY * Version 1.0 - <NAME> * * DESCRIPTION * Motion Sensor example using HC-SR501 * http://www.mysensors.org/build/motion * */ // Enable debug prints #define MY_DEBUG // Enable and select radio type attached #define MY_RADIO_RF24 //#define MY_RADIO_NRF5_ESB //#define MY_RADIO_RFM69 //#define MY_RADIO_RFM95 #define MY_PARENT_NODE_ID 0 #define MY_NODE_ID 21 #define MY_BAUD_RATE 38400 #include <MySensors.h> // important settings #define SLEEP_TIME 120000 // 2min - Sleep time between reports (in ms) #define WINDOW_SENSOR 3 // The digital input you attached your motion sensor. (Only 2 and 3 generates interrupt!) #define STATUS_LED 4 #define CHILD_ID_WINDOW 1 // Id of the sensor child #define CHILD_ID_VOLTAGE 2 // Id of the sensor child #define BATTERY_SENSE_PIN 16 // A0 #define VOLTS_PER_BIT 0.003363075 // if voltage divider with 1M - 470K #define MAX_VOLTAGE 3 // max battery voltage (100%) #define MIN_VOLTAGE 1.8 // min voltage possible (0%) // calculate some variables from settings const float difference = MAX_VOLTAGE - MIN_VOLTAGE; // const uint32_t sleep_time = SLEEP_TIME * 60 * 1000; const uint32_t sleep_time = 120000; // initialize some variables bool window_success, voltage_success, percent_success; // Initialize window message MyMessage msg_window(CHILD_ID_WINDOW, V_TRIPPED); MyMessage msg_voltage(CHILD_ID_VOLTAGE, V_VOLTAGE); void setup() { // use the 1.1 V internal reference #if defined(__AVR_ATmega2560__) analogReference(INTERNAL1V1); #else analogReference(INTERNAL); #endif // pinMode declaration pinMode(WINDOW_SENSOR, INPUT); pinMode(STATUS_LED, OUTPUT); // trigger status LED after connecting digitalWrite(STATUS_LED, HIGH); sleep(500); digitalWrite(STATUS_LED, LOW); } void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo("WindowSensor 1", "1.0"); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID_WINDOW, S_DOOR); present(CHILD_ID_VOLTAGE, S_MULTIMETER); } void loop() { // Sleep until interrupt from window sensor. Send update perdiodically Serial.println("Sleeping"); int8_t x = sleep(digitalPinToInterrupt(WINDOW_SENSOR), CHANGE, SLEEP_TIME); if (x == digitalPinToInterrupt(WINDOW_SENSOR)) { Serial.println("Wakeup by INT"); } else if (x == MY_WAKE_UP_BY_TIMER) { Serial.println("Wakeup by TIMER"); } // maybe some sleep time to wake up properly sleep(500); // get window state bool open = digitalRead(WINDOW_SENSOR) == HIGH; // get battery voltage int aR = analogRead(BATTERY_SENSE_PIN); float battery_voltage = aR * VOLTS_PER_BIT; // calculate battery percent uint8_t battery_percent = 0; if (battery_voltage > MIN_VOLTAGE){ battery_percent = uint8_t(100 * (battery_voltage - MIN_VOLTAGE) / difference); } // DEBUG PRINT #ifdef MY_DEBUG Serial.print("Window state: "); Serial.println(open?"open":"closed"); Serial.print("Battery Read: "); Serial.println(aR); Serial.print("Battery Voltage: "); Serial.print(battery_voltage, 3); Serial.println(" V"); Serial.print("Battery percent: "); Serial.print(battery_percent); Serial.println(" %"); #endif // SEND TO GATEWAY window_success = send(msg_window.set(open?"1":"0")); voltage_success = send(msg_voltage.set(battery_voltage, 3)); percent_success = sendBatteryLevel(battery_percent); // trigger status LED after sucessfully sending if (window_success && voltage_success && percent_success){ digitalWrite(STATUS_LED, HIGH); sleep(100); digitalWrite(STATUS_LED, LOW); } }
b7d03243dee7bbdd512646a98cf9addd7562248b
[ "Markdown", "C++" ]
2
Markdown
Z18Aplha/window_sensor_mysensors
3b9bee9115e7cc632bfc3543dbaf82942838afb6
283f57ffb78dce70ad2a33f828060dcc91dcb0a6
refs/heads/master
<repo_name>TypeLemon/ICS2O1CPT<file_sep>/CPT.py """ ---------------------------------------------------------------------------------------------- Name: CPT.py Purpose: Interactive mini-games that test the user's computer knowledge on course content Author: Yeh.A Created: 28/03/2021 ---------------------------------------------------------------------------------------------- """ import pygame pygame.init() # Define some colors black = (0, 0, 0) white = (255, 255, 255) salmon = (219, 156, 145) orange = (232, 170, 56) lavender = (203, 155, 242) light_green = (153, 199, 135) coral = (240, 122, 101) grey = (211, 211, 211) red = (212, 45, 19) off_white = (245, 245, 245) off_white_2 = (246, 246, 246) yellow = (249, 212, 89) # Set the width and height of the screen size = (800, 600) screen = pygame.display.set_mode(size) pygame.display.set_caption("ICS2O1 CPT") # Set positions trivia_x = 455 trivia_y = 460 shopping_x = 260 shopping_y = 460 button_length = 160 button_width = 80 exit_x = 0 exit_y = 0 exit_length = 95 exit_width = 65 cart_x = 70 cart_y = 327 cart_length = 305 cart_width = 255 true_x = 530 true_y = 525 false_x = 660 false_y = 525 tf_length = 110 tf_width = 60 mouse_click_position = [0,0] scene = 0 cursor_size = [10, 10] # Set booleans button_pressed = False CPU_selected = False mouse_selected = False monitor_selected = False power_supply_selected = False antivirus_selected = False motherboard_selected = False RAM_selected = False graphics_card_selected = False keyboard_selected = False hard_drive_selected = False true_selected = False false_selected = False white_box_cover = False # Loop until the user clicks the close button. done = False # Set other variables checklist_set = 1 question = 1 # Load and size images title = pygame.image.load("title.png").convert() title_image = pygame.transform.scale(title, [700, 230]) exit_arrow = pygame.image.load("exitarrow.png").convert() exit_arrow.set_colorkey(white) exit_image = pygame.transform.scale(exit_arrow, [90, 50]) typing = pygame.image.load("typing.jpeg").convert() typing_image = pygame.transform.scale(typing, [250, 145]) brain = pygame.image.load("brain.jpeg").convert() brain_image = pygame.transform.scale(brain, [210, 145]) note = pygame.image.load("stickynote.png").convert() note.set_colorkey(white) notepad_image = pygame.transform.scale(note, [250, 230]) antivirus = pygame.image.load("antivirus.png").convert() antivirus.set_colorkey(white) antivirus_image = pygame.transform.scale(antivirus, [90, 100]) CPU = pygame.image.load("CPU.png").convert() CPU.set_colorkey(white) CPU_image = pygame.transform.scale(CPU, [80, 90]) motherboard = pygame.image.load("motherboard.jpeg").convert() motherboard.set_colorkey(white) motherboard_image = pygame.transform.scale(motherboard, [100, 90]) RAM = pygame.image.load("RAM.png").convert() RAM.set_colorkey(white) RAM_image = pygame.transform.scale(RAM, [110, 100]) graphics = pygame.image.load("graphicscard.png").convert() graphics.set_colorkey(white) graphics_image = pygame.transform.scale(graphics, [110, 90]) keyboard = pygame.image.load("keyboard.png").convert() keyboard.set_colorkey(white) keyboard_image = pygame.transform.scale(keyboard, [120, 80]) hard_drive = pygame.image.load("harddrive.jpeg").convert() hard_drive.set_colorkey(white) hard_drive_image = pygame.transform.scale(hard_drive, [100, 100]) power_supply = pygame.image.load("powersupply.png").convert() power_supply.set_colorkey(white) power_supply_image = pygame.transform.scale(power_supply, [110, 100]) monitor = pygame.image.load("monitor.jpg").convert() monitor.set_colorkey(white) monitor_image = pygame.transform.scale(monitor, [110, 90]) mouse = pygame.image.load("mouse.jpg").convert() mouse.set_colorkey(white) mouse_image = pygame.transform.scale(mouse, [70, 90]) cart = pygame.image.load("shoppingcart.png").convert() cart.set_colorkey(off_white) cart_image = pygame.transform.scale(cart, [cart_length, cart_width]) floor_image = pygame.image.load("floor.png").convert() trans_box = pygame.image.load("transparentbox.png").convert() reset = pygame.image.load("reset.png").convert() reset.set_colorkey(off_white_2) reset_button = pygame.transform.scale(reset, [90, 90]) x_mark = pygame.image.load("x_mark.png").convert() x_mark.set_colorkey(off_white_2) x_mark_image = pygame.transform.scale(x_mark, [25, 25]) checkmark = pygame.image.load("checkmark.png").convert() checkmark.set_colorkey(off_white_2) checkmark_image = pygame.transform.scale(checkmark, [25, 25]) sticky_box = pygame.image.load("sticky_box.png").convert() sticky_box_image = pygame.transform.scale(sticky_box, [25, 25]) gameshow = pygame.image.load("gameshow.png").convert() gameshow_back = pygame.transform.scale(gameshow, [800, 520]) true_image = pygame.image.load("true.png").convert() true_button = pygame.transform.scale(true_image, [tf_length, tf_width]) false_image = pygame.image.load("false.png").convert() false_button = pygame.transform.scale(false_image, [tf_length, tf_width]) grey_rect = pygame.image.load("greyrectangle.png").convert() grey_image = pygame.transform.scale(grey_rect, [800, 90]) speech = pygame.image.load("bubble.jpg").convert() speech.set_colorkey(black) speech_bubble = pygame.transform.scale(speech, [190, 170]) congratulations = pygame.image.load("congratulations.png").convert() congratulations_box = pygame.transform.scale(congratulations, [380, 480]) virus_image = pygame.image.load("virus.png").convert() virus_meme = pygame.transform.scale(virus_image, [255, 220]) OS_image = pygame.image.load("OSmeme.png").convert() OS_meme = pygame.transform.scale(OS_image, [290, 220]) # Set images to variables for mouse click CPU_var = CPU_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image motherboard_var = motherboard_image antivirus_var = antivirus_image cursor = trans_box # Used to manage how fast the screen updates clock = pygame.time.Clock() """ Numbers that control the different screens 0 = Main Menu 1 = Completed Trivia Game Congratulations 2 = Trivia Mini Game (lavender) 3 = Shopping Mini Game (orange) """ # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close print("User asked to quit.") done = True # Flag that we are done so we exit this loop if event.type == pygame.MOUSEBUTTONDOWN: print("User pressed a mouse button.") mouse_click_position = pygame.mouse.get_pos() cursor_x = mouse_click_position[0] - cursor_size[0]/2; cursor_y = mouse_click_position[1] - cursor_size[1]/2; if scene == 2: if question < 11: if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: question = question + 1 true_selected = False false_selected = False mouse_click_position = (-1, -1) if scene == 0: # Check if the mouse click is in the trivia mini game button area if (trivia_x <= mouse_click_position[0] and mouse_click_position[0] <= trivia_x + button_length) and (trivia_y <= mouse_click_position[1] and mouse_click_position[1] <= trivia_y + button_width): trivia_button_pressed = True else: trivia_button_pressed = False # Check if the mouse click is in the shopping mini game button area if (shopping_x <= mouse_click_position[0] and mouse_click_position[0] <= shopping_x + button_length) and (shopping_y <= mouse_click_position[1] and mouse_click_position[1] <= shopping_y + button_width): shop_button_pressed = True else: shop_button_pressed = False # Main menu buttons that switch screens if trivia_button_pressed: print("Started trivia game.") scene = 2 elif shop_button_pressed: print("Started shopping game.") scene = 3 if scene == 1 or scene == 2 or scene == 3: if (exit_x <= mouse_click_position[0] and mouse_click_position[0] <= exit_x + exit_length) and (exit_y <= mouse_click_position[1] and mouse_click_position[1] <= exit_y + exit_width): print("User quit, go to main menu.") scene = 0 if scene == 2: # Check if mouse click is on true button if (true_x <= mouse_click_position[0] and mouse_click_position[0] <= true_x + tf_length) and (true_y <= mouse_click_position[1] and mouse_click_position[1] <= true_y + tf_width): print("User pressed true button") true_selected = True # Check if mouse click is on false button if (false_x <= mouse_click_position[0] and mouse_click_position[0] <= false_x + tf_length) and (false_y <= mouse_click_position[1] and mouse_click_position[1] <= false_y + tf_width): print("User pressed false button") false_selected = True if scene == 3: # Check if mouse click is on CPU icon if (180 <= mouse_click_position[0] and mouse_click_position[0] <= 180 + 80) and (100 <= mouse_click_position[1] and mouse_click_position[1] <= 100 + 90): print("CPU selected") CPU_var = trans_box cursor = CPU_image CPU_selected = True antivirus_var = antivirus_image motherboard_var = motherboard_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on antivirus icon if (280 <= mouse_click_position[0] and mouse_click_position[0] <= 280 + 90) and (100 <= mouse_click_position[1] and mouse_click_position[1] <= 100 + 100): print("Antivirus selected") antivirus_var = trans_box cursor = antivirus_image antivirus_selected = True CPU_var = CPU_image motherboard_var = motherboard_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on motherboard icon if (370 <= mouse_click_position[0] and mouse_click_position[0] <= 370 + 100) and (100 <= mouse_click_position[1] and mouse_click_position[1] <= 100 + 90): print("Motherboard selected") motherboard_var = trans_box cursor = motherboard_image motherboard_selected = True CPU_var = CPU_image antivirus_var = antivirus_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on the RAM icon if (470 <= mouse_click_position[0] and mouse_click_position[0] <= 470 + 110) and (100 <= mouse_click_position[1] and mouse_click_position[1] <= 100 + 100): print("RAM selected") RAM_var = trans_box cursor = RAM_image RAM_selected = True CPU_var = CPU_image antivirus_var = antivirus_image motherboard_var = motherboard_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on the graphics card icon if (580 <= mouse_click_position[0] and mouse_click_position[0] <= 580 + 110) and (105 <= mouse_click_position[1] and mouse_click_position[1] <= 105 + 90): print("Graphics card selected") graphics_var = trans_box cursor = graphics_image graphics_card_selected = True CPU_var = CPU_image antivirus_var = antivirus_image motherboard_var = motherboard_image RAM_var = RAM_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on the keyboard icon if (95 <= mouse_click_position[0] and mouse_click_position[0] <= 95 + 120) and (240 <= mouse_click_position[1] and mouse_click_position[1] <= 240 + 80): print("Keyboard selected") keyboard_var = trans_box cursor = keyboard_image keyboard_selected = True CPU_var = CPU_image antivirus_var = antivirus_image motherboard_var = motherboard_image RAM_var = RAM_image graphics_var = graphics_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on the hard drive icon if (230 <= mouse_click_position[0] and mouse_click_position[0] <= 230 + 100) and (235 <= mouse_click_position[1] and mouse_click_position[1] <= 235 + 100): print("Hard drive selected") hard_drive_var = trans_box cursor = hard_drive_image hard_drive_selected = True CPU_var = CPU_image antivirus_var = antivirus_image motherboard_var = motherboard_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on the power supply icon if (340 <= mouse_click_position[0] and mouse_click_position[0] <= 340 + 110) and (235 <= mouse_click_position[1] and mouse_click_position[1] <= 235 + 100): print("Power supply selected") supply_var = trans_box cursor = power_supply_image power_supply_selected = True CPU_var = CPU_image antivirus_var = antivirus_image motherboard_var = motherboard_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image monitor_var = monitor_image mouse_var = mouse_image # Check if mouse click is on the monitor icon if (480 <= mouse_click_position[0] and mouse_click_position[0] <= 480 + 110) and (235 <= mouse_click_position[1] and mouse_click_position[1] <= 235 + 90): print("Monitor selected") monitor_var = trans_box cursor = monitor_image monitor_selected = True CPU_var = CPU_image antivirus_var = antivirus_image motherboard_var = motherboard_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image mouse_var = mouse_image # Check if mouse click is on the mouse icon if (620 <= mouse_click_position[0] and mouse_click_position[0] <= 620 + 70) and (230 <= mouse_click_position[1] and mouse_click_position[1] <= 230 + 90): print("Mouse selected") mouse_var = trans_box cursor = mouse_image mouse_selected = True CPU_var = CPU_image antivirus_var = antivirus_image motherboard_var = motherboard_image RAM_var = RAM_image graphics_var = graphics_image keyboard_var = keyboard_image hard_drive_var = hard_drive_image supply_var = power_supply_image monitor_var = monitor_image # Check if mouse click is on the reset button if (10 <= mouse_click_position[0] and mouse_click_position[0] <= 10 + 90) and (500 <= mouse_click_position[1] and mouse_click_position[1] <= 500 + 90): print("User chose to switch to checklist 2") cursor = trans_box motherboard_var = motherboard_image hard_drive_var = hard_drive_image antivirus_var = antivirus_image keyboard_var = keyboard_image RAM_var = RAM_image graphics_var = graphics_image supply_var = power_supply_image monitor_var = monitor_image mouse_var = mouse_image CPU_var = CPU_image checklist_set = 2 mouse_selected = False monitor_selected = False power_supply_selected = False hard_drive_selected = False keyboard_selected = False graphics_card_selected = False RAM_selected = False motherboard_selected = False antivirus_selected = False CPU_selected = False # Render font and text button_font = pygame.font.SysFont("Oswald", 25, False, False) large_font = pygame.font.SysFont("Oswald", 30, False, False) small_font = pygame.font.SysFont("Alegreya", 23, False, False) incorrect_font = pygame.font.SysFont("Oswald", 20, False, False) trivia_text = button_font.render("Trivia Mini-Game", True, white) shopping_text_1 = button_font.render("Shopping", True, white) shopping_text_2 = button_font.render("Mini-Game", True, white) checklist_text_1 = button_font.render("Checklist 1", True, black) checklist_text_2 = button_font.render("Checklist 2", True, black) CPU_text = small_font.render("CPU", True, black) mouse_text = small_font.render("Mouse", True, black) monitor_text = small_font.render("Monitor", True, black) power_text = small_font.render("Power", True, black) supply_text = small_font.render("Supply", True, black) graphics_text = small_font.render("Graphics", True, black) card_text = small_font.render("Card", True, black) RAM_text = small_font.render("RAM", True, black) keyboard_text = small_font.render("Keyboard", True, black) antivirus_text = small_font.render("Antivirus", True, black) hard_drive_text = small_font.render("Hard Drive", True, black) motherboard_text = small_font.render("Motherboard", True, black) instr_text_1 = button_font.render("Welcome to the computer hardware shopping game! The checklist below tells you", True, black) instr_text_2 = button_font.render("which items to click and put into the cart. You'll know you chose the correct item", True, black) instr_text_3 = button_font.render("when the red x turns into a checkmark. Once you get all 5 checkmarks, click on", True, black) instr_text_4 = button_font.render("the reset button to get the second checklist and repeat!", True, black) q_number_1 = button_font.render("Question 1", True, salmon) q_number_2 = button_font.render("Question 2", True, salmon) q_number_3 = button_font.render("Question 3", True, salmon) q_number_4 = button_font.render("Question 4", True, salmon) q_number_5 = button_font.render("Question 5", True, salmon) q_number_6 = button_font.render("Question 6", True, salmon) q_number_7 = button_font.render("Question 7", True, salmon) q_number_8 = button_font.render("Question 8", True, salmon) q_number_9 = button_font.render("Question 9", True, salmon) q_number_10 = button_font.render("Question 10", True, salmon) question_1 = small_font.render("The sequence of events in the information processing cycle is", True, black) question_1_2 = small_font.render("input, processing, output, and storage.", True, black) question_2 = small_font.render("1 byte = 10 bits", True, black) question_3 = small_font.render("Megabytes and gigabytes are usually used to measure computer", True, black) question_3_2 = small_font.render("storage and memory.", True, black) question_4 = small_font.render("The higher the dpi or ppi, the less information that can be", True, black) question_4_2 = small_font.render("captured or displayed.", True, black) question_5 = small_font.render("Monitors, speakers, trackballs, and touchscreen are all input devices.", True, black) question_6 = small_font.render("Computer worms are malware that destroy data and files on the", True, black) question_6_2 = small_font.render("computer. They also replicate themselves to spread.", True, black) question_7 = small_font.render("The CPU is the brain of the computer.", True, black) question_8 = small_font.render("Multimedia, design, and productivity are all types of application", True, black) question_8_2 = small_font.render("software.", True, black) question_9 = small_font.render("It's better to build faster single cores than multicore processors", True, black) question_9_2 = small_font.render("for the CPU.", True, black) question_10 = small_font.render("Modems convert data into a format so that it can be transmitted", True, black) question_10_2 = small_font.render("from computer to computer.", True, black) correct_msg = button_font.render("Correct!", True, light_green) incorrect_msg = small_font.render("Incorrect.", True, red) incorrect_2_2 = small_font.render("1 byte = 8 bits", True, red) incorrect_4_2 = incorrect_font.render("The higher the dpi,", True, red) incorrect_4_3 = incorrect_font.render("the more information", True, red) incorrect_4_4 = incorrect_font.render("that can be", True, red) incorrect_4_5 = incorrect_font.render("displayed.", True, red) incorrect_5_2 = incorrect_font.render("Monitors and speakers", True, red) incorrect_5_3 = incorrect_font.render("are output devices.", True, red) incorrect_9_2 = incorrect_font.render("They would generate", True, red) incorrect_9_3 = incorrect_font.render("too much heat if", True, red) incorrect_9_4 = incorrect_font.render("they went faster.", True, red) congrats_msg = large_font.render("You completed all the questions!", True, grey) have = button_font.render("Have some memes", True, black) triv_instr_1 = button_font.render("Welcome to the ICS2O1 gameshow! Based on the", True, black) triv_instr_2 = button_font.render("questions shown below, select either True or", True, black) triv_instr_3 = button_font.render("False. The host will tell you if your answer is", True, black) triv_instr_4 = button_font.render("correct or not. Press the enter key to move", True, black) triv_instr_5 = button_font.render("onto the next question!", True, black) # Copy images to screen if scene == 0: screen.fill(light_green) screen.blit(title_image, [70, 50]) screen.blit(typing_image, [170, 280]) screen.blit(brain_image, [455, 280]) if scene == 1: screen.fill(yellow) screen.blit(congratulations_box, [60, 75]) screen.blit(virus_meme, [500, 100]) screen.blit(OS_meme, [480, 350]) if scene == 2: screen.blit(gameshow_back, [0, 0]) screen.blit(grey_image, [0, 510]) screen.blit(true_button, [true_x, true_y]) screen.blit(false_button, [false_x, false_y]) screen.blit(speech_bubble, [175, 15]) if scene == 3: screen.fill(grey) screen.blit(CPU_var, [180, 100]) screen.blit(antivirus_var, [280, 100]) screen.blit(motherboard_var, [370, 100]) screen.blit(RAM_var, [470, 100]) screen.blit(graphics_var, [580, 105]) screen.blit(keyboard_var, [95, 240]) screen.blit(hard_drive_var, [230, 235]) screen.blit(supply_var, [340, 235]) screen.blit(monitor_var, [480, 235]) screen.blit(mouse_var, [620, 230]) screen.blit(cursor, [cursor_x, cursor_y]) screen.blit(cart_image, [cart_x, cart_y]) screen.blit(floor_image, [0, 550]) screen.blit(notepad_image, [545, 355]) screen.blit(reset_button, [10, 500]) screen.blit(x_mark_image, [583, 430]) screen.blit(x_mark_image, [583, 457]) screen.blit(x_mark_image, [583, 484]) screen.blit(x_mark_image, [583, 511]) screen.blit(x_mark_image, [670, 452]) if checklist_set == 1: if CPU_selected: screen.blit(sticky_box_image, [583, 430]) screen.blit(checkmark_image, [583, 430]) if mouse_selected: screen.blit(sticky_box_image, [583, 457]) screen.blit(checkmark_image, [583, 457]) if RAM_selected: screen.blit(sticky_box_image, [583, 484]) screen.blit(checkmark_image, [583, 484]) if hard_drive_selected: screen.blit(sticky_box_image, [583, 511]) screen.blit(checkmark_image, [583, 511]) if power_supply_selected: screen.blit(sticky_box_image, [670, 452]) screen.blit(checkmark_image, [670, 452]) if checklist_set == 2: if antivirus_selected: screen.blit(sticky_box_image, [583, 430]) screen.blit(checkmark_image, [583, 430]) if monitor_selected: screen.blit(sticky_box_image, [583, 457]) screen.blit(checkmark_image, [583, 457]) if keyboard_selected: screen.blit(sticky_box_image, [583, 484]) screen.blit(checkmark_image, [583, 484]) if motherboard_selected: screen.blit(sticky_box_image, [583, 511]) screen.blit(checkmark_image, [583, 511]) if graphics_card_selected: screen.blit(sticky_box_image, [670, 452]) screen.blit(checkmark_image, [670, 452]) # --- Drawing code if scene == 0: pygame.draw.rect(screen, orange, [shopping_x, shopping_y, button_length, button_width]) pygame.draw.rect(screen, lavender, [trivia_x, trivia_y, button_length, button_width]) if scene == 1: pygame.draw.rect(screen, white, [124, 425, 260, 100]) if scene == 1 or scene == 2 or scene == 3: pygame.draw.rect(screen, coral, [exit_x, exit_y, exit_length, exit_width]) screen.blit(exit_image, [exit_x, exit_y + 5]) # --- Text code if scene == 0: screen.blit(shopping_text_1, [shopping_x + 40, shopping_y + 20]) screen.blit(shopping_text_2, [shopping_x + 35, shopping_y + 40]) screen.blit(trivia_text, [trivia_x + 8, trivia_y + 30]) if scene == 2: screen.blit(triv_instr_1, [362, 18]) screen.blit(triv_instr_2, [370, 38]) screen.blit(triv_instr_3, [378, 58]) screen.blit(triv_instr_4, [385, 78]) screen.blit(triv_instr_5, [465, 98]) if question == 1: screen.blit(q_number_1, [25, 523]) screen.blit(question_1, [25, 553]) screen.blit(question_1_2, [25, 570]) if true_selected: screen.blit(correct_msg, [235, 90]) true_selected = False if false_selected: screen.blit(incorrect_msg, [235, 90]) false_selected = False if question == 2: screen.blit(q_number_2, [25, 523]) screen.blit(question_2, [25, 553]) if true_selected: screen.blit(incorrect_msg, [215, 80]) screen.blit(incorrect_2_2, [215, 95]) true_selected = False if false_selected: screen.blit(correct_msg, [235, 90]) false_selected = False if question == 3: screen.blit(q_number_3, [25, 523]) screen.blit(question_3, [25, 553]) screen.blit(question_3_2, [25, 570]) if true_selected: screen.blit(correct_msg, [235, 90]) true_selected = False if false_selected: screen.blit(incorrect_msg, [235, 90]) false_selected = False if question == 4: screen.blit(q_number_4, [25, 523]) screen.blit(question_4, [25, 553]) screen.blit(question_4_2, [25, 570]) if true_selected: screen.blit(incorrect_msg, [213, 77]) screen.blit(incorrect_4_2, [213, 95]) screen.blit(incorrect_4_3, [213, 110]) screen.blit(incorrect_4_4, [213, 125]) screen.blit(incorrect_4_5, [213, 140]) true_selected = False if false_selected: screen.blit(correct_msg, [235, 90]) false_selected = False if question == 5: screen.blit(q_number_5, [25, 523]) screen.blit(question_5, [23, 553]) if true_selected: screen.blit(incorrect_msg, [208, 77]) screen.blit(incorrect_5_2, [208, 95]) screen.blit(incorrect_5_3, [208, 110]) true_selected = False if false_selected: screen.blit(correct_msg, [230, 90]) false_selected = False if question == 6: screen.blit(q_number_6, [25, 523]) screen.blit(question_6, [25, 553]) screen.blit(question_6_2, [25, 570]) if true_selected: screen.blit(correct_msg, [235, 90]) true_selected = False if false_selected: screen.blit(incorrect_msg, [235, 90]) false_selected = False if question == 7: screen.blit(q_number_7, [25, 523]) screen.blit(question_7, [25, 553]) if true_selected: screen.blit(correct_msg, [235, 90]) true_selected = False if false_selected: screen.blit(incorrect_msg, [235, 90]) false_selected = False if question == 8: screen.blit(q_number_8, [25, 523]) screen.blit(question_8, [25, 553]) screen.blit(question_8_2, [25, 570]) if true_selected: screen.blit(correct_msg, [235, 90]) true_selected = False if false_selected: screen.blit(incorrect_msg, [235, 90]) false_selected = False if question == 9: screen.blit(q_number_9, [25, 523]) screen.blit(question_9, [25, 553]) screen.blit(question_9_2, [25, 570]) if true_selected: screen.blit(incorrect_msg, [205, 77]) screen.blit(incorrect_9_2, [205, 95]) screen.blit(incorrect_9_3, [205, 110]) screen.blit(incorrect_9_4, [205, 125]) true_selected = False if false_selected: screen.blit(correct_msg, [235, 90]) false_selected = False if question == 10: screen.blit(q_number_10, [25, 523]) screen.blit(question_10, [25, 553]) screen.blit(question_10_2, [25, 570]) if true_selected: screen.blit(correct_msg, [235, 90]) true_selected = False if false_selected: screen.blit(incorrect_msg, [235, 90]) false_selected = False if question == 11: scene = 1 if scene == 1: screen.blit(congrats_msg, [95, 435]) screen.blit(have, [550, 70]) if scene == 3: screen.blit(instr_text_1, [110, 13]) screen.blit(instr_text_2, [110, 33]) screen.blit(instr_text_3, [110, 53]) screen.blit(instr_text_4, [110, 73]) # Shopping checklist possibilities 1 & 2 if checklist_set == 1: screen.blit(checklist_text_1, [615, 410]) screen.blit(CPU_text, [608, 440]) screen.blit(mouse_text, [608, 465]) screen.blit(RAM_text, [608, 490]) screen.blit(hard_drive_text, [608, 515]) screen.blit(power_text, [693, 460]) screen.blit(supply_text, [693, 477]) if checklist_set == 2: screen.blit(checklist_text_2, [615, 410]) screen.blit(antivirus_text, [608, 440]) screen.blit(monitor_text, [608, 465]) screen.blit(keyboard_text, [608, 490]) screen.blit(motherboard_text, [608, 515]) screen.blit(graphics_text, [693, 460]) screen.blit(card_text, [693, 477]) # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) # Close the window and quit. # If you forget this line, the program will 'hang' # on exit if running from IDLE. pygame.quit()
f94349ec23410f349db196681b6f1ef8911fa85a
[ "Python" ]
1
Python
TypeLemon/ICS2O1CPT
9fa1f73bba1e4fa583e98c9e1a40b1d3dd4eab02
dc85c268b3bb7817bf7e1d93fa4fac6c8ef64b47
refs/heads/master
<repo_name>samuelfm/FAtiMA-DST<file_sep>/FAtiMA-Server/Entities.cs using RolePlayCharacter; namespace FAtiMA_Server { public class Entity { public int GUID { get; set; } public int X { get; set; } public int Y { get; set; } public int Z { get; set; } public Entity(int GUID, float x, float y, float z) { this.GUID = GUID; X = (int) x; Y = (int) y; Z = (int) z; } public override string ToString() { return "Entity: " + this.GUID + "(" + X + "," + Y + "," + Z + ")"; } } public class Item : Entity { public string Prefab { get; set; } public int Quantity { get; set; } public bool ChopWorkable { get; set; } public bool HammerWorkable { get; set; } public bool DigWorkable { get; set; } public bool MineWorkable { get; set; } public bool Pickable { get; set; } public Item(int GUID, float x, float y, float z, string prefab, int quantity, bool chopworkable, bool hammerworkable, bool digworkable, bool mineworkable, bool pickable) : base(GUID, x, y, z) { Prefab = prefab; Quantity = quantity; ChopWorkable = chopworkable; HammerWorkable = hammerworkable; DigWorkable = digworkable; MineWorkable = mineworkable; Pickable = pickable; } public void UpdatePerception(RolePlayCharacterAsset rpc) { string b = rpc.GetBeliefValue("Entity(" + GUID + "," + Prefab + ")"); if ( b == null || !(b.Equals(Quantity.ToString()))) rpc.Perceive(EventHelper.PropertyChange("Entity(" + GUID + "," + Prefab + ")", Quantity.ToString(), rpc.CharacterName.ToString())); b = rpc.GetBeliefValue("ChopWorkable(" + GUID + ")"); if ( b == null || !(b.Equals(ChopWorkable.ToString()))) rpc.Perceive(EventHelper.PropertyChange("ChopWorkable(" + GUID + ")", ChopWorkable.ToString(), rpc.CharacterName.ToString())); b = rpc.GetBeliefValue("HammerWorkable(" + GUID + ")"); if (b == null || !(b.Equals(HammerWorkable.ToString()))) rpc.Perceive(EventHelper.PropertyChange("HammerWorkable(" + GUID + ")", HammerWorkable.ToString(), rpc.CharacterName.ToString())); b = rpc.GetBeliefValue("DigWorkable(" + GUID + ")"); if (b == null || !(b.Equals(DigWorkable.ToString()))) rpc.Perceive(EventHelper.PropertyChange("DigWorkable(" + GUID + ")", DigWorkable.ToString(), rpc.CharacterName.ToString())); b = rpc.GetBeliefValue("MineWorkable(" + GUID + ")"); if (b == null || !(b.Equals(MineWorkable.ToString()))) rpc.Perceive(EventHelper.PropertyChange("MineWorkable(" + GUID + ")", MineWorkable.ToString(), rpc.CharacterName.ToString())); b = rpc.GetBeliefValue("Pickable(" + GUID + ")"); if ( b == null || !(b.Equals(Pickable.ToString()))) rpc.Perceive(EventHelper.PropertyChange("Pickable(" + GUID + ")", Pickable.ToString(), rpc.CharacterName.ToString())); b = rpc.GetBeliefValue("PosX(" + GUID + ")"); if ( b == null || !(b.Equals(X.ToString()))) rpc.Perceive(EventHelper.PropertyChange("PosX(" + GUID + ")", X.ToString(), rpc.CharacterName.ToString())); /* * The Y-axis is always equal to zero, no need to save it in the knowledge base * */ //b = rpc.GetBeliefValue("PosY(" + GUID + ")"); //if ( b == null || !(b.Equals(Y.ToString()))) // rpc.Perceive(EventHelper.PropertyChange("PosY(" + GUID + ")", Y.ToString(), rpc.CharacterName.ToString())); b = rpc.GetBeliefValue("PosZ(" + GUID + ")"); if ( b == null || !(b.Equals(Z.ToString()))) rpc.Perceive(EventHelper.PropertyChange("PosZ(" + GUID + ")", Z.ToString(), rpc.CharacterName.ToString())); } public override string ToString() { return Quantity + " x " + Prefab + "(" + X.ToString() + "," + Y.ToString() + "," + Z.ToString() + ")"; } } public class EquippedItems : Item { public string Slot { get; set; } public EquippedItems(int GUID, float x, float y, float z, string prefab, int count, bool chopworkable, bool hammerworkable, bool digworkable, bool mineworkable, bool pickable, string slot) : base(GUID, x, y, z, prefab, count, chopworkable, hammerworkable, digworkable, mineworkable, pickable) { Slot = slot; } public override string ToString() { return Slot + ": " + Prefab; } } }
bc40bb6f76ef68d75c75550e984ca9ceaf4cc782
[ "C#" ]
1
C#
samuelfm/FAtiMA-DST
bd20cd5c5b8b3e217aa381cad9f2e66eb8a8948a
d1c11a92585d75b5546dbfa6af0445e0be2db973
refs/heads/master
<repo_name>HedvigS/microbio<file_sep>/R/read.breseq.gd.R read.breseq.gd <- function(file.gd) { types = c("SNP", "SUB", "DEL", "INS", "MOB", "AMP", "CON", "INV", "RA", "MC", "JC", "UN", "TSEQ", "PFLP", "RFLP", "PFGE", "PHYL", "CURA") fileOuts = c() for (ty in types) { fileOut = paste0(tempfile(), "_", ty) system(paste0("grep ^", ty, " ", file.gd, " > ", fileOut)) fileOuts = c(fileOuts,fileOut) } RES = list() for ( file in fileOuts ) { type = unlist(strsplit(basename(file),"_"))[2] if(type=="SNP") { if(file.info(file)$size!=0) { SNP = data.frame(type=NA, evidence_id=NA, parent_ids=NA, seq_id=NA, position=NA, new_seq=NA, aa_new_seq=NA, aa_position=NA, aa_ref_seq=NA, codon_new_seq=NA, codon_number=NA, codon_position=NA, codon_ref_seq=NA, gene_list=NA, gene_name=NA, gene_position=NA, gene_product=NA, gene_strand=NA, html_gene_name=NA, locus_tag=NA, snp_type=NA, transl_table=NA, stringsAsFactors=FALSE ) RL = readLines(file) totLines = length(RL) for ( i in 1 : totLines ) { cat(i,"\n") line = unlist(strsplit(RL[i],"\t")) field_values = sapply(strsplit(line,"="),function(s) s[2]) newEntry = c(line[1:6], field_values[7:22]) SNP = rbind(SNP, newEntry) } SNP = SNP[-1,] RES[[type]]=SNP } else { RES[[type]]=NULL } } if(type == "RA") RA = data.frame(type=NA, evidence_id=NA, parent_ids=NA, seq_id=NA, insert_position=NA, ref_base=NA, ref_base=NA ) if(file.info(file)$size!=0){ } } }
c104208639c0dd62d0595cb628b62a9d2b442e62
[ "R" ]
1
R
HedvigS/microbio
efa892326c05061f9bf62ef2f3a0e848ebde0651
411bab2288ce2ed15ff048c9d2bfc2a605ea4318
refs/heads/master
<file_sep>""" This library allows you to quickly and easily use the SendGrid Web API v3 via Python. For more information on this library, see the README on Github. http://github.com/sendgrid/sendgrid-python For more information on the SendGrid v3 API, see the v3 docs: http://sendgrid.com/docs/API_Reference/api_v3.html For the user guide, code examples, and more, visit the main docs page: http://sendgrid.com/docs/index.html This file provides the SendGrid API Client. """ import os import warnings import python_http_client class SendGridAPIClient(object): """The SendGrid API Client. Use this object to interact with the v3 API. For example: sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) ... mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) For examples and detailed use instructions, see https://github.com/sendgrid/sendgrid-python """ def __init__( self, apikey=None, api_key=None, impersonate_subuser=None, host='https://api.sendgrid.com', **opts): # TODO: remove **opts for 6.x release """ Construct SendGrid v3 API object. Note that underlying client being set up during initialization, therefore changing attributes in runtime will not affect HTTP client behaviour. :param apikey: SendGrid API key to use. If not provided, key will be read from environment variable "SENDGRID_API_KEY" :type apikey: basestring :param api_key: SendGrid API key to use. Provides backward compatibility .. deprecated:: 5.3 Use apikey instead :type api_key: basestring :param impersonate_subuser: the subuser to impersonate. Will be passed by "On-Behalf-Of" header by underlying client. See https://sendgrid.com/docs/User_Guide/Settings/subusers.html for more details :type impersonate_subuser: basestring :param host: base URL for API calls :type host: basestring :param opts: dispatcher for deprecated arguments. Added for backward-compatibility with `path` parameter. Should be removed during 6.x release """ from . import __version__ if opts: warnings.warn( 'Unsupported argument(s) provided: {}'.format(list(opts.keys())), DeprecationWarning) self.apikey = apikey or api_key or os.environ.get('SENDGRID_API_KEY') self.impersonate_subuser = impersonate_subuser self.host = host self.useragent = 'sendgrid/{};python'.format(__version__) self.version = __version__ self.client = python_http_client.Client(host=self.host, request_headers=self._default_headers, version=3) @property def _default_headers(self): headers = { "Authorization": 'Bearer {}'.format(self.apikey), "User-agent": self.useragent, "Accept": 'application/json' } if self.impersonate_subuser: headers['On-Behalf-Of'] = self.impersonate_subuser return headers def reset_request_headers(self): self.client.request_headers = self._default_headers @property def api_key(self): """ Alias for reading API key .. deprecated:: 5.3 Use apikey instead """ return self.apikey @api_key.setter def api_key(self, value): self.apikey = value def send(self, message): response = self.client.mail.send.post(request_body=message.get()) return response <file_sep>import io import os from distutils.file_util import copy_file from setuptools import setup, find_packages def getRequires(): deps = ['python_http_client>=3.0'] return deps dir_path = os.path.abspath(os.path.dirname(__file__)) readme = io.open(os.path.join(dir_path, 'README.rst'), encoding='utf-8').read() version = io.open(os.path.join(dir_path, 'VERSION.txt'), encoding='utf-8').read().strip() copy_file(os.path.join(dir_path, 'VERSION.txt'), os.path.join(dir_path, 'sendgrid', 'VERSION.txt'), verbose=0) setup( name='sendgrid', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', url='https://github.com/sendgrid/sendgrid-python/', packages=find_packages(exclude=["temp*.py", "test"]), include_package_data=True, license='MIT', description='SendGrid library for Python', long_description=readme, install_requires=getRequires(), python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ] )
5ce8b6299a4af2fd8d5654f5dd8af5820f7d9a51
[ "Python" ]
2
Python
tarun-developer/sendgrid_api
d33a0b20aa876a53cfc19109346178a27cb72d38
baf3aa1718e1f63a5c4bd779fab18ea5ca55afd8
refs/heads/main
<repo_name>rfdd/changeBg<file_sep>/README.md # changeBg Change background image after submit contact form
4dcf910fbc7826c92acd7b7614c5cd1fc4ad75a8
[ "Markdown" ]
1
Markdown
rfdd/changeBg
c5a631bdf8738bac07edc343aff3cb714884c637
b50c4588d787d29dd1caf447caee5cfe82e1f594
refs/heads/master
<file_sep># encoding: utf-8 module Sawarineko # Handle command line interfaces logic. class CLI # Initialize a CLi. def initialize @options = {} end # Entry point for the application logic. Process command line arguments and # run the Sawarineko. # # args - An Array of Strings user passed. # # Returns an Integer UNIX exit code. def run(args = ARGV) @options, paths = Option.new.parse(args) source = if paths.empty? $stdin.read else IO.read(paths[0], encoding: @options[:encoding]) end converter = Converter.new(@options[:encoding]) puts converter.convert(source) 0 end end end <file_sep># encoding: utf-8 # Helper methods for testing Converter. module ConverterHelper # Convert the source with given encoding. # # converter - The Converter instance to process. # encoding - The Encoding used in converter. # source - The String source with UTF-8 encoding. # # Returns the converted source String. def convert_source(converter, encoding, source) converter.convert(source.encode(encoding)) end end <file_sep>#!/usr/bin/env ruby # encoding: utf-8 $LOAD_PATH.unshift(File.expand_path('../../lib', File.realpath(__FILE__))) require 'sawarineko' cli = Sawarineko::CLI.new exit cli.run <file_sep># encoding: utf-8 require 'spec_helper' RSpec.describe Sawarineko::CLI do include FileHelper include_context 'isolated environment' subject(:cli) { described_class.new } before(:example) { $stdout = StringIO.new } after(:example) { $stdout = STDOUT } it 'converts text file passed as an argument' do create_file('sawarineko.txt', ['ななめななじゅうななどの' \ 'ならびでなくなくいななく' \ 'ななはんななだいなんなく' \ 'ならべてながながめ']) expect(cli.run(['sawarineko.txt'])).to be(0) expect($stdout.string).to eq('にゃにゃめにゃにゃじゅうにゃにゃどの' \ 'にゃらびでにゃくにゃくいにゃにゃく' \ 'にゃにゃはんにゃにゃだいにゃんにゃく' \ "にゃらべてにゃがにゃがめ\n") end it 'converts string passed as an stdin argument' do allow($stdin).to receive(:read).once .and_return('ななめななじゅうななどの' \ 'ならびでなくなくいななく' \ 'ななはんななだいなんなく' \ 'ならべてながながめ') expect(cli.run([])).to be(0) expect($stdout.string).to eq('にゃにゃめにゃにゃじゅうにゃにゃどの' \ 'にゃらびでにゃくにゃくいにゃにゃく' \ 'にゃにゃはんにゃにゃだいにゃんにゃく' \ "にゃらべてにゃがにゃがめ\n") end describe '-e/--encoding' do it 'converts text file with given encoding' do create_file('sawarineko.txt', ['ななめななじゅうななどの' \ 'ならびでなくなくいななく' \ 'ななはんななだいなんなく' \ 'ならべてながながめ'.encode(Encoding::CP949)]) expect(cli.run(['--encoding', 'cp949', 'sawarineko.txt'])).to be(0) expect($stdout.string).to eq('にゃにゃめにゃにゃじゅうにゃにゃどの' \ 'にゃらびでにゃくにゃくいにゃにゃく' \ 'にゃにゃはんにゃにゃだいにゃんにゃく' \ "にゃらべてにゃがにゃがめ\n") end end end <file_sep># encoding: utf-8 require 'spec_helper' RSpec.describe Sawarineko::Converter do include ConverterHelper describe '#initialize' do subject(:converter) { described_class.new } it 'stores default encoding' do encoding = converter.instance_variable_get(:@encoding) expect(encoding).to be(Encoding::UTF_8) end context 'with Encoding object' do subject(:converter) { described_class.new(encoding) } let(:encoding) { Encoding::UTF_16LE } it 'stores given encoding' do encoding = converter.instance_variable_get(:@encoding) expect(encoding).to be(Encoding::UTF_16LE) end end context 'with string encoding name' do subject(:converter) { described_class.new(encoding) } let(:encoding) { 'utf-16le' } it 'converts given name to Encoding object and stores' do encoding = converter.instance_variable_get(:@encoding) expect(encoding).to be(Encoding::UTF_16LE) end end context 'with string encoding alias name' do subject(:converter) { described_class.new(encoding) } let(:encoding) { 'eucKR' } it 'converts given name to Encoding object and stores' do encoding = converter.instance_variable_get(:@encoding) expect(encoding).to be(Encoding::EUC_KR) end end end context 'with UTF-8 encoding' do subject(:converter) { described_class.new(encoding) } let(:encoding) { Encoding::UTF_8 } it_behaves_like 'a converter supports japanese', Encoding::UTF_8 it_behaves_like 'a converter supports hangul', Encoding::UTF_8 it 'converts all languages at once' do new_source = convert_source(converter, encoding, %w(な ナ 나).join("\n")) expect(new_source).to eq(%w(にゃ ニャ 냐).join("\n").encode(encoding)) end end context 'with UTF-16BE encoding' do it_behaves_like 'a converter supports japanese', Encoding::UTF_16BE it_behaves_like 'a converter supports hangul', Encoding::UTF_16BE end context 'with UTF-16LE encoding' do it_behaves_like 'a converter supports japanese', Encoding::UTF_16LE it_behaves_like 'a converter supports hangul', Encoding::UTF_16LE end context 'with EUC-JP encoding' do it_behaves_like 'a converter supports japanese', Encoding::EUC_JP end context 'with Shift_JIS encoding' do it_behaves_like 'a converter supports japanese', Encoding::Shift_JIS end context 'with EUC-KR encoding' do subject(:converter) { described_class.new(encoding) } let(:encoding) { Encoding::EUC_KR } it_behaves_like 'a converter supports japanese', Encoding::EUC_KR it 'converts hangul 나, 낙, 난, 날, 남, 낭 to 냐, 냑, 냔, 냘, 냠, 냥' do %w(나 낙 난 날 남 낭).zip(%w(냐 냑 냔 냘 냠 냥)).each do |na, nya| new_source = convert_source(converter, encoding, na) expect(new_source).to eq(nya.encode(encoding)) end new_source = convert_source(converter, encoding, '나랑 너랑 봄나들이 배낭 매고 봄나들이 ' \ '버드나무 낭창낭창 남실바람 남실남실 ' \ '개나리 꽃에 나비가 하나 ' \ '배낭 속에 바나나가 하나') expect(new_source).to eq('냐랑 너랑 봄냐들이 배냥 매고 봄냐들이 ' \ '버드냐무 냥창냥창 냠실바람 냠실냠실 ' \ '개냐리 꽃에 냐비가 하냐 ' \ '배냥 속에 바냐냐가 하냐'.encode(encoding)) end it 'preserves other hangul in range 나-낳' do %w(낚 낟 낡 낢 납 낫 났 낮 낯 낱 낳).each do |ch| new_source = convert_source(converter, encoding, ch) expect(new_source).to eq(ch.encode(encoding)) end end end context 'with CP949 encoding' do it_behaves_like 'a converter supports japanese', Encoding::CP949 it_behaves_like 'a converter supports hangul', Encoding::CP949 end end <file_sep># encoding: utf-8 module Sawarineko # Hold Sawarineko's version information. module Version STRING = '1.2.0' end end <file_sep># encoding: utf-8 module Sawarineko # Convert plain text to Sawarineko text. class Converter # Array of convertible character code on EUC-KR encoding. CONVERTIBLE_EUC_KR = %w(나 낙 난 날 남 낭).map { |ch| ch.encode(Encoding::EUC_KR).ord }.freeze private_constant :CONVERTIBLE_EUC_KR # Initialize a Converter. Get the encoding of source. Initialize Regexps for # conversion. # # encoding - The Encoding of source (default: Encoding::UTF_8). # # Examples # # # UTF-8 is default. # Converter.new # # # Encoding object. # Converter.new(Encoding::UTF_16LE) # # # Encoding name. # Converter.new('EUC-JP') # # # Alias of encoding name. # Converter.new('eucKR') def initialize(encoding = Encoding::UTF_8) @encoding = Encoding.find(encoding) @hiragana_regex = Regexp.new('な'.encode(@encoding)).freeze @katakana_regex = Regexp.new('ナ'.encode(@encoding)).freeze @hangul_regex = case @encoding when Encoding::UTF_8, Encoding::UTF_16BE, Encoding::UTF_16LE, Encoding::EUC_KR Regexp.new('[나-낳]'.encode(@encoding)).freeze when Encoding::CP949 Regexp.new('[나-낳낛-낤낥-낲]'.encode(@encoding)).freeze end end # Convert the source. # # source - The String source to convert. # # Returns the String converted to Sawarineko. def convert(source) new_source = source.gsub(@hiragana_regex, 'にゃ'.encode(@encoding).freeze) .gsub(@katakana_regex, 'ニャ'.encode(@encoding).freeze) if @hangul_regex new_source.gsub(@hangul_regex) { |ch| convert_hangul(ch) } else new_source end end private # Convert a hangul character to Sawarineko. # # ch - A hangul character to convert. # # Returns the converted character. def convert_hangul(ch) if @encoding == Encoding::EUC_KR && !CONVERTIBLE_EUC_KR.include?(ch.ord) return ch end (ch.encode(Encoding::UTF_8).ord + 56).chr(Encoding::UTF_8) .encode(@encoding) end end end <file_sep># encoding: utf-8 require 'sawarineko/version' require 'sawarineko/converter' require 'sawarineko/option' require 'sawarineko/cli' # Get your Nya! module Sawarineko # Make the source to Sawarineko. See Converter. # # source - The String source to convert. # encoding - The Encoding of the source (default: Encoding::UTF_8). # # Returns the String converted to Sawarineko. def self.nya(source, encoding = Encoding::UTF_8) Converter.new(encoding).convert(source) end end <file_sep># Sawarineko [![Gem Version](https://badge.fury.io/rb/sawarineko.svg)](http://badge.fury.io/rb/sawarineko) [![Build Status](https://travis-ci.org/yous/sawarineko.svg?branch=master)](https://travis-ci.org/yous/sawarineko) [![Dependency Status](https://gemnasium.com/yous/sawarineko.svg)](https://gemnasium.com/yous/sawarineko) [![Code Climate](https://codeclimate.com/github/yous/sawarineko/badges/gpa.svg)](https://codeclimate.com/github/yous/sawarineko) [![Coverage Status](https://img.shields.io/coveralls/yous/sawarineko.svg)](https://coveralls.io/r/yous/sawarineko?branch=master) [![Inline docs](http://inch-ci.org/github/yous/sawarineko.svg?branch=master)](http://inch-ci.org/github/yous/sawarineko) [![sawarineko API Documentation](https://www.omniref.com/ruby/gems/sawarineko.png)](https://www.omniref.com/ruby/gems/sawarineko) > ななめななじゅうななどのならびでなくなくいななくななはんななだいなんなくならべてながながめ Get your Nya! ## Installation ``` sh gem install sawarineko ``` Or add this line to your application's Gemfile: ``` ruby gem 'sawarineko' ``` ## Usage Just get your Nya with Sawarineko: ``` ruby Sawarineko.nya('ばなな') # => "ばにゃにゃ" Sawarineko.nya('バナナ') # => "バニャニャ" Sawarineko.nya('바나나') # => "바냐냐" ``` Run `sawarineko` with no arguments to pass texts through terminal input. ``` sh sawarineko ``` Or pass `sawarineko` a file to convert like `sawarineko README.md | head -3`: ``` sh sawarineko something.txt ``` For additional command-line options: ``` sh sawarineko -h ``` Command flag | Description --------------------------|------------------------------- `-e, --encoding ENCODING` | Specify the encoding of input. `-h, --help` | Print this message. `-v, --version` | Print version. ## Contributing 1. Fork it (https://github.com/yous/sawarineko/fork) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request ## Changelog See [CHANGELOG.md](CHANGELOG.md). ## License Copyright (c) <NAME>. See [LICENSE.txt](LICENSE.txt) for further details. <file_sep># encoding: utf-8 require 'spec_helper' shared_examples 'a converter supports japanese' do |encoding| include ConverterHelper subject(:converter) { described_class.new(encoding) } describe '#convert' do it 'converts hiragana な to にゃ' do new_source = convert_source(converter, encoding, 'な') expect(new_source).to eq('にゃ'.encode(encoding)) new_source = convert_source(converter, encoding, 'ななめななじゅうななどの' \ 'ならびでなくなくいななく' \ 'ななはんななだいなんなく' \ 'ならべてながながめ') expect(new_source).to eq('にゃにゃめにゃにゃじゅうにゃにゃどの' \ 'にゃらびでにゃくにゃくいにゃにゃく' \ 'にゃにゃはんにゃにゃだいにゃんにゃく' \ 'にゃらべてにゃがにゃがめ'.encode(encoding)) end it 'converts katakana ナ to ニャ' do new_source = convert_source(converter, encoding, 'ナ') expect(new_source).to eq('ニャ'.encode(encoding)) new_source = convert_source(converter, encoding, 'ナナメナナジュウナナドノ' \ 'ナラビデナクナクイナナク' \ 'ナナハンナナダイナンナク' \ 'ナラベテナガナガメ') expect(new_source).to eq('ニャニャメニャニャジュウニャニャドノ' \ 'ニャラビデニャクニャクイニャニャク' \ 'ニャニャハンニャニャダイニャンニャク' \ 'ニャラベテニャガニャガメ'.encode(encoding)) end end end <file_sep># encoding: utf-8 require 'spec_helper' RSpec.describe Sawarineko::Option do include ExitCodeMatchers subject(:option) { described_class.new } before(:example) { $stdout = StringIO.new } after(:example) { $stdout = STDOUT } describe 'option' do describe '-h/--help' do it 'exits cleanly' do expect { option.parse(['-h']) }.to exit_with_code(0) expect { option.parse(['--help']) }.to exit_with_code(0) end it 'shows help text' do begin option.parse(['--help']) rescue SystemExit # rubocop:disable Lint/HandleExceptions end expected_help = <<-END Usage: sawarineko [options] [source] -e, --encoding ENCODING Specify the encoding of input. -h, --help Print this message. -v, --version Print version. END expect($stdout.string).to eq(expected_help) end end describe '-v/--version' do it 'exits cleanly' do expect { option.parse(['-v']) }.to exit_with_code(0) expect { option.parse(['--version']) }.to exit_with_code(0) expect($stdout.string).to eq("#{Sawarineko::Version::STRING}\n" * 2) end end end end <file_sep># Changelog ## 1.2.0 (2014-10-29) - [#2](https://github.com/yous/sawarineko/issues/2): Add encoding support to Converter (UTF-8, UTF-16BE, UTF-16LE, EUC-JP, Shift_JIS, EUC-KR, CP949) - [#2](https://github.com/yous/sawarineko/issues/2): Add `-e/--encoding` option to CLI ## 1.1.0 (2014-10-28) - Add `Sawarineko.nya` - Make `Converter#convert` to get the source as argument ## 1.0.0 (2014-10-27) - Fix crash in `Converter#convert` ## 0.2.0 (2014-10-12) - Add katakana support ## 0.1.0 (2014-10-12) - First release <file_sep># encoding: utf-8 require 'spec_helper' shared_examples 'a converter supports hangul' do |encoding| include ConverterHelper subject(:converter) { described_class.new(encoding) } describe '#convert' do it 'converts hangul 나-낳 to 냐-냫' do ('나'..'낳').zip('냐'..'냫').each do |na, nya| new_source = convert_source(converter, encoding, na) expect(new_source).to eq(nya.encode(encoding)) end new_source = convert_source(converter, encoding, '나랑 너랑 봄나들이 배낭 매고 봄나들이 ' \ '버드나무 낭창낭창 남실바람 남실남실 ' \ '개나리 꽃에 나비가 하나 ' \ '배낭 속에 바나나가 하나') expect(new_source).to eq('냐랑 너랑 봄냐들이 배냥 매고 봄냐들이 ' \ '버드냐무 냥창냥창 냠실바람 냠실냠실 ' \ '개냐리 꽃에 냐비가 하냐 ' \ '배냥 속에 바냐냐가 하냐'.encode(encoding)) end end end <file_sep># encoding: utf-8 require 'spec_helper' RSpec.describe Sawarineko do subject(:sawarineko) { described_class } describe '.nya' do it { is_expected.to respond_to(:nya) } it 'converts string passed as an argument' do expect(sawarineko.nya('ななめななじゅうななどの' \ 'ならびでなくなくいななく' \ 'ななはんななだいなんなく' \ 'ならべてながながめ')) .to eq('にゃにゃめにゃにゃじゅうにゃにゃどの' \ 'にゃらびでにゃくにゃくいにゃにゃく' \ 'にゃにゃはんにゃにゃだいにゃんにゃく' \ 'にゃらべてにゃがにゃがめ') end end end
8283ac6eddc9e099c91fbed262c7df99eedb56d4
[ "Markdown", "Ruby" ]
14
Ruby
yous/sawarineko
0877409957f4196ee71333e5c523e5d11600245c
3c575fefa094d02bc5782996a50771de40534aa5
refs/heads/master
<repo_name>nbaltaci/cpac_extension<file_sep>/README.md # cpac_extension This repository is for the implementation of the GAGM module and CPAC Execution algorithm for the following paper: <NAME>, <NAME>. Separation of Duty Extension to Attribute Based Access Control Approach for Cyber-Physical Systems. (to be submitted to Elsevier Computer & Security journal) (tentative title) Note: 1) Before building the project, "WSO2APICall.jar" should be added as a library to the project as "ExecutionOfCPAC" class makes use of the methods implemented in it for authorization decision. 2) This jar should be added after files with ".RSA" and ".SF" extensions are removed from the jar. Otherwise, "invalid signature file" error will be thrown since the jar itself makes use of some signed jars. In order to remove signed files, the following command should be executed within the directory where "WSO2APICall.jar" resides in: zip -d WSO2APICall.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*SF' <file_sep>/src/com/nuray/gagm/pathfinder/Vertex.java package com.nuray.gagm.pathfinder; import java.util.ArrayList; import java.util.List; /** * Created by TOSHIBA on 1/2/2017. */ public class Vertex{ private int vertexID; private double risk; private List<Edge> edgeList; /** * To hold a previous node in the shortest path. (This would hold a single * node only in one of the possible shortest paths.) */ private Vertex previous; /** * A distance measure for this vertex from source vertex. */ public double sourceDistance = Double.POSITIVE_INFINITY; /** * A List of all previous nodes in all the possible shortest paths. */ private List<Vertex> prev; public Vertex(int vertexNo) { this.vertexID=vertexNo; this.edgeList=new ArrayList<>(); } public void setRisk(double risk) { this.risk=risk; } public double getRisk() { return this.risk; } @Override public boolean equals(Object obj) { Vertex other = (Vertex)obj; return other.getVertexID() == this.getVertexID(); } public void addEdge(Edge edge) { this.edgeList.add(edge); } public int getVertexID() { return this.vertexID; } public List<Edge> getEdges() { return this.edgeList; } // The following methods are added for supporting multiple shortest path between a given source node and destination node public List<Vertex> getPrev() { return prev; } public void setPrev(List<Vertex> prev) { this.prev = prev; } public Vertex getPrevious() { return previous; } public void setPrevious(Vertex previous) { this.previous = previous; } public double getSourceDistance() { return sourceDistance; } public void setSourceDistance(double sourceDistance) { this.sourceDistance = sourceDistance; } } <file_sep>/src/com/nuray/gagm/test/Test.java package com.nuray.gagm.test; import com.nuray.cpacexecution.enforcementfunctions.VirtualAccessRequest; import com.nuray.cpacexecution.storage.ActionBase; import com.nuray.gagm.experiment.CompleteGraph; import com.nuray.gagm.experiment.Sparse; import com.nuray.gagm.pathfinder.*; import java.util.*; /** * Created by TOSHIBA on 1/2/2017. */ public class Test { private static int[][] adjacencyMatrix; private static Sparse sparse; private static CompleteGraph complete; private static com.nuray.gagm.pathfinder.VARGeneration VARGeneration; private static com.nuray.gagm.pathfinder.VARGenerationMultipleShortestPathVersion VARGenerationMultipleShortestPathVersion; public static void main(String[] args) throws Exception { // printResultsforSparseGraph(1,1,3,new int[]{3}); // printResultsforSparseGraph(2,1,6, new int[]{6}); // printResultsforSparseGraph(2,5,12, new int[]{12}); // printResultsforCompleteGraph(3,1,3, new int[]{4}); // ==> this is a complete one // // System.out.println("NOW RUNNING FOR ACTUAL SET OF FINAL STATES"); // int[] finalStates=new int[]{6,12}; // printResultsforSparseGraph(2,5,12, finalStates); varSetTest("sparse",1,1,3,new int[]{3,4}); // test the case when there may be multiple shortest paths between a given source and destination vertex // printResultsForMultiplePathCase("sparse",4,1,3,new int[]{3}); // test the case when there may be multiple shortest paths between a given source and destination vertex, but // multiple paths are reduced to a single shortest path based on minimum privilege criteria (allowed permissions on // edges) // printResultsforReducedCase("sparse",4,1,3,new int[]{3}); // Reduced case test for generating vars varSetTestForReducedCase("sparse",4,1,3,new int[]{3}); } private static void printResultsforSparseGraph(int testCaseNumber, int sourceVertex,int destinationVertex,int[] finalStates) throws Exception { printResultsforTestCases("sparse",testCaseNumber,sourceVertex,destinationVertex,finalStates); } private static void printResultsforCompleteGraph(int testCaseNumber, int sourceVertex,int destinationVertex,int[] finalStates) throws Exception { printResultsforTestCases("complete",testCaseNumber,sourceVertex,destinationVertex,finalStates); } private static void printResultsForMultiplePathCase(String graphType,int testCaseNumber, int sourceVertex,int destinationVertex, int[] finalStates) throws Exception { Graph graph=initializeGraph(graphType,testCaseNumber,finalStates); System.out.println("TEST CASE "+testCaseNumber+":"); System.out.println("Shortest Paths:\n From vertex "+sourceVertex+" to vertex "+destinationVertex); long beginTime=new Date().getTime(); VARGenerationMultipleShortestPathVersion varGenMSPVersion = new VARGenerationMultipleShortestPathVersion(graph, sourceVertex, destinationVertex, finalStates); varGenMSPVersion.solve(); long endTime=new Date().getTime(); System.out.println("Running time for "+adjacencyMatrix.length+" vertices: "+(endTime-beginTime)); } private static void printResultsforReducedCase(String graphType,int testCaseNumber, int sourceVertex,int destinationVertex, int[] finalStates) throws Exception { Graph graph=initializeGraph(graphType,testCaseNumber,finalStates); System.out.println("TEST CASE "+testCaseNumber+":"); System.out.println("Shortest Paths:\n From vertex "+sourceVertex+" to vertex "+destinationVertex); long beginTime=new Date().getTime(); VARGenerationMultipleShortestPathVersion varGenMSPVersion = new VARGenerationMultipleShortestPathVersion(graph, sourceVertex, destinationVertex, finalStates); varGenMSPVersion.solveReduced(); long endTime=new Date().getTime(); System.out.println("Running time for "+adjacencyMatrix.length+" vertices: "+(endTime-beginTime)); } private static void printResultsforTestCases(String graphType,int testCaseNumber, int sourceVertex,int destinationVertex, int[] finalStates) throws Exception { Graph graph=initializeGraph(graphType,testCaseNumber,finalStates); System.out.println("TEST CASE "+testCaseNumber+":"); System.out.println("Shortest Paths:\n From vertex "+sourceVertex+" to vertex "+destinationVertex); long beginTime=new Date().getTime(); VARGeneration =new VARGeneration(graph,sourceVertex,destinationVertex,finalStates); VARGeneration.solve(); long endTime=new Date().getTime(); System.out.println("Running time for "+adjacencyMatrix.length+" vertices: "+(endTime-beginTime)); } private static void varSetTest(String graphType,int testCaseNumber, int sourceVertex,int destinationVertex, int[] finalStates) throws Exception { Graph graph = initializeGraph(graphType, testCaseNumber, finalStates); System.out.println("TEST CASE "+testCaseNumber+":"); VARGeneration =new VARGeneration(graph,sourceVertex,destinationVertex,finalStates); Set<Graph> subGraphSet=new HashSet<Graph>(); subGraphSet.add(graph); Map<String, Queue<Map<Vertex, Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>>>> varSet = VARGeneration.generateVAR(subGraphSet); Iterator<String> varSetIterator = varSet.keySet().iterator(); while (varSetIterator.hasNext()) { String m = varSetIterator.next(); // m = operational mode Queue<Map<Vertex, Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>>> varSet_m = varSet.get(m); System.out.println("Now printing varSet for " + m + " mode:"); System.out.println("\t Shortest Paths (vars on the shortest path):"); while (!varSet_m.isEmpty()) { Map<Vertex, Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>> varListMap = varSet_m.poll(); Iterator<Vertex> varListIterator = varListMap.keySet().iterator(); while (varListIterator.hasNext()) { Vertex sourceState = varListIterator.next(); Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>> varList_v_Map = varListMap.get(sourceState); while (!varList_v_Map.isEmpty()) { Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>> varList_v = varList_v_Map.poll(); Iterator<Vertex> varList_v_Iterator = varList_v.keySet().iterator(); while (varList_v_Iterator.hasNext()) { Vertex finalState = varList_v_Iterator.next(); Queue<Map<Edge, VirtualAccessRequest>> varList_f = varList_v.get(finalState); System.out.println("\t \t From vertex " + sourceState.getVertexID() + " to vertex " + finalState.getVertexID() + "\n"); while (!varList_f.isEmpty()) { Map<Edge, VirtualAccessRequest> edgeVarMap = varList_f.poll(); Iterator<Edge> edgeIterator = edgeVarMap.keySet().iterator(); while (edgeIterator.hasNext()) { Edge edge = edgeIterator.next(); VirtualAccessRequest var = edgeVarMap.get(edge); int requestId = var.getRequestId(); System.out.println("\t \t \t v" + edge.getSourceVertex().getVertexID() + " --> v" + edge.getTargetVertex().getVertexID() + ": var" + requestId); } } } } } } } } private static void varSetTestForReducedCase(String graphType,int testCaseNumber, int sourceVertex,int destinationVertex, int[] finalStates) throws Exception { Graph graph = initializeGraph(graphType, testCaseNumber, finalStates); System.out.println("TEST CASE "+testCaseNumber+":"); VARGenerationMultipleShortestPathVersion = new VARGenerationMultipleShortestPathVersion(graph,sourceVertex,destinationVertex,finalStates); Set<Graph> subGraphSet=new HashSet<Graph>(); subGraphSet.add(graph); Map<String, Queue<Map<Vertex, Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>>>> varSet = VARGenerationMultipleShortestPathVersion.generateVAR(subGraphSet); Iterator<String> varSetIterator = varSet.keySet().iterator(); while (varSetIterator.hasNext()) { String m = varSetIterator.next(); // m = operational mode Queue<Map<Vertex, Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>>> varSet_m = varSet.get(m); System.out.println("Now printing varSet for " + m + " mode:"); System.out.println("\t Shortest Paths (vars on the shortest path):"); while (!varSet_m.isEmpty()) { Map<Vertex, Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>> varListMap = varSet_m.poll(); Iterator<Vertex> varListIterator = varListMap.keySet().iterator(); while (varListIterator.hasNext()) { Vertex sourceState = varListIterator.next(); Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>> varList_v_Map = varListMap.get(sourceState); while (!varList_v_Map.isEmpty()) { Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>> varList_v = varList_v_Map.poll(); Iterator<Vertex> varList_v_Iterator = varList_v.keySet().iterator(); while (varList_v_Iterator.hasNext()) { Vertex finalState = varList_v_Iterator.next(); Queue<Map<Edge, VirtualAccessRequest>> varList_f = varList_v.get(finalState); System.out.println("\t \t From vertex " + sourceState.getVertexID() + " to vertex " + finalState.getVertexID() + "\n"); while (!varList_f.isEmpty()) { Map<Edge, VirtualAccessRequest> edgeVarMap = varList_f.poll(); Iterator<Edge> edgeIterator = edgeVarMap.keySet().iterator(); while (edgeIterator.hasNext()) { Edge edge = edgeIterator.next(); VirtualAccessRequest var = edgeVarMap.get(edge); int requestId = var.getRequestId(); System.out.println("\t \t \t v" + edge.getSourceVertex().getVertexID() + " --> v" + edge.getTargetVertex().getVertexID() + ": var" + requestId); } } } } } } } } public static Graph initializeGraph(String graphType,int testCaseNumber, int[] finalStates) throws Exception { adjacencyMatrix = ReadAdjacency.read("src/adjacent matrix for test case-"+testCaseNumber+".txt"); String[][] edgeTypeMatrix=null; VirtualAccessRequest[][] varMatrix=null; if(graphType.equalsIgnoreCase("sparse")) { sparse=new Sparse(adjacencyMatrix.length,0,100,1,100,0.5); sparse.setAdjacencyMatrix(adjacencyMatrix); edgeTypeMatrix=sparse.generateEdgeTypeMatrix(); varMatrix=sparse.generateVarMatrix(5,1,1,5, new ActionBase(),"emergency"); } else if (graphType.equalsIgnoreCase("complete")) { complete=new CompleteGraph(adjacencyMatrix.length,0,100,1,100,0.5); complete.setAdjacencyMatrix(adjacencyMatrix); edgeTypeMatrix=complete.generateEdgeTypeMatrix(); varMatrix=complete.generateVarMatrix(5,1,1,5, new ActionBase(),"emergency"); } else { throw new Exception("invalid graph type, should be either complete or sparse!"); } double[] riskValues=new double[adjacencyMatrix.length]; Arrays.fill(riskValues,100); Graph graph=new Graph(adjacencyMatrix,riskValues,edgeTypeMatrix,varMatrix,finalStates,"emergency"); return graph; } } <file_sep>/src/com/nuray/gagm/experiment/TimePerformance.java package com.nuray.gagm.experiment; import com.nuray.cpacexecution.enforcementfunctions.VirtualAccessRequest; import com.nuray.cpacexecution.storage.ActionBase; import com.nuray.gagm.pathfinder.Graph; import com.nuray.gagm.pathfinder.VARGeneration; import java.util.Date; /** * Created by TOSHIBA on 1/4/2017. */ public class TimePerformance { private static int[][] adjacencyMatrix; private static double[] riskValues; private static String[][] edgeTypeMatrix; private static VirtualAccessRequest[][] varMatrix; private static com.nuray.gagm.pathfinder.VARGeneration VARGeneration; private static CompleteGraph completeGraph; private static Sparse sparse; private static Random random; public static void main(String[] args) throws Exception { for(int i=10;i<=100;i=i+10) { solveSparse((100*i),0,100,1,100, 0.5,1,10,null); } // System.out.println("Results for complete graph..."); // for(int i=10;i<=100;i=i+10) // { // solveComplete((10*i),0,100,1,100,1,100); // } System.out.println("Results for sparse graph..."); for(int i=10;i<=100;i=i+10) { solveSparse((100*i),0,100,1,100, 0.5,1,10,null); } } /** * * @param numberOfVertices * @param weightLower * @param weightUpper * @param riskLower * @param riskUpper * @param fraction: this is the ratio of critical edges to the total edges (critical edge vs. action edge) * @param sourceVertex * @param destinationVertex * @param finalStates: if this is null, two random vertices will be selected as final states */ private static void solveComplete(int numberOfVertices,int weightLower,int weightUpper,int riskLower, int riskUpper, double fraction,int sourceVertex,int destinationVertex, int[] finalStates) throws Exception { completeGraph=new CompleteGraph(numberOfVertices,weightLower,weightUpper,riskLower,riskUpper,fraction); solve("complete",numberOfVertices,sourceVertex,destinationVertex,finalStates); } /** * * @param numberOfVertices * @param weightLower * @param weightUpper * @param riskLower * @param riskUpper * @param fraction: this is the ratio of critical edges to the total edges (critical edge vs. action edge) * @param sourceVertex * @param destinationVertex * @param finalStates: if this is null, two random vertices will be selected as final states */ private static void solveSparse(int numberOfVertices,int weightLower,int weightUpper,int riskLower, int riskUpper,double fraction, int sourceVertex,int destinationVertex, int[] finalStates) throws Exception { sparse=new Sparse(numberOfVertices,weightLower,weightUpper,riskLower,riskUpper,fraction); solve("sparse",numberOfVertices,sourceVertex,destinationVertex,finalStates); } private static void solve(String graphType,int numberOfVertices,int sourceVertex,int destinationVertex,int[] finalStates) throws Exception { if(graphType.equalsIgnoreCase("complete")) { adjacencyMatrix=completeGraph.generateAdjacencyMatrix(); riskValues=completeGraph.generateRiskValues(); edgeTypeMatrix=completeGraph.generateEdgeTypeMatrix(); varMatrix=completeGraph.generateVarMatrix(5,1,1,5, new ActionBase(),"emergency"); } else if (graphType.equalsIgnoreCase("sparse")) { adjacencyMatrix=sparse.generateAdjacencyMatrix(); riskValues=sparse.generateRiskValues(); edgeTypeMatrix=sparse.generateEdgeTypeMatrix(); varMatrix=sparse.generateVarMatrix(5,1,1,5, new ActionBase(),"emergency"); } random=new Random(1,adjacencyMatrix.length); Graph graph=new Graph(adjacencyMatrix,riskValues,edgeTypeMatrix,varMatrix,null,"emergency"); int totalTime=0; double avgTime; for(int i=0;i<100;i++) { int source=random.generateRandomIndex(); int destination=random.generateRandomIndex(); long beginTime=new Date().getTime(); VARGeneration =new VARGeneration(graph,source,destination,finalStates); VARGeneration.solveExperiment(); long endTime=new Date().getTime(); totalTime+=(endTime-beginTime); } avgTime=totalTime/100; System.out.println("Running time for "+numberOfVertices+" vertices: "+(avgTime)); } } <file_sep>/src/com/nuray/cpacexecution/enforcementfunctions/Permission.java package com.nuray.cpacexecution.enforcementfunctions; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Resource; import java.util.List; public class Permission { private int permissionId; private Resource resource; // private String resourceID; //'resource_id' is a string that is used to describe the the resource itself (machine1, file2 etc.) private List<Action> actionList; //'action_id' is a string that is used to describe the action itself (read, write etc.) public Permission(Resource resource, List<Action> actionList) { if(resource==null) { throw new NullPointerException("resource cannot be null in a permission!"); } if(actionList.isEmpty()) { throw new NullPointerException("action list cannot be empty in a permission!"); } this.resource=resource; this.actionList=actionList; permissionId++; } @Override public boolean equals(Object obj) { Permission other = (Permission) obj; Resource resource = this.resource; Resource otherResource = other.resource; List<Action> actionList=this.actionList; List<Action> otherActionList=other.actionList; return resource.equals(otherResource) && actionList.equals(otherActionList); } @Override public int hashCode() { return 13*resource.hashCode()*actionList.hashCode(); } public int getPermissionId() { return permissionId; } public Resource getResource() { return resource; } public List<Action> getActionList() { return actionList; } } <file_sep>/src/com/nuray/cpacexecution/test/SimpleTest.java package com.nuray.cpacexecution.test; import com.nuray.cpacexecution.cpacmodel.Agent; import com.nuray.cpacexecution.cpacmodel.Attribute; import com.nuray.cpacexecution.cpacmodel.AttributeRange; import com.nuray.cpacexecution.enforcementfunctions.PolicyRule; import java.sql.SQLOutput; import java.util.*; public class SimpleTest { public static void main(String[] args) throws Exception { Agent agent=new Agent("agn1","human"); AttributeRange ar=new AttributeRange(5,10); Attribute attribute=new Attribute("name",ar,"numeric"); attribute.setAttributeValueNumeric(7); agent.addAgentAttribute(attribute); Attribute attToTest=new Attribute("name",ar,"numeric"); attToTest.setAttributeValueNumeric(7); System.out.println(agent.hasAttribute(attToTest)); } } <file_sep>/src/com/nuray/gagm/test/ReadAdjacency.java package com.nuray.gagm.test; import java.io.BufferedReader; import java.io.FileReader; /** * Created by TOSHIBA on 1/2/2017. */ public class ReadAdjacency { public static int[][] read(String name) { int[][] adjacency = null; BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(name)); String line = bufferedReader.readLine(); int count = 0; String[] temp = line.split("\\s+"); adjacency = new int[temp.length][temp.length]; adjacency[0][0] = 0; for (int i = 1; i < temp.length; i++) { if (temp[i].equals(".")) { adjacency[count][i] = Integer.MAX_VALUE; } else { adjacency[count][i] = Integer.parseInt(temp[i]); } } while (line != null) { line = bufferedReader.readLine(); count++; if (line == null) { break; } temp = line.split("\\s+"); for (int i = 0; i < temp.length; i++) { if (temp[i].equals(".")) { if (i == count) { adjacency[count][i] = 0; } else { adjacency[count][i] = Integer.MAX_VALUE; } } else { adjacency[count][i] = Integer.parseInt(temp[i]); } } } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return adjacency; } } <file_sep>/src/com/nuray/gagm/pathfinder/VARGenerationMultipleShortestPathVersion.java package com.nuray.gagm.pathfinder; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Attribute; import com.nuray.cpacexecution.enforcementfunctions.VirtualAccessRequest; import java.util.*; public class VARGenerationMultipleShortestPathVersion { private Set<List<Vertex>> allShortestPaths; private Graph graph; private int graphSize; private Vertex startVertex; private Vertex targetVertex; private PriorityQueue<QVertex> Q; private Set<Vertex> finalStateSet; private Queue<Map<Edge, VirtualAccessRequest>> varList_f; // this is for a single source and a single destination state in a graph private Queue<Map<Vertex,Queue<Map<Edge, VirtualAccessRequest>>>> varList_v; // this is for a single source and a set of destination (final) states in a graph private Queue<Map<Vertex,Queue<Map<Vertex,Queue<Map<Edge, VirtualAccessRequest>>>>>> varSet_m; // this is for a set of source and a set of destination states in a graph private Map<String,Queue<Map<Vertex,Queue<Map<Vertex,Queue<Map<Edge, VirtualAccessRequest>>>>>>> varSet; public VARGenerationMultipleShortestPathVersion(Graph graph, int startVertex, int targetVertex, int[] finalStates) { this.graph=graph; this.graphSize = graph.getNumberOfVertices(); this.startVertex = graph.getVertices().stream().filter(item -> item.getVertexID() == startVertex).findAny().orElse(null); this.targetVertex = graph.getVertices().stream().filter(item -> item.getVertexID() == targetVertex).findAny().orElse(null); finalStateSet = new HashSet<>(); for (int i = 0; i < finalStates.length; i++) { int stateNo = finalStates[i]; Vertex vertexToAdd = graph.getVertices().stream().filter(item -> item.getVertexID() == stateNo).findAny().orElse(null); this.finalStateSet.add(vertexToAdd); } } public Map<String, Queue<Map<Vertex, Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>>>> generateVAR(Set<Graph> graphSet) { varList_v=new LinkedList<>(); varSet_m=new LinkedList<>(); varSet=new HashMap<>(); for (Graph graph:graphSet) { varList_f=new LinkedList<>(); List<Vertex> vertices = graph.getVertices(); //get only non-final states // vertices.removeAll(finalStateSet); for (Vertex vertex:vertices) { varList_v = findVarList(vertex, finalStateSet); Map<Vertex,Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>>> map=new HashMap<>(); map.put(vertex,varList_v); varSet_m.add(map); varList_v=new LinkedList<>(); } String operationalMode=graph.getOperationalMode(); varSet.put(operationalMode,varSet_m); varSet_m=new LinkedList<>(); } return varSet; } public Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>> findVarList(Vertex source, Set<Vertex> finalStateSet) { for (Vertex finalState:finalStateSet) { // startVertex=source; findOptimumReduced(source); findVarListSingleDest(source,finalState); Map<Vertex,Queue<Map<Edge,VirtualAccessRequest>>> map=new HashMap<>(); if(varList_f!=null) { map.put(finalState,varList_f); varList_v.add(map); } varList_f=new LinkedList<>(); } return varList_v; } private Queue<Map<Edge, VirtualAccessRequest>> findVarListSingleDest(Vertex sourceVertex, Vertex destinationVertex) { if(sourceVertex==destinationVertex) { return null; } if (destinationVertex==null) { return null; } Vertex previousVertex=destinationVertex.getPrevious(); if(previousVertex!=startVertex) { findVarListSingleDest(sourceVertex, previousVertex); } if(previousVertex!=null) { List<Edge> edgeList=previousVertex.getEdges(); for (Edge e:edgeList) { if( e.getTargetVertex().getVertexID()== destinationVertex.getVertexID()) { VirtualAccessRequest var = e.getVar(); if(var!=null) { Map<Edge,VirtualAccessRequest> map=new HashMap<>(); map.put(e,var); varList_f.add(map); } } } } return varList_f; } /** * This method prints the single shortest path found by the findOptimumReduced() method */ public void solveReduced() { // findOptimumReduced(); List<Vertex> path = getShortestPathTo(targetVertex); for (Vertex v:path) { System.out.print("v"+v.getVertexID()+" "); } printShortestPathLength(path); } public void solve() { findOptimum(); Set<List<Vertex>> allShortestPaths =getAllShortestPathsTo(targetVertex); int i = 1; for (List<Vertex> path:allShortestPaths) { System.out.print("Path "+i+": "); for (Vertex v:path) { System.out.print("v"+v.getVertexID()+" "); } printShortestPathLength(path); i++; } // printVertexesOnShortestPath(startVertex, targetVertex); // printShortestPathLength(); } public void solveExperiment() { findOptimum(); } private void findOptimum() { //initialize pq Q = new PriorityQueue<>(graphSize, new Comparator<QVertex>() { @Override public int compare(QVertex o1, QVertex o2) { return Double.compare(o1.getTotalRisk(), o2.getTotalRisk()); } }); // 9/12/2018 nuray: initialize set of visited vertices // Set<Vertex> visitedVertices = new HashSet<>(); //initialize shortest distance of all vertices to infinity, and distance of starting vertex to zero for (Vertex v:graph.getVertices()) { v.setPrevious(null); v.setSourceDistance(Double.MAX_VALUE); } startVertex.sourceDistance=0; Q.add(new QVertex(startVertex, 0)); List<Vertex> prev = null; while (!Q.isEmpty()) { QVertex minQVertex = Q.poll(); Vertex minVertex = minQVertex.getVertex(); // 10/22/2019 I commented out the following lines because it prevents the method from finding multiple paths. // When a single path is found and the final state is reached, it exits the loop and method stops. // // 9/12/2018 NURAY: check if a final state is reached (Fg in our paper) // if(visitedVertices.containsAll(finalStateSet)) // { // break; // } List<Edge> edgeList = minVertex.getEdges(); for (Edge e : edgeList) { Vertex adjacent = e.getTargetVertex(); QVertex adjacentVertex=new QVertex(adjacent,adjacent.getRisk()); prev = adjacent.getPrev(); // double newDistance = e.getProbability() * adjacent.getRisk() + minQVertex.getTotalRisk(); // double newDistance = e.getProbability()+ minVertex.sourceDistance; double newDistance=e.getProbability()*adjacent.getRisk()+minVertex.sourceDistance; if (newDistance < adjacent.sourceDistance) { Q.remove(adjacentVertex); adjacent.sourceDistance = newDistance; adjacent.setPrevious(minVertex); Q.add(new QVertex(adjacent, adjacent.sourceDistance)); prev = new ArrayList<Vertex>(); prev.add(minVertex); adjacent.setPrev(prev); } else if (newDistance == adjacent.sourceDistance) { if (prev != null) prev.add(minVertex); else { prev = new ArrayList<Vertex>(); prev.add(minVertex); adjacent.setPrev(prev); } } // if (!visitedVertices.contains(adjacent)) // { // visitedVertices.add(adjacent); // } } } } /** * This method also finds multiple paths between a given start and target vertex, but it reduces to a * single path considering the authorization privileges assigned to edges (min privilege) * @return */ private void findOptimumReduced(Vertex source) { //initialize pq Q = new PriorityQueue<>(graphSize, new Comparator<QVertex>() { @Override public int compare(QVertex o1, QVertex o2) { return Double.compare(o1.getTotalRisk(), o2.getTotalRisk()); } }); // 9/12/2018 nuray: initialize set of visited vertices // Set<Vertex> visitedVertices = new HashSet<>(); //initialize shortest distance of all vertices to infinity, and distance of starting vertex to zero for (Vertex v:graph.getVertices()) { v.setPrevious(null); v.setSourceDistance(Double.MAX_VALUE); } source.sourceDistance=0; Q.add(new QVertex(source, 0)); int minPrivSize=Integer.MAX_VALUE; // for selecting edges that have equal distance while (!Q.isEmpty()) { QVertex minQVertex = Q.poll(); Vertex minVertex = minQVertex.getVertex(); List<Edge> edgeList = minVertex.getEdges(); for (Edge e : edgeList) { Vertex adjacent = e.getTargetVertex(); QVertex adjacentVertex=new QVertex(adjacent,adjacent.getRisk()); // double newDistance = e.getProbability()+ minVertex.sourceDistance; double newDistance=e.getProbability()*adjacent.getRisk()+minVertex.sourceDistance; if (newDistance < adjacent.sourceDistance) { Q.remove(adjacentVertex); adjacent.sourceDistance = newDistance; adjacent.setPrevious(minVertex); Q.add(new QVertex(adjacent, adjacent.sourceDistance)); } else if (newDistance == adjacent.sourceDistance) { VirtualAccessRequest var = e.getVar(); if(var!=null) { Map<Action, List<Attribute>> actionAttributes = var.getActionAttributes(); Set<Action> actions = actionAttributes.keySet(); int privilegeSize=actions.size(); if(privilegeSize<minPrivSize) { minPrivSize=privilegeSize; adjacent.setPrevious(minVertex); } } } } } } /** * @param target * @return A List of nodes in order as they would appear in a shortest path. * (There can be multiple shortest paths present. This method * returns just one of those paths.) */ public List<Vertex> getShortestPathTo(Vertex target) { List<Vertex> path = new ArrayList<Vertex>(); for (Vertex vertex = target; vertex != null; vertex = vertex .getPrevious()) path.add(vertex); Collections.reverse(path); return path; } /** * @param target * @return A set of all possible shortest paths from the source to the given * target. */ public Set<List<Vertex>> getAllShortestPathsTo(Vertex target) { allShortestPaths = new HashSet<List<Vertex>>(); getShortestPath(new ArrayList<Vertex>(), target); return allShortestPaths; } /** * Recursive method to enumerate all possible shortest paths and add each * path in the set of all possible shortest paths. * * @param shortestPath * @param target * @return */ private List<Vertex> getShortestPath(List<Vertex> shortestPath, Vertex target) { List<Vertex> prev = target.getPrev(); if (prev == null) { // shortestPath.add(target); Collections.reverse(shortestPath); List<Vertex> tempPath=new ArrayList<>(); tempPath.add(target); tempPath.addAll(shortestPath); shortestPath=tempPath; allShortestPaths.add(shortestPath); } else { List<Vertex> updatedPath = new ArrayList<Vertex>(shortestPath); updatedPath.add(target); for (Vertex v:prev) { getShortestPath(updatedPath,v); } } return shortestPath; } private void printShortestPathLength(List<Vertex> path) { //System.out.println("\nWeight:" + length[targetVertex.getVertexID() - 1]); Vertex target=path.get(path.size()-1); System.out.println("\n Length of shortest path: "+target.sourceDistance); } } <file_sep>/src/com/nuray/gagm/pathfinder/Graph.java package com.nuray.gagm.pathfinder; import com.nuray.cpacexecution.enforcementfunctions.VirtualAccessRequest; import com.nuray.gagm.experiment.Random; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * Created by TOSHIBA on 1/2/2017. */ public class Graph { private List<Vertex> vertices; private Random finalStateGenerator; private String operationalMode; int[] finalStates; public Graph() { } /** * * @param adjacencyMatrix * @param riskOfVertices * @param edgeTypeMatrix * @param varMatrix * @param finalStates: if this is null, two random vertices will be selected as final states * @param operationalMode */ public Graph(int[][] adjacencyMatrix, double[] riskOfVertices, String[][] edgeTypeMatrix, VirtualAccessRequest[][] varMatrix, int[] finalStates,String operationalMode) { this.operationalMode=operationalMode; vertices=new ArrayList<>(); for(int i=0;i<adjacencyMatrix.length;i++) { Vertex v=new Vertex(i+1); v.setRisk(riskOfVertices[i]); vertices.add(v); } for(int i=0;i<adjacencyMatrix.length;i++) { for (int j = 0; j < adjacencyMatrix.length; j++) { if (adjacencyMatrix[i][j] != 0&&adjacencyMatrix[i][j] != Integer.MAX_VALUE) { double weight=adjacencyMatrix[i][j]/100.00; weight=formatDecimalPoints(weight); Edge edge=new Edge(vertices.get(i), vertices.get(j), weight, edgeTypeMatrix[i][j],varMatrix[i][j]); vertices.get(i).addEdge(edge); } } } finalStateGenerator=new Random(1,vertices.size()); if(finalStates==null) { this.finalStates=generateRandomFinalStates(2); } else { this.finalStates=finalStates; } } public List<Vertex> getVertices() { return this.vertices; } public int getNumberOfVertices() { return vertices.size(); } public String getOperationalMode() { return operationalMode; } private double formatDecimalPoints(double numberToFormat) { DecimalFormat df = new DecimalFormat("#.00"); String numberFormatted = df.format(numberToFormat); double numberToReturn=Double.parseDouble(numberFormatted); return numberToReturn; } public int[] generateRandomFinalStates(int numberOfFinalStates) { List<Integer> finalStateList=new LinkedList<>(); for(int i=0;i<numberOfFinalStates;i++) { int randomVertex=finalStateGenerator.generateRandomIndex(); if(!finalStateList.contains(randomVertex)) { finalStateList.add(randomVertex); } } finalStates=finalStateList.stream().mapToInt(Integer::intValue).toArray(); return finalStates; } public int[] getFinalStates() { return finalStates; } } <file_sep>/src/com/nuray/cpacexecution/storage/AgentBase.java package com.nuray.cpacexecution.storage; import com.nuray.cpacexecution.cpacmodel.Agent; import com.nuray.cpacexecution.cpacmodel.Attribute; import java.io.IOException; import java.io.UncheckedIOException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class AgentBase { private List<Agent> agentList; Map<String, Agent> agentMap; public AgentBase() { agentList=new ArrayList<>(); agentMap=new HashMap<>(); } public void addAgent(Agent agent) { agentList.add(agent); agentMap.put(agent.getAgentID(),agent); } public void deleteAgent(Agent agent) throws Exception { if (agentList.contains(agent)) { agentList.remove(agent); agentMap.remove(agent.getAgentID()); } else { throw new Exception("Resource cannot be removed since it is not in the list!"); } } public Agent getAgent(Agent agent) { if (agentList.contains(agent)) { return agent; } else { return null; } } public List<Agent> getAgentList() { return agentList; } public List<Agent> getAgentsWithAttributeValue(Attribute attribute) throws Exception { List<Agent> result=new LinkedList<>(); Iterator<Agent> agentIterator = agentList.iterator(); if(attribute.isValueSet()) { return agentMap.values() .stream() .filter(agn -> agn.hasAttribute(attribute)) // .filter(agn -> agn.getAgentAttributes() // .stream() // .filter(att -> att.isValueSet()) // .filter(att -> att.getAttributeType().equalsIgnoreCase(attribute.getAttributeType())) // .filter(att -> // { // boolean filterResult = false; // try { // if (attribute.getAttributeType().equalsIgnoreCase("categorical")) { // filterResult = att.getAttributeValueCategorical().equalsIgnoreCase(attribute.getAttributeValueCategorical()); // } else if (attribute.getAttributeType().equalsIgnoreCase("numeric")) { // filterResult = att.getAttributeValueNumeric() == attribute.getAttributeValueNumeric(); // } // } catch (Exception e) { // e.printStackTrace(); // } // return filterResult; // }).count() != 0 // // ) .collect(Collectors.toList()); } // while (agentIterator.hasNext()) // { // Agent agent = agentIterator.next(); // //// List<Attribute> agentAttributes = agent.getAgentAttributes(); // Map<String, Attribute> agentAttributes = agent.getAgentAttributes(); // // for (Attribute agentAtt:agentAttributes) // { // if(agentAtt.getAttributeName().equalsIgnoreCase(attribute.getAttributeName())) // { // if(agentAtt.isValueSet()) // { // if(agentAtt.getAttributeType().equalsIgnoreCase("categorical")) // { // if(agentAtt.getAttributeValueCategorical().equalsIgnoreCase(attribute.getAttributeValueCategorical())) // { // result.add(agent); // } // } // if(agentAtt.getAttributeType().equalsIgnoreCase("numeric")) // { // if(agentAtt.getAttributeValueNumeric()==attribute.getAttributeValueNumeric()) // { // result.add(agent); // } // } // } // } // } return result; } } <file_sep>/src/com/nuray/gagm/pathfinder/GraphInt.java package com.nuray.gagm.pathfinder; import com.nuray.cpacexecution.enforcementfunctions.VirtualAccessRequest; import com.nuray.cpacexecution.storage.ActionBase; import java.util.List; /** * Created by TOSHIBA on 1/4/2017. */ public interface GraphInt { public int[][] generateAdjacencyMatrix(); public double[] generateRiskValues(); String[][] generateEdgeTypeMatrix(); VirtualAccessRequest[][] generateVarMatrix(int nAgentAtt, int nResAtt, int nActionAtt, int nActions, ActionBase actionBase, String operationalMode) throws Exception; // this is for generating virtual access requests for labels of critical edges public List<Vertex> getVertices(); public void setAdjacencyMatrix(int[][] adjacencyMatrix); public int getNumberOfVertices(); public double formatDecimalPoints(double numberToFormat); } <file_sep>/src/com/nuray/cpacexecution/cpacmodel/Agent.java package com.nuray.cpacexecution.cpacmodel; import java.util.*; public class Agent { private List<Attribute> agentAttributes; private Set<Attribute> agentAttributeSet; /* note that 'agentId' is not the same as 'agent_id' attribute. 'agentId' is an int that is simply used to identify the count of attribute whereas 'agent_id' is a string that is used to describe the agent itself (such as username for a human agent, machine ID for a physical resource (e.g. heparinDevice1), and any identification for a cyber resource (e.g. fileName, applicationName etc.). */ private int agentId; private String agentID; private String type; private Attribute userName; private Attribute email; private Attribute role; private Attribute age; /** * * @param agentID: This basically represents the name of the agent. An example for a human agent: "<EMAIL>" * @param type: This corresponds to the type of agent. Valid options are: "human", "physical", and "cyber". * (see CPACSpecifications.java) */ public Agent(String agentID, String type) throws Exception { if(!CPACSpecifications.elementTypes.contains(type)) { throw new IllegalArgumentException("Type should be one of the values specified in" + " \"CPACSpecifications.java\" file, i.e. human, physical, or cyber"+ type); } this.agentID=agentID; this.type=type; agentId++; userName=new Attribute("agentID",null,"categorical"); email=new Attribute("email",null,"categorical"); role=new Attribute("role",null,"categorical"); age=new Attribute("age",new AttributeRange(15.0,85.00),"numeric"); userName.setAttributeValueCategorical(agentID); agentAttributeSet=new HashSet<>(); // agentAttributes=new ArrayList<>(Arrays.asList(new Attribute[]{userName,email,role,age})); agentAttributes=new ArrayList<>(); addAgentAttribute(userName); addAgentAttribute(email); addAgentAttribute(role); addAgentAttribute(age); } @Override public boolean equals(Object obj) { Agent other = (Agent) obj; return other.agentID==this.agentID; } public String getAgentID() { return agentID; } public int getAgentId() { return agentId; } public Attribute getUserName() { return userName; } public Attribute getEmail() { return email; } public Attribute getRole() { return role; } public Attribute getAge() { return age; } public List<Attribute> getAgentAttributes() { return agentAttributes; } public void setUserName(Attribute userName) { this.userName = userName; } public void setEmail(Attribute email) { this.email = email; } public void setRole(Attribute role) { this.role = role; } public void setAge(Attribute age) { this.age = age; } public void addAgentAttribute(Attribute attribute) { agentAttributes.add(attribute); agentAttributeSet.add(attribute); } public boolean hasAttribute(Attribute attribute) { return agentAttributeSet.contains(attribute); } } <file_sep>/src/com/nuray/cpacexecution/ExecutionOfCPAC_MERVersion.java package com.nuray.cpacexecution; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Agent; import com.nuray.cpacexecution.cpacmodel.Attribute; import com.nuray.cpacexecution.enforcementfunctions.*; import com.nuray.cpacexecution.storage.*; import com.nuray.gagm.pathfinder.Edge; import com.nuray.gagm.pathfinder.Vertex; import com.nuray.wso2.Test; import org.wso2.carbon.identity.entitlement.stub.EntitlementAdminServiceStub; import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceEntitlementException; import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceStub; import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceException; import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; import java.rmi.RemoteException; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class ExecutionOfCPAC_MERVersion { private ResourceBase resourceBase; private ActionBase actionBase; private AgentBase agentBase; private PolicyBase policyBase; private SODBase sodBase; AuthorizationDecision authorizationDecision; // WSO2 IS related variables EntitlementPolicyAdminServiceStub EPASadminStub; // RemoteUserStoreManagerServiceStub RUSMSadminStub; public ExecutionOfCPAC_MERVersion(ResourceBase resourceBase, ActionBase actionBase, AgentBase agentBase, PolicyBase policyBase, SODBase sodBase) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException, EntitlementServiceException { this.resourceBase=resourceBase; this.actionBase=actionBase; this.agentBase=agentBase; this.policyBase=policyBase; this.sodBase=sodBase; // publish AC policies to PAP List<Policy> policyList=policyBase.getPolicyList(); authorizationDecision=new AuthorizationDecision(); EPASadminStub = authorizationDecision.getEPASadminStub(); // authorizationDecision.publishPolicies(policyList); // publishPolicies(policyList); //publish SOD policies to PAP here... List<SODPolicy> sodPolicyList = sodBase.getSODPolicyList(); publishSODPolicies(sodPolicyList); } /** * * @param iar * @param varList_v_cur * @param m_cur * @param v_cur */ public List<Agent> executeCPAC(InitialAccessRequest iar, Queue<Map<Vertex,Queue<Map<Edge, VirtualAccessRequest>>>> varList_v_cur, String m_cur, Vertex v_cur, Vertex v_next, VirtualAccessRequest[] vars) throws Exception { // line 1: initialization List<Agent> agentList_v_cur=new ArrayList<>(); List<Agent> agentList_v_next=new ArrayList<>(); // Vertex v_next = null; // line 2: if this is a var generated by GAGM if(varList_v_cur!=null) { // line 3: Extract var for the current and next state from varList_v_cur // VirtualAccessRequest[] vars = extractVars(varList_v_cur,v_cur); VirtualAccessRequest var_v_cur = vars[0]; VirtualAccessRequest var_v_next = vars[1]; // line 4: query eligible agents for var_v_cur and var_v_next from PIP & add List<Attribute> var_v_curAgentAttributes = var_v_cur.getAgentAttributes(); agentList_v_cur= queryEligibleAgents(var_v_curAgentAttributes); if(var_v_next!=null) { List<Attribute> var_v_nextAgentAttributes = var_v_next.getAgentAttributes(); agentList_v_next= queryEligibleAgents(var_v_nextAgentAttributes); // line 5 List<Agent> agentList_intersection = intersectAgentLists(agentList_v_cur, agentList_v_next); if(!agentList_intersection.isEmpty()) { // line 6 agentList_v_cur=agentList_intersection; } } // line 7: Extract perm_var from var_v_cur Permission perm_var=var_v_cur.extractPermission(resourceBase); // line 8: check applicable sod policies to perm_var List<SODPolicyRule> applicableSoDs=checkApplicableSoDPolicies(perm_var); List<Agent> tempListForEligibleAgents=new LinkedList<>(agentList_v_cur); //=> this is to prevent concurrent // modification exception to the agentList_v_cur (below in the inner for loop) if(!applicableSoDs.isEmpty()) // line 9 { for (SODPolicyRule sod:applicableSoDs) // line 10 { Set<SODPolicyRule.MERConstraint> MERSet = sod.getMERSet(); if (MERSet!=null) { for (SODPolicyRule.MERConstraint merConstraint:MERSet) { for (Agent agent:agentList_v_cur) { List<PolicyRule> validPolicyRules=computeValidSetForAgent(merConstraint,agent); if (validPolicyRules.size()>merConstraint.getM()) { if(m_cur.equalsIgnoreCase("emergency")) // line 13 { if(v_next==null) { System.out.println("v_next is null!"); } else if(sod.getRiskOfSoDPolicy()>(Math.abs(v_cur.getRisk()-v_next.getRisk()))) // line 14 { tempListForEligibleAgents.remove(agent); // line 15 } } else { tempListForEligibleAgents.remove(agent); } } } } } } } agentList_v_cur=tempListForEligibleAgents; for (Agent agent:agentList_v_cur) // line 18 { // line 19: Send perm_var to PEP of agn_i (this can be realized by creating a PEP object for each client in the system // and calling a method implemented for token management such as: manageToken(agni,permvar,timestamp). // Please note that this is not in the scope of the paper. } } // line 20: if this an access request submitted by an agent if(iar!=null) { // line 21: extract the requested permission and requesting agent from iar Agent agent = iar.getAgent(); Permission perm_iar = iar.getPermission(); Agent authorizedAgent=null; // line 22: check applicable sod policies to perm_iar List<SODPolicyRule> applicableSoDs=checkApplicableSoDPolicies(perm_iar); if(!applicableSoDs.isEmpty()) // line 23 { for (SODPolicyRule sod:applicableSoDs) // line 24 { Set<SODPolicyRule.MERConstraint> MERSet = sod.getMERSet(); for (SODPolicyRule.MERConstraint merConstraint:MERSet) { List<PolicyRule> validPolicyRules=computeValidSetForAgent(merConstraint,agent); if (validPolicyRules.size()>merConstraint.getM()) { if(m_cur.equalsIgnoreCase("emergency")) // line 13 { if(sod.getRiskOfSoDPolicy()<=(Math.abs(v_cur.getRisk()-v_next.getRisk()))) // line 14 { authorizedAgent = evaluate(iar, m_cur);// line 28 } } } else { authorizedAgent = evaluate(iar, m_cur);// line 28 } } } } else // line 31 { authorizedAgent=evaluate(iar,m_cur); // line 32 } if(authorizedAgent!=null) { agentList_v_cur.add(authorizedAgent); // line 33 } } return agentList_v_cur; // line 34 } private boolean checkMEPSet(Set<SODPolicyRule.MERConstraint> MERSet, List<Agent> agentList_v_cur) { boolean flag=true; for (SODPolicyRule.MERConstraint merConstraint:MERSet) { flag=check_MEP(merConstraint,agentList_v_cur); if (flag==false) { return false; } } return true; } private boolean check_MEP(SODPolicyRule.MERConstraint merConstraint,List<Agent> agentList_v_cur) { for (Agent agent:agentList_v_cur) { List<PolicyRule> validPolicyRules= find_valid_set(merConstraint,agent); if (validPolicyRules.size()>merConstraint.getM()) { return false; } } return true; } private List<PolicyRule> find_valid_set(SODPolicyRule.MERConstraint merConstraint, Agent agent) { Set<PolicyRule> merConstraintPolicyRules = merConstraint.getPolicyRules(); List<PolicyRule> validPolicyRules = merConstraintPolicyRules .stream() .filter(policyRule -> policyRule.getRuleEffect().equalsIgnoreCase("permit")) .filter(policyRule -> policyRule.getAgentAttributes().values() .stream() .flatMap(agentAttributeGroup -> agentAttributeGroup.stream() .flatMap(agentAttribute -> agentAttribute.keySet().stream())) .allMatch(policyRuleAttribute -> agent.hasAttribute(policyRuleAttribute))).collect(Collectors.toList()); return validPolicyRules; } public VirtualAccessRequest[] extractVars(Queue<Map<Vertex,Queue<Map<Edge, VirtualAccessRequest>>>> varList_v_cur, Vertex startVertex) throws Exception { // line 3: Extract var for the current and next state from varList_v_cur VirtualAccessRequest var_v_cur = null; VirtualAccessRequest var_v_next = null; if(!varList_v_cur.isEmpty()&&varList_v_cur!=null) { Iterator<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>> varList_v_iterator = varList_v_cur.iterator(); while(varList_v_iterator.hasNext()) { Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>> vertexQueueMap = varList_v_iterator.next(); Vertex finalState = vertexQueueMap.keySet().iterator().next(); Queue<Map<Edge, VirtualAccessRequest>> varList_f = vertexQueueMap.get(finalState); Iterator<Map<Edge, VirtualAccessRequest>> edgeMapIterator = varList_f.iterator(); while (edgeMapIterator.hasNext()) { Map<Edge, VirtualAccessRequest> edgeVarMap = edgeMapIterator.next(); //check if there is an edge from v_cur. If so, it is safe to find v_next and call executeCPAC(). // otherwise, there is no need to call executeCPAC() since there will be no var_v_cur Edge nextEdge = edgeVarMap.keySet().iterator().next();// => there is only one mapping btw an edge and a var if(nextEdge.getSourceVertex().equals(startVertex)) { var_v_cur=nextEdge.getVar(); Vertex v_next = findVarNextOnShortestPath(startVertex, varList_v_cur); if(edgeMapIterator.hasNext()) { edgeVarMap=edgeMapIterator.next(); nextEdge = edgeVarMap.keySet().iterator().next(); if (v_next!=null&&nextEdge.getSourceVertex().equals(v_next)) { var_v_next=nextEdge.getVar(); } } } } } } VirtualAccessRequest[] vars=new VirtualAccessRequest[2]; vars[0]=var_v_cur; vars[1]=var_v_next; return vars; } public Vertex findVarNextOnShortestPath(Vertex v_cur,Queue<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>> varList_v_cur) throws Exception { Vertex v_next=null; if(varList_v_cur!=null&&varList_v_cur.size()!=0) { Iterator<Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>>> iterator = varList_v_cur.iterator(); while (iterator.hasNext()) { Map<Vertex, Queue<Map<Edge, VirtualAccessRequest>>> vertexQueueMap = iterator.next(); Iterator<Vertex> finalStateIterator = vertexQueueMap.keySet().iterator(); while (finalStateIterator.hasNext()) { Vertex finalState = finalStateIterator.next(); Queue<Map<Edge, VirtualAccessRequest>> varList_f = vertexQueueMap.get(finalState); Iterator<Map<Edge, VirtualAccessRequest>> edgeMapIterator = varList_f.iterator(); while (edgeMapIterator.hasNext()) { Map<Edge, VirtualAccessRequest> edgeVarMap = edgeMapIterator.next(); //check if there is an edge from v_cur. If so, it is safe to find v_next and call executeCPAC(). // otherwise, there is no need to call executeCPAC() since there will be no var_v_cur Edge nextEdge = edgeVarMap.keySet().iterator().next();// => there is only one mapping btw an edge and a var if(nextEdge.getSourceVertex().equals(v_cur)) { List<Edge> edges = v_cur.getEdges(); for (Edge e:edges) { if(e.getTargetVertex().equals(nextEdge.getTargetVertex())) { if (edgeMapIterator.hasNext()) { edgeVarMap=edgeMapIterator.next(); nextEdge=edgeVarMap.keySet().iterator().next(); if(nextEdge.getSourceVertex().equals(e.getTargetVertex())) { v_next=nextEdge.getSourceVertex(); } else { v_next=e.getTargetVertex(); } } else { v_next=e.getTargetVertex(); } } } } } } } } return v_next; } private List<Agent> queryEligibleAgents(List<Attribute> attributes) throws Exception { Date date=new Date(); List<Agent> existingEligibleAgents=new ArrayList<>(); for (Attribute attribute:attributes) { List<Agent> agentsWithAttributeValue = agentBase.getAgentsWithAttributeValue(attribute); if(existingEligibleAgents.size()==0) { existingEligibleAgents.addAll(agentsWithAttributeValue); } else { existingEligibleAgents =intersectAgentLists(existingEligibleAgents,agentsWithAttributeValue); } } Date date2=new Date(); // System.out.println("Time for queryEligibleAgents() is: "+(date2.getTime()-date.getTime())); return existingEligibleAgents; } private List<Agent> intersectAgentLists(List<Agent> agentList1, List<Agent> agentList2) { Date date=new Date(); List<Agent> intersection = new LinkedList<>(); for(Agent agent : agentList1) { if(agentList2.contains(agent)) { if (!intersection.contains(agent)) { intersection.add(agent); } } } Date date2=new Date(); // System.out.println("Time for intersectAgentLists() is: "+(date2.getTime()-date.getTime())); return intersection; } /** * To compute valid set (of permissions) for an agent, first find the policy rules that are applicable to the given agent and have * "permit" type of rule effect. * @param agent * @throws Exception */ private List<PolicyRule> computeValidSetForAgent(SODPolicyRule.MERConstraint merConstraint, Agent agent) throws Exception { Set<PolicyRule> merConstraintPolicyRules = merConstraint.getPolicyRules(); // List<PolicyRule> policyRulesWithPermit = merConstraintPolicyRules // .stream() // .filter(policyRule -> policyRule.getRuleEffect().equalsIgnoreCase("permit")) // .collect(Collectors.toList()); // // List<PolicyRule> validPolicyRules = policyRulesWithPermit // .stream() // .filter(policyRule -> // policyRule.getAgentAttributes().values() // .stream() // .flatMap(agentAttributeGroup -> // agentAttributeGroup.stream() // .flatMap(agentAttribute -> agentAttribute.keySet().stream())) // .allMatch(policyRuleAttribute -> agent.hasAttribute(policyRuleAttribute))).collect(Collectors.toList()); List<PolicyRule> validPolicyRules = merConstraintPolicyRules .stream() .filter(policyRule -> policyRule.getRuleEffect().equalsIgnoreCase("permit")) .filter(policyRule -> policyRule.getAgentAttributes().values() .stream() .flatMap(agentAttributeGroup -> agentAttributeGroup.stream() .flatMap(agentAttribute -> agentAttribute.keySet().stream())) .allMatch(policyRuleAttribute -> agent.hasAttribute(policyRuleAttribute))).collect(Collectors.toList()); return validPolicyRules; } private List<SODPolicyRule> checkApplicableSoDPolicies(Permission permission) { Date date=new Date(); List<SODPolicyRule> applicableSODPolicyRules=new ArrayList<>(); List<SODPolicy> sodPolicyList = sodBase.getSODPolicyList(); for (SODPolicy sodPolicy:sodPolicyList) { List<SODPolicyRule> sodPolicyRules = sodPolicy.getSodPolicyRules(); for (SODPolicyRule rule:sodPolicyRules) { List<Permission> Perm=rule.getPerm(); for (Permission p:Perm) { if(p.getResource().equals(permission.getResource())) { List<Action> actionListInRequestedPerm = permission.getActionList(); for (Action action:actionListInRequestedPerm) { if(p.getActionList().contains(action)) { if(!applicableSODPolicyRules.contains(rule)) { applicableSODPolicyRules.add(rule); } } } } } // if (Perm.contains(permission)) // { // applicableSODPolicyRules.add(rule); // } } } Date date2=new Date(); // System.out.println("Time for checkApplicableSoDPolicies() is: "+(date2.getTime()-date.getTime())); return applicableSODPolicyRules; } private List<Permission> intersectPermissionLists(List<Permission> permissionList1, List<Permission> permissionList2) { Date date=new Date(); List<Permission> intersection = new LinkedList<>(); for(Permission perm1 : permissionList1) { for (Permission perm2:permissionList2) { if(perm1.getResource().equals(perm2.getResource())) { List<Action> perm1ActionList = perm1.getActionList(); boolean allActionsIncluded=true; for (Action action:perm1ActionList) { if(!perm2.getActionList().contains(action)) { allActionsIncluded=false; // intersection.add(perm1); } } if(allActionsIncluded) { if(!intersection.contains(perm1)) { intersection.add(perm1); } } } } } Date date2=new Date(); // System.out.println("Time for intersectPermissionLists() is: "+(date2.getTime()-date.getTime())); return intersection; } private Agent evaluate(InitialAccessRequest iar, String m_cur) throws Exception { // line 36: Extend iar with registered attributes in PIP AgentInitiatedAccessRequest aar=new AgentInitiatedAccessRequest(iar,m_cur,resourceBase,actionBase,agentBase); // line 37: Get policy set from PAP ==> this is done by WSO2 IS entitlement stub (ESadminStub) (inside auth method of my // AuthorizationDecision.java class // line 38 String decisionXML = authorizationDecision.auth(aar); String decision=authorizationDecision.parseDecision(decisionXML); if(decision.equalsIgnoreCase("Permit")) // line 39 { // line 38: Send perm_iar to PEP of agn (this can be realized by creating a PEP object for each client in the system // and calling a method implemented for token management such as: manageToken(agn,perm_iar,timestamp). // Please note that this is not in the scope of the paper. return iar.getAgent(); // line 41 } return null; // line 42 } // private void publishPolicies(List<Policy> policyList) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { // //publish these policies to the PAP // for (Policy policy:policyList) // { // PolicyDTO policyToPublish = new PolicyDTO(); // policyToPublish.setPolicyId(policy.getPolicyID()); // policyToPublish.setPolicy(policy.getPolicyContentXACML()); // policyToPublish.setActive(true); // policyToPublish.setPromote(true); // // authorizationDecision.getEPASadminStub().addPolicy(policyToPublish); // //// EPASadminStub.addPolicy(policyToPublish); // } // } private void publishSODPolicies(List<SODPolicy> sodPolicyList) { // TODO: to be implemented later if needed (for publishing SOD policies to WSO2 identity server, for now it is not needed) } public AuthorizationDecision getAuthorizationDecision() { return authorizationDecision; } } <file_sep>/src/com/nuray/cpacexecution/enforcementfunctions/AgentInitiatedAccessRequest.java package com.nuray.cpacexecution.enforcementfunctions; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Agent; import com.nuray.cpacexecution.cpacmodel.Attribute; import com.nuray.cpacexecution.cpacmodel.Resource; import com.nuray.cpacexecution.storage.ActionBase; import com.nuray.cpacexecution.storage.AgentBase; import com.nuray.cpacexecution.storage.ResourceBase; import java.util.List; public class AgentInitiatedAccessRequest extends Request { private Agent agent; private InitialAccessRequest iar; public AgentInitiatedAccessRequest(InitialAccessRequest iar, String operationalMode, ResourceBase resourceBase, ActionBase actionBase, AgentBase agentBase) throws Exception { super(operationalMode); this.iar=iar; this.permission=iar.getPermission(); this.agent=iar.getAgent(); enhanceIAR(resourceBase,actionBase,agentBase); requestContentXACML=constructXACMLRequest(); } public InitialAccessRequest getIar() { return iar; } /** * This function enhances an IAR (initial access request submitted by agent to the AC system) * to an AAR (agent-initiated requested, which is a well-defined access request, enriched with * attributes of the agent, resource, action_ID etc.) * @param resourceBase * @param actionBase * @param agentBase * @throws Exception */ public void enhanceIAR(ResourceBase resourceBase, ActionBase actionBase, AgentBase agentBase) throws Exception { Resource resource = permission.getResource(); Resource resourceMatched = resourceBase.getResource(resource); if(resourceMatched!=null) { resourceAttributes = resourceMatched.getResourceAttributes(); } List<Action> actionList=permission.getActionList(); for (Action action:actionList) { Action actionMatched= actionBase.getAction(action); if(actionMatched==null) { throw new Exception("There is no such action defined, so it cannot be requested: "+action); } List<Attribute> actionAttList=actionMatched.getActionAttributes(); actionAttributes.put(actionMatched,actionAttList); } Agent agentMatched = agentBase.getAgent(this.agent); if(agentMatched!=null) { agentAttributes = agentMatched.getAgentAttributes(); } } } <file_sep>/src/com/nuray/cpacexecution/enforcementfunctions/XACMLSpecifications.java package com.nuray.cpacexecution.enforcementfunctions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class XACMLSpecifications { /* NOTE: following functions, rule combining algorithms etc. are given in XACML specification here: http://docs.oasis-open.org/xacml/3.0/xacml-3.0-core-spec-os-en.html#_Toc325047239 */ public static final String[] STRING_MATCH_FUNCTIONS_ARRAY =new String[]{"urn:oasis:names:tc:xacml:1.0:function:string-equal", "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case", "urn:oasis:names:tc:xacml:3.0:function:string-contains", "urn:oasis:names:tc:xacml:3.0:function:string-starts-with", "urn:oasis:names:tc:xacml:3.0:function:string-ends-with"}; public static final List<String> STRING_MATCH_FUNCTIONS = new ArrayList<>(Arrays.asList(STRING_MATCH_FUNCTIONS_ARRAY)); public static final String[] DOUBLE_MATCH_FUNCTIONS_ARRAY =new String[]{"urn:oasis:names:tc:xacml:1.0:function:double-equal", "urn:oasis:names:tc:xacml:1.0:function:double-greater-than", "urn:oasis:names:tc:xacml:1.0:function:double-greater-than-or-equal", "urn:oasis:names:tc:xacml:1.0:function:double-less-than", "urn:oasis:names:tc:xacml:1.0:function:double-less-than-or-equal"}; public static final List<String> DOUBLE_MATCH_FUNCTIONS = new ArrayList<>(Arrays.asList(DOUBLE_MATCH_FUNCTIONS_ARRAY)); public static final String[] DATE_MATCH_FUNCTIONS_ARRAY =new String[]{"urn:oasis:names:tc:xacml:1.0:function:date-equal", "urn:oasis:names:tc:xacml:1.0:function:date-greater-than", "urn:oasis:names:tc:xacml:1.0:function:date-greater-than-or-equal", "urn:oasis:names:tc:xacml:1.0:function:date-less-than", "urn:oasis:names:tc:xacml:1.0:function:date-less-than-or-equal"}; public static final List<String> DATE_MATCH_FUNCTIONS = new ArrayList<>(Arrays.asList(DATE_MATCH_FUNCTIONS_ARRAY)); public static final String[] TIME_MATCH_FUNCTIONS_ARRAY =new String[]{"urn:oasis:names:tc:xacml:1.0:function:time-equal", "urn:oasis:names:tc:xacml:1.0:function:time-greater-than", "urn:oasis:names:tc:xacml:1.0:function:time-greater-than-or-equal", "urn:oasis:names:tc:xacml:1.0:function:time-less-than", "urn:oasis:names:tc:xacml:1.0:function:time-less-than-or-equal", "urn:oasis:names:tc:xacml:2.0:function:time-in-range"}; public static final List<String> TIME_MATCH_FUNCTIONS = new ArrayList<>(Arrays.asList(TIME_MATCH_FUNCTIONS_ARRAY)); public static final String[] RULE_COMBINIG_ALGORITHMS_ARRAY= new String[]{ "urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides", "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides", "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:deny-unless-permit", "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-unless-deny"}; public static final List<String> RULE_COMBINIG_ALGORITHMS=new ArrayList<>(Arrays.asList(RULE_COMBINIG_ALGORITHMS_ARRAY)); } <file_sep>/src/com/nuray/cpacexecution/storage/SODBase.java package com.nuray.cpacexecution.storage; import com.nuray.cpacexecution.enforcementfunctions.SODPolicy; import com.nuray.cpacexecution.enforcementfunctions.SODPolicyRule; import java.util.ArrayList; import java.util.List; public class SODBase { private List<SODPolicy> sodPolicies; public SODBase() { sodPolicies=new ArrayList<>(); } public void addSODPolicy(SODPolicy sodPolicy) { sodPolicies.add(sodPolicy); } public void deleteSODPolicy(SODPolicy sodPolicy) throws Exception { if(sodPolicies.contains(sodPolicy)) { sodPolicies.remove(sodPolicy); } else { throw new Exception("SoD policy cannot be removed since it is not in the list!"); } } public SODPolicy getSODPolicy(SODPolicy sodPolicy) { if (sodPolicies.contains(sodPolicy)) { return sodPolicy; } return null; } public List<SODPolicy> getSODPolicyList() { return sodPolicies; } } <file_sep>/src/com/nuray/gagm/experiment/Random.java package com.nuray.gagm.experiment; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Attribute; import com.nuray.cpacexecution.cpacmodel.AttributeRange; import com.nuray.cpacexecution.enforcementfunctions.VirtualAccessRequest; import com.nuray.cpacexecution.storage.ActionBase; import java.util.*; /** * Created by TOSHIBA on 1/2/2017. */ public class Random { private int upperLimit, lowerLimit; // private double fraction; // for the fraction of critical edges in a graph private int agentAttValueCounter; // for generating random attribute values private int resourceAttValueCounter; // for generating random attribute values private int actionAttValueCounter; // for generating random attribute values private int resourceCounter; // for generating random resources into resourceBase private int agentCounter; // for generating random agents into agentBase public Random() { } public Random(int lowerLimit, int upperLimit) { this.lowerLimit = lowerLimit; this.upperLimit = upperLimit; agentAttValueCounter=0; resourceAttValueCounter=0; actionAttValueCounter=0; } public int generateRandomWeight() { return (int)(Math.random()*((upperLimit-lowerLimit)+1)) + lowerLimit; } public int generateRandomIndex() { return lowerLimit+(int)(Math.random()*((upperLimit-lowerLimit)+1)); // return (int)(Math.random()*((upperLimit-lowerLimit)+1)); } public double doubleRandomInclusive(double max, double min) { double r = Math.random(); if (r < 0.5) { return ((1 - Math.random()) * (max - min) + min); } return (Math.random() * (max - min) + min); } public String generateRandomEdgeType(double fraction) { // if randomly generated boolean value is true, assign the edge "critical" type, otherwise assign "action" type return getRandomBooleanWithFraction(fraction)==true? "critical" : "action"; } /** * * @param fraction: for the fraction of critical edges in a graph * @return */ private boolean getRandomBooleanWithFraction(double fraction) { // fraction==> this is the % time that a "true" value is generated. e.g. if it is 0.5, the // values generated by Math.random() method will be less than 0.5 50% of the time. return Math.random() < fraction; } public boolean getRandomBoolean() { int randNum= (int) Math.round(Math.random()); if(randNum==1) { return true; } else { return false; } } public VirtualAccessRequest generateRandomVar(ActionBase actionBase, String operationalMode) throws Exception { // generate agent attributes List<Attribute> agentAttList=new LinkedList<Attribute>(); Attribute userName=new Attribute("agentID",null,"categorical"); Attribute email=new Attribute("email",null,"categorical"); Attribute role=new Attribute("role",null,"categorical"); Attribute age=new Attribute("age",new AttributeRange(15.0,85.00),"numeric"); agentAttList.addAll(Arrays.asList(new Attribute[]{userName,email,role,age})); // userName.setAttributeValueCategorical("agent"); boolean attExistenceFlag=false; for(int i=0; i<agentAttList.size();i++) { attExistenceFlag=getRandomBoolean(); if (attExistenceFlag==true) { Attribute attribute = agentAttList.get(i); agentAttValueCounter++; if(attribute.getAttributeType().equalsIgnoreCase("categorical")) { attribute.setAttributeValueCategorical("value"+agentAttValueCounter); } if(attribute.getAttributeType().equalsIgnoreCase("numeric")) { Random random = new Random(0, 100); attribute.setAttributeValueNumeric(Math.random()*((upperLimit-lowerLimit)+1)); } } } // generate resource attributes List<Attribute> resourceAttList=new LinkedList<Attribute>(); Attribute resourceName=new Attribute("resourceID",null,"categorical"); resourceAttList.addAll(Arrays.asList(new Attribute[]{resourceName})); resourceAttValueCounter++; resourceAttList.get(0).setAttributeValueCategorical("value"+resourceAttValueCounter); // generate action & action attributes (here I assume a single action) List<Attribute> actionAttList=new LinkedList<Attribute>(); Attribute actionName=new Attribute("actionID",null,"categorical"); actionAttList.addAll(Arrays.asList(new Attribute[]{actionName})); actionAttValueCounter++; Attribute actionAtt=actionAttList.get(0); actionAtt.setAttributeValueCategorical("value"+actionAttValueCounter); Map<Action,List<Attribute>> actionToAttMap=new HashMap<>(); //generate a random action type (from these options: human, cyber, physical) String actionType=generateActionType(); Action action=new Action(actionAtt.getAttributeValueCategorical(),actionType); actionBase.addAction(action); actionToAttMap.put(action,actionAttList); // generate var VirtualAccessRequest virtualAccessRequest=new VirtualAccessRequest(agentAttList,resourceAttList,actionToAttMap,operationalMode); return virtualAccessRequest; } /** * * @param nAgentAtt : number of agent attributes to generate synthetically, note that these are not real attributes defined * in "Agent" class in "CPACExecution" module. * @param nResAtt : number of resource attributes to generate synthetically, note that these are not real attributes defined * * in "Agent" class in "CPACExecution" module. * @param nActionAtt : number of action attributes to generate synthetically, note that these are not real attributes defined * * in "Agent" class in "CPACExecution" module. * @param actionBase * @param operationalMode * @return */ public VirtualAccessRequest generateRandomVar(int nAgentAtt, int nResAtt, int nActionAtt, int nActions, ActionBase actionBase, String operationalMode) throws Exception { // generate agent attributes List<Attribute> agentAttList=generateAttributes(nAgentAtt); // generate resource attributes List<Attribute> resourceAttList=generateAttributes(nResAtt); //generate action attributes Map<Action,List<Attribute>> actionToAttMap=generateActionsAndActionAttributes(nActionAtt,nActions,actionBase); VirtualAccessRequest virtualAccessRequest=new VirtualAccessRequest(agentAttList,resourceAttList,actionToAttMap,operationalMode); return virtualAccessRequest; } private Map<Action,List<Attribute>> generateActionsAndActionAttributes(int nAttributes, int nActions, ActionBase actionBase) throws Exception { Map<Action,List<Attribute>> actionToAttMap=new HashMap<>(); for(int i=0;i<nActions;i++) { // generate action attributes List<Attribute> attList=generateAttributes(nAttributes); //generate a random action type (from these options: object-oriented or cyber-physical) String actionType=generateActionType(); Action action=new Action("action"+(i+1),actionType); actionBase.addAction(action); actionToAttMap.put(action,attList); } return actionToAttMap; } // private List<Attribute> generateAttsForVar(int nAttributes) throws Exception // { // // generate resource attributes // List<Attribute> attList=new LinkedList<Attribute>(); // // for(int i=0; i<nAttributes; i++) // { // Attribute attribute=new Attribute("attribute"+(i+1),null,"categorical"); // attribute.setAttributeValueCategorical("value"+(i+1)); // attList.add(attribute); // } // return attList; // } public List<Attribute> generateAttributes(int nAttributes) throws Exception { Attribute attribute=null; Random random=new Random(); List<Attribute> attributes=new LinkedList<>(); for(int i=0;i<nAttributes;i++) { boolean isCategoricalAttribute = random.getRandomBoolean(); if (isCategoricalAttribute) { // generate 5 possible string attribute values String[] values = new String[5]; for (int j = 0; j < 5; j++) { values[j] = "value" + (j + 1); } List<String> possibleValues = new ArrayList<>(Arrays.asList(values)); AttributeRange attributeRange = new AttributeRange(possibleValues); attribute = new Attribute("attributeName" + (i + 1), attributeRange, "categorical"); // // assign an attribute value to the attribute randomly from randomly generated attribute range values // Random random2 = new Random(1, 5); // int index = random2.generateRandomIndex(); // String value = values[index - 1]; // attribute.setAttributeValueCategorical(value); } else { attribute = new Attribute("attributeName" + (i + 1), new AttributeRange(150, 200), "numeric"); // attribute.setAttributeValueNumeric(attribute.getAttributeRange().getLowerLimit() + 1); } attribute=generateAttributeValue(attribute); attributes.add(attribute); } return attributes; } public Attribute generateAttributeValue(Attribute attribute) throws Exception { // Attribute attributeToReturn=null; String attributeType = attribute.getAttributeType(); boolean isCategorical=attributeType.equalsIgnoreCase("categorical")?true:false; if(isCategorical) { // assign an attribute value to the attribute randomly from randomly generated attribute range values AttributeRange attributeRange = attribute.getAttributeRange(); List<String> possibleValues = attributeRange.getPossibleValues(); Random random = new Random(1, possibleValues.size()); int index = random.generateRandomIndex(); String value = possibleValues.get(index-1); // attributeToReturn=new Attribute(attribute.getAttributeName(),attributeRange,attributeType); // attributeToReturn.setAttributeValueCategorical(value); attribute.setAttributeValueCategorical(value); } else { AttributeRange attributeRange = attribute.getAttributeRange(); double lowerLimit = attributeRange.getLowerLimit(); double upperLimit = attributeRange.getUpperLimit(); Random random=new Random(); double value=random.doubleRandomInclusive(lowerLimit,upperLimit); // double value=lowerLimit+Math.random()*((upperLimit-lowerLimit)+1); // value=(attributeRange.getUpperLimit()+attributeRange.getLowerLimit())/2; // attributeToReturn=new Attribute(attribute.getAttributeName(),attributeRange,attributeType); // attributeToReturn.setAttributeValueNumeric(value); attribute.setAttributeValueNumeric(value); } // return attributeToReturn; return attribute; } public String generateActionType() { //generate a random action type (from these options: "object-oriented" or"cyber-physical) return getRandomBoolean() ? "object-oriented":"cyber-physical"; // return actionType; } public String generateResourceOrAgentType(Random random) { int index = random.generateRandomIndex(); String type=""; if(index==1) { type="human"; } else if (index==2) { type="cyber"; } else { type="physical"; } return type; } } <file_sep>/src/com/nuray/cpacexecution/enforcementfunctions/VirtualAccessRequest.java package com.nuray.cpacexecution.enforcementfunctions; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Attribute; import com.nuray.cpacexecution.cpacmodel.Resource; import com.nuray.cpacexecution.storage.ActionBase; import com.nuray.cpacexecution.storage.ResourceBase; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; public class VirtualAccessRequest extends Request { private final static String RESOURCE_LINE="<Attributes Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\">"; private final static String ACTION_LINE="<Attributes Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:action\">"; public VirtualAccessRequest(List<Attribute> agentAtts, List<Attribute> resourceAtts, Map<Action,List<Attribute>> actionAtts, String operationalMode) throws Exception { super(operationalMode); this.agentAttributes=agentAtts; this.resourceAttributes=resourceAtts; this.actionAttributes=actionAtts; } public Permission getPermission(ResourceBase resourceBase, ActionBase actionBase) { this.permission=extractPermissionFromRequestXACML(getRequestContentXACML(),resourceBase,actionBase); return permission; } public Permission extractPermissionFromRequestXACML(String requestContentXACML, ResourceBase resourceBase, ActionBase actionBase) { String resourceID=null; List<Action> actionList=new ArrayList<>(); Scanner sc=new Scanner(requestContentXACML); while (sc.hasNext()) { String line=sc.next(); String attributeIDString="AttributeId"; String resourceIDString="resource-id"; String actionIDString="action-id"; if(line.equalsIgnoreCase(RESOURCE_LINE)) { line=sc.next(); //check if the next line is a resource-id attribute if ((line.indexOf(attributeIDString)!=-1) && (line.indexOf(resourceIDString)!=-1)) { line=sc.next(); int endIndexOfResourceID=line.indexOf("</AttributeValue>"); int startIndexOfResourceID=line.indexOf(">")+1; resourceID=line.substring(startIndexOfResourceID,endIndexOfResourceID); } } if(line.equalsIgnoreCase(ACTION_LINE)) { line=sc.next(); //check if the next line is an action-id attribute if( (line.indexOf(attributeIDString)!=-1) && (line.indexOf(actionIDString)!=-1) ) { int endIndexOfActionID=line.indexOf("</AttributeValue>"); int startIndexOfActionID=line.indexOf(">")+1; String actionID=line.substring(startIndexOfActionID,endIndexOfActionID); Action actionMatched = actionBase.getActionWithActionID(actionID); actionList.add(actionMatched); } } } //retrieve the permission from the PermissionBase Resource resourceMatched = resourceBase.getResourceWithResourceID(resourceID); return new Permission(resourceMatched,actionList); } } <file_sep>/src/com/nuray/cpacexecution/storage/ActionBase.java package com.nuray.cpacexecution.storage; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Attribute; import java.util.*; import java.util.stream.Collectors; public class ActionBase { private List<Action> actionList; Map<String, Action> actionMap; public ActionBase() { actionList=new ArrayList<>(); actionMap=new HashMap<>(); } public void addAction(Action action) { actionList.add(action); actionMap.put(action.getActionID(),action); } public void deleteAction(Action action) throws Exception { if(actionList.contains(action)) { actionList.remove(action); actionMap.remove(action.getActionID()); } else { throw new Exception("Action cannot be removed since it is not in the list!"); } } public Action getAction(Action action) { if (actionList.contains(action)) { return action; } return null; } public Action getActionWithActionID(String actionID) { return actionMap.get(actionID); } public List<Action> getActionList() { return actionList; } public List<Action> getActionsWithAttributeValue(Attribute attribute) throws Exception { List<Action> result=new LinkedList<>(); Iterator<Action> actionIterator = actionList.iterator(); if(attribute.isValueSet()) { return actionMap.values() .stream() .filter(action -> action.hasAttribute(attribute)) .collect(Collectors.toList()); } // while (actionIterator.hasNext()) // { // Action action = actionIterator.next(); // // List<Attribute> actionAttributes=action.getActionAttributes(); // // for (Attribute actionAtt:actionAttributes) // { // if(actionAtt.getAttributeName().equalsIgnoreCase(attribute.getAttributeName())) // { // if(actionAtt.isValueSet()) // { // if(actionAtt.getAttributeType().equalsIgnoreCase("categorical")) // { // if(actionAtt.getAttributeValueCategorical().equalsIgnoreCase(attribute.getAttributeValueCategorical())) // { // result.add(action); // } // } // if(actionAtt.getAttributeType().equalsIgnoreCase("numeric")) // { // if(actionAtt.getAttributeValueNumeric()==attribute.getAttributeValueNumeric()) // { // result.add(action); // } // } // } // } // } // } return result; } } <file_sep>/src/com/nuray/cpacexecution/cpacmodel/Attribute.java package com.nuray.cpacexecution.cpacmodel; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalTime; import java.util.Date; public class Attribute { private String attributeType; private String dataType; private String attributeName; private AttributeRange attributeRange; // this is only for numeric attributes private double attributeValueNumeric; private String attributeValueCategorical; private Date attributeValDate; private LocalTime attributeValTime; private boolean valueIsSet; /** * * @param attributeName * @param attributeRange: this is only for numeric attributes such as age, it should be null otherwise * @param attributeType: Type should be one of the values specified in "CPACSpecifications.java" file, i.e. numeric, categorical, * date, or time. * Date: a date attribute should be in the following format: dd/mm/yyyy * Time: a time attribute should be in the following format: HH:MM:SS */ public Attribute(String attributeName, AttributeRange attributeRange, String attributeType) { if(!CPACSpecifications.attributeTypes.contains(attributeType)) { throw new IllegalArgumentException("Type should be one of the values specified in" + " \"CPACSpecifications.java\" file, i.e. numeric, categorical, date, or time: "+ attributeType); } if(attributeType.equalsIgnoreCase("categorical")) { dataType="http://www.w3.org/2001/XMLSchema#string"; } else if(attributeType.equalsIgnoreCase("numeric")) { if(attributeRange==null) { throw new IllegalArgumentException("An attribute range should be defined for numeric attributes"); } dataType="http://www.w3.org/2001/XMLSchema#double"; } else if(attributeType.equalsIgnoreCase("date")) { dataType="http://www.w3.org/2001/XMLSchema#date"; } else if(attributeType.equalsIgnoreCase("time")) { dataType="http://www.w3.org/2001/XMLSchema#time"; } this.attributeName=attributeName; this.attributeRange=attributeRange; this.attributeType =attributeType; } @Override public boolean equals(Object obj) { Attribute another= (Attribute) obj; return another.attributeName==this.attributeName; } @Override public int hashCode() { if(attributeValueCategorical!=null) { return 13*attributeName.hashCode()*attributeType.hashCode()*attributeValueCategorical.hashCode(); } else { return 13*attributeName.hashCode()*attributeType.hashCode()*Double.hashCode(attributeValueNumeric); } } public String getAttributeName() { return this.attributeName; } public AttributeRange getAttributeRange() { return attributeRange; } public String getDataType() { return dataType; } public double getAttributeValueNumeric() throws Exception { if(!isValueSet()) { throw new Exception("set attribute value first!"); } return attributeValueNumeric; } public double safeGetAttributeValueNumeric() { try { return getAttributeValueNumeric(); } catch (Exception ex) { throw new RuntimeException(ex); } } public String getAttributeValueCategorical() throws Exception { if ((!isValueSet())) { throw new Exception("set attribute value first!"); } return attributeValueCategorical; } public String safeGetAttributeValueCategorical() { try { return getAttributeValueCategorical(); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(),ex); } } public Date getAttributeValDate() { return attributeValDate; } public LocalTime getAttributeValTime() { return attributeValTime; } public void setAttributeValueNumeric(double attributeValue) throws Exception { if(attributeValue<attributeRange.getLowerLimit() ||attributeValue>attributeRange.getUpperLimit()) { String errorMessage="Attribute value is out of the range."; throw new Exception(errorMessage); } else { this.attributeValueNumeric = attributeValue; valueIsSet=true; } } public void setAttributeValueCategorical(String attributeValue) throws Exception { if(attributeRange!=null) // => note that attribute range may be null for categorical attributes { if(!attributeRange.getPossibleValues().contains(attributeValue)) { throw new Exception("Attribute value is out of the range."); } this.attributeValueCategorical=attributeValue; valueIsSet=true; } else { this.attributeValueCategorical=attributeValue; valueIsSet=true; } } public void setAttributeValDate(String attributeValDate) throws ParseException { this.attributeValDate=new SimpleDateFormat("dd/MM/yyyy").parse(attributeValDate); valueIsSet=true; } /** * * @param attributeValTime should be in the following format: HH:MM:SS */ public void setAttributeValTime(String attributeValTime) { this.attributeValTime=LocalTime.parse(attributeValTime); } public boolean isValueSet() { return valueIsSet; } public String getAttributeType() { return attributeType; } } <file_sep>/src/com/nuray/cpacexecution/cpacmodel/Resource.java package com.nuray.cpacexecution.cpacmodel; import java.util.*; public class Resource { private List<Attribute> resourceAttributes; private Set<Attribute> resourceAttributeSet; /* note that 'resourceId' is not the same as 'resource_id' attribute. 'resourceId' is an int that is simply used to identify the count of attribute whereas 'resource_id' is a string that is used to describe the resource itself (machine1, file2 etc.) */ private int resourceId; private String resourceID; private String type; private Attribute resourceName; /** * * @param resourceID: This basically represents the name of the resource. An example for a cyber resource * is a URL such as: "http://127.0.0.1/service/very_secure/" * @param type: This corresponds to the type of resource. Valid options are: "human", "physical", and "cyber". * * (see CPACSpecifications.java) */ public Resource(String resourceID, String type) throws Exception { if(!CPACSpecifications.elementTypes.contains(type)) { throw new IllegalArgumentException("Type should be one of the values specified in" + " \"CPACSpecifications.java\" file, i.e. human, physical, or cyber"+ type); } this.resourceID=resourceID; this.type=type; resourceId++; resourceName=new Attribute("resourceID",null,"categorical"); resourceName.setAttributeValueCategorical(resourceID); resourceAttributeSet=new HashSet<>(); // resourceAttributes=new ArrayList<>(Arrays.asList(new Attribute[]{resourceName})); resourceAttributes=new ArrayList<>(); addResourceAttribute(resourceName); } @Override public boolean equals(Object obj) { Resource other = (Resource) obj; return other.resourceID.equalsIgnoreCase(this.resourceID); } public String getResourceID() { return resourceID; } public int getResourceId() { return resourceId; } public String getType() { return type; } public Attribute getResourceName() { return resourceName; } public List<Attribute> getResourceAttributes() { return resourceAttributes; } public void setResourceName(Attribute resourceName) { this.resourceName = resourceName; } public void addResourceAttribute(Attribute attribute) { resourceAttributes.add(attribute); resourceAttributeSet.add(attribute); } public boolean hasAttribute(Attribute attribute) { return resourceAttributeSet.contains(attribute); } } <file_sep>/src/com/nuray/cpacexecution/enforcementfunctions/Request.java package com.nuray.cpacexecution.enforcementfunctions; import com.nuray.cpacexecution.cpacmodel.Action; import com.nuray.cpacexecution.cpacmodel.Attribute; import com.nuray.cpacexecution.cpacmodel.Resource; import com.nuray.cpacexecution.storage.ResourceBase; import java.time.LocalTime; import java.util.*; public abstract class Request { protected int requestId; protected String requestContentXACML; protected Permission permission; protected String operationalMode; List<Attribute> resourceAttributes; List<Attribute> agentAttributes; Map<Action,List<Attribute>> actionAttributes; //note that there may be multiple actions, so this is a map from an action to its attributes public Request() throws Exception { resourceAttributes=new ArrayList<>(); agentAttributes=new ArrayList<>(); actionAttributes=new HashMap<>(); requestId++; // requestContentXACML=constructXACMLRequest(); } public Request(String operationalMode) throws Exception { this(); this.operationalMode=operationalMode; } @Override public boolean equals(Object obj) { Request other = (Request) obj; return other.requestId==this.requestId; } public List<Attribute> getAgentAttributes() { return agentAttributes; } public List<Attribute> getResourceAttributes() { return resourceAttributes; } public Map<Action, List<Attribute>> getActionAttributes() { return actionAttributes; } public Permission getPermission() { return this.permission; } public void setPermission(ResourceBase resourceBase) throws Exception { Permission permission = extractPermission(resourceBase); this.permission= permission; } public String getOperationalMode() { return operationalMode; } public int getRequestId() { return requestId; } public Permission extractPermission(ResourceBase resourceBase) throws Exception { Resource resource=null; List<Action> actionsInPermission=new ArrayList<>(); for (Attribute attribute:resourceAttributes) { if(attribute.getAttributeName()=="resourceID") { resource = resourceBase.getResourceWithResourceID(attribute.getAttributeValueCategorical()); } } Iterator<Action> iterator = actionAttributes.keySet().iterator(); while (iterator.hasNext()) { Action action=iterator.next(); actionsInPermission.add(action); } Permission permission=new Permission(resource,actionsInPermission); this.permission=permission; return permission; } public String getRequestContentXACML() { return requestContentXACML; } /** * This function is used to construct an XACML request from an AAR (Agent-initated Access Request). * To use this method, "enhanceIAR()" method should be used first in order to enhance a given * IAR (initial access request) and obtained an AAR. * * @return the constructed XACML request from the AAR * @throws Exception */ public String constructXACMLRequest() throws Exception { //request start line String startLine="<Request CombinedDecision=\"false\" ReturnPolicyIdList=\"false\" xmlns=\"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\">"; String subjectLines=constructSubjectPartOfRequest(); String resourceLines=constructResourcePartOfRequest(); String actionLines=constructActionPartOfRequest(); return startLine+"\n"+subjectLines+"\n"+resourceLines+"\n"+actionLines+"\n</Request>"; } private String constructSubjectPartOfRequest() throws Exception { String subjectXACML=" <Attributes Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:subject\">\n" ; String agentAttributeBlock = constructAttributes(agentAttributes,false,true,false); subjectXACML=subjectXACML+agentAttributeBlock; subjectXACML= subjectXACML + " </Attributes>"; return subjectXACML; } private String constructResourcePartOfRequest() throws Exception { String resourceXACML=" <Attributes Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\">\n"; String resourceAttributeBlock = constructAttributes(resourceAttributes,true,false,false); resourceXACML=resourceXACML+resourceAttributeBlock; resourceXACML= resourceXACML + " </Attributes>"; return resourceXACML; } private String constructActionPartOfRequest() throws Exception { String actionXACML=" <Attributes Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:action\">\n"; Set<Action> actionSet = actionAttributes.keySet(); Iterator<Action> actionIterator = actionSet.iterator(); String actionAttributeBlock =""; while (actionIterator.hasNext()) { Action nextAction = actionIterator.next(); List<Attribute> nextActionAttributes = nextAction.getActionAttributes(); actionAttributeBlock = constructAttributes(nextActionAttributes,false,false,true); actionXACML=actionXACML+actionAttributeBlock; } actionXACML= actionXACML + " </Attributes>"; return actionXACML; } /** * This is a helper method used in "constructSubjectPartOfRequest", "constructResourcePartOfRequest", and * "constructActionPartOfRequest" methods to eliminate repetitive code. Basically, it constructs an "attribute block" * as follows: * * <Attribute AttributeId="http://sample/ATTRIBUTE1" IncludeInResult="false"> * <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">abc</AttributeValue> * </Attribute> * * @param attribute * @return */ private String constructAttributeBlock(Attribute attribute, boolean isResourceAtt, boolean isSubjectAtt, boolean isActionAtt) throws Exception { String attributeBlock=""; if(!attribute.isValueSet()==false) { String attributeName=attribute.getAttributeName();; String attributeType=attribute.getAttributeType(); String dataType=attribute.getDataType(); if(isResourceAtt) { attributeBlock= " <Attribute AttributeId=\"" +attributeName+"\" IncludeInResult=\"false\">\n"; } else if(isSubjectAtt) { attributeBlock= " <Attribute AttributeId=\""+attributeName+"\" IncludeInResult=\"false\">\n"; } else if (isActionAtt) { attributeBlock= " <Attribute AttributeId=\""+attributeName+"\" IncludeInResult=\"false\">\n"; } else { throw new IllegalArgumentException("Attribute can be either resource attribute, " + "subject attribute, or action attribute"); } attributeBlock= attributeBlock + " <AttributeValue DataType=\""+dataType+"\">"; if(attributeType.equalsIgnoreCase("categorical")) { String attributeValueCategorical = attribute.getAttributeValueCategorical(); attributeBlock=attributeBlock+attributeValueCategorical; } else if(attributeType.equalsIgnoreCase("numeric")) { double attributeValueNumeric = attribute.getAttributeValueNumeric(); attributeBlock=attributeBlock+attributeValueNumeric; } else if(attributeType.equalsIgnoreCase("date")) { Date attributeValDate = attribute.getAttributeValDate(); attributeBlock=attributeBlock+attributeValDate; } else if(attributeType.equalsIgnoreCase("time")) { LocalTime attributeValTime = attribute.getAttributeValTime(); attributeBlock = attributeBlock+attributeValTime; } attributeBlock=attributeBlock+"</AttributeValue>\n" + " </Attribute>\n"; } return attributeBlock; } /** * This method constructs multiple blocks of attributes in XACML format for a given category. * For example, if a list of resource attributes is given as parameter to the method, it constructs * resource block of an XACML request with multiple resource attributes. * @param attributeList * @return */ private String constructAttributes(List<Attribute> attributeList, boolean isResourceAtt, boolean isSubjectAtt, boolean isActionAtt) throws Exception { String XACMLblock=""; for (Attribute attribute:attributeList) { String attributeBlock = constructAttributeBlock(attribute,isResourceAtt,isSubjectAtt,isActionAtt); XACMLblock= XACMLblock+attributeBlock; } return XACMLblock; } }
a9bb9c320e0e4c06c0a766394cb2032bbc7b7bbe
[ "Markdown", "Java" ]
22
Markdown
nbaltaci/cpac_extension
6869ceda756cf901981e6003ecbe98412289882c
832de80c2c30e5e817483237c00593ed23a94737
refs/heads/master
<repo_name>Ashanen/PopularMovies<file_sep>/app/src/main/java/com/example/android/popularmovies1/Database/FavouriteMoviesRepository.java package com.example.android.popularmovies1.Database; import android.app.Application; import android.arch.lifecycle.LiveData; import android.os.AsyncTask; import java.util.List; /** * A Repository is a class that abstracts access to multiple data sources. * The Repository is not part of the Architecture Components libraries, * but is a suggested best practice for code separation and architecture. * A Repository class handles data operations. * It provides a clean API to the rest of the app for app data. */ public class FavouriteMoviesRepository { private FavouritiesDao mFavouritiesDao; private LiveData<List<FavouriteMovie>> mFavouriteListLiveData; public FavouriteMoviesRepository(Application application) { FavouriteMoviesRoomDatabase db = FavouriteMoviesRoomDatabase.getDatabase(application); mFavouritiesDao = db.favouritiesDao(); mFavouriteListLiveData = mFavouritiesDao.getAllFavourites(); } public LiveData<List<FavouriteMovie>> getAllFavourites() { return mFavouriteListLiveData; } public void insert(FavouriteMovie favouriteMovie) { new insertAsyncTask(mFavouritiesDao).execute(favouriteMovie); } public void deleteMovieByTitle(String title) { new deleteAsyncTask(mFavouritiesDao).execute(title); } public void deleteMovieById(Integer id) { new deleteAsyncTaskById(mFavouritiesDao).execute(id); } public LiveData<FavouriteMovie> getMovieById(int id) { new getMovieByIdAsync(mFavouritiesDao).execute(id); return null; } public LiveData<FavouriteMovie> getMovieByTitle(String title) { // new getMovieByTitleAsync(mFavouritiesDao).execute(title); return mFavouritiesDao.getMovieByTitle(title); } public static class insertAsyncTask extends AsyncTask<FavouriteMovie, Void, Void> { private FavouritiesDao mAsyncTaskDao; insertAsyncTask(FavouritiesDao dao) { mAsyncTaskDao = dao; } @Override protected Void doInBackground(final FavouriteMovie... favouriteMovies) { mAsyncTaskDao.insert(favouriteMovies[0]); return null; } } public static class deleteAsyncTask extends AsyncTask<String, Void, Void> { private FavouritiesDao mAsyncTaskDao; deleteAsyncTask(FavouritiesDao dao) { mAsyncTaskDao = dao; } @Override protected Void doInBackground(final String... title) { mAsyncTaskDao.deleteMovieByTitle(title[0]); return null; } } public static class deleteAsyncTaskById extends AsyncTask<Integer, Void, Void> { private FavouritiesDao mAsyncTaskDao; deleteAsyncTaskById(FavouritiesDao dao) { mAsyncTaskDao = dao; } @Override protected Void doInBackground(final Integer... id) { mAsyncTaskDao.deleteMovieById(id[0]); return null; } } public static class getMovieByIdAsync extends AsyncTask<Integer, Void, Void> { private FavouritiesDao mAsyncTaskDao; getMovieByIdAsync(FavouritiesDao dao) { mAsyncTaskDao = dao; } @Override protected Void doInBackground(final Integer... id) { mAsyncTaskDao.getMovieById(id[0]); return null; } } public static class getMovieByTitleAsync extends AsyncTask<FavouriteMovie, Void, Void> { private FavouritiesDao mAsyncTaskDao; getMovieByTitleAsync(FavouritiesDao dao) { mAsyncTaskDao = dao; } @Override protected Void doInBackground(final FavouriteMovie... movie) { // mAsyncTaskDao.getMovieByTitle(movie[0]); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); } } } <file_sep>/app/src/main/java/com/example/android/popularmovies1/Models/TrailerResponse.java package com.example.android.popularmovies1.Models; import com.google.gson.annotations.SerializedName; import java.util.List; public class TrailerResponse { @SerializedName("results") private final List<Trailer> results; public TrailerResponse(List<Trailer> results) { this.results = results; } public List<Trailer> getListOfTrailers() { return results; } } <file_sep>/app/src/main/java/com/example/android/popularmovies1/MainActivity.java package com.example.android.popularmovies1; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import com.example.android.popularmovies1.APIcontroler.APIclient; import com.example.android.popularmovies1.APIcontroler.IAPIforRetrofit; import com.example.android.popularmovies1.Adapters.FavouritesAdapter; import com.example.android.popularmovies1.Adapters.MovieAdapter; import com.example.android.popularmovies1.Database.FavouriteMovie; import com.example.android.popularmovies1.Fragments.FavouritesFragment; import com.example.android.popularmovies1.Fragments.PopularMoviesFragment; import com.example.android.popularmovies1.Fragments.TopRatedMoviesFragment; import com.example.android.popularmovies1.Fragments.UpcomingMoviesFragment; import com.example.android.popularmovies1.Models.DatabaseJSONresponse; import com.example.android.popularmovies1.Models.FavouriteMoviesViewModel; import com.example.android.popularmovies1.Models.Movies; import com.example.android.popularmovies1.Utils.ConstantValues; import com.example.android.popularmovies1.Utils.NetworkConnectivity; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.example.android.popularmovies1.Utils.ConstantValues.API_KEY; public class MainActivity extends AppCompatActivity { public RecyclerView recyclerView; private List<FavouriteMovie> favouriteMoviesNewList; private List<Movies> movieList = new ArrayList<>(); private Fragment selectedFragment; private FavouritesAdapter moviesAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FavouriteMoviesViewModel favouriteMoviesViewModel = ViewModelProviders.of(this).get(FavouriteMoviesViewModel.class); favouriteMoviesViewModel.getmAllFavourites().observe(this, new Observer<List<FavouriteMovie>>() { @Override public void onChanged(@Nullable List<FavouriteMovie> favouriteMovies) { favouriteMoviesNewList = favouriteMovies; if(selectedFragment instanceof FavouritesFragment){ openFavourites(); } } }); init(); } public void getPopularMovies(String preferred) { if (!NetworkConnectivity.isInternetWorking(getApplicationContext())) { Toast.makeText(this, getString(R.string.no_internet), Toast.LENGTH_LONG).show(); } else { try { if (ConstantValues.API_KEY.isEmpty()) { Toast.makeText(this, getString(R.string.provide_api_key), Toast.LENGTH_LONG).show(); } else { IAPIforRetrofit apiInterface = APIclient.getApiClient().create(IAPIforRetrofit.class); Call<DatabaseJSONresponse> moviesResult = null; if (preferred.equals(getString(R.string.most_popular_key))) { moviesResult = apiInterface.getPopularMovies(API_KEY); } else if (preferred.equals(getString(R.string.top_rated_key))) { moviesResult = apiInterface.getTopRatedMovies(API_KEY); } else if (preferred.equals(getString(R.string.upcoming_key))) { moviesResult = apiInterface.getUpcomingMovies(API_KEY); } if (moviesResult != null) { moviesResult.enqueue(new Callback<DatabaseJSONresponse>() { @Override public void onResponse(@NonNull Call<DatabaseJSONresponse> call, @NonNull Response<DatabaseJSONresponse> response) { List<Movies> movies = response.body().getResults(); recyclerView.setAdapter(new MovieAdapter(movies, getApplicationContext())); } @Override public void onFailure(Call<DatabaseJSONresponse> call, Throwable throwable) { throwable.printStackTrace(); } }); } } } catch (Exception exception) { exception.printStackTrace(); } } } private void openFavourites() { recyclerView = findViewById(R.id.recyclerView); moviesAdapter = new FavouritesAdapter(this, favouriteMoviesNewList); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(moviesAdapter); moviesAdapter.notifyDataSetChanged(); } private void init() { recyclerView = findViewById(R.id.recyclerView); MovieAdapter moviesAdapter = new MovieAdapter(movieList, this); gridLayoutManagement(); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(moviesAdapter); moviesAdapter.notifyDataSetChanged(); getPopularMovies(getString(R.string.most_popular_key)); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu, menu); return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } private void gridLayoutManagement(){ if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { recyclerView.setLayoutManager(new GridLayoutManager(this, 3)); } else { recyclerView.setLayoutManager(new GridLayoutManager(this, 3)); } } @Override public boolean onOptionsItemSelected(MenuItem item) { selectedFragment = null; int movie_sort_type_id = item.getItemId(); switch (movie_sort_type_id) { case R.id.menu_sort_top_rated: selectedFragment = TopRatedMoviesFragment.newInstance(); getPopularMovies(getString(R.string.top_rated_key)); break; case R.id.menu_sort_popularity: selectedFragment = PopularMoviesFragment.newInstance(); getPopularMovies(getString(R.string.most_popular_key)); break; case R.id.menu_sort_upcoming: selectedFragment = UpcomingMoviesFragment.newInstance(); getPopularMovies(getString(R.string.upcoming_key)); break; case R.id.menu_sort_fav: selectedFragment = FavouritesFragment.newInstance(); openFavourites(); break; } if (selectedFragment != null) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.frame_layout_for_movie, selectedFragment); fragmentTransaction.commit(); } return true; } } <file_sep>/app/src/main/java/com/example/android/popularmovies1/Utils/ConstantValues.java package com.example.android.popularmovies1.Utils; /** * Created by <NAME> on 10,April,2018 */ public class ConstantValues { public static final String API_KEY = ""; public static final String ORIGINAL_TITLE = "original_title"; public static final String OVERVIEW = "overview"; public static final String VOTE_AVERAGE = "vote_average"; public static final String RELEASE_DATE = "release_date"; public static final String POSTER_PATH = "poster_path"; public static final String BACKDROP_PATH = "backdrop_path"; public static final String MOVIES_KEY = "movies_key"; public static final String BASE_URL = "http://api.themoviedb.org/3/"; public static final String MOVIE_POSTER_PATH = "https://image.tmdb.org/t/p/w500"; public static final String MOVIE_BACKDROP_IMAGE_PATH = "https://image.tmdb.org/t/p/w500"; public static final String POPULAR = "movie/popular?api_key="; public static final String TOP_RATED = "movie/top_rated?api_key="; public static final String UPCOMING = "movie/upcoming?api_key="; public static final String TRAILERS = "movie/{movie_id}/videos"; public static final String REVIEWS = "movie/{movie_id}/reviews"; } <file_sep>/app/src/main/java/com/example/android/popularmovies1/APIcontroler/IAPIforRetrofit.java package com.example.android.popularmovies1.APIcontroler; import com.example.android.popularmovies1.Models.DatabaseJSONresponse; import com.example.android.popularmovies1.Models.ReviewsResponse; import com.example.android.popularmovies1.Models.TrailerResponse; import com.example.android.popularmovies1.Utils.ConstantValues; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface IAPIforRetrofit { /** The @GET annotation declares that this request uses the HTTP GET method. */ @GET(ConstantValues.TOP_RATED) Call<DatabaseJSONresponse> getTopRatedMovies(@Query("api_key") String apiKey); @GET(ConstantValues.POPULAR) Call<DatabaseJSONresponse> getPopularMovies(@Query("api_key") String apiKey); @GET(ConstantValues.UPCOMING) Call<DatabaseJSONresponse> getUpcomingMovies(@Query("api_key") String apiKey); @GET(ConstantValues.TRAILERS) Call<TrailerResponse> getListOfTrailers(@Path("movie_id") int id, @Query("api_key") String apiKey); @GET(ConstantValues.REVIEWS) Call<ReviewsResponse> getListOfReviews(@Path("movie_id") int id, @Query("api_key") String apiKey); } <file_sep>/README.md # Introducing PopularMovies app <img src="https://i.imgflip.com/2deluz.gif" title="made at imgflip.com"/></a> The PopularMovies Android app was made as part of Udacity's Android Developer Nanodegree Program. It displays the Most Popular, Upcoming and Top Rated Movies from The Movie Database (TMDb). User has the ability to save favourite movies locally and view them offline. Also can view movie details (rating, release date, duration, etc.), watch trailers, read reviews. # Libraries : Retrofit Picasso Room ViewModel # How to make it work at your device : The app fetches movie information using The Movie Database (TMDb) API. You have to enter your own API key into String/Constant Values class. API_KEY="Your Api Key" If you don’t already have an account, you will need to create one in order to request an API Key at https://www.themoviedb.org/documentation/api ![device-2018-07-04-185453](https://user-images.githubusercontent.com/30993768/42289566-92d54cd0-7fc0-11e8-8f44-021f8d255c66.png)
ea53f3b804bdaff59ef80779c7058fd925713440
[ "Markdown", "Java" ]
6
Java
Ashanen/PopularMovies
d790a5f68afc76fdacd01a25f7f6b6fbe71482ec
d674a009ed39348711462bed88b78246e72ca0d3
refs/heads/master
<repo_name>aconstlink/tool_prototypes<file_sep>/worldomat/game/world/block.cpp #include "block.h" using namespace prototype ; //******************************************************** block::block( void_t ) { } //******************************************************** block::block( material_id_t mid ) { _mid = mid ; } //******************************************************** block::block( this_cref_t rhv ) { _mid = rhv._mid ; } //******************************************************** block::block( this_rref_t rhv ) { _mid = std::move( rhv._mid ) ; } //******************************************************** block::~block( void_t ) { } //******************************************************** block::this_ptr_t block::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_memory::global_t::alloc( std::move( rhv ), p ) ; } //******************************************************** block::this_ptr_t block::destroy( this_ptr_t ptr ) { so_memory::global_t::dealloc( ptr ) ; return nullptr ; } //******************************************************** block::this_ref_t block::operator = ( this_cref_t rhv ) { _mid = rhv._mid ; return *this ; } //******************************************************** block::this_ref_t block::operator = ( this_rref_t rhv ) { _mid = std::move( rhv._mid ) ; return *this ; } //******************************************************** material_id block::get_material( void_t ) const { return _mid ; }<file_sep>/worldomat/app/app_tool.cpp #include "app.h" #include "../game/world/world.h" #include "../game/world/block.h" #include <snakeoil/log/global.h> using namespace prototype ; //******************************************** class my_app::tool_event_listener : public prototype::tool_t::event_listener { so_this_typedefs( tool_event_listener ) ; private: my_app_ptr_t _owner ; public: tool_event_listener( my_app * owner ) : _owner( owner ) { } tool_event_listener( this_rref_t rhv ) { so_move_member_ptr( _owner, rhv ) ; } virtual void_t on_material( prototype::tool_t::material_action ma ) { so_log::global_t::status( "Material: " "Chunk( " + std::to_string( ma.chunk.x() ) + " ; " + std::to_string( ma.chunk.y() ) + " ) " "Block( " + std::to_string( ma.block.x() ) + " ; " + std::to_string( ma.block.y() ) + " )") ; so_math::vec2ui_t const dif = ma.cb.block_dif() ; auto const dd = _owner->get_dims_data() ; so_math::vec2ui_t start = ma.cb.block_min() ; for( uint_t x=0; x<dif.x()+1; ++x ) { for( uint_t y=0; y<dif.y()+1; ++y ) { auto const cur_ij = start + so_math::vec2ui_t( x, y ) ; so_math::vec2ui_t chunk_ij ; so_math::vec2ui_t block_ij ; dd.global_to_local( cur_ij, chunk_ij, block_ij ) ; _owner->_game->get_world()->add_block( ma.layer, chunk_ij, block_ij, prototype::block_t( ma.material_id ) ) ; } } // access application //_owner -> //for( ma.cb.) prototype::world_ptr_t wrl = _owner->_game->get_world() ; //wrl->add_block } }; //******************************************** void_t my_app::set_tool_event_listener( void_t ) { _tevl_ptr = so_memory::global_t::alloc( my_app::tool_event_listener(this), "][ : tool_event_listener" ) ; }<file_sep>/worldomat/game/game.cpp #include "game.h" #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/gpx/system/render_system.h> using namespace prototype ; //********************************************************** game::game( so_gpx::render_system_ptr_t rs ) { _rs = rs ; } //********************************************************** game::game( this_rref_t rhv ) { so_move_member_ptr( _rs, rhv ) ; so_move_member_ptr( _world, rhv ) ; } //********************************************************** game::~game( void_t ) { world_t::destroy( _world ) ; } //********************************************************** game::this_ptr_t game::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_memory::global_t::alloc( std::move(rhv), p ) ; } //********************************************************** void_t game::destroy( this_ptr_t ptr ) { so_memory::global_t::dealloc( ptr ) ; } //********************************************************** void_t game::init( dims_data_cref_t dd ) { _world = prototype::world_t::create( prototype::world_t( dd ), "[game] : world" ) ; } //********************************************************** void_t game::deinit( void_t ) { _world = world_t::destroy( _world ) ; } //********************************************************** void_t game::render( render_info_in_t rin ) { prototype::world_t::render_info_t wri ; wri.rnd = rin.rnd ; wri.cam_pos = rin.cam_pos ; wri.dd = rin.dd ; wri.view_area_radius = rin.view_area_radius ; _world->render( wri ) ; } //********************************************************** void_t game::update( void_t ) { } //********************************************************** world_ptr_t game::get_world( void_t ) { return _world ; } //**********************************************************<file_sep>/worldomat/game/material/material_id.h #pragma once #include "../typedefs.h" #include <snakeoil/core/types.hpp> #include <snakeoil/core/macros/typedef.h> namespace prototype { class material_id { so_this_typedefs( material_id ) ; public: size_t _id = size_t( -1 ) ; public: material_id( void_t ) {} material_id( size_t const id ) { _id = id ; } material_id( this_cref_t rhv ) { _id = rhv._id ; } ~material_id( void_t ) {} public: size_t get_id( void_t ) const { return _id ; } bool_t is_valid( void_t ) const { return _id != size_t( -1 ) ; } }; so_typedef( material_id ) ; }<file_sep>/worldomat/game/material/material.h #pragma once #include "../typedefs.h" #include <snakeoil/core/types.hpp> #include <snakeoil/core/macros/typedef.h> namespace prototype { class material { so_this_typedefs( material ) ; }; so_typedef( material ) ; }<file_sep>/worldomat/main.cpp #include "main.h" #include "app/app.h" #include <snakeoil/appx/application/appx_application.h> #include <snakeoil/appx/system/iwindow_state_informer.h> #include <snakeoil/imex/global.h> #include <snakeoil/device/global.h> #include <snakeoil/io/global.h> #include <snakeoil/thread/global.h> #include <snakeoil/memory/global.h> int main( int argc, char ** argv ) { { so_appx::appx_application_t application ; { so_app::gl_info_t gli ; { gli.version.major = 3 ; gli.version.minor = 3 ; gli.vsync_enabled = true ; } so_app::window_info_t wi ; { wi.x = 1920 / 8 ; wi.y = 1080 / 8; wi.w = 1920 * 3 / 4 ; wi.h = 1080 *3 / 4 ; wi.window_name = "Spritomat" ; wi.fullscreen = false ; wi.show_cursor = true ; } application.create_window( gli, wi ) ; } application.register_app( prototype::my_app::create() ) ; application.exec() ; } so_imex::global::deinit() ; so_device::global::deinit() ; so_thread::global::deinit() ; so_io::global::deinit() ; so_memory::global::dump_to_std() ; return 0 ; } <file_sep>/spritomat/app/app_render.cpp #include "app.h" #include <snakeoil/degui/system/system.h> #include <snakeoil/flow/walker/serial_node_walker.h> #include <snakeoil/gfx/text/text_render_2d.h> #include <snakeoil/gfx/line/line_render_2d.h> #include <snakeoil/gfx/image/image_render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> #include <snakeoil/gfx/plugs/post_process/predef_post.h> #include <snakeoil/gfx/plugs/framebuffer/predef_framebuffer.h> #include <snakeoil/gfx/sprite/sprite_manager.h> #include <snakeoil/device/devices/mouse/three_button_mouse.h> #include <snakeoil/device/component/keys/ascii_key.h> #include <snakeoil/collide/2d/bounds/aabb.hpp> #include <snakeoil/log/logger/store_logger.h> #include <snakeoil/log/global.h> #include <snakeoil/collide/2d/bounds/aabb.hpp> #include <snakeoil/animation/keyframe_sequence/linear_keyframe_sequence.hpp> #include <snakeoil/math/vector/vector2b.hpp> #include <snakeoil/math/utility/fn.hpp> #include <snakeoil/math/utility/3d/orthographic_projection.hpp> #include <random> using namespace examples ; //************************************************************************* so_appx::result my_app::on_render( so_appx::render_data_cref_t rd ) { this_t::render_begin( rd ) ; // draw mouse pos { _rect_rnd_ptr->draw_rect( 0, _cur_mouse_pos, so_math::vec2f_t( 0.5f, 0.5f ), so_math::vec2f_t( 5.0f ), 0.0f, so_math::vec4f_t( 1.0f ) ) ; } if( _selected_list_item != uint_t(-1) && _list_items[ _selected_list_item ].rects.size() != 0 ) { auto const key = _list_items[ _selected_list_item ].key ; so_gfx::sprite_manager_t::sprite_datas_t sds ; { //auto const res = _sp_mgr_ptr->get_sequence( key, sd ) ; //if( so_core::is_not( res ) ) { so_gfx::sprite_manager_t::sprite_infos_t sis ; for( auto const & item : _list_items[ _selected_list_item ].rects ) { if( so_core::is_not( item.valid ) ) continue ; so_gfx::sprite_manager_t::sprite_info_t si ; si.rect = item.rect ; si.rect.z( si.rect.z() + 1 ) ; si.rect.y( si.rect.y() - 0 ) ; si.rect.w( si.rect.w() + 1 ) ; si.pivot = item.pivot * so_math::vec2f_t( item.end.x()-item.beg.x(), item.end.y()-item.beg.y() ) ; si.duration = item.duration ; sis.push_back( si ) ; } _sp_mgr_ptr->set_sequence( _images[ 0 ].img_ptr, key, sis ) ; } } auto const res = _sp_mgr_ptr->get_sequence( key, sds ) ; // false can happen if all valid checkboxes are off if( res ) { typedef so_ani::linear_keyframe_sequence< size_t > image_kfs_t ; image_kfs_t ikfs ; uint_t max_duration = 0 ; for( size_t i = 0; i < sds.size(); ++i ) { uint_t const dur = sds[ i ].duration ; ikfs.insert( image_kfs_t::keyframe_t( i * dur, i ) ) ; max_duration += dur ; } ikfs.insert( image_kfs_t::keyframe_t( max_duration, sds.size() ) ) ; { static size_t time = 0 ; time += size_t( rd.dts * 1000.0 ) ; if( time >= max_duration ) time = 0 ; size_t i ; if( ikfs( time, i ) == so_ani::evaluation_result::in_range ) { _image_rnd_ptr->draw_image( 10, sds[ i ].img_id, false, so_math::vec2f_t( -600.0f, 0.0f ), sds[ i ].pivot, so_math::vec2f_t( 1.0f, -1.0f ) * sds[ i ].scale*10.0f, 0.0f, so_math::vec4f_t( 1.0f ) ) ; } else if( sds.size() == 1 ) { _image_rnd_ptr->draw_image( 10, sds[ 0 ].img_id, false, so_math::vec2f_t( -600.0f, 0.0f ), sds[ 0 ].pivot, so_math::vec2f_t( 1.0f, -1.0f ) * sds[ 0 ].scale*10.0f, 0.0f, so_math::vec4f_t( 1.0f ) ) ; } else { int const bp = 0 ; } } } //_image_rnd_ptr->set_view_projection( 10, so_math::mat4f_t().identity(), // so_math::so_3d::orthographic<float_t>::create( 1920.0f, 1080.0f, 0.1f, 1000.0f ) ) ; } this_t::render_end( rd ) ; return so_appx::result::ok ; } //************************************************************************* void_t my_app::render_begin( so_appx::render_data_cref_t rd ) { if( _show_imgui ) { _imguis->begin_draw( rd.dts, _vp_window_ptr->get_data().get_width(), _vp_window_ptr->get_data().get_height(), _vp_window_ptr->get_data().get_width(), _vp_window_ptr->get_data().get_height() ); } { so_gfx::text_render_2d_t::canvas_info_t ci ; ci.vp = _vp_window_ptr->get_data() ; _text_rnd_ptr->set_canvas_info( ci ) ; } // update time { auto dur = clock_t::now() - _tp ; size_t const dt = std::chrono::duration_cast< std::chrono::microseconds >( dur ).count() ; _tp = clock_t::now() ; accum += dt ; } // update parameters for rendering { so_flow::serial_node_walker_t snw ; snw.walk( { &_vn } ) ; } // begin on screen stuff rendering { _gfxp_fb->schedule_for_begin() ; _gfxp_fb->schedule_for_clear() ; } } //************************************************************************* void_t my_app::render_end( so_appx::render_data_cref_t rd ) { { _line_rnd_ptr->prepare_for_rendering() ; _text_rnd_ptr->prepare_for_rendering() ; _rect_rnd_ptr->prepare_for_rendering() ; _image_rnd_ptr->prepare_for_rendering() ; } // render everything for( size_t i = 0; i < 100; ++i ) { _image_rnd_ptr->render( i ) ; _text_rnd_ptr->render( i ) ; _rect_rnd_ptr->render( i ) ; _line_rnd_ptr->render( i ) ; } { _gfxp_blit->set_dest_rect( _vp_window_ptr->get_data() ) ; _gfxp_blit->schedule() ; } if( _show_imgui ) { this_t::draw_imgui( rd ) ; // render all _imguis->render( 0 ) ; } } //************************************************************************* void_t my_app::draw_imgui( so_appx::render_data_cref_t rd ) { _imguis->draw( [=] ( ImGuiContext * ctx, so_imgui::system_ptr_t self ) { ImGui::SetCurrentContext( ctx ) ; if( ImGui::BeginMainMenuBar() ) { if( ImGui::BeginMenu( "File" ) ) { if( ImGui::MenuItem( "Save", "CTRL+S" ) ) { this_t::save_to_file() ; } ImGui::EndMenu() ; } if( ImGui::BeginMenu( "Options" ) ) { if( ImGui::MenuItem( "Show ImGui Demo", "", &_show_imgui_demo ) ) { } ImGui::EndMenu() ; } ImGui::EndMainMenuBar() ; } if( _show_imgui_demo ) { ImGui::ShowDemoWindow() ; } // render logger { auto * logger = so_log::global_t::get_store() ; auto const a = logger->get_max_items() ; auto const b = logger->get_num_items() ; ImGui::Begin( "Log Window" ); ImGui::BeginChild( "Console Scrollarea" ) ; so_std::vector< so_log::store_logger::store_data > data ; ImGuiListClipper clip( ( int_t ) b ); while( clip.Step() ) { //for( int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++ ) logger->for_each( size_t( clip.DisplayStart ), size_t( clip.DisplayEnd ), [&] ( so_log::store_logger_t::store_data_cref_t d ) { ImVec4 col = ImGui::GetStyleColorVec4( ImGuiCol_Text ); if( d.ll == so_log::log_level::error ) col = ImColor( 1.0f, 0.4f, 0.4f, 1.0f ) ; else if( d.ll == so_log::log_level::warning ) col = ImColor( 1.0f, 1.0f, 0.4f, 1.0f ) ; else if( d.ll == so_log::log_level::status ) col = ImColor( 0.1f, 1.0f, 0.1f, 1.0f ) ; ImGui::PushStyleColor( ImGuiCol_Text, col ); ImGui::TextUnformatted( d.msg.c_str() ); ImGui::PopStyleColor(); } ) ; } ImGui::EndChild(); ImGui::End() ; } { ImGui::Begin( "Reload Techniques" ); //if( ImGui::Button( "Reload gfx post" ) ) { // _gfxp_blit->schedule_for_reload() ; } ImGui::End() ; } // change input params { ImGuiIO & io = ImGui::GetIO(); _image_area_params.zoom_changed = false ; if( std::abs( io.MouseWheel ) > 0.0001f ) { _image_area_params.zoom_level = size_t( so_math::fn<int_t>::clamp( int_t( _image_area_params.zoom_level ) + int_t( io.MouseWheel ), 0, 20 ) ) ; _image_area_params.zoom_changed = true ; } if( io.KeyCtrl && ImGui::IsMouseClicked( 1 ) ) { _image_area_params.pixel = _image_area_params.cur_pixel ; } } // layout { ImGui::Begin( "Editor" ); this_t::draw_left_side( _image_area_params ) ; this_t::draw_right_side( _image_area_params ) ; // right side ImGui::End() ; } #if 0 { ImGuiIO & io = ImGui::GetIO(); ImGui::Begin( "Some values" ); //ImGui::SetWindowSize( so_math::vec2f_t( 200.0f, 200.0f) ) ; so_math::vec2f_t const v1 = ImGui::GetWindowPos() ; so_math::vec2f_t const v2 = so_math::vec2f_t(ImGui::GetCursorScreenPos()) - so_math::vec2f_t( io.MousePos ) ; so_math::vec2f_t v3 = ImGui::GetCursorScreenPos() ; ImGui::Text("Window Pos: (%.2f, %.2f)", v1.x(), v1.y() ); ImGui::Text("Cursor Pos: (%.2f, %.2f)", v3.x(), v3.y() ); v3 = ImGui::GetCursorScreenPos() ; ImGui::Text("Mouse Screen Pos: (%.2f, %.2f)", v2.x(), -v2.y() ); ImGui::Text("Cursor Pos: (%.2f, %.2f)", v3.x(), v3.y() ); { so_math::vec2f_t const v = ImGui::GetContentRegionAvail() ; ImGui::Text("GetContentRegionAvail: (%.2f, %.2f)", v.x(), v.y() ); } { so_math::vec2f_t const v = ImGui::GetWindowSize() ; ImGui::Text( "GetWindowSize: (%.2f, %.2f)", v.x(), v.y() ); } ImGui::End() ; } #endif } ) ; } //************************************************************************* void_t my_app::draw_left_side( image_area_params_cref_t ) { ImGui::BeginGroup() ; so_math::vec2f_t const avail_fac( 0.7f, 1.0f ) ; // image area { so_math::vec2f_t const avail = ImGui::GetContentRegionAvail() ; so_math::vec2f_t const wh ( avail.x() * avail_fac.x(), avail.y() * avail_fac.y() ) ; ImGui::BeginChild( "Image", wh, false, ImGuiWindowFlags_NoMove ) ; // dont change the order here! { this_t::calc_width_height( _image_area_params ) ; this_t::calc_pixels( _image_area_params ) ; this_t::calc_image_dim( _image_area_params ) ; // background color behind the image { ImVec2 const pos = ImGui::GetCursorScreenPos(); so_math::vec2f_t const area_a( pos.x, pos.y ) ; so_math::vec2f_t const area_b = area_a + wh ; ImGui::GetWindowDrawList()->AddRectFilled( area_a, area_b, IM_COL32( 100, 100, 100, 255 ) ); } this_t::draw_imgui_editor_image( _image_area_params ) ; this_t::draw_cur_mouse_rect_and_track_drag( _image_area_params ) ; this_t::handle_animation_rects( _image_area_params ) ; this_t::handle_pivot_point( _image_area_params ) ; } ImGui::EndChild() ; } // bottom area { //this_t::draw_imgui_bottom_area( rd ) ; } // bottom area #if 0 { so_math::vec2f_t avail = ImGui::GetContentRegionAvail() ; so_math::vec2f_t const wh ( avail.x()* avail_fac.x(), avail.y() ) ; ImVec2 const area_begin = ImGui::GetCursorPos() ; { ImVec2 const pos = ImGui::GetCursorScreenPos(); ImGui::GetWindowDrawList()->AddRectFilled( ImVec2( pos.x, pos.y ), ImVec2( pos.x + wh.x(), pos.y + wh.y() ), IM_COL32( 255, 0, 0, 255 ) ); ImGui::Text( "Cursor Screen Pos: (%.2f, %.2f)", pos.x, pos.y ) ; ImGui::Text( "Begin of Area: (%.2f, %.2f)", area_begin.x, area_begin.y ) ; } ImGui::Dummy( wh - so_math::vec2f_t( 0.0f, ImGui::GetCursorPos().y - area_begin.y ) ) ; } #endif ImGui::EndGroup() ; ImGui::SameLine() ; } //************************************************************************* void_t my_app::draw_right_side( image_area_params_cref_t ) { ImGui::BeginGroup() ; so_math::vec2f_t const avail_fac( 0.0f ) ; // animated sprite preview // rendering sprite animation in imgui currently not possible #if 0 { so_math::vec2f_t const avail = ImGui::GetContentRegionAvail() ; so_math::vec2f_t const wh( avail.x(), avail.y() * avail_fac.y() ) ; ImVec2 const area_begin = ImGui::GetCursorPos() ; ImGui::BeginChild( "Preview", wh, false, ImGuiWindowFlags_NoMove ) ; { ImVec2 const pos = ImGui::GetCursorScreenPos(); ImGui::GetWindowDrawList()->AddRectFilled( ImVec2( pos.x, pos.y ), ImVec2( pos.x + wh.x(), pos.y + wh.y() ), IM_COL32( 255, 0, 255, 255 ) ); ImGui::Text( "Cursor Screen Pos: (%.2f, %.2f)", pos.x, pos.y ) ; ImGui::Text( "Begin of Area: (%.2f, %.2f)", area_begin.x, area_begin.y ) ; } ImGui::EndChild() ; } #endif if( ImGui::IsKeyDown( int_t( so_device::ascii_key::ctrl_left ) ) && ImGui::IsKeyReleased( int_t( so_device::ascii_key::n ) ) && so_core::is_not( _list_item_is_editing ) ) { int const bp = 0 ; list_item_t ti ; ti.rename = true ; ti.key = "" ; _list_items.push_back( ti ) ; } // sequences { so_math::vec2f_t avail = ImGui::GetContentRegionAvail() ; so_math::vec2f_t const wh ( avail.x(), avail.y() ) ; ImVec2 const area_begin = ImGui::GetCursorPos() ; ImGui::BeginChild( "Sequences", wh*so_math::vec2f_t(1.0f,0.49f), false, ImGuiWindowFlags_NoMove ) ; { if( ImGui::ListBoxHeader( "SequencesList", ImGui::GetContentRegionAvail() ) ) { uint_t remove_i = uint_t( -1 ) ; bool_t remove_last = false ; uint_t item_i = 0 ; for( auto & item : _list_items ) { if( so_core::is_not( item.rename ) ) { ImGui::Selectable( item.key.c_str(), item_i == _selected_list_item, 0, so_math::vec2f_t( avail.x() * 0.8f, 0.0f ) ); if( ImGui::IsItemClicked() ) { _selected_list_item = item_i ; } } if( item.rename ) { ImGui::SetKeyboardFocusHere(); _list_item_is_editing = true ; item.rename = true ; char_t buf[ 255 ] ; buf[ 0 ] = '\0' ; if( ImGui::InputText( "", buf, 255 ) ){} if( ImGui::IsKeyPressed( int_t(so_device::ascii_key::escape) ) ) { remove_last = true ; if( item.key != "" ) { remove_last = false ; item.rename = false ; } _list_item_is_editing = false ; _selected_list_item = uint_t(-1) ; } if( ImGui::IsKeyPressed( int_t( so_device::ascii_key::k_return ) ) ) { _selected_list_item = item_i ; item.rename = false ; if( so_std::string_t( buf ).empty() ) { remove_last = true ; } { auto const iter = std::find_if( _list_items.begin(), _list_items.end(), [&]( list_item_cref_t ti ) { return ti.key == so_std::string_t( buf ) ; } ) ; if( iter != _list_items.end() ) { remove_last = true ; } } if( remove_last == false ) { item.key = so_std::string_t( buf ) ; } // _list_item_is_editing: could mean via "r" // item.key != "": means new item if( _list_item_is_editing && item.key != "" ) remove_last = false ; _list_item_is_editing = false ; } } ImGui::SameLine() ; if( ImGui::SmallButton( "r" ) ){} if( ImGui::IsItemClicked( 0 ) ) { item.rename = true ; } ImGui::SameLine() ; if( ImGui::SmallButton("d") ) {} if( ImGui::IsItemClicked(0) ) { remove_i = item_i ; } ++item_i ; } if( remove_i != uint_t(-1) ) { _selected_list_item = uint_t( -1 ) ; _list_items.erase( _list_items.begin() + remove_i ) ; } if( remove_last ) { _list_items.erase( _list_items.end() - 1 ) ; _selected_list_item = uint_t( -1 ) ; } ImGui::ListBoxFooter(); } } ImGui::EndChild() ; ImGui::BeginChild( "Properties", wh*so_math::vec2f_t(1.0f,0.5f), false, ImGuiWindowFlags_NoMove ) ; if( _selected_list_item != uint_t(-1) ) { if( ImGui::TreeNode( "Properties" ) ) { ImGui::TreePop(); } if( ImGui::TreeNode( "Boxes" ) ) { uint_t delete_item_id = uint_t(-1) ; for( size_t i=0; i<_list_items[ _selected_list_item ].rects.size(); ++i ) { auto & r = _list_items[ _selected_list_item ].rects[i] ; so_std::string_t const name = "Box_" + std::to_string( i ) ; { bool_t v = r.valid ; if( ImGui::Checkbox( "", &v ) ) {} if( ImGui::IsItemClicked(0)) { r.valid = !r.valid ; } } ImGui::SameLine(0.0f, 10.0f) ; if( ImGui::TreeNode( name.c_str() ) ) { // side options { if( ImGui::Button( "del" ) ) { delete_item_id = uint_t(i) ; } } // duration { int_t ms = r.duration ; ImGui::SliderInt( "ms", &ms, 100, 1000 ); r.duration = ms ; } // Pivot point { so_math::vec2f_t const piv = r.pivot ; so_math::vec2i_t const whl = so_math::vec2i_t( r.end - r.beg ) ; int_t xy[ 2 ] = { int_t( piv.x() * float_t( whl.x() ) ), int_t( piv.y() * float_t( whl.y() ) ) }; auto const b0 = ImGui::SliderInt( "pivot x", &xy[ 0 ], -whl.x(), whl.x()) ; auto const b1 = ImGui::SliderInt( "pivot y", &xy[ 1 ], -whl.y(), whl.y()) ; if( b0 || b1 ) { r.pivot = so_math::vec2f_t( float_t( xy[ 0 ] ) / float_t( whl.x() ), float_t( xy[ 1 ] ) / float_t( whl.y() ) ) ; } } // box min { auto const dims = this_t::cur_spritesheet_dims() ; so_math::vec2f_t const v = r.beg ; float_t xy[ 2 ] = { v.x(), v.y() }; ImGui::SliderFloat2( "begin", &xy[ 0 ], 0.0f, std::max(dims.x(), dims.y()) ) ; r.beg = so_math::vec2f_t( xy[ 0 ], xy[ 1 ] ) ; } ImGui::TreePop(); } } if( delete_item_id != uint_t( -1 ) ) { auto iter = _list_items[ _selected_list_item ].rects.begin() + delete_item_id ; _list_items[ _selected_list_item ].rects.erase( iter ) ; delete_item_id = uint_t( -1 ) ; } ImGui::TreePop(); } } ImGui::EndChild() ; } //ImGui::Text("Window Pos: (%.2f, %.2f)", pos.x, pos.y ); ImGui::EndGroup() ; //ImGui::Dummy( wh ); } //************************************************************************* void_t my_app::calc_width_height( image_area_params_ref_t ip ) { // width/height { so_math::vec2f_t const avail = ImGui::GetContentRegionAvail() ; so_math::vec2f_t const wh_img = this_t::cur_spritesheet_dims() ; so_math::vec2f_t const aspect( avail.y() * ( wh_img.x() / wh_img.y() ), avail.x() * ( wh_img.y() / wh_img.x() ) ) ; // computer zoom 0 as reference size ... so_math::vec2f_t wh = so_math::vec2f_t( aspect.x(), avail.y() ) ; // ... and handle to the boundary snapping. Scale based on the // longest image side if( wh.x() >= avail.x() ) { wh = so_math::vec2f_t( avail.x(), aspect.y() ) ; } // just 2x each zoom level ip.wh = wh + wh * ip.zoom_level ; } } //************************************************************************* void_t my_app::calc_image_dim( image_area_params_ref_t ip ) { so_math::vec2f_t zoom_dif ; { auto const center = (ip.wh * 0.5f) / ip.pwh ; zoom_dif = ( ip.pixel_to_pos( ip.pixel ) - ip.pixel_to_pos(center) ) ; } // ensure image is in the middle zoom_dif = ip.zoom_level == 0 ? so_math::vec2f_t() : zoom_dif ; // image begin/end { so_math::vec2f_t const pos = ImGui::GetCursorScreenPos() ; so_math::vec2f_t const avail = ImGui::GetContentRegionAvail() ; auto the_center = pos + avail * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const img_center = the_center - zoom_dif ; so_math::vec2f_t img_begin = img_center - ip.wh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t img_end = img_center + ip.wh * so_math::vec2f_t( 0.5f ) ; ip.img_begin = img_begin ; ip.img_end = img_end ; //ImGui::Text( "Zoom Center: (%.2f, %.2f)", img_center.x(), img_center.y() ) ; } } //************************************************************************* void_t my_app::calc_pixels( image_area_params_ref_t ip ) { // compute zoom mouse over pixel // do before zoom wh is computed ip.pixel = ip.zoom_changed ? ip.cur_pixel : ip.pixel ; // recalc pixel width/height { ip.pwh = ip.wh / this_t::cur_spritesheet_dims() ; } // compute current mouse over pixel { so_math::vec2f_t mpos( ImGui::GetMousePos() ) ; so_math::vec2f_t const pixel = ( ( mpos - ip.img_begin ) / ip.pwh ).floored() ; ip.cur_pixel = pixel ; } } //************************************************************************* void_t my_app::draw_cur_mouse_rect_and_track_drag( image_area_params_ref_t ip ) { static so_math::vec2f_t dbeg ; so_math::vec2f_t const dend = ip.cur_pixel ; static bool_t dragging = false ; if( ImGui::GetIO().KeyCtrl && ImGui::IsMouseClicked( 0, false ) ) { dbeg = ip.cur_pixel ; dragging = true ; } if( dragging ) { so_math::vec2f_t const a = ip.pixel_to_pos( dbeg ) ; so_math::vec2f_t const b = ip.pixel_to_pos( dend ) ; ImGui::GetWindowDrawList()->AddRect( a, b, IM_COL32( 255, 255, 255, 255 ) ); } if( dragging && ImGui::IsMouseReleased( 0 ) && (dend-dbeg).abs().length2() > 0.5f ) { animation_rect_t ar ; ar.beg = dbeg ; ar.end = dend ; ar.compute_rect() ; //_animrs.push_back( ar ) ; if( _selected_list_item != uint_t(-1) ) { _list_items[ _selected_list_item ].rects.push_back( ar ) ; } dragging = false ; } } //************************************************************************* void_t my_app::handle_animation_rects( image_area_params_cref_t ip ) { static uint_t hit_i = uint_t( -1 ) ; _hovered_animation_rect = hit_i == uint_t(-1) ? uint_t( -1 ) : _hovered_animation_rect ; if( _selected_list_item == uint_t ( -1 ) ) return ; for( uint_t i=0; i< _list_items[_selected_list_item].rects.size(); ++i ) { auto const & ar = _list_items[ _selected_list_item ].rects[i] ; so_collide::so_2d::aabbf_t const bb( ar.rect.xy(), ar.rect.zw() ) ; bool_t const is_inside = bb.is_inside( ip.cur_pixel ) ; ImU32 const color = is_inside ? IM_COL32( 255, 127, 64, 255 ) : IM_COL32( 255, 255, 255, 255 ) ; _hovered_animation_rect = is_inside && hit_i == uint_t(-1)? i : _hovered_animation_rect ; so_math::vec2f_t const a = ip.pixel_to_pos( ar.beg ) ; so_math::vec2f_t const b = ip.pixel_to_pos( ar.end ) ; ImGui::GetWindowDrawList()->AddRect( a, b, color ); } if( _hovered_animation_rect != uint_t(-1) ) { auto & r = _list_items[ _selected_list_item ].rects[_hovered_animation_rect] ; so_math::vec2f_t const fours[4] = { so_math::vec2f_t( r.rect.x(), r.rect.y() ) + so_math::vec2f_t(1.0f,1.0f), so_math::vec2f_t( r.rect.x(), r.rect.w() ) + so_math::vec2f_t(1.0f,-1.0f), so_math::vec2f_t( r.rect.z(), r.rect.y() ) + so_math::vec2f_t(-1.0f,1.0f), so_math::vec2f_t( r.rect.z(), r.rect.w() ) + so_math::vec2f_t(-1.0f,-1.0f), } ; for( uint_t i=0; i<4; ++i ) { so_math::vec2f_t centerl = fours[i] * ip.pwh + ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const a = ip.img_begin + centerl - ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const b = ip.img_begin + centerl + ip.pwh * so_math::vec2f_t( 0.5f ) ; bool_t const is_hit = so_math::vec2ui_t( ip.cur_pixel ). equal( so_math::vec2ui_t( fours[ i ] ) ).all() ; hit_i = is_hit && hit_i == uint_t(-1) ? i : hit_i ; ImU32 const color = is_hit ? IM_COL32( 255, 127, 64, 255 ) : IM_COL32( 255, 255, 255, 255 ) ; //ImGui::Text( "hit: %s", is_hit ? "yes" : "no" ) ; ImGui::GetWindowDrawList()->AddRectFilled( a, b, color ); } if( hit_i != uint_t( -1 ) && ImGui::IsMouseDown( 0 ) ) { auto const dif = ip.cur_pixel - fours[ hit_i ] ; if( hit_i == 0 ) { r.beg.x( r.beg.x() + dif.x() ) ; r.beg.y( r.beg.y() + dif.y() ) ; } else if( hit_i == 1 ) { r.beg.x( r.beg.x() + dif.x() ) ; r.end.y( r.end.y() + dif.y() ) ; } else if( hit_i == 2 ) { r.end.x( r.end.x() + dif.x() ) ; r.beg.y( r.beg.y() + dif.y() ) ; } else if( hit_i == 3 ) { r.end.x( r.end.x() + dif.x() ) ; r.end.y( r.end.y() + dif.y() ) ; } //ImGui::Text( "dif: (%.2f, %.2f)", dif.x(), dif.y() ) ; r.compute_rect() ; } else if( ImGui::IsMouseDown( 0 ) ) { auto const dif = ip.cur_pixel - (r.end + r.beg)*0.5f ; r.beg += dif.floored() ; r.end += dif.floored() ; r.compute_rect() ; } if( so_core::is_not( ImGui::IsMouseDown( 0 ) ) ) { hit_i = uint_t( -1 ) ; } } } //************************************************************************* void_t my_app::draw_imgui_editor_image( image_area_params_cref_t ip ) { ImGui::GetWindowDrawList()->AddImage( this_t::cur_imex_tx(), ip.img_begin, ip.img_end, // no uv zoom at the moment. so_math::vec2f_t( 0.0f, 0.0f ), so_math::vec2f_t( 1.0f, 1.0f ) ) ; //ImGui::Text( "Zoom: %d", ip.zoom_level ) ; //ImGui::Text( "Region: (%.2f, %.2f)", region.x(), region.y() ) ; // SECTION: Render rect as pixel { so_math::vec2f_t centerl = ip.cur_pixel * ip.pwh + ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const a = ip.img_begin + centerl - ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const b = ip.img_begin + centerl + ip.pwh * so_math::vec2f_t( 0.5f ) ; ImGui::GetWindowDrawList()->AddRectFilled( a, b, IM_COL32( 255, 255, 255, 255 ) ); //ImGui::Text( "Image Begin: (%.2f, %.2f)", ip.img_begin.x(), ip.img_begin.y() ) ; //ImGui::Text( "Pixel: (%.2f, %.2f)", ip.cur_pixel.x(), ip.cur_pixel.y() ) ; //ImGui::Text( "Wh: (%.2f, %.2f)", ip.wh.x(), ip.wh.y() ) ; //ImGui::Text( "pWh: (%.2f, %.2f)", ip.pwh.x(), ip.pwh.y() ) ; } // SECTION: Render rect as pixel { so_math::vec2f_t centerl = ip.pixel * ip.pwh + ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const a = ip.img_begin + centerl - ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const b = ip.img_begin + centerl + ip.pwh * so_math::vec2f_t( 0.5f ) ; ImGui::GetWindowDrawList()->AddRectFilled( a, b, IM_COL32( 255, 255, 255, 255 ) ); //ImGui::Text( "Image Begin: (%.2f, %.2f)", ip.img_begin.x(), ip.img_begin.y() ) ; //ImGui::Text( "Pixel: (%.2f, %.2f)", ip.pixel.x(), ip.pixel.y() ) ; //ImGui::Text( "Wh: (%.2f, %.2f)", ip.wh.x(), ip.wh.y() ) ; //ImGui::Text( "pWh: (%.2f, %.2f)", ip.pwh.x(), ip.pwh.y() ) ; } /*{ ImGui::GetWindowDrawList()->AddLine( ip.zoom_center, ip.zoom_center + ip.zoom_dif, IM_COL32( 255, 255, 255, 255 ), 5.0f ); }*/ } //************************************************************************* void_t my_app::draw_imgui_bottom_area( void_t ) { } //************************************************************************* void_t my_app::handle_pivot_point( image_area_params_cref_t ip ) { if( _selected_list_item == uint_t( -1 ) ) return ; for( auto & r : _list_items[_selected_list_item].rects ) { auto const rpiv = r.pivot * so_math::vec2f_t( 0.5f ) + so_math::vec2f_t( 0.5f ) ; auto const piv = so_math::vec2f_t( rpiv.x(), 1.0f ) - so_math::vec2f_t( 0.0f, rpiv.y() ) ; so_math::vec2f_t const p = r.rect.xy() + piv * ( r.rect.zw() - r.rect.xy() ) ; ; so_math::vec2f_t const pixel = ( ( p ) / ip.pwh ).floored() ; so_math::vec2f_t centerl = p * ip.pwh + ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const a = ip.img_begin + centerl - ip.pwh * so_math::vec2f_t( 0.5f ) ; so_math::vec2f_t const b = ip.img_begin + centerl + ip.pwh * so_math::vec2f_t( 0.5f ) ; ImGui::GetWindowDrawList()->AddRectFilled( a, b, IM_COL32( 255, 0, 0, 255 ) ); } }<file_sep>/worldomat/game/world/layer.cpp #include "layer.h" #include <algorithm> using namespace prototype ; //********************************************************* layer::layer( dims_data_cref_t dd ) : _dims_data(dd) {} //********************************************************* layer::layer( this_rref_t rhv ) : _dims_data( rhv._dims_data ) {} //********************************************************* layer::~layer( void_t ) { for( size_t i=0; i<_chunks.size(); ++i ) { prototype::chunk_t::destroy( _chunks[ i ].cptr ) ; } } //********************************************************* layer::this_ptr_t layer::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_memory::global_t::alloc( std::move( rhv ), p ) ; } //********************************************************* layer::this_ptr_t layer::destroy( this_ptr_t ptr ) { so_memory::global_t::dealloc( ptr ) ; return nullptr ; } //********************************************************* bool_t layer::add_block( uint_t const ci, uint_t const cj, uint_t const bi, uint_t const bj, block_cref_t b ) { chunk_ptr_t lptr = this_t::find_or_add_chunk( ci, cj ) ; return lptr->add_block( bi, bj, b ) ; } //********************************************************* void_t layer::render( uint_t const lno, this_t::render_info_in_t ri ) { auto const dif = ri.cbs.chunk_dif() ; for( uint_t i = 0; i <= dif.x(); ++i ) { for( uint_t j = 0; j <= dif.y(); ++j ) { so_math::vec2ui_t const ij = ri.cbs.chunk_min() + so_math::vec2ui_t( i, j ) ; uint_t const index = ij.x() + _dims_data.layer_dims.x() * ij.y() ; prototype::chunk_ptr_t cptr = this_t::find_chunk( index ) ; if( so_core::is_nullptr( cptr ) ) continue ; cptr->render( lno, ij, _dims_data, ri.rnd ) ; } } } //********************************************************* chunk_ptr_t layer::find_or_add_chunk( uint_t const ci, uint_t const cj ) { uint_t const index = cj * _dims_data.layer_dims.x() + ci ; auto iter = std::find_if( _chunks.begin(), _chunks.end(), [&] ( data_cref_t d ) { return d.index == index ; } ) ; if( iter == _chunks.end() ) { this_t::data_t d ; d.index = index ; d.i = ci ; d.j = cj ; d.cptr = prototype::chunk_t::create( prototype::chunk_t( _dims_data.chunk_dims ), "[layer::add_block] : chunk" ) ; _chunks.push_back( d ) ; iter = _chunks.end() - 1 ; } return iter->cptr ; } //********************************************************* chunk_ptr_t layer::find_chunk( uint_t const index ) { auto iter = std::find_if( _chunks.begin(), _chunks.end(), [&] ( data_cref_t d ) { return d.index == index ; } ) ; return iter == _chunks.end() ? nullptr : iter->cptr ; } //********************************************************* bool_t layer::get_chunk_by_id( uint_t const index, chunk_info_out_t co ) { auto iter = std::find_if( _chunks.begin(), _chunks.end(), [&] ( data_cref_t d ) { return d.index == index ; } ) ; if( iter == _chunks.end() ) return false ; chunk_info_t ci ; ci.id = index ; ci.i = iter->i ; ci.j = iter->j ; ci.cptr = iter->cptr ; co = ci ; return true ; } //********************************************************* bool_t layer::get_chunk_by_dim( uint_t const i, uint_t const j, chunk_info_out_t co ) { uint_t const index = j * _dims_data.chunk_dims.x() + i ; return this_t::get_chunk_by_id( index, co ) ; } //********************************************************* void_t layer::get_chunks_in_area( so_collide::so_2d::aabbf_cref_t area, chunk_infos_out_t ciso ) { this_t::chunk_infos_t cis ; for( size_t i=0; i<_chunks.size(); ++i ) { } ciso = std::move( cis ) ; } //*********************************************************<file_sep>/worldomat/game/world/layer.h #pragma once #include "chunk.h" #include <snakeoil/collide/2d/bounds/aabb.hpp> #include <snakeoil/std/container/vector.hpp> #include <snakeoil/core/types.hpp> #include <snakeoil/core/macros/typedef.h> namespace prototype { class layer { so_this_typedefs( layer ) ; private: struct data { // j * width + i uint_t index ; uint_t i ; uint_t j ; chunk_ptr_t cptr ; }; so_typedef( data ) ; so_typedefs( so_std::vector< data_t >, chunks ) ; chunks_t _chunks ; dims_data_t _dims_data ; public: public: layer( dims_data_cref_t ) ; layer( this_cref_t ) = delete ; layer( this_rref_t ) ; ~layer( void_t ) ; public: static this_ptr_t create( this_rref_t, so_memory::purpose_cref_t ) ; static this_ptr_t destroy( this_ptr_t ) ; public: bool_t add_block( uint_t const ci, uint_t const cj, uint_t const bi, uint_t const bj, block_cref_t ) ; public: struct render_info { prototype::dims_data_t::chunks_and_blocks_t cbs ; so_gfx::render_2d_ptr_t rnd ; }; so_typedef( render_info ) ; void_t render( uint_t const lno, render_info_in_t ) ; public: struct chunk_info { uint_t id ; uint_t i ; uint_t j ; chunk_ptr_t cptr ; }; so_typedef( chunk_info ) ; so_typedefs( so_std::vector< chunk_info >, chunk_infos ) ; bool_t get_chunk_by_id( uint_t const, chunk_info_out_t ) ; bool_t get_chunk_by_dim( uint_t const i, uint_t const j, chunk_info_out_t ) ; void_t get_chunks_in_area( so_collide::so_2d::aabbf_cref_t area, chunk_infos_out_t ) ; private: chunk_ptr_t find_or_add_chunk( uint_t const ci, uint_t const cj ) ; chunk_ptr_t find_chunk( uint_t const index ) ; }; so_typedef( layer ) ; }<file_sep>/worldomat/game/game.h #pragma once #include "typedefs.h" #include "world/world.h" #include <snakeoil/gfx/protos.h> #include <snakeoil/gpx/protos.h> namespace prototype { class game { so_this_typedefs( game ) ; private: so_gpx::render_system_ptr_t _rs ; world_ptr_t _world = nullptr ; public: game( so_gpx::render_system_ptr_t ) ; game( this_cref_t ) = delete ; game( this_rref_t ) ; ~game( void_t ) ; static this_ptr_t create( this_rref_t, so_memory::purpose_cref_t ) ; static void_t destroy( this_ptr_t ) ; public: void_t init( dims_data_cref_t ) ; void_t deinit( void_t ) ; void_t update( void_t ) ; public: struct render_info { so_math::vec2i_t cam_pos ; so_math::vec2ui_t view_area_radius ; prototype::dims_data_t dd ; so_gfx::render_2d_ptr_t rnd ; }; so_typedef( render_info ) ; void_t render( render_info_in_t ) ; public: world_ptr_t get_world( void_t ) ; }; so_typedef( game ) ; }<file_sep>/spritomat/CMakeLists.txt set( SOURCES typedefs.h main.h main.cpp app/app.h app/app.cpp app/app_initialize.cpp app/app_update.cpp app/app_render.cpp ) so_vs_src_dir( SOURCES ) set( PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR} ) add_definitions( -DPP_PROJECT_SRC_DIR="${PROJECT_DIR}" ) get_filename_component(ProjectId ${CMAKE_CURRENT_SOURCE_DIR} NAME) add_executable( ${ProjectId} ${SOURCES} ) target_link_libraries( ${ProjectId} snakeoil::complete ) <file_sep>/worldomat/tool/tool.h #pragma once #include "../typedefs.h" #include "grid_overlay.h" #include "../game/util/camera.h" #include "../game/dims_data.h" #include <snakeoil/gfx/protos.h> #include <snakeoil/gpx/protos.h> #include <snakeoil/device/component/buttons/three_button.h> #include <snakeoil/device/component/buttons/button_state.h> #include <snakeoil/degui/system/system.h> #include <snakeoil/math/vector/vector2.hpp> namespace prototype { class tool { so_this_typedefs( tool ) ; private: so_gpx::render_system_ptr_t _rs ; so_gfx::render_2d_ptr_t _rnd_2d ; grid_overlay_ptr_t _grid ; uint_t _radius = 0 ; public: struct material_action { uint_t layer ; so_math::vec2ui_t chunk ; so_math::vec2ui_t block ; prototype::dims_data_t::chunks_and_blocks_t cb ; size_t material_id ; }; so_typedef( material_action ) ; class event_listener { public: virtual void_t on_material( material_action ) = 0 ; }; so_typedef( event_listener ) ; struct update_info { // cam view so_math::vec2f_t cam_view ; // the current zoom of the scene so_math::vec2f_t zoom ; so_math::vec2f_t zoomed_cam_view( void_t ) const { return cam_view / zoom ; } }; so_typedef( update_info ) ; struct render_info { // contains matrices for rendering prototype::camera_t cam ; // the current camera world pos so_math::vec2f_t cam_pos ; // cam view so_math::vec2f_t cam_view ; // the current zoom of the scene so_math::vec2f_t zoom ; /// in view space so_math::vec2f_t cur_mouse ; dims_data_t dd ; so_math::vec2f_t zoomed_cam_view( void_t ) const{ return cam_view / zoom ; } }; so_typedef( render_info ) ; struct test_info { // the current camera world pos so_math::vec2f_t cam_pos ; // cam view so_math::vec2f_t cam_view ; // the current zoom of the scene so_math::vec2f_t zoom ; /// in view space so_math::vec2f_t cur_mouse ; dims_data_t dd ; so_device::three_button three_button ; so_device::button_state button_state ; this_t::event_listener_ptr_t elptr ; so_math::vec2f_t zoomed_cam_view( void_t ) const { return cam_view / zoom ; } }; so_typedef( test_info ) ; public: tool( so_gpx::render_system_ptr_t ) ; tool( this_cref_t ) = delete ; tool( this_rref_t ) ; ~tool( void_t ) ; public: static this_ptr_t create( this_rref_t, so_memory::purpose_cref_t ) ; static void_t destroy( this_ptr_t ) ; public: void_t render( this_t::render_info_cref_t ) ; void_t update( void_t ) ; void_t render_imgui( so_imgui::system_ptr_t imguis ) ; public: uint_t get_radius( void_t ) const { return _radius ; } void_t test_mouse( test_info_cref_t ) ; private: void_t draw_chunk_block_lines_grid( this_t::render_info_cref_t ) ; void_t draw_mouse_over( this_t::render_info_cref_t ) ; private: void_t destroy_all_listeners( void_t ) ; }; so_typedef( tool ) ; }<file_sep>/spritomat/app/app_update.cpp #include "app.h" #include <snakeoil/degui/system/system.h> #include <snakeoil/device/devices/mouse/three_button_mouse.h> #include <snakeoil/device/devices/keyboard/ascii_keyboard.h> #include <snakeoil/animation/keyframe_sequence/linear_keyframe_sequence.hpp> using namespace examples ; //************************************************************************* so_appx::result my_app::on_update( so_appx::update_data_cref_t ud ) { if( so_core::is_not_nullptr( _keyboard ) ) { if( _keyboard->is_pressing( so_device::ascii_key::escape ) && _keyboard->is_pressing( so_device::ascii_key::shift_left )) { return so_appx::terminate ; } if( _keyboard->is_released( so_device::ascii_key::q ) ) {} if( _keyboard->is_released( so_device::ascii_key::f1 ) ) { _show_imgui = !_show_imgui ; } } bool_t imgui_want_mouse = false ; if( _show_imgui ) { _imguis->check_status( [&] ( ImGuiContext * ctx, so_imgui::system_ptr_t self ) { ImGui::SetCurrentContext( ctx ) ; auto & io = ImGui::GetIO() ; imgui_want_mouse = so_core::is_not( io.WantCaptureMouse ) ; } ) ; } if( so_core::is_not_nullptr( _mouse ) ) { auto const p = _mouse->get_local_position() ; } // mouse hit { so_math::vec2f_t pos = _mouse->get_local_position( so_math::vec2f_t( 0.5f, 0.5f ) ) ; pos = pos * so_math::vec2f_t( float_t( 1920 ), float_t( 1080 ) ) ; _cur_mouse_pos = pos ; } return so_appx::result::ok ; }<file_sep>/worldomat/CMakeLists.txt set( SOURCES typedefs.h main.h main.cpp app/app.h app/app.cpp app/app_initialize.cpp app/app_update.cpp app/app_render.cpp app/app_tool.cpp tool/tool.h tool/tool.cpp tool/grid_overlay.h tool/grid_overlay.cpp game/dims_data.h game/game.h game/game.cpp game/util/camera.h game/typedefs.h game/material/material_id.h game/world/world.h game/world/world.cpp game/world/layer.h game/world/layer.cpp game/world/chunk.h game/world/chunk.cpp game/world/block.h game/world/block.cpp ) so_vs_src_dir( SOURCES ) set( PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR} ) add_definitions( -DPP_PROJECT_SRC_DIR="${PROJECT_DIR}" ) get_filename_component(ProjectId ${CMAKE_CURRENT_SOURCE_DIR} NAME) add_executable( ${ProjectId} ${SOURCES} ) target_link_libraries( ${ProjectId} snakeoil::complete ) <file_sep>/README.md # prototypes using for some prototype code <file_sep>/worldomat/tool/grid_overlay.h #pragma once namespace prototype { class grid_overlay { so_this_typedefs( grid_overlay ) ; }; so_typedef( grid_overlay ) ; }<file_sep>/spritomat/app/app.h #pragma once #include "../typedefs.h" #include <snakeoil/appx/app/app.h> #include <snakeoil/gfx/protos.h> #include <snakeoil/degui/protos.h> #include <snakeoil/gpx/technique/technique_id.h> #include <snakeoil/gpu/viewport/viewport_2d.h> #include <snakeoil/flow/variable/variable.hpp> #include <snakeoil/flow/variable/variable_set.h> #include <snakeoil/flow/node/variable/variable_node.h> #include <snakeoil/degui/protos.h> #include <snakeoil/degui/system/system.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet.h> namespace examples { using namespace so_core::so_types ; //******************************************************************************* class my_app : public so_appx::app { so_this_typedefs( my_app ) ; private: // gpx techniques so_gfx::predef_framebuffer_ptr_t _gfxp_fb = nullptr ; so_gfx::predef_post_ptr_t _gfxp_blit = nullptr ; private: // gfx stuff so_gfx::text_render_2d_ptr_t _text_rnd_ptr = nullptr ; so_gfx::line_render_2d_ptr_t _line_rnd_ptr = nullptr ; so_gfx::image_render_2d_ptr_t _image_rnd_ptr = nullptr ; so_gfx::rect_render_2d_ptr_t _rect_rnd_ptr = nullptr ; so_gfx::resource_bridge_ptr_t _res_brd_ptr = nullptr ; so_gfx::sprite_manager_ptr_t _sp_mgr_ptr = nullptr ; private: // node so_flow::variable<so_gpu::viewport_2d_t> * _vp_window_ptr = nullptr ; so_flow::variable_set_t _vs ; so_flow::variable_node_t _vn ; private: // devices so_device::three_button_mouse_ptr_t _mouse = nullptr ; so_device::ascii_keyboard_ptr_t _keyboard = nullptr ; private: // imgui / ui so_imgui::system_ptr_t _imguis = nullptr ; bool_t _show_imgui = true ; bool_t _show_imgui_demo = false ; so_math::vec2f_t _cur_mouse_pos ; struct image_data { // sprite sheet xml data representation size_t width ; size_t height ; so_imgui::system_t::imgui_texture_data_ptr_t imgui_tx_id ; so_imex::image_ptr_t img_ptr ; }; so_typedef( image_data ) ; so_typedefs( so_std::vector< image_data_t >, image_datas ) ; image_datas_t _images ; size_t _use_sprite = 0 ; image_data_ref_t cur_spritesheet( void_t ) ; so_imgui::system_t::imgui_texture_data_ptr_t cur_imex_tx( void_t ) ; so_math::vec2f_t cur_spritesheet_dims( void_t ) const ; so_math::vec2f_t cur_spritesheet_dims_recip( void_t ) const ; private: so_typedefs( std::chrono::high_resolution_clock, clock ) ; clock_t::time_point _tp ; size_t accum = 0 ; private: so_math::vec2f_t _bb_dims = so_math::vec2f_t( 1920.0f, 1080.0f ) ; public: my_app( void_t ) ; my_app( this_rref_t rhv ) ; my_app( this_cref_t ) = delete ; virtual ~my_app( void_t ) ; public: static this_ptr_t create( void_t ) ; static void_t destroy( this_ptr_t ptr ) ; public: virtual so_appx::result on_update( so_appx::update_data_cref_t ud ) ; virtual so_appx::result on_render( so_appx::render_data_cref_t rd ) ; virtual so_appx::result on_initialize( so_appx::init_data_cref_t ) ; virtual so_appx::result has_initialized( void_t ) ; virtual so_appx::result on_event( so_appx::window_event_data_cref_t we ) ; virtual so_appx::result on_activate( void_t ) { return so_appx::result::ok ; } virtual so_appx::result has_activated( void_t ) { return so_appx::result::ok ; } virtual so_appx::result on_deactivate( void_t ) { return so_appx::result::ok ; } virtual so_appx::result has_deactivated( void_t ) { return so_appx::result::ok ; } virtual so_appx::result on_shutdown( void_t ) ; virtual so_appx::result has_shutdown( void_t ) { return so_appx::result::ok ; } virtual so_appx::result destroy( void_t ) ; private: // image area -> dont touch struct image_area_params { bool_t zoom_changed = false ; size_t zoom_level = 0 ; so_math::vec2f_t cur_pixel ; so_math::vec2f_t pixel ; so_math::vec2f_t wh ; so_math::vec2f_t pwh ; so_math::vec2f_t img_begin ; so_math::vec2f_t img_end ; so_math::vec2f_t cur_pixel_center( void_t ) const{ return img_begin + cur_pixel * pwh + pwh * 0.5f ; } so_math::vec2f_t pixel_to_pos( so_math::vec2f_cref_t pix ) const { return img_begin + pix * pwh + pwh * 0.5f ; } }; so_typedef( image_area_params ) ; image_area_params_t _image_area_params ; void_t render_begin( so_appx::render_data_cref_t rd ) ; void_t render_end( so_appx::render_data_cref_t rd ) ; void_t draw_imgui( so_appx::render_data_cref_t rd ) ; void_t draw_cur_mouse_rect_and_track_drag( image_area_params_ref_t ) ; void_t calc_width_height(image_area_params_ref_t ) ; void_t calc_image_dim( image_area_params_ref_t ) ; void_t calc_pixels( image_area_params_ref_t ) ; void_t draw_imgui_editor_image( image_area_params_cref_t ) ; void_t draw_imgui_bottom_area( void_t ) ; void_t draw_left_side( image_area_params_cref_t ) ; void_t draw_right_side( image_area_params_cref_t ) ; void_t handle_pivot_point( image_area_params_cref_t ) ; void_t save_to_file( void_t ) ; void_t load_from( so_imex::so_snakeoil::spritesheet_cref_t ) ; private: // base of xml so_io::path_t _base_path ; // xml file so_io::path_t _file ; // sprite sheet image file name from // xml description file so_io::path_t _ss_file ; private: // test area struct animation_rect { so_math::vec2f_t beg ; so_math::vec2f_t end ; so_math::vec4f_t rect ; so_math::vec2f_t pivot ; uint_t duration = 200 ; bool_t valid = true ; void_t compute_rect( void_t ) { rect = so_math::vec4ui_t( uint_t( std::floor( std::min( beg.x(), end.x() ) ) ), uint_t( std::ceil( std::min( beg.y(), end.y() ) ) ), uint_t( std::ceil( std::max( beg.x(), end.x() ) ) ), uint_t( std::ceil( std::max( beg.y(), end.y() ) ) ) ) ; } }; so_typedef( animation_rect ) ; so_typedefs( std::vector< animation_rect >, animation_rects ) ; animation_rects_t _animrs ; void_t handle_animation_rects( image_area_params_cref_t ) ; private: // box tree area bool_t _list_item_is_editing = false ; uint_t _selected_list_item = uint_t( -1 ) ; uint_t _hovered_animation_rect = uint_t( -1 ) ; struct list_item { bool_t rename = false ; so_std::string_t key ; // sequence animation_rects_t rects ; }; so_typedef( list_item ) ; so_typedefs( so_std::vector< list_item_t >, tree_items ) ; tree_items_t _list_items ; }; }<file_sep>/worldomat/tool/tool.cpp #include "tool.h" #include <snakeoil/degui/system/system.h> #include <snakeoil/gfx/line/line_render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/gpx/system/render_system.h> #include <snakeoil/math/matrix/matrix4.hpp> using namespace prototype ; //****************************************************** tool::tool( so_gpx::render_system_ptr_t rs ) { _rs = rs ; _rnd_2d = so_gfx::render_2d_t::create( so_gfx::render_2d_t( _rs ), "[tool::tool] : render_2d" ) ; _rnd_2d->init() ; } //****************************************************** tool::tool( this_rref_t rhv ) { so_move_member_ptr( _rs, rhv ) ; so_move_member_ptr( _rnd_2d, rhv ) ; } //****************************************************** tool::~tool( void_t ) { so_gfx::render_2d_t::destroy( _rnd_2d ) ; } //****************************************************** tool::this_ptr_t tool::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_memory::global_t::alloc( this_t(std::move(rhv)), p ) ; } //****************************************************** void_t tool::destroy( this_ptr_t ptr ) { so_memory::global_t::dealloc( ptr ) ; } //****************************************************** void_t tool::render( this_t::render_info_cref_t ri ) { _rnd_2d->set_view_projection( ri.cam.view, ri.cam.proj ) ; this_t::draw_chunk_block_lines_grid( ri ) ; this_t::draw_mouse_over( ri ) ; _rnd_2d->prepare_for_rendering() ; _rnd_2d->render_range( 0, 100 ) ; } //****************************************************** void_t tool::update( void_t ) { } //****************************************************** void_t tool::render_imgui( so_imgui::system_ptr_t imguis ) { imguis->draw( [=] ( ImGuiContext * ctx, so_imgui::system_ptr_t self ) { ImGui::SetCurrentContext( ctx ) ; ImGui::Begin( "The Tool" ); { int_t radius = _radius ; ImGui::SliderInt( "Radius", &radius, 0, 20 ) ; _radius = uint_t( radius ) ; } ImGui::End() ; } ) ; } //****************************************************** void_t tool::draw_chunk_block_lines_grid( this_t::render_info_cref_t ri ) { so_math::vec2f_t const cam_view = ri.zoomed_cam_view() ; so_math::vec2ui_t const field_dims = ri.dd.layer_dims * ri.dd.chunk_dims * ri.dd.block_dims ; so_math::vec2ui_t const chunk_dims = ri.dd.chunk_dims * ri.dd.block_dims ; so_math::vec2ui_t const block_dims = ri.dd.block_dims ; so_math::vec2i_t vstart = so_math::vec2i_t( ri.cam_pos ) - so_math::vec2i_t( cam_view ) / so_math::vec2i_t( 2 ) ; so_math::vec2i_t const start = so_math::vec2i_t( field_dims / so_math::vec2ui_t( 2 ) ).negated() ; so_math::vec2ui_t const dif = vstart - start ; so_math::vec2ui_t const which_chunk = so_math::vec2ui_t( dif / chunk_dims ) ; so_math::vec2ui_t const which_block = so_math::vec2ui_t( dif / block_dims ) ; so_math::vec2f_t const wh = cam_view ; // draw chunks { so_math::vec2f_t const start_draw = start + so_math::vec2f_t( which_chunk ) * so_math::vec2f_t( chunk_dims ) ; /// how many lines per dimension <=> number of chunks in each dimension so_math::vec2ui_t const num_lines = cam_view / chunk_dims ; // chunk lines in x direction { so_math::vec2f_t const pos0( start_draw.x(), float_t( start_draw.y() ) ) ; so_math::vec2f_t const pos1( start_draw.x(), float_t( start_draw.y() ) + wh.y() + dif.y() ) ; _rnd_2d->get_line_render_2d()->draw_lines( 0, size_t( num_lines.x() ) + 2, [&] ( size_t const i ) { so_math::vec2f_t const iv( float_t( i ), 0.0f ) ; so_gfx::line_render_2d_t::line_info_t li ; li.pos0 = pos0 + iv * so_math::vec2f_t( chunk_dims ) ; li.pos1 = pos1 + iv * so_math::vec2f_t( chunk_dims ) ; li.color = so_math::vec4f_t( 1.0f ) ; return std::move( li ) ; } ) ; } // chunk lines in y direction { so_math::vec2f_t const pos0( start_draw.x(), float_t( start_draw.y() ) ) ; so_math::vec2f_t const pos1( start_draw.x() + wh.x() + dif.x(), float_t( start_draw.y() ) ) ; _rnd_2d->get_line_render_2d()->draw_lines( 0, size_t( num_lines.y() ) + 2, [&] ( size_t const i ) { so_math::vec2f_t const iv( 0.0f, float_t( i ) ) ; so_gfx::line_render_2d_t::line_info_t li ; li.pos0 = pos0 + iv * so_math::vec2f_t( chunk_dims ) ; li.pos1 = pos1 + iv * so_math::vec2f_t( chunk_dims ) ; li.color = so_math::vec4f_t( 1.0f ) ; return std::move( li ) ; } ) ; } } // draw blocks if( ri.zoom.greater_equal_than(so_math::vec2f_t( .2f )).any() ) { so_math::vec2f_t const start_draw = start + so_math::vec2f_t( which_block ) * so_math::vec2f_t( block_dims ) ; /// how many lines per dimension <=> number of blocks in each dimension so_math::vec2ui_t const num_lines = (cam_view ) / block_dims ; // chunk lines in x direction { so_math::vec2f_t const pos0( start_draw.x(), float_t( start_draw.y() ) ) ; so_math::vec2f_t const pos1( start_draw.x(), float_t( start_draw.y() ) + wh.y() + dif.y() ) ; _rnd_2d->get_line_render_2d()->draw_lines( 0, size_t( num_lines.x() ) + 2, [&] ( size_t const i ) { so_math::vec2f_t const iv( float_t( i ), 0.0f ) ; so_gfx::line_render_2d_t::line_info_t li ; li.pos0 = pos0 + iv * so_math::vec2f_t( block_dims ) ; li.pos1 = pos1 + iv * so_math::vec2f_t( block_dims ) ; li.color = so_math::vec4f_t( 0.7f ) ; return std::move( li ) ; } ) ; } // chunk lines in y direction { so_math::vec2f_t const pos0( start_draw.x(), float_t( start_draw.y() ) ) ; so_math::vec2f_t const pos1( start_draw.x() + wh.x() + dif.x(), float_t( start_draw.y() ) ) ; _rnd_2d->get_line_render_2d()->draw_lines( 0, size_t( num_lines.y() ) + 2, [&] ( size_t const i ) { so_math::vec2f_t const iv( 0.0f, float_t( i ) ) ; so_gfx::line_render_2d_t::line_info_t li ; li.pos0 = pos0 + iv * so_math::vec2f_t( block_dims ) ; li.pos1 = pos1 + iv * so_math::vec2f_t( block_dims ) ; li.color = so_math::vec4f_t( 0.7f ) ; return std::move( li ) ; } ) ; } } } //****************************************************** void_t tool::draw_mouse_over( this_t::render_info_cref_t ri ) { so_math::vec2ui_t const field_dims = ri.dd.layer_dims * ri.dd.chunk_dims * ri.dd.block_dims ; so_math::vec2ui_t const chunk_dims = ri.dd.chunk_dims * ri.dd.block_dims ; so_math::vec2ui_t const block_dims = ri.dd.block_dims ; so_math::vec2i_t const start = so_math::vec2i_t( field_dims / so_math::vec2ui_t( 2 ) ).negated() ; so_math::vec2i_t const cam_view = ri.zoomed_cam_view() ; so_math::vec2i_t const mouse_pos = ri.cam_pos + ri.cur_mouse ; so_math::vec2ui_t const which_chunk = ri.dd.calc_chunk_ij( mouse_pos ) ; so_math::vec2ui_t const which_block = ri.dd.calc_block_ij_global( mouse_pos ) ; uint_t const radius = _radius ; prototype::dims_data_t::chunks_and_blocks_t od ; ri.dd.calc_chunks_and_blocks( mouse_pos, so_math::vec2ui_t( radius ), od ) ; // draw chunk rect { so_math::vec2ui_t const dif = od.chunk_dif() ; for( uint_t x = 0; x <= dif.x(); ++x ) { so_math::vec2i_t start_draw = start + so_math::vec2i_t( od.chunk_min() ) * so_math::vec2i_t( chunk_dims ) + so_math::vec2i_t( chunk_dims ) * so_math::vec2i_t( x, 0 ) ; for( uint_t y=0; y<=dif.y(); ++y ) { _rnd_2d->get_rect_render_2d()->draw_rect( 50, start_draw + so_math::vec2f_t( chunk_dims ) * so_math::vec2f_t( 0.5f ), so_math::vec2f_t( 0.5f, 0.5f ), chunk_dims, 0.0f, so_math::vec4f_t( 0.4f ) ) ; start_draw += so_math::vec2i_t( chunk_dims ) * so_math::vec2i_t( 0, 1 ) ; } } } // draw block rect only if zoom is ok if( ri.zoom.greater_equal_than(so_math::vec2f_t( .2f )).any() ) { if( radius > 0 ) { so_math::vec2ui_t const start = od.block_min() * ri.dd.block_dims + ri.dd.block_dims / so_math::vec2ui_t( 2 ); so_math::vec2ui_t const dif = od.block_dif() ; for( uint_t x = 0; x <= dif.x(); ++x ) { so_math::vec2ui_t const pos_off = start + so_math::vec2i_t( int_t( x ), 0 ) * ri.dd.block_dims ; so_math::vec2i_t pos = ri.dd.transform_to_center( pos_off ) ; for( uint_t y = 0; y <= dif.y(); ++y ) { _rnd_2d->get_rect_render_2d()->draw_rect( 51, so_math::vec2f_t( pos ), so_math::vec2f_t( 0.5f, 0.5f ), so_math::vec2f_t( ri.dd.block_dims ), 0.0f, so_math::vec4f_t( 0.6f ) ) ; pos += so_math::vec2i_t( 0, 1 ) * ri.dd.block_dims ; } } } else { so_math::vec2i_t const start_draw = so_math::vec2i_t( start ) + ( so_math::vec2i_t( which_block ) - so_math::vec2i_t( radius ) )* so_math::vec2i_t( block_dims ) + so_math::vec2i_t( block_dims ) / so_math::vec2i_t( 2 ) ; _rnd_2d->get_rect_render_2d()->draw_rect( 50, start_draw, so_math::vec2f_t( 0.5f, 0.5f ), block_dims, 0.0f, so_math::vec4f_t( 0.6f ) ) ; } } } //****************************************************** void_t tool::test_mouse( test_info_cref_t info ) { so_math::vec2i_t const mouse_pos = so_math::vec2i_t( info.cam_pos + info.cur_mouse ) ; so_math::vec2ui_t const which_chunk = info.dd.calc_chunk_ij( mouse_pos ) ; so_math::vec2ui_t const which_block = info.dd.calc_block_ij_local( mouse_pos ) ; if( info.three_button == so_device::three_button::left && info.button_state == so_device::button_state::pressed ) { material_action ma ; ma.material_id = 0 ; ma.chunk = which_chunk ; ma.block = which_block ; ma.layer = 0 ; info.dd.calc_chunks_and_blocks( mouse_pos, _radius, ma.cb ) ; info.elptr->on_material( ma ) ; } else if( info.three_button == so_device::three_button::right && info.button_state == so_device::button_state::pressed ) { } else if( info.three_button == so_device::three_button::middle && info.button_state == so_device::button_state::pressed ) { } }<file_sep>/worldomat/game/world/chunk.cpp #include "chunk.h" #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> using namespace prototype ; //**************************************************************** chunk::chunk( so_math::vec2ui_cref_t dims ) { _width = dims.x() ; _height = dims.y() ; _blocks.resize( dims.x() * dims.y() ) ; } //**************************************************************** chunk::chunk( this_rref_t rhv ) { _blocks = std::move( rhv._blocks ) ; _width = rhv._width ; _height = rhv._height ; } //**************************************************************** chunk::~chunk( void_t ) { } //**************************************************************** chunk::this_ptr_t chunk::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_memory::global_t::alloc( std::move( rhv ), p ) ; } //**************************************************************** void_t chunk::destroy( this_ptr_t ptr ) { so_memory::global_t::dealloc( ptr ) ; } //**************************************************************** bool_t chunk::add_block( uint_t const i, uint_t const j, block_cref_t b ) { uint_t const index = ( j%_height ) * _width + i ; _blocks[ index ] = prototype::block_t(b) ; return true ; } //**************************************************************** bool_t chunk::get_block( uint_t const i, uint_t const j, block_ref_t bout ) { size_t const index = j * _width + i ; if( index >= _width * _height ) return false ; bout = _blocks[ index ] ; return true ; } //**************************************************************** void_t chunk::remove_block( size_t const i, size_t const j ) {} //**************************************************************** void_t chunk::render( uint_t const layer, so_math::vec2ui_cref_t ij, dims_data_cref_t dd, so_gfx::render_2d_ptr_t rnd ) { so_math::vec2i_t start = ij * dd.chunk_dims * dd.block_dims ; start += so_math::vec2i_t(dd.block_dims / so_math::vec2ui_t( 2 )) - so_math::vec2i_t((dd.layer_dims * dd.chunk_dims * dd.block_dims) /so_math::vec2ui_t(2)); #if 0 for( uint_t x=0; x<_width; ++x ) { for( uint_t y=0; y<_height; ++y ) { uint_t const index = y * _width + x ; auto const & b = _blocks[ index ] ; if( b.get_material().get_id() == size_t(-1) ) continue; so_math::vec2i_t const pos = (so_math::vec2ui_t(x,y) * dd.block_dims) ; rnd->get_rect_render_2d()->draw_rect( layer, start + pos, so_math::vec2f_t(0.5f), so_math::vec2f_t( dd.block_dims ), 0.0f, so_math::vec4f_t( 1 ) ) ; } } #endif rnd->get_rect_render_2d()->draw_rects( layer, _width * _height, [&]( size_t const index, so_gfx::rect_render_2d_t::rect_info_out_t ro ) { uint_t const x = uint_t(index) % _width ; uint_t const y = uint_t(index) / _width ; auto const & b = _blocks[ index ] ; if( b.get_material().get_id() == size_t( -1 ) ) return false; so_math::vec2i_t const pos = (so_math::vec2ui_t(x,y) * dd.block_dims) ; start + pos, so_math::vec2f_t( 0.5f ), so_math::vec2f_t( dd.block_dims ), 0.0f, so_math::vec4f_t( 1 ) ; ro.color = so_math::vec4f_t( 1 ) ; ro.pivot = so_math::vec2f_t( 0.5f ) ; ro.pos = start + pos; ro.rot = 0.0f ; ro.scale = so_math::vec2f_t( dd.block_dims ) ; return true ; } ) ; } <file_sep>/spritomat/app/app_initialize.cpp #include "app.h" #include <snakeoil/degui/system/system.h> #include <snakeoil/imex/global.h> #include <snakeoil/imex/system/isystem.h> #include <snakeoil/imex/module/module_registry.h> #include <snakeoil/imex/manager/manager_registry.h> #include <snakeoil/imex/manager/image_manager.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet_parser.h> #include <snakeoil/gfx/text/text_render_2d.h> #include <snakeoil/gfx/line/line_render_2d.h> #include <snakeoil/gfx/image/image_render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> #include <snakeoil/gfx/plugs/post_process/predef_post.h> #include <snakeoil/gfx/plugs/framebuffer/predef_framebuffer.h> #include <snakeoil/gfx/plugs/resource_bridge/resource_bridge.h> #include <snakeoil/gfx/sprite/sprite_manager.h> #include <snakeoil/font/glyph_atlas/glyph_atlas.h> #include <snakeoil/font/glyph_atlas/stb/stb_glyph_atlas_creator.h> #include <snakeoil/device/global.h> #include <snakeoil/device/system/device_system.h> #include <snakeoil/device/devices/mouse/three_button_mouse.h> #include <snakeoil/device/devices/keyboard/ascii_keyboard.h> #include <snakeoil/io/global.h> #include <snakeoil/thread/global.h> #include <snakeoil/thread/task/itask_scheduler.h> #include <snakeoil/math/utility/3d/orthographic_projection.hpp> using namespace examples ; //************************************************************************* so_appx::result my_app::on_initialize( so_appx::init_data_cref_t ) { // get some devices { _mouse = so_device::global::device_system()->find_three_button_mouse() ; _keyboard = so_device::global::device_system()->find_ascii_keyboard() ; } // init imgui { _imguis = so_imgui::system_t::create( so_imgui::system_t( this_t::rsys() ), "imgui system" ) ; _imguis->init() ; } // init text render { _text_rnd_ptr = so_gfx::text_render_2d_t::create( so_gfx::text_render_2d_t( this_t::rsys() ), "[] : text_render_2d" ) ; /*_text_rnd_ptr->init_fonts( 50, { so_io::path_t( so_std::string_t( PP_PROJECT_SRC_DIR ) + "/../assets/fonts/LCD_solid.ttf" ) } ) ;*/ } // init line render { _line_rnd_ptr = so_gfx::line_render_2d_t::create( so_gfx::line_render_2d_t( this_t::rsys() ), "[] : line_render_2d" ) ; _line_rnd_ptr->init() ; _line_rnd_ptr->set_view_projection( so_math::mat4f_t().identity(), //so_math::mat4f_t().identity() ) ; so_math::so_3d::orthographic<float_t>::create( 1920.0f, 1080.0f, 0.1f, 1000.0f ) ) ; } // sprite manager { _sp_mgr_ptr = so_gfx::sprite_manager_t::create( so_gfx::sprite_manager_t(_image_rnd_ptr), "][: sprite_manager" ) ; } { _rect_rnd_ptr = so_gfx::rect_render_2d_t::create( so_gfx::rect_render_2d_t( this_t::rsys() ), "[] : rect_render_2d" ) ; _rect_rnd_ptr->init() ; _rect_rnd_ptr->set_view_projection( so_math::mat4f_t().identity(), //so_math::mat4f_t().identity() ) ; so_math::so_3d::orthographic<float_t>::create( 1920.0f, 1080.0f, 0.1f, 1000.0f ) ) ; } // init framebuffer { so_gfx::predef_framebuffer_t fbp( so_gfx::predef_framebuffer_type::color888_alpha8, this_t::rsys() ) ; fbp.init( "scene", 1920, 1080 ) ; fbp.set_clear_color( so_math::vec4f_t( 0.4f, 0.3f, 0.7f, 1.0f ) ) ; _gfxp_fb = so_gfx::predef_framebuffer_t::create( std::move( fbp ), "][ : so_gfx::predef_framebuffer_t" ) ; } // init post blit { so_gfx::predef_post_t sp( so_gfx::predef_post_type::vignette, this_t::rsys() ) ; sp.set_source_rect( so_math::vec4f_t(0.0f,0.0f,1920.0f,1080.0f) ) ; sp.set_dest_rect( so_math::vec4f_t(0.0f,0.0f,1920.0f,1080.0f) ) ; sp.set_source_color_name( "scene_color_0" ) ; _gfxp_blit = so_gfx::predef_post_t::create( std::move( sp ), "][ : so_gfx::predef_post_t" ) ; } // init res bridge { so_gfx::resource_bridge_t rb( this_t::rsys() ) ; _res_brd_ptr = so_gfx::resource_bridge_t::create( std::move( rb ), "][ : so_gfx::resource_bridge_t" ) ; } // load sprite and upload { _file = "./assets/mario.xml" ; // in IDE mode, use PP_PROJECT_SRC_DIR, in distributed mode, use the exe's path _base_path = so_std::string_t( PP_PROJECT_SRC_DIR ) ; so_io::path_t xml_load_file = so_io::path_t( _base_path ) / _file ; so_std::string_t cnt ; { so_io::load_handle_t hnd = so_io::global_t::load( xml_load_file ) ; auto const res = hnd.wait_for_operation( [&] ( char_cptr_t cin, size_t sib, so_io::result r ) { if( r != so_io::result::ok ) return ; cnt = so_std::string_t( cin, sib ) ; } ) ; } so_imex::so_snakeoil::spritesheet_t ss = so_imex::so_snakeoil:: spritesheet_parser_t::from_string( cnt ) ; _ss_file = ss.uri ; so_imex::sync_object_t so ; so_imex::iimage_module_t::import_params ip ; ip.key = "sprites" ; if( ss.uri.is_relative() ) ip.path_to_file = xml_load_file.parent_path() / ss.uri ; else ip.path_to_file = ss.uri ; ip.sync_ptr = &so ; auto tg = std::move( so_imex::global_t::system()->get_module_registry()->import_image( ip ) ) ; so_thread::global_t::task_scheduler()->async_now( std::move( tg ) ) ; so.wait() ; _res_brd_ptr->upload_image( "sprites", "sprites" ) ; { so_imex::image_manager_t::handle_t hnd ; auto const res = so_imex::global_t::manager_registry()->get_image_manager()->acquire( "sprites", "reading image properties", hnd ) ; so_log::global_t::error_and_exit( so_core::is_not(res), "[] : image can not be missing here" ) ; auto * img = dynamic_cast< so_imex::image_ptr_t > ( hnd->data_ptr ) ; if( so_core::is_not_nullptr(img) ) { so_imgui::system_t::imgui_texture_data_t td ; td.name = "sprites" ; this_t::image_data_t id ; id.width = img->width ; id.height = img->height ; id.imgui_tx_id = so_memory::global_t::alloc( std::move( td ), "" ) ; id.img_ptr = img ; _images.push_back( std::move(id) ) ; } } this_t::load_from( ss ) ; } return so_appx::result::ok ; } //************************************************************************* so_appx::result my_app::has_initialized( void_t ) { _tp = clock_t::now() ; return so_appx::result::ok ; }<file_sep>/worldomat/app/app_initialize.cpp #include "app.h" #include <snakeoil/degui/system/system.h> #include <snakeoil/imex/global.h> #include <snakeoil/imex/system/isystem.h> #include <snakeoil/imex/module/module_registry.h> #include <snakeoil/imex/manager/manager_registry.h> #include <snakeoil/imex/manager/image_manager.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet_parser.h> #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/gfx/text/text_render_2d.h> #include <snakeoil/gfx/line/line_render_2d.h> #include <snakeoil/gfx/image/image_render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> #include <snakeoil/gfx/plugs/post_process/predef_post.h> #include <snakeoil/gfx/plugs/framebuffer/predef_framebuffer.h> #include <snakeoil/gfx/plugs/resource_bridge/resource_bridge.h> #include <snakeoil/gfx/sprite/sprite_manager.h> #include <snakeoil/font/glyph_atlas/glyph_atlas.h> #include <snakeoil/font/glyph_atlas/stb/stb_glyph_atlas_creator.h> #include <snakeoil/device/global.h> #include <snakeoil/device/system/device_system.h> #include <snakeoil/device/devices/mouse/three_button_mouse.h> #include <snakeoil/device/devices/keyboard/ascii_keyboard.h> #include <snakeoil/io/global.h> #include <snakeoil/thread/global.h> #include <snakeoil/thread/task/itask_scheduler.h> #include <snakeoil/math/utility/3d/orthographic_projection.hpp> using namespace prototype ; //************************************************************************* so_appx::result my_app::on_initialize( so_appx::init_data_cref_t ) { // get some devices { _mouse = so_device::global::device_system()->find_three_button_mouse() ; _keyboard = so_device::global::device_system()->find_ascii_keyboard() ; } // init imgui { _imguis = so_imgui::system_t::create( so_imgui::system_t( this_t::rsys() ), "imgui system" ) ; _imguis->init() ; } // init text render { _text_rnd_ptr = so_gfx::text_render_2d_t::create( so_gfx::text_render_2d_t( this_t::rsys() ), "[] : text_render_2d" ) ; /*_text_rnd_ptr->init_fonts( 50, { so_io::path_t( so_std::string_t( PP_PROJECT_SRC_DIR ) + "/../assets/fonts/LCD_solid.ttf" ) } ) ;*/ } // init render 2d { _rnd_2d = so_gfx::render_2d_t::create( so_gfx::render_2d_t( this_t::rsys() ), "[] : render_2d" ) ; _rnd_2d->init() ; _rnd_2d->set_view_projection( so_math::mat4f_t().identity(), //so_math::mat4f_t().identity() ) ; so_math::so_3d::orthographic<float_t>::create( _game_view.x(), _game_view.y(), 0.1f, 1000.0f ) ) ; } // sprite manager { _sp_mgr_ptr = so_gfx::sprite_manager_t::create( so_gfx::sprite_manager_t( _rnd_2d->get_image_render_2d() ), "][: sprite_manager" ) ; } // init framebuffer { so_gfx::predef_framebuffer_t fbp( so_gfx::predef_framebuffer_type::color888_alpha8, this_t::rsys() ) ; fbp.init( "scene", 1920, 1080 ) ; fbp.set_clear_color( so_math::vec4f_t( 0.0f,0.0f,0.0f, 1.0f ) ) ; _gfxp_fb = so_gfx::predef_framebuffer_t::create( std::move( fbp ), "][ : so_gfx::predef_framebuffer_t" ) ; } // init post blit { so_gfx::predef_post_t sp( so_gfx::predef_post_type::toscreen, this_t::rsys() ) ; sp.set_source_rect( so_math::vec4f_t(0.0f,0.0f,1920.0f,1080.0f) ) ; sp.set_dest_rect( so_math::vec4f_t(0.0f,0.0f,1920.0f,1080.0f) ) ; sp.set_source_color_name( "scene_color_0" ) ; _gfxp_blit = so_gfx::predef_post_t::create( std::move( sp ), "][ : so_gfx::predef_post_t" ) ; } // init res bridge { so_gfx::resource_bridge_t rb( this_t::rsys() ) ; _res_brd_ptr = so_gfx::resource_bridge_t::create( std::move( rb ), "][ : so_gfx::resource_bridge_t" ) ; } // init tool { _tool = prototype::tool_t::create( prototype::tool_t( this_t::rsys() ), "][ : Tool" ) ; this_t::set_tool_event_listener() ; } // init game { _game = prototype::game_t::create( prototype::game_t( this_t::rsys() ), "][ : game" ) ; prototype::dims_data_t const dd( _field_dims, _chunk_dims, _block_dims ) ; _game->init( dd ) ; _game->get_world()->add_block( 6, 5, 5, 0, 0, prototype::block_t(1) ) ; _game->get_world()->add_block( 4, 5, 5, 0, 0, prototype::block_t(1) ) ; _game->get_world()->add_block( 3, 5, 5, 0, 0, prototype::block_t(1) ) ; _game->get_world()->add_block( 1, 5, 5, 0, 0, prototype::block_t(1) ) ; _game->get_world()->add_block( 0, 5, 5, 0, 0, prototype::block_t(1) ) ; } return so_appx::result::ok ; } //************************************************************************* so_appx::result my_app::has_initialized( void_t ) { _tp = clock_t::now() ; return so_appx::result::ok ; }<file_sep>/worldomat/game/world/world.h #pragma once #include "layer.h" #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/std/container/vector.hpp> #include <snakeoil/core/types.hpp> #include <snakeoil/core/macros/typedef.h> namespace prototype { class world { so_this_typedefs( world ) ; private: static const size_t small_block = 8 ; static const size_t medium_block = 16 ; static const size_t big_block = 32 ; typedef byte_t chunk_byte_t ; static const size_t chunk_size = 32 ; private: struct data { uint_t layer_id ; layer_ptr_t lptr ; }; so_typedef( data ) ; so_typedefs( so_std::vector< data_t >, layers ) ; layers_t _layers ; dims_data_t _dims_data ; public: world( dims_data_cref_t dd ) ; world( this_cref_t ) = delete ; world( this_rref_t ) ; ~world( void_t ) ; public: static this_ptr_t create( this_rref_t, so_memory::purpose_cref_t ) ; static this_ptr_t destroy( this_ptr_t ) ; public: bool_t add_block( uint_t const l, uint_t const ci, uint_t const cj, uint_t const bi, uint_t const bj, block_cref_t ) ; bool_t add_block( uint_t const l, so_math::vec2ui_cref_t chunk_ij, so_math::vec2ui_cref_t block_ij, block_cref_t ) ; public: typedef std::function< void_t ( uint_t const l, layer_ptr_t ) > for_each_layer_funk_t ; void for_each_layer( for_each_layer_funk_t ) ; public: struct render_info { so_math::vec2i_t cam_pos ; so_math::vec2ui_t view_area_radius ; prototype::dims_data_t dd ; so_gfx::render_2d_ptr_t rnd ; }; so_typedef( render_info ) ; void_t render( render_info_in_t ) ; public: struct layer_info { size_t lid ; layer_ptr_t lptr ; }; so_typedef( layer_info ) ; size_t get_num_layers( void_t ) const ; layer_info_t get_layer( size_t const ) ; private: layer_ptr_t find_or_add_layer( uint_t const l ) ; }; so_typedef( world ) ; }<file_sep>/worldomat/game/typedefs.h #pragma once #include <snakeoil/memory/global.h> #include <snakeoil/core/types.hpp> namespace prototype { using namespace so_core::so_types ; }<file_sep>/worldomat/game/dims_data.h #pragma once #include "typedefs.h" #include <snakeoil/collide/2d/bounds/aabb.hpp> #include <snakeoil/math/vector/vector2.hpp> namespace prototype { struct dims_data { so_this_typedefs( dims_data ) ; /// in chunks per layer so_math::vec2ui_t layer_dims ; /// in blocks per chunk so_math::vec2ui_t chunk_dims ; /// in pixels per block so_math::vec2ui_t block_dims ; dims_data( void_t ){} dims_data( so_math::vec2ui_cref_t ldims, so_math::vec2ui_cref_t cdims, so_math::vec2ui_cref_t bdims ) { layer_dims = ldims ; chunk_dims = cdims ; block_dims = bdims ; } dims_data( this_cref_t rhv ) { layer_dims = rhv.layer_dims ; chunk_dims = rhv.chunk_dims ; block_dims = rhv.block_dims ; } this_ref_t operator = ( this_cref_t rhv ) { layer_dims = rhv.layer_dims ; chunk_dims = rhv.chunk_dims ; block_dims = rhv.block_dims ; return *this ; } //************************************************************************** so_math::vec2i_t transform_to_center( so_math::vec2ui_cref_t pos ) const { auto const dims = block_dims * chunk_dims * layer_dims ; auto const dims_half = dims / so_math::vec2ui_t( 2 ) ; return pos - dims_half ; } //************************************************************************** /// @param pos in pixels from the center of the field so_math::vec2ui_t calc_chunk_ij( so_math::vec2i_cref_t pos ) const { auto const cdims = block_dims * chunk_dims ; auto const cdims_half = cdims / so_math::vec2ui_t( 2 ) ; auto const dims = cdims * layer_dims ; auto const dims_half = dims / so_math::vec2ui_t( 2 ) ; so_math::vec2ui_t const pos_global = dims_half + pos ; return pos_global / cdims ; } //************************************************************************** /// @param pos in pixels from the center of the field so_math::vec2ui_t calc_block_ij_global( so_math::vec2i_cref_t pos ) const { auto const cdims = block_dims * chunk_dims ; auto const cdims_half = cdims / so_math::vec2ui_t( 2 ) ; auto const dims = cdims * layer_dims ; auto const dims_half = dims / so_math::vec2ui_t( 2 ) ; so_math::vec2ui_t const pos_global = dims_half + pos ; return pos_global / block_dims ; } //************************************************************************** /// @param pos in pixels from the center of the field so_math::vec2ui_t calc_block_ij_local( so_math::vec2i_cref_t pos ) const { return this_t::calc_block_ij_global( pos ) % chunk_dims ; } //************************************************************************** /// pass global block ij and get chunk ij and local block ij void global_to_local( so_math::vec2ui_in_t global_ij, so_math::vec2ui_out_t chunk_ij, so_math::vec2ui_out_t local_ij ) const { chunk_ij = global_ij / chunk_dims ; local_ij = global_ij % chunk_dims ; } //************************************************************************** /// world space chunk bounding box so_collide::so_2d::aabbf_t calc_chunk_bounds( uint_t const ci, uint_t const cj ) const { so_math::vec2ui_t const ij( ci, cj ) ; auto const cdims = block_dims * chunk_dims ; auto const cdims_half = cdims / so_math::vec2ui_t( 2 ) ; auto const dims = cdims * layer_dims ; auto const dims_half = dims / so_math::vec2ui_t(2) ; so_math::vec2i_t const start = so_math::vec2i_t(dims_half).negated() ; so_math::vec2f_t const min = start + cdims * ( ij + so_math::vec2ui_t( 0 ) ) ; so_math::vec2f_t const max = start + cdims * ( ij + so_math::vec2ui_t( 1 ) ) ; return so_collide::so_2d::aabbf_t( min, max ) ; } //************************************************************************** so_collide::so_2d::aabbf_t calc_block_bounds( uint_t const ci, uint_t const cj ) const { return so_collide::so_2d::aabbf_t() ; } struct chunks_and_blocks { so_math::vec2ui_t chunks[4] ; so_math::vec2ui_t blocks[4] ; so_math::vec2ui_t block_dif( void_t ) const { return blocks[ 2 ] - blocks[ 0 ] ; } so_math::vec2ui_t block_min( void_t ) const { return blocks[ 0 ] ; } so_math::vec2ui_t chunk_dif( void_t ) const { return chunks[ 2 ] - chunks[ 0 ] ; } so_math::vec2ui_t chunk_min( void_t ) const { return chunks[ 0 ] ; } }; so_typedef( chunks_and_blocks ) ; //************************************************************************** void calc_chunks_and_blocks( so_math::vec2i_cref_t pos, so_math::vec2ui_cref_t radius, chunks_and_blocks_ref_t od ) const { // blocks { auto const ij = this_t::calc_block_ij_global( pos ) ; auto const min = ij - so_math::vec2ui_t( radius ) ; auto const max = ij + so_math::vec2ui_t( radius ) ; od.blocks[ 0 ] = min ; od.blocks[ 1 ] = so_math::vec2ui_t( min.x(), max.y() ) ; od.blocks[ 2 ] = max ; od.blocks[ 3 ] = so_math::vec2ui_t( max.x(), min.y() ) ; } // chunks { for( size_t i=0; i<4; ++i ) { od.chunks[i] = od.blocks[ i ] / chunk_dims ; } } } }; so_typedef( dims_data ) ; }<file_sep>/worldomat/game/util/camera.h #pragma once #include "../typedefs.h" #include <snakeoil/math/matrix/matrix4.hpp> namespace prototype { struct camera { so_math::mat4f_t view ; so_math::mat4f_t proj ; }; so_typedef( camera ) ; }<file_sep>/worldomat/game/world/world.cpp #include "world.h" #include <snakeoil/memory/global.h> #include <snakeoil/log/global.h> #include <algorithm> using namespace prototype ; //**************************************************** world::world( dims_data_cref_t dd ) : _dims_data(dd) {} //**************************************************** world::world( this_rref_t rhv ) : _dims_data( rhv._dims_data) {} //**************************************************** world::~world( void_t ) { } //**************************************************** world::this_ptr_t world::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_memory::global_t::alloc( std::move(rhv), p ) ; } //**************************************************** world::this_ptr_t world::destroy( this_ptr_t p ) { return so_memory::global_t::dealloc( p ) ; } //**************************************************** bool_t world::add_block( uint_t const l, uint_t const ci, uint_t const cj, uint_t const bi, uint_t const bj, block_cref_t b ) { layer_ptr_t layer = this_t::find_or_add_layer( l ) ; so_assert( so_core::is_not_nullptr( layer ) ) ; return layer->add_block( ci, cj, bi, bj, b ) ; } //**************************************************** bool_t world::add_block( uint_t const l, so_math::vec2ui_cref_t chunk_ij, so_math::vec2ui_cref_t block_ij, block_cref_t b ) { return this_t::add_block( l, chunk_ij.x(), chunk_ij.y(), block_ij.x(), block_ij.y(), b ) ; } //**************************************************** layer_ptr_t world::find_or_add_layer( uint_t const lid ) { // 1. try find auto iter = std::find_if( _layers.begin(), _layers.end(), [&] ( data_cref_t d ) { return d.layer_id == lid ; } ) ; // 2. not found insert ordered if( iter == _layers.end() ) { this_t::data_t d ; d.layer_id = lid ; d.lptr = prototype::layer_t::create( layer_t( _dims_data ), "[world::find_or_add_layer] : layer" ) ; iter = std::find_if( _layers.begin(), _layers.end(), [&] ( data_cref_t d ) { return d.layer_id > lid ; } ) ; iter = _layers.insert( iter, d ) ; } return iter->lptr ; } //**************************************************** void world::for_each_layer( for_each_layer_funk_t funk ) { for( auto & l : _layers ) { funk( l.layer_id, l.lptr ) ; } } //**************************************************** void_t world::render( render_info_in_t ri ) { prototype::dims_data_t::chunks_and_blocks_t cb ; // 1. compute involved chunks { auto const rad = ri.view_area_radius / ri.dd.block_dims + so_math::vec2ui_t( 1 ) ; ri.dd.calc_chunks_and_blocks( ri.cam_pos, rad, cb ) ; } // 2. render only involved chunks for each layer for( auto & l : _layers ) { prototype::layer_t::render_info_t lri ; lri.rnd = ri.rnd ; lri.cbs = cb ; l.lptr->render( l.layer_id, lri ) ; } } //**************************************************** size_t world::get_num_layers( void_t ) const { return _layers.size() ; } //**************************************************** world::layer_info_t world::get_layer( size_t const l ) { return layer_info_t( { _layers[ l ].layer_id, _layers[ l ].lptr } ) ; }<file_sep>/worldomat/app/app.cpp #include "app.h" #include <snakeoil/appx/system/window_state_informer.h> #include <snakeoil/application/window/window_message.h> #include <snakeoil/degui/system/system.h> #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/gfx/text/text_render_2d.h> #include <snakeoil/gfx/line/line_render_2d.h> #include <snakeoil/gfx/image/image_render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> #include <snakeoil/gfx/plugs/post_process/predef_post.h> #include <snakeoil/gfx/plugs/framebuffer/predef_framebuffer.h> #include <snakeoil/gfx/plugs/resource_bridge/resource_bridge.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet_parser.h> #include <snakeoil/io/global.h> #include <snakeoil/log/global.h> using namespace prototype ; //************************************************************************* my_app::my_app( void_t ) { // add viewport variable { _vp_window_ptr = so_flow::variable<so_gpu::viewport_2d_t>::create( so_gpu::viewport_2d_t(), "[my_app] : window viewport" ) ; _vs.add( "vp_window", _vp_window_ptr ) ; _vn.create_output_connections( _vs ) ; } } //************************************************************************* my_app::my_app( this_rref_t rhv ) { _vn = std::move( rhv._vn ) ; _vs = std::move( rhv._vs ) ; so_move_member_ptr( _vp_window_ptr, rhv ) ; so_move_member_ptr( _text_rnd_ptr, rhv ) ; so_move_member_ptr( _res_brd_ptr, rhv ) ; so_move_member_ptr( _sp_mgr_ptr, rhv ) ; so_move_member_ptr( _gfxp_fb, rhv ) ; so_move_member_ptr( _gfxp_blit, rhv ) ; so_move_member_ptr( _rnd_2d, rhv ) ; so_move_member_ptr( _tool, rhv ) ; so_move_member_ptr( _game, rhv ) ; } //************************************************************************* my_app::~my_app( void_t ) { prototype::game_t::destroy( _game ) ; prototype::tool_t::destroy( _tool ) ; so_gfx::text_render_2d_t::destroy( _text_rnd_ptr ) ; so_gfx::predef_post_t::destroy( _gfxp_blit ) ; so_gfx::predef_framebuffer_t::destroy( _gfxp_fb ) ; so_gfx::resource_bridge_t::destroy( _res_brd_ptr ) ; so_gfx::render_2d_t::destroy( _rnd_2d ) ; // destroy via rref assignment operator _vs = so_flow::variable_set_t() ; _vn = so_flow::variable_node_t() ; so_imgui::system_t::destroy( _imguis ) ; } //************************************************************************* my_app::this_ptr_t my_app::create( void_t ) { return so_memory::global::alloc( this_t(), "" ) ; } //************************************************************************* void_t my_app::destroy( this_ptr_t ptr ) { so_memory::global::dealloc( ptr ) ; } //************************************************************************* so_appx::result my_app::on_shutdown( void_t ) { _text_rnd_ptr->release() ; _rnd_2d->release() ; _imguis->release() ; return so_appx::result::ok ; } //************************************************************************* so_appx::result my_app::destroy( void_t ) { this_t::destroy( this ) ; return so_appx::result::ok ; } //************************************************************************* so_appx::result my_app::on_event( so_appx::window_event_data_cref_t we ) { { so_app::resize_message_t msg ; if( we.wsi->has_resize_message( msg ) ) { _vp_window_ptr->set_data( so_gpu::viewport_2d( msg.x, msg.y, msg.w, msg.h ) ) ; } } return so_appx::result::ok ; } //************************************************************************* void_t my_app::save_to_file( void_t ) { } //************************************************************************* void_t my_app::load_from( so_imex::so_snakeoil::spritesheet_cref_t ss ) { } //************************************************************************* so_math::vec2f_t my_app::calc_game_view( void_t ) const { return _game_view / _zoom ; } //************************************************************************* so_math::vec2f_t my_app::cam_pos( void_t ) const { return _cam_pos ; } //************************************************************************* dims_data_t my_app::get_dims_data( void_t ) const { return dims_data_t( _field_dims, _chunk_dims, _block_dims ) ; }<file_sep>/CMakeLists.txt cmake_minimum_required( VERSION 3.6 ) project( "prototypes" ) find_package( snakeoil ) set( SUBDIRS spritomat worldomat ) foreach( _SUBDIR ${SUBDIRS} ) set( CUR_LIB_NAME "${PROJECT_NAME}_${_SUBDIR}" ) add_subdirectory(${_SUBDIR}) endforeach() so_vs_gen_bat_for_dlls() <file_sep>/worldomat/app/app_update.cpp #include "app.h" #include <snakeoil/degui/system/system.h> #include <snakeoil/device/devices/mouse/three_button_mouse.h> #include <snakeoil/device/devices/keyboard/ascii_keyboard.h> #include <snakeoil/animation/keyframe_sequence/linear_keyframe_sequence.hpp> using namespace prototype ; //************************************************************************* so_appx::result my_app::on_update( so_appx::update_data_cref_t ud ) { if( so_core::is_not_nullptr( _keyboard ) ) { if( _keyboard->is_pressing( so_device::ascii_key::escape ) && _keyboard->is_pressing( so_device::ascii_key::shift_left )) { return so_appx::terminate ; } if( _keyboard->is_released( so_device::ascii_key::q ) ) {} if( _keyboard->is_released( so_device::ascii_key::f1 ) ) { _toggle_all_gui = !_toggle_all_gui ; if( _toggle_all_gui ) { if( !_show_tool && !_show_imgui ) _show_gui.x( true ) ; _show_tool = _show_gui.x() ; _show_imgui = _show_gui.y() ; } else { _show_tool = false ; _show_imgui = false ; } } else if( _keyboard->is_released( so_device::ascii_key::f2 ) ) { _show_gui.x( !_show_gui.x() ) ; _show_tool = _show_gui.x() ; } else if( _keyboard->is_released( so_device::ascii_key::f3 ) ) { _show_gui.y( !_show_gui.y() ) ; _show_imgui = _show_gui.y() ; } } bool_t imgui_want_mouse = false ; if( _show_tool ) { _imguis->check_status( [&] ( ImGuiContext * ctx, so_imgui::system_ptr_t self ) { ImGui::SetCurrentContext( ctx ) ; auto & io = ImGui::GetIO() ; imgui_want_mouse = so_core::is_not( io.WantCaptureMouse ) ; } ) ; } if( so_core::is_not_nullptr( _mouse ) ) { auto const p = _mouse->get_local_position( so_math::vec2f_t( 0.5f, 0.5f ) ) * this_t::calc_game_view() ; // tool mouse hit { prototype::tool_t::test_info ri ; so_math::vec2ui_t const field_dims = _chunk_dims * _block_dims ; ri.cam_pos = this_t::cam_pos() ; ri.cam_view = _game_view ; ri.zoom = _zoom ; ri.cur_mouse = p ; ri.dd = prototype::dims_data_t( _field_dims, _chunk_dims, _block_dims ) ; ri.elptr = _tevl_ptr ; { auto const ts = so_device::three_button::left ; ri.three_button = ts ; ri.button_state = _mouse->get_button_state( ts ) ; _tool->test_mouse( ri ) ; } { auto const ts = so_device::three_button::middle ; ri.three_button = ts ; ri.button_state = _mouse->get_button_state( ts ) ; _tool->test_mouse( ri ) ; } { auto const ts = so_device::three_button::right ; ri.three_button = ts ; ri.button_state = _mouse->get_button_state( ts ) ; _tool->test_mouse( ri ) ; } } if( _mouse->is_pressed( so_device::three_button::middle ) ) { _mouse_down_pos = p ; } else if( _mouse->is_pressing( so_device::three_button::middle ) ) { _cam_pos = _lock_cam_pos + (p-_mouse_down_pos) ; } else if( _mouse->is_released( so_device::three_button::middle ) ) { _mouse_down_pos = so_math::vec2f_t() ; _lock_cam_pos = _cam_pos ; } // zoom { auto const s = _mouse->get_scroll() ; _zoom += so_math::vec2f_t( float_t( s ) ) * ( _zoom.greater_equal_than( so_math::vec2f_t( 1.5f ) ).any() ? so_math::vec2f_t( .5f ) : so_math::vec2f_t( .1f ) ) ; _zoom.x( std::min( std::max( 0.1f, _zoom.x() ), 10.0f ) ) ; _zoom.y( std::min( std::max( 0.1f, _zoom.y() ), 10.0f ) ) ; } // mouse hit { so_math::vec2f_t const pos = _mouse->get_local_position( so_math::vec2f_t( 0.5f, 0.5f ) ) ; _cur_mouse_pos = pos * so_math::vec2f_t( _screen_dims.get_width_height<float_t>() ) ; _cur_mouse_pos_minus_plus = pos ; } } _tool->update() ; _game->update() ; return so_appx::result::ok ; }<file_sep>/worldomat/app/app.h #pragma once #include "../typedefs.h" #include "../tool/tool.h" #include "../game/game.h" #include <snakeoil/appx/app/app.h> #include <snakeoil/gfx/protos.h> #include <snakeoil/degui/protos.h> #include <snakeoil/gpx/technique/technique_id.h> #include <snakeoil/gpu/viewport/viewport_2d.h> #include <snakeoil/flow/variable/variable.hpp> #include <snakeoil/flow/variable/variable_set.h> #include <snakeoil/flow/node/variable/variable_node.h> #include <snakeoil/degui/protos.h> #include <snakeoil/degui/system/system.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet.h> namespace prototype { using namespace so_core::so_types ; //******************************************************************************* class my_app : public so_appx::app { so_this_typedefs( my_app ) ; private: // gpx techniques so_gfx::predef_framebuffer_ptr_t _gfxp_fb = nullptr ; so_gfx::predef_post_ptr_t _gfxp_blit = nullptr ; private: // gfx stuff so_gfx::text_render_2d_ptr_t _text_rnd_ptr = nullptr ; so_gfx::resource_bridge_ptr_t _res_brd_ptr = nullptr ; so_gfx::sprite_manager_ptr_t _sp_mgr_ptr = nullptr ; so_gfx::render_2d_ptr_t _rnd_2d = nullptr ; private: // node so_flow::variable<so_gpu::viewport_2d_t> * _vp_window_ptr = nullptr ; so_flow::variable_set_t _vs ; so_flow::variable_node_t _vn ; private: // camera so_math::vec2f_t _lock_cam_pos = so_math::vec2f_t(0.0f,0.0f) ; so_math::vec2f_t _cam_pos = so_math::vec2f_t(0.0f,0.0f) ; so_math::mat4f_t _view ; so_math::mat4f_t _proj ; /// width and height of the viewing area so_math::vec2f_t _game_view = so_math::vec2f_t( 1920.0f/1.0f, 1080.0f/1.0f ) ; private: // devices so_device::three_button_mouse_ptr_t _mouse = nullptr ; so_device::ascii_keyboard_ptr_t _keyboard = nullptr ; so_math::vec2f_t _mouse_down_pos ; private: // imgui / ui so_imgui::system_ptr_t _imguis = nullptr ; bool_t _toggle_all_gui = true ; so_math::vec2b_t _show_gui = so_math::vec2b_t(true, true) ; bool_t _show_tool = true ; bool_t _show_imgui = true ; bool_t _show_imgui_demo = false ; so_math::vec2f_t _cur_mouse_pos ; so_math::vec2f_t _cur_mouse_pos_minus_plus ; prototype::tool_ptr_t _tool ; prototype::tool_t::event_listener_ptr_t _tevl_ptr = nullptr ; void_t set_tool_event_listener( void_t ) ; class tool_event_listener ; so_typedef( tool_event_listener ) ; friend class tool_event_listener ; private: // game //so_math::vec2ui_t _dims = so_math::vec2ui_t( 20000 ) ; so_math::vec2f_t _zoom = so_math::vec2f_t( 1.0f ) ; /// how many chunks per layer so_math::vec2ui_t _field_dims = so_math::vec2ui_t( 10 ) ; /// how many blocks per chunk so_math::vec2ui_t _chunk_dims = so_math::vec2ui_t( 32 ) ; /// how many pixels per block so_math::vec2ui_t _block_dims = so_math::vec2ui_t( 32 ) ; prototype::game_ptr_t _game = nullptr ; public: dims_data_t get_dims_data( void_t ) const ; private: so_typedefs( std::chrono::high_resolution_clock, clock ) ; clock_t::time_point _tp ; size_t accum = 0 ; private: so_math::viewport_2d_t _screen_dims = so_math::viewport_2d_t( 0, 0, 1920, 1080 ) ; so_math::vec2f_t _bb_dims = so_math::vec2f_t( 1920.0f, 1080.0f ) ; public: my_app( void_t ) ; my_app( this_rref_t rhv ) ; my_app( this_cref_t ) = delete ; virtual ~my_app( void_t ) ; public: static this_ptr_t create( void_t ) ; static void_t destroy( this_ptr_t ptr ) ; public: virtual so_appx::result on_update( so_appx::update_data_cref_t ud ) ; virtual so_appx::result on_render( so_appx::render_data_cref_t rd ) ; virtual so_appx::result on_initialize( so_appx::init_data_cref_t ) ; virtual so_appx::result has_initialized( void_t ) ; virtual so_appx::result on_event( so_appx::window_event_data_cref_t we ) ; virtual so_appx::result on_activate( void_t ) { return so_appx::result::ok ; } virtual so_appx::result has_activated( void_t ) { return so_appx::result::ok ; } virtual so_appx::result on_deactivate( void_t ) { return so_appx::result::ok ; } virtual so_appx::result has_deactivated( void_t ) { return so_appx::result::ok ; } virtual so_appx::result on_shutdown( void_t ) ; virtual so_appx::result has_shutdown( void_t ) { return so_appx::result::ok ; } virtual so_appx::result destroy( void_t ) ; private: // void_t render_begin( so_appx::render_data_cref_t rd ) ; void_t render_end( so_appx::render_data_cref_t rd ) ; void_t draw_imgui( so_appx::render_data_cref_t rd ) ; void_t save_to_file( void_t ) ; void_t load_from( so_imex::so_snakeoil::spritesheet_cref_t ) ; so_math::vec2f_t calc_game_view( void_t ) const ; so_math::vec2f_t cam_pos( void_t ) const ; private: // base of xml so_io::path_t _base_path ; // xml file so_io::path_t _file ; // sprite sheet image file name from // xml description file so_io::path_t _ss_file ; }; so_typedef( my_app ) ; }<file_sep>/worldomat/game/world/chunk.h #pragma once #include "block.h" #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/std/container/vector.hpp> #include <snakeoil/math/vector/vector2.hpp> #include <snakeoil/core/types.hpp> #include <snakeoil/core/macros/typedef.h> namespace prototype { class chunk { so_this_typedefs( chunk ) ; private: so_typedefs( so_std::vector< block_t >, blocks ) ; blocks_t _blocks ; uint_t _width = 0 ; uint_t _height = 0 ; public: chunk( so_math::vec2ui_cref_t dims ) ; chunk( this_rref_t ) ; chunk( this_cref_t ) = delete ; ~chunk( void_t ) ; static this_ptr_t create( this_rref_t, so_memory::purpose_cref_t ) ; static void_t destroy( this_ptr_t ) ; public: bool_t add_block( uint_t const i, uint_t const j, block_cref_t ) ; bool_t get_block( uint_t const i, uint_t const j, block_ref_t ) ; void_t remove_block( size_t const i, size_t const j ) ; public: void_t render( uint_t const layer, so_math::vec2ui_cref_t ij, dims_data_cref_t, so_gfx::render_2d_ptr_t ) ; }; so_typedef( chunk ) ; }<file_sep>/worldomat/game/world/block.h #pragma once #include "../typedefs.h" #include "../dims_data.h" #include "../material/material_id.h" namespace prototype { class block { so_this_typedefs( block ) ; private: material_id_t _mid ; public: block( void_t ) ; block( material_id_t ) ; block( this_cref_t ) ; block( this_rref_t ) ; ~block( void_t ) ; public: static this_ptr_t create( this_rref_t, so_memory::purpose_cref_t ) ; static this_ptr_t destroy( this_ptr_t ) ; public: material_id get_material( void_t ) const ; public: this_ref_t operator = ( this_cref_t ) ; this_ref_t operator = ( this_rref_t ) ; }; so_typedef( block ) ; }<file_sep>/worldomat/app/app_render.cpp #include "app.h" #include "../game/dims_data.h" #include <snakeoil/degui/system/system.h> #include <snakeoil/flow/walker/serial_node_walker.h> #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/gfx/text/text_render_2d.h> #include <snakeoil/gfx/line/line_render_2d.h> #include <snakeoil/gfx/image/image_render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> #include <snakeoil/gfx/plugs/post_process/predef_post.h> #include <snakeoil/gfx/plugs/framebuffer/predef_framebuffer.h> #include <snakeoil/gfx/sprite/sprite_manager.h> #include <snakeoil/device/devices/mouse/three_button_mouse.h> #include <snakeoil/device/component/keys/ascii_key.h> #include <snakeoil/collide/2d/bounds/aabb.hpp> #include <snakeoil/log/logger/store_logger.h> #include <snakeoil/log/global.h> #include <snakeoil/collide/2d/bounds/aabb.hpp> #include <snakeoil/animation/keyframe_sequence/linear_keyframe_sequence.hpp> #include <snakeoil/math/vector/vector2b.hpp> #include <snakeoil/math/utility/fn.hpp> #include <snakeoil/math/utility/3d/look_at.hpp> #include <snakeoil/math/utility/3d/orthographic_projection.hpp> #include <random> using namespace prototype ; //************************************************************************* so_appx::result my_app::on_render( so_appx::render_data_cref_t rd ) { _rnd_2d->set_view_projection( _view, _proj ) ; this_t::render_begin( rd ) ; // draw mouse pos /*{ _rnd_2d->get_rect_render_2d()->draw_rect( 0, _cur_mouse_pos, so_math::vec2f_t( 0.5f, 0.5f ), so_math::vec2f_t( 5.0f ), 0.0f, so_math::vec4f_t( 1.0f ) ) ; }*/ // render game { prototype::game_t::render_info_t ri ; ri.rnd = _rnd_2d ; ri.cam_pos = this_t::cam_pos() ; ri.dd = prototype::dims_data_t( _field_dims, _chunk_dims, _block_dims ) ; ri.view_area_radius = so_math::vec2ui_t( this_t::calc_game_view() * so_math::vec2f_t(0.5f) ) ; _game->render( ri) ; } // render tool if( _show_tool ) { prototype::tool_t::render_info_t ri ; prototype::camera_t cam ; cam.view = _view ; cam.proj = _proj ; so_math::vec2ui_t const field_dims = _chunk_dims * _block_dims ; ri.cam = cam ; ri.cam_pos = this_t::cam_pos() ; ri.cam_view = _game_view ; ri.zoom = _zoom ; ri.cur_mouse = _cur_mouse_pos_minus_plus * this_t::calc_game_view() ; ri.dd = prototype::dims_data_t( _field_dims, _chunk_dims, _block_dims ) ; _tool->render( ri ) ; } if( _show_imgui ) { _tool->render_imgui( _imguis ) ; } this_t::render_end( rd ) ; return so_appx::result::ok ; } //************************************************************************* void_t my_app::render_begin( so_appx::render_data_cref_t rd ) { // update camera { so_math::mat4f_t cam ; so_math::so_3d::create_lookat_dir<float_t>( so_math::vec3f_t( this_t::cam_pos(), 0.0f ), so_math::vec3f_t(0.0f,0.0f,1.0f), cam ) ; so_math::so_3d::create_view_matrix( cam, _view ) ; _proj = so_math::so_3d::orthographic<float_t>::create( calc_game_view().x(), calc_game_view().y(), 0.1f, 1000.0f ) ; } if( _show_imgui ) { _imguis->begin_draw( rd.dts, _vp_window_ptr->get_data().get_width(), _vp_window_ptr->get_data().get_height(), _vp_window_ptr->get_data().get_width(), _vp_window_ptr->get_data().get_height() ); } { so_gfx::text_render_2d_t::canvas_info_t ci ; ci.vp = _vp_window_ptr->get_data() ; _text_rnd_ptr->set_canvas_info( ci ) ; } // update time { auto dur = clock_t::now() - _tp ; size_t const dt = std::chrono::duration_cast< std::chrono::microseconds >( dur ).count() ; _tp = clock_t::now() ; accum += dt ; } // update parameters for rendering { so_flow::serial_node_walker_t snw ; snw.walk( { &_vn } ) ; } // begin on screen stuff rendering { _gfxp_fb->schedule_for_begin() ; _gfxp_fb->schedule_for_clear() ; } } //************************************************************************* void_t my_app::render_end( so_appx::render_data_cref_t rd ) { _rnd_2d->prepare_for_rendering() ; _rnd_2d->render_range( 0, 100 ) ; { _gfxp_blit->set_dest_rect( _vp_window_ptr->get_data() ) ; _gfxp_blit->schedule() ; } { if( _show_imgui ) { this_t::draw_imgui( rd ) ; // render all _imguis->render( 0 ) ; } } } //************************************************************************* void_t my_app::draw_imgui( so_appx::render_data_cref_t rd ) { _imguis->draw( [=] ( ImGuiContext * ctx, so_imgui::system_ptr_t self ) { ImGui::SetCurrentContext( ctx ) ; if( ImGui::BeginMainMenuBar() ) { if( ImGui::BeginMenu( "File" ) ) { if( ImGui::MenuItem( "Save", "CTRL+S" ) ) { this_t::save_to_file() ; } ImGui::EndMenu() ; } if( ImGui::BeginMenu( "Options" ) ) { if( ImGui::MenuItem( "Show ImGui Demo", "", &_show_imgui_demo ) ) { } ImGui::EndMenu() ; } ImGui::EndMainMenuBar() ; } if( _show_imgui_demo ) { ImGui::ShowDemoWindow() ; } // render logger { auto * logger = so_log::global_t::get_store() ; auto const a = logger->get_max_items() ; auto const b = logger->get_num_items() ; ImGui::Begin( "Log Window" ); ImGui::BeginChild( "Console Scrollarea" ) ; so_std::vector< so_log::store_logger::store_data > data ; ImGuiListClipper clip( ( int_t ) b ); while( clip.Step() ) { //for( int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++ ) logger->for_each( size_t( clip.DisplayStart ), size_t( clip.DisplayEnd ), [&] ( so_log::store_logger_t::store_data_cref_t d ) { ImVec4 col = ImGui::GetStyleColorVec4( ImGuiCol_Text ); if( d.ll == so_log::log_level::error ) col = ImColor( 1.0f, 0.4f, 0.4f, 1.0f ) ; else if( d.ll == so_log::log_level::warning ) col = ImColor( 1.0f, 1.0f, 0.4f, 1.0f ) ; else if( d.ll == so_log::log_level::status ) col = ImColor( 0.1f, 1.0f, 0.1f, 1.0f ) ; ImGui::PushStyleColor( ImGuiCol_Text, col ); ImGui::TextUnformatted( d.msg.c_str() ); ImGui::PopStyleColor(); } ) ; } ImGui::EndChild(); ImGui::End() ; } { ImGui::Begin( "Reload Techniques" ); //if( ImGui::Button( "Reload gfx post" ) ) { // _gfxp_blit->schedule_for_reload() ; } ImGui::End() ; } // game stats { ImGui::Begin( "Global Parameters" ); // zoom { float_t zoom[ 1 ] = { _zoom.x() } ; if( ImGui::SliderFloat( "Zoom", zoom, 0.1f, 10.0f ) ) { _zoom = so_math::vec2f_t( zoom[ 0 ], zoom[ 0 ] ) ; } } //if( ImGui::Button( "Reload gfx post" ) ) { // _gfxp_blit->schedule_for_reload() ; } ImGui::End() ; } // change input params { ImGuiIO & io = ImGui::GetIO(); } // layout { ImGui::Begin( "Editor" ); ImGui::End() ; } { ImGui::Begin( "Some Values" ); { prototype::dims_data_t const dd( _field_dims, _chunk_dims, _block_dims ) ; auto const p = so_math::vec2i_t( _cam_pos + ( _game_view / _zoom ) * _cur_mouse_pos_minus_plus ) ; { auto const ij = dd.calc_chunk_ij( p ) ; ImGui::SliderInt2( "Chunk ij", ( int_ptr_t ) ( &ij ), 0, dd.layer_dims.x() ) ; } { auto const ij = dd.calc_block_ij_local( p ) ; ImGui::SliderInt2( "Block ij", ( int_ptr_t ) ( &ij ), 0, dd.chunk_dims.x() ) ; } } ImGui::End() ; } } ) ; }<file_sep>/spritomat/app/app.cpp #include "app.h" #include <snakeoil/appx/system/window_state_informer.h> #include <snakeoil/application/window/window_message.h> #include <snakeoil/degui/system/system.h> #include <snakeoil/gfx/text/text_render_2d.h> #include <snakeoil/gfx/line/line_render_2d.h> #include <snakeoil/gfx/image/image_render_2d.h> #include <snakeoil/gfx/rect/rect_render_2d.h> #include <snakeoil/gfx/plugs/post_process/predef_post.h> #include <snakeoil/gfx/plugs/framebuffer/predef_framebuffer.h> #include <snakeoil/gfx/plugs/resource_bridge/resource_bridge.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet.h> #include <snakeoil/imex/snakeoil/spritesheet/spritesheet_parser.h> #include <snakeoil/io/global.h> #include <snakeoil/log/global.h> using namespace examples ; //************************************************************************* my_app::my_app( void_t ) { // add viewport variable { _vp_window_ptr = so_flow::variable<so_gpu::viewport_2d_t>::create( so_gpu::viewport_2d_t(), "[my_app] : window viewport" ) ; _vs.add( "vp_window", _vp_window_ptr ) ; _vn.create_output_connections( _vs ) ; } } //************************************************************************* my_app::my_app( this_rref_t rhv ) { _vn = std::move( rhv._vn ) ; _vs = std::move( rhv._vs ) ; _images = std::move( rhv._images ) ; so_move_member_ptr( _vp_window_ptr, rhv ) ; so_move_member_ptr( _line_rnd_ptr, rhv ) ; so_move_member_ptr( _text_rnd_ptr, rhv ) ; so_move_member_ptr( _image_rnd_ptr, rhv ) ; so_move_member_ptr( _rect_rnd_ptr, rhv ) ; so_move_member_ptr( _res_brd_ptr, rhv ) ; so_move_member_ptr( _sp_mgr_ptr, rhv ) ; so_move_member_ptr( _gfxp_fb, rhv ) ; so_move_member_ptr( _gfxp_blit, rhv ) ; } //************************************************************************* my_app::~my_app( void_t ) { so_gfx::text_render_2d_t::destroy( _text_rnd_ptr ) ; so_gfx::line_render_2d_t::destroy( _line_rnd_ptr ) ; so_gfx::image_render_2d_t::destroy( _image_rnd_ptr ) ; so_gfx::rect_render_2d_t::destroy( _rect_rnd_ptr ) ; so_gfx::predef_post_t::destroy( _gfxp_blit ) ; so_gfx::predef_framebuffer_t::destroy( _gfxp_fb ) ; so_gfx::resource_bridge_t::destroy( _res_brd_ptr ) ; // destroy via rref assignment operator _vs = so_flow::variable_set_t() ; _vn = so_flow::variable_node_t() ; so_imgui::system_t::destroy( _imguis ) ; for( auto & id : _images ) { so_memory::global_t::dealloc( id.imgui_tx_id ) ; } } //************************************************************************* my_app::this_ptr_t my_app::create( void_t ) { return so_memory::global::alloc( this_t(), "" ) ; } //************************************************************************* void_t my_app::destroy( this_ptr_t ptr ) { so_memory::global::dealloc( ptr ) ; } //************************************************************************* so_appx::result my_app::on_shutdown( void_t ) { _text_rnd_ptr->release() ; _line_rnd_ptr->release() ; _imguis->release() ; return so_appx::result::ok ; } //************************************************************************* so_appx::result my_app::destroy( void_t ) { this_t::destroy( this ) ; return so_appx::result::ok ; } //************************************************************************* so_appx::result my_app::on_event( so_appx::window_event_data_cref_t we ) { { so_app::resize_message_t msg ; if( we.wsi->has_resize_message( msg ) ) { _vp_window_ptr->set_data( so_gpu::viewport_2d( msg.x, msg.y, msg.w, msg.h ) ) ; } } return so_appx::result::ok ; } //************************************************************************* my_app::image_data_ref_t my_app::cur_spritesheet( void_t ) { return _images[ _use_sprite ] ; } //************************************************************************* so_imgui::system_t::imgui_texture_data_ptr_t my_app::cur_imex_tx( void_t ) { return _images[ _use_sprite ].imgui_tx_id ; } //************************************************************************* so_math::vec2f_t my_app::cur_spritesheet_dims( void_t ) const { auto const & d = _images[ _use_sprite ] ; return so_math::vec2f_t( float_t(d.width), float_t(d.height) ) ; } //************************************************************************* so_math::vec2f_t my_app::cur_spritesheet_dims_recip( void_t ) const { auto const & d = _images[ _use_sprite ] ; return so_math::vec2f_t( 1.0f/float_t( d.width ), float_t( 1.0f/d.height ) ) ; } //************************************************************************* void_t my_app::save_to_file( void_t ) { so_imex::so_snakeoil::spritesheet_t ss ; ss.uri = _ss_file ; for( auto const & item : _list_items ) { so_imex::so_snakeoil::spritesheet_sequence_t sss ; sss.id = item.key ; sss.speed = 1.0f ; for( auto const & r : item.rects ) { so_imex::so_snakeoil::spritesheet_frame_t ssf ; ssf.rect = r.rect ; ssf.duration = r.duration ; ssf.pivot = r.pivot ; sss.frames.push_back( std::move( ssf ) ) ; } ss.sequences.push_back( std::move(sss) ) ; } auto const s = so_imex::so_snakeoil::spritesheet_parser_t::from_data( ss ) ; { auto hnd = so_io::global_t::store( _base_path / _file, s.c_str(), s.size() ) ; hnd.wait_for_operation( [&] ( so_io::result const res ) { so_log::global_t::status( so_io::success( res ), "File stored" ) ; so_log::global_t::status( so_io::no_success( res ), "File stored failed" ) ; } ) ; } } //************************************************************************* void_t my_app::load_from( so_imex::so_snakeoil::spritesheet_cref_t ss ) { for( auto const & s : ss.sequences ) { this_t::list_item_t li ; li.key = s.id ; li.rename = false ; for( auto const & f : s.frames ) { this_t::animation_rect_t ar ; ar.beg = so_math::vec2ui_t( f.rect.xy() ) ; ar.end = so_math::vec2ui_t( f.rect.zw() ) ; ar.pivot = f.pivot ; ar.compute_rect() ; li.rects.push_back( ar ) ; } _list_items.push_back( li ) ; } }
5cbd6de551e94fb504ee7bf3e572fd3b0830a4f0
[ "Markdown", "CMake", "C++" ]
34
C++
aconstlink/tool_prototypes
6d596bb8f6a462d4cc6d2286330d174a9a0f9f68
f69af8589903644c5ca029c202df3fa9fe9df435
refs/heads/master
<file_sep>#-*- coding:utf8 -*- import csv import json from csv import DictReader class CsvtoJson(): def __init__(self,filename): #Input filename first self.filename=filename def PrintcsvField(self): #Show you fieldname array=list() with open(self.filename) as csvfiles: data=DictReader(csvfiles) for row in data.fieldnames: array.append(row) csvfiles.close() print(array) def CsvtoJson(self): file=self.filename jsonfilename=file.split('.')[0]+'.json'#Use input filename to split and make new json file name jsonfile=open(jsonfilename,'w') with open(file) as csvfile: reader = DictReader(csvfile) #make csvfile to dict format for row in reader: #use ensure_ascii to prevent unicode,indent make page good json.dump(row, jsonfile, sort_keys=True,indent=4, separators=(',', ': '),ensure_ascii=False) csvfile.close() print("The Json file has done") if __name__ == "__main__" : test=CsvtoJson("yiland_a.csv") test.PrintcsvField() test.CsvtoJson() <file_sep># CsvtoJson Program by python3.5. Can transfer csv file to json file Just change the filename(yiland_a.csv) to what you want if __name__ == "__main__" : test=CsvtoJson("yiland_a.csv") test.PrintcsvField() test.CsvtoJson()
740a53552069ccd85419d970b47258f089f19fac
[ "Markdown", "Python" ]
2
Python
l1254879/CsvtoJson
246c9c646211ef2dcb3a255975d81543739a4b43
f021ba6d73e2f74631b617f0c9164f0f0626eb15
refs/heads/master
<repo_name>baudiachatb/demo_login_fb_google<file_sep>/src/App.js import React, {Component} from 'react'; import logo from './logo.svg'; import './App.css'; import GoogleLogin from "react-google-login"; class App extends Component { render() { const onGoogleLoginSuccess = (response) => { console.log(response); }; return ( <div className="App"> <GoogleLogin onSuccess={onGoogleLoginSuccess} onFailure={onGoogleLoginSuccess} clientId={'486030383439-u2heo6q9nqql23u608bqjhj54i9qudco.apps.googleusercontent.com'}> </GoogleLogin> </div> ) } } export default App;
e75eca44cd2978d832d3040135f492e876bea7c9
[ "JavaScript" ]
1
JavaScript
baudiachatb/demo_login_fb_google
1c04581aeb3fdc69132cdfe8a95690be656a8cf1
bf91d79f5f408fe111ce77f486711469242ff647
refs/heads/master
<file_sep> /** ****************************************************************************** * @file app.c * @author MCD Application Team * @version V1.1.0 * @date 19-March-2012 * @brief This file provides all the Application firmware functions. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_conf.h" #include "usbd_cdc_core.h" #include "usbd_usr.h" #include "usb_conf.h" #include "usbd_desc.h" #include "core_cm4.h" #include "stm32f4xx_rcc.h" #include "stm32f4xx.h" #include "usbd_cdc_vcp.h" #include "HMC624.h" #include "HMC345.h" #include "HMC833.h" #include "TIM.h" #define PREPEND0 //#define APPEND0 //#define SEND2_ONLY __ALIGN_BEGIN USB_OTG_CORE_HANDLE USB_OTG_dev __ALIGN_END ; extern uint8_t USB_Rx_Buffer [CDC_DATA_MAX_PACKET_SIZE]; extern uint32_t APP_Rx_length ; extern uint16_t USB_Rx_Cnt; int main(void) { SystemInit(); LED_init(); LED_on(LED_GREEN); SPI_Initialize(); HMC624_init(); HMC345_init(); ADC_init(); ADC_set_ST_values(&ADC_ST_values_inst); HMC345_set_path(HMC345_PATH_1); HMC624_set_attenuation(0); HMC833_set_clockout(); HMC833_initial_config(); TIM_warm_up(); // HMC833_set_frequency((double)2402.589); // uint8_t tempbuf[3]; // uint8_t tempbuf5[3] = {0}; // // //configure delta sigma modulator // uint8_t zeros[3] = {0}; // uint8_t delta_sigma[3]; // delta_sigma[0] = 0x03; // delta_sigma[1] = 0x07; // delta_sigma[2] = 0xca; // SPI_write( HMC833_REG_SD_CFG, delta_sigma ); // SPI_read( HMC833_REG_SD_CFG, tempbuf ); // ////charge_pump // uint8_t chpump[3]; // SPI_read( HMC833_REG_CHARGE_PUMP, chpump ); // chpump[0] = 0x00; // chpump[1] = 0x00; // chpump[2] = 0x80; // SPI_write( HMC833_REG_CHARGE_PUMP, chpump); ////vco registers // // uint8_t vco[3]; //#ifdef PREPEND0 // //reg04 // vco[2] = 0b10100000; // vco[1] = 0b01100000; // vco[0] = 0; // SPI_write( HMC833_REG_SPI,vco); // //reg05 // vco[2] = 0b00101000; // vco[1] = 0b00010110; // vco[0] = 0; // SPI_write( HMC833_REG_SPI,vco); //#endif // //#ifdef APPEND0 // //reg04 // vco[1] = 0b10100000; // vco[0] = 0b01100000; // vco[2] = 0; // SPI_write( HMC833_REG_SPI,vco); // //reg05 // vco[1] = 0b00101000; // vco[0] = 0b00010110; // vco[2] = 0; // SPI_write( HMC833_REG_SPI,vco); //#endif // //#ifdef SEND2_ONLY // vco[1] = 0b10100000; // vco[0] = 0b01100000; // SPI_writetwo( HMC833_REG_SPI,vco); // vco[1] = 0b00101000; // vco[0] = 0b00010110; // SPI_writetwo( HMC833_REG_SPI,vco); //#endif // SPI_read( 0x05, tempbuf5 ); // zeros[1] = 0x00; // SPI_write( HMC833_REG_SPI,zeros); // //SPI_writetwo( HMC833_REG_SPI,zeros); // // // /////////temp // uint8_t tempbufa[3]; // tempbufa[2] = 0x61; // tempbufa[1] = 0x80; // tempbufa[0] = 0x0f; // SPI_write(0x0B,tempbufa); // // uint8_t freqreg[3] = {0}; // freqreg[2] = 0x72; // SPI_write(HMC833_REG_FREQ , freqreg); USBD_Init(&USB_OTG_dev, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_CDC_cb, &USR_cb); FLASH_read_reglin(&Cali_reglin_inst); Cali_reglin_inst.is_serialnum_set = 1; // HMC624_set_attenuation(10.0); // to be deleted // Current_results_inst.current_attenuation = 10;//change to 31,5 while (1) { __WFI(); } } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>#include "HMC833.h" #include "SPI.h" uint8_t r[3] = {0}; Current_HMC833_config Current_HMC833_config_inst; void HMC833_set_clockout() { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_PinAFConfig(GPIOC, GPIO_PinSource9 , GPIO_AF_MCO); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 ; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init( GPIOC, &GPIO_InitStructure); RCC_MCO2Config(RCC_MCO2Source_HSE, RCC_MCO2Div_1); // No need for register config. In case of changing MCO2 reg do it before HSE enabling. //MCO2[1:0] = 00 SYSCLK //MCO2PRE = 000 DIV = NO } void HMC833_initial_config(void) { Current_HMC833_config_inst.VCO_reg02[0] = 0x00; Current_HMC833_config_inst.VCO_reg02[1] = 0x60; Current_HMC833_config_inst.VCO_reg02[2] = 0x90; r[0] = 0x00; r[1] = 0x00; r[2] = 0x02; SPI_write(HMC833_REG_RST , r); r[0] = 0x00; r[1] = 0x00; r[2] = 0x01; SPI_write(HMC833_REG_REFDIV , r); r[0] = 0x00; r[1] = 0x16; r[2] = 0x28; SPI_write(HMC833_REG_SPI , r); r[0] = 0x00; r[1] = 0x60; r[2] = 0xa0; SPI_write(HMC833_REG_SPI , r); ///////////////////////////// // r[0] = 0x00; // r[1] = 0x2A; // r[2] = 0x98; // SPI_write(0x05 , r); ///////////////////////////////// proba tlumikow internal // r[0] = 0x00; // r[1] = 0x00; // r[2] = 0x90; // SPI_write(HMC833_REG_SPI , r); // HMC833_set_atten1(ATTEN1_3); ///////////////////////////////////////////// HMC833_send_zero_to_05reg(); //intiger // r[0] = 0x20; // r[1] = 0x03; // r[2] = 0xca; //fractional r[0] = 0x20; r[1] = 0x0b; r[2] = 0x4a; SPI_write(HMC833_REG_SD_CFG , r); r[0] = 0x00; r[1] = 0x01; r[2] = 0x4d; SPI_write(HMC833_REG_LOCK_DETECT , r); r[0] = 0xc1; r[1] = 0xbe; r[2] = 0xff; SPI_write(HMC833_REG_ANALOG_EN , r); //intiger mode // r[0] = 0x00; // r[1] = 0x3f; // r[2] = 0xff; //fractional r[0] = 0x54; r[1] = 0x7f; r[2] = 0xff; SPI_write(HMC833_REG_CHARGE_PUMP , r); r[0] = 0x00; r[1] = 0x20; r[2] = 0x46; SPI_write(HMC833_REG_VCO_AUTOCAL , r); //intiger mode // r[0] = 0x0f; // r[1] = 0x80; // r[2] = 0x61; //fractional r[0] = 0x07; r[1] = 0xc0; r[2] = 0x21; SPI_write(HMC833_REG_PD , r); r[0] = 0x00; r[1] = 0x00; r[2] = 0x00; SPI_write(HMC833_EXACT_FREQ_MODE , r); SPI_write(0x0d , r); SPI_write(0x0e , r); r[0] = 0x00; r[1] = 0x00; r[2] = 0x81; SPI_write(HMC833_REG_GPO_SPI_RDIV , r); r[0] = 0x00; r[1] = 0x00; r[2] = 0xf0; SPI_write(HMC833_REG_FREQ , r); r[0] = 0x33; r[1] = 0x33; r[2] = 0x33; SPI_write(0x04 , r); } void HMC833_set_frequency(double freq) { uint8_t *temp_ptr; freq /= XREFP_DIV_R_FREQ_MHZ; long int number = (long int)floor(freq); double fraction = freq - (double)number; temp_ptr = &number; r[2] = temp_ptr[0]; r[1] = temp_ptr[1]; r[0] = temp_ptr[2]; SPI_write(HMC833_REG_FREQ , r); fraction = fraction * TWO_POW_24; number = lround(fraction); if(number < 16) number = 16; r[2] = temp_ptr[0]; r[1] = temp_ptr[1]; r[0] = temp_ptr[2]; SPI_write(HMC833_REG_FREQ_FRACT , r); } void HMC833_set_multiplier(uint8_t doubler_not_fundamental) { if(doubler_not_fundamental == TRUE) { r[0] = 0x00; r[1] = 0x00; r[2] = 0x18; } else { r[0] = 0x00; r[1] = 0x08; r[2] = 0x98; } SPI_write(HMC833_REG_SPI , r); HMC833_send_zero_to_05reg(); } void HMC833_set_divider(uint8_t div) { div &= 0b00111111; if(div&0b00000001)Current_HMC833_config_inst.VCO_reg02[2] |= 0b10000000 ; else Current_HMC833_config_inst.VCO_reg02[2] &= ~0b10000000 ; if(div&0b00000010)Current_HMC833_config_inst.VCO_reg02[1] |= 0b00000001 ; else Current_HMC833_config_inst.VCO_reg02[1] &= ~0b00000001 ; if(div&0b00000100)Current_HMC833_config_inst.VCO_reg02[1] |= 0b00000010 ; else Current_HMC833_config_inst.VCO_reg02[1] &= ~0b00000010 ; if(div&0b00001000)Current_HMC833_config_inst.VCO_reg02[1] |= 0b00000100 ; else Current_HMC833_config_inst.VCO_reg02[1] &= ~0b00000100 ; if(div&0b00010000)Current_HMC833_config_inst.VCO_reg02[1] |= 0b00001000 ; else Current_HMC833_config_inst.VCO_reg02[1] &= ~0b00001000 ; if(div&0b00100000)Current_HMC833_config_inst.VCO_reg02[1] |= 0b00010000 ; else Current_HMC833_config_inst.VCO_reg02[1] &= ~0b00010000 ; SPI_write(HMC833_REG_SPI , Current_HMC833_config_inst.VCO_reg02); HMC833_send_zero_to_05reg(); } void HMC833_set_atten1(uint8_t attenuation1) { switch (attenuation1) { case ATTEN1_0: Current_HMC833_config_inst.VCO_reg02[1] |= 0b01100000 ; break; case ATTEN1_3: Current_HMC833_config_inst.VCO_reg02[1] |= 0b01000000 ; Current_HMC833_config_inst.VCO_reg02[1] &= 0b11011111 ; break; case ATTEN1_6: Current_HMC833_config_inst.VCO_reg02[1] |= 0b00100000 ; Current_HMC833_config_inst.VCO_reg02[1] &= 0b10111111 ; break; case ATTEN1_9: Current_HMC833_config_inst.VCO_reg02[1] &= 0b10011111 ; break; } SPI_write(HMC833_REG_SPI , Current_HMC833_config_inst.VCO_reg02); HMC833_send_zero_to_05reg(); } void HMC833_set_atten2(uint8_t attenuation1) { switch (attenuation1) { case ATTEN2_0: Current_HMC833_config_inst.VCO_reg02[1] |= 0b10000000; break; case ATTEN2_3: Current_HMC833_config_inst.VCO_reg02[1] &= 0b01111111; break; } SPI_write(HMC833_REG_SPI , Current_HMC833_config_inst.VCO_reg02); HMC833_send_zero_to_05reg(); } inline void HMC833_send_zero_to_05reg(void) { r[0] = 0x00; r[1] = 0x00; r[2] = 0x00; SPI_write(HMC833_REG_SPI , r); } uint8_t HMC833_is_busy(void) { SPI_read( HMC833_REG_VCO_TUNE , r); if(r[1]&0b00000001)return TRUE; else return FALSE; } <file_sep>/* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __SPI_H #define __SPI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_rcc.h" #include "stm32f4xx.h" #include "stm32f4xx_gpio.h" #include "stm32f4xx_spi.h" /* Exported functions ------------------------------------------------------- */ void SPI_Initialize(void); void SPI_read( uint8_t address, uint8_t *rxbuff); void SPI_write( uint8_t address, uint8_t *txbuff); #ifdef __cplusplus } #endif #endif /* __STM32L1xx_IT_H */ <file_sep>#ifndef __HMC833_H_ #define __HMC833_H_ #include "stm32f4xx_conf.h" typedef struct { uint8_t VCO_reg02[3]; } Current_HMC833_config; extern uint8_t r[3]; #define TRUE 1 #define FALSE 0 #define TWO_POW_24 0x1000000 #define ATTEN1_0 0x00 #define ATTEN1_3 0x01 #define ATTEN1_6 0x02 #define ATTEN1_9 0x03 #define ATTEN2_0 0x00 #define ATTEN2_3 0x01 #define XREFP_DIV_R_FREQ_MHZ 10.0 //PLL REGISTER MAP #define HMC833_REG_ID 0x00 #define HMC833_REG_OM_RX_ADDR 0x00 #define HMC833_REG_RST 0x01 #define HMC833_REG_REFDIV 0x02 #define HMC833_REG_FREQ 0x03 #define HMC833_REG_FREQ_FRACT 0x04 #define HMC833_REG_SPI 0x05 #define HMC833_REG_SD_CFG 0x06 #define HMC833_REG_LOCK_DETECT 0x07 #define HMC833_REG_ANALOG_EN 0x08 #define HMC833_REG_CHARGE_PUMP 0x09 #define HMC833_REG_VCO_AUTOCAL 0x0A #define HMC833_REG_PD 0x0B #define HMC833_EXACT_FREQ_MODE 0x0C #define HMC833_REG_GPO_SPI_RDIV 0x0F #define HMC833_REG_VCO_TUNE 0x10 #define HMC833_REG_SAR 0x11 #define HMC833_REG_GPO2 0x12 #define HMC833_REG_BIST 0x13 // VCO REG MAP ( via 05 register) #define HMC833_REG_VCO_TUNING 0x00 #define HMC833_REG_VCO_ENABLES 0x01 #define HMC833_REG_VCO_BIASES 0x02 #define HMC833_REG_VCO_CONFIG 0x03 #define HMC833_REG_VCO_CAL_BIAS 0x04 #define HMC833_REG_VCO_CF_CAL 0x05 #define HMC833_REG_VCO_MSB_CAL 0x06 #define HMC833_CEN GPIO_Pin_8 // GPIOD #define HMC833_SEN GPIO_Pin_12 //GPIOB inline void HMC833_send_zero_to_05reg(void); uint8_t HMC833_is_busy(void); void HMC833_set_frequency(double freq); void HMC833_set_atten1(uint8_t attenuation1); void HMC833_set_atten2(uint8_t attenuation1); void HMC833_set_divider(uint8_t div); #endif <file_sep>/* Includes ------------------------------------------------------------------*/ #include "SPI.h" /* Private variables ---------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ void SPI_Initialize(void) { GPIO_InitTypeDef GPIO_InitStructure; SPI_InitTypeDef SPI_InitStructure; /* Peripheral Clock Enable -------------------------------------------------*/ RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); GPIO_PinAFConfig(GPIOB, GPIO_PinSource13 , GPIO_AF_SPI2); GPIO_PinAFConfig(GPIOB, GPIO_PinSource14 , GPIO_AF_SPI2); GPIO_PinAFConfig(GPIOB, GPIO_PinSource15 , GPIO_AF_SPI2); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15 ; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; GPIO_Init( GPIOB, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_Init( GPIOB, &GPIO_InitStructure); SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2; //NOT SURE SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI2, &SPI_InitStructure); SPI_Cmd(SPI2, ENABLE); GPIO_SetBits(GPIOB ,GPIO_Pin_12); TIM_delay_ms(3); GPIO_ResetBits(GPIOB ,GPIO_Pin_12); } void SPI_read( uint8_t address, uint8_t *rxbuff) { int i = 0; GPIO_SetBits(GPIOB, GPIO_Pin_12); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2,(0x80 | (address << 1))); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET); SPI_I2S_ReceiveData(SPI2); for(i=0; i<3; i++) { while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2, 0xFF); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET); rxbuff[i] = SPI_I2S_ReceiveData(SPI2); } GPIO_ResetBits(GPIOB, GPIO_Pin_12); } void SPI_write( uint8_t address, uint8_t *txbuff) { int i = 0; GPIO_SetBits(GPIOB, GPIO_Pin_12); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2,(0x00 | (address << 1) | (*(txbuff+0) >> 7))); // while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET); // SPI_I2S_ReceiveData(SPI2); for(i=0; i<3; i++) { while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2,(txbuff[i] << 1 | (txbuff[i+1] >> 7))); } SPI_I2S_ReceiveData(SPI2); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET); GPIO_ResetBits(GPIOB, GPIO_Pin_12); } void SPI_writetwo( uint8_t address, uint8_t *txbuff) { int i = 0; GPIO_SetBits(GPIOB, GPIO_Pin_12); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2,(0x00 | (address << 1) | (*(txbuff+0) >> 7))); // while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET); // SPI_I2S_ReceiveData(SPI2); for(i=0; i<2; i++) { while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2,(txbuff[i] << 1 | (txbuff[i+1] >> 7))); } SPI_I2S_ReceiveData(SPI2); while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET); GPIO_ResetBits(GPIOB, GPIO_Pin_12); } <file_sep>#ifndef __HMC345_H_ #define __HMC345_H_ #include "stm32f4xx_conf.h" //GPIOE #define HMC345_1_CTLA GPIO_Pin_12 #define HMC345_1_CTLB GPIO_Pin_13 #define HMC345_2_CTLA GPIO_Pin_15 #define HMC345_2_CTLB GPIO_Pin_14 // Path 1 - LPF 2,75GHz #define HMC345_PATH_1 0b00001100 // Path 2 - BPF 2,7 - 5Ghz #define HMC345_PATH_2 0b00000110 // Path 3 - BPF 4,7 - 6GHz #define HMC345_PATH_3 0b00001001 // Path 4 - 4x multiplier, BPF 5,5 - 10,6GHz #define HMC345_PATH_4 0b00000011 void HMC345_init(void); void HMC345_set_path(uint8_t path); #endif <file_sep>#include "measurement functions.h" #include "LED.h" #include "FLASH.h" #include "HMC624.h" #include "LED.h" #include "TIM.h" #include "ADC.h" #include "HMC833.h" #include "HMC345.h" Current_results Current_results_inst; extern Cali_reglin Cali_reglin_inst; void Current_result_clear(Current_results* Current_results_struct) { LED_off(LED_RED); Current_results_struct->current_error_log_1 = 0; Current_results_struct->current_error_log_2 = 0; Current_results_struct->current_ADC_ref_voltage = 0; Current_results_struct->current_ADC_temperature = 0; Current_results_struct->current_ADC_voltage = 0; } inline void set_warm_up_state(uint8_t is_warmed_up) { if(is_warmed_up == 0) LED_on(LED_ORANGE); else { LED_off(LED_ORANGE); Current_results_inst.current_is_warmed_up = is_warmed_up; } } void clear_buf(char* buf, int bytes_to_clear) { int k = 0; for ( k = 0; k <= bytes_to_clear; k++) { buf[k] = 0; } } void select_frequency(double freq) { if(freq < 3011)//f podstawowa mnożnik wyjciowy ustawić na 1 { HMC345_set_path(HMC345_PATH_1); HMC833_set_multiplier(FALSE); HMC833_set_frequency(freq); } else if(freq < 4700)//ustawić f podstawową na 1/2freq; mnożnik na 2 { HMC345_set_path(HMC345_PATH_2); HMC833_set_frequency(freq/2.0); TIM_delay_ms(1); while(HMC833_is_busy()){} HMC833_set_multiplier(TRUE); } else if(freq < 6000)// ustawić f podstawową na 1/2freq; mnożnik na 2 { HMC345_set_path(HMC345_PATH_3); HMC833_set_frequency(freq/2.0); TIM_delay_ms(1); while(HMC833_is_busy()){} HMC833_set_multiplier(TRUE); } else// ustawić f/4 mnożnik na 1 { HMC345_set_path(HMC345_PATH_4); HMC833_set_multiplier(FALSE); HMC833_set_frequency(freq/4.0); } } <file_sep>#ifndef __MEASUREMENT_FUNCTIONS_H_ #define __MEASUREMENT_FUNCTIONS_H_ #include "stm32f4xx_conf.h" #define ERROR_V_REF 0b00000001 #define ERROR_TEMPERATURE 0b00000010 #define ERROR_CALIBRATION 0b00000100 #define ERROR_WARM_UP 0b00001000 #define ERROR_SERIAL_NUM 0b00010000 typedef struct { float current_ADC_voltage; float current_attenuation; float current_ADC_temperature; float current_detector_temperature; float current_ADC_ref_voltage; uint8_t current_error_log_1; uint8_t current_error_log_2; uint8_t current_is_warmed_up; } Current_results; extern Current_results Current_results_inst; inline void set_warm_up_state(uint8_t is_warmed_up); #endif <file_sep>#ifndef __HMC624_H_ #define __HMC624_H_ #include "stm32f4xx_conf.h" #include "measurement functions.h" //GPIOB #define HMC624_ATTEN_LE GPIO_Pin_0 //GPIOC #define HMC624_ATTEN_D0 GPIO_Pin_5 #define HMC624_ATTEN_D1 GPIO_Pin_4 // GPIOA #define HMC624_ATTEN_D2 GPIO_Pin_7 #define HMC624_ATTEN_D3 GPIO_Pin_6 #define HMC624_ATTEN_D4 GPIO_Pin_5 #define HMC624_ATTEN_D5 GPIO_Pin_4 //Exported functions inline void HMC624_init(void); inline void HMC624_set_attenuation(float attenuation); #endif <file_sep>#ifndef __ADC_H_ #define __ADC_H_ #include "stm32f4xx_conf.h" #include "measurement functions.h" #include "FLASH.h" typedef struct { float ADC_ST_Vref; float ADC_ST_V25; float ADC_ST_V30; float ADC_ST_avg_slope; }ADC_ST_values; extern ADC_ST_values ADC_ST_values_inst; //Exported functions inline void ADC_init(void); void ADC_measurement(Current_results* Current_results_struct); void ADC_temperature_measurement(Current_results* Current_results_struct, ADC_ST_values* ADC_ST_values_structure); void ADC_reference_V_measurement(Current_results* Current_results_struct, ADC_ST_values* ADC_ST_values_structure); void ADC_set_ST_values(ADC_ST_values* ADC_ST_values_structure); #endif <file_sep>#ifndef __LED_H_ #define __LED_H_ #include "stm32f4xx_conf.h" //GPIOD #define LED_GREEN GPIO_Pin_12 #define LED_BLUE GPIO_Pin_11 #define LED_ORANGE GPIO_Pin_10 #define LED_RED GPIO_Pin_9 inline void LED_init(); inline void LED_on(uint16_t LED); inline void LED_off(uint16_t LED); inline void LED_toggle(uint16_t LED); #endif <file_sep>#include "TIM.h" void TIM_delay_ms(uint16_t time) { RCC->APB1ENR |= RCC_APB1ENR_TIM4EN; // TIM4 clock enable TIM4->PSC = 41999; // TIM4 prescaler: 84MHZ/(PSC+1) TIM4->CR1 &= ~TIM_CR1_DIR; // Counter used as upcounter TIM4->CR1 |= TIM_CR1_ARPE; // Auto-reload preload enable TIM4->ARR = 65535; ///max time=65535 // TIM4 auto-reload value TIM4->EGR |= TIM_EGR_UG; // Update generation TIM4->CR1 |= TIM_CR1_CEN; //Counter enable TIM4->CNT = 0; // counter reset TIM4->CR1 |= TIM_CR1_CEN; //Counter enable while (TIM4->CNT <= 2*time); // delay time ms TIM4->CR1 &= ~TIM_CR1_CEN; //Counter disable } void TIM_delay_us(uint16_t time) { RCC->APB1ENR |= RCC_APB1ENR_TIM4EN; // TIM4 clock enable TIM4->PSC = 42; // TIM4 prescaler: 84MHZ/(PSC+1) TIM4->CR1 &= ~TIM_CR1_DIR; // Counter used as upcounter TIM4->CR1 |= TIM_CR1_ARPE; // Auto-reload preload enable TIM4->ARR = 65535; ///max time=65535 // TIM4 auto-reload value TIM4->EGR |= TIM_EGR_UG; // Update generation TIM4->CR1 |= TIM_CR1_CEN; //Counter enable TIM4->CNT = 0; // counter reset TIM4->CR1 |= TIM_CR1_CEN; //Counter enable while (TIM4->CNT <= 2*time); // delay time ms TIM4->CR1 &= ~TIM_CR1_CEN; //Counter disable } inline void TIM_warm_up(void) { set_warm_up_state(0); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_3); NVIC_InitTypeDef NVIC_InitStruct; NVIC_InitStruct.NVIC_IRQChannel = TIM3_IRQn; NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 6; NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStruct); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); TIM_TimeBaseInitTypeDef TIM_InitStruct; TIM_InitStruct.TIM_Prescaler = 41999; //84M/42k = 2k TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_InitStruct.TIM_Period = 2000-1; //2kHz down to 1Hz (1s) TIM_InitStruct.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3, &TIM_InitStruct); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); TIM_Cmd(TIM3,ENABLE); } //void TIM2_init(void) //{ // RCC->AHB1ENR |= 0x01; // Clock for PortA // RCC->APB1ENR |= 0x01; // Clock for Timer2 // RCC->APB1ENR |= 0x08; // Clock for Timer5 // // GPIOA->MODER |= 0x00000008; // all inputs but: PA1 => AF mode // GPIOA->AFR[0] |= 0x00000010; // select AF1 (TIM2) for PA01 -> TIM2_CH2 // // // TIM2->CCMR1 |= 0x0100; // Ch. 2 as TI2 //CC2S = 01 // TIM2->SMCR |= 0x0007; // Ext. clk mode 1 //SMS = 111 // TIM2->SMCR |= 0x0060; // TI2FP2 as ext. clock //TS = 110 // TIM2->SMCR |= 0x0080;// MSM = 1 // TIM2->CR2 |= 0x0010; //send enable of tim2 as trigger to tim5 //MMS = 001 // // TIM5->SMCR |= 0x0006; //TIM5 in trig mode // // TIM2->CR1 |= 0x0001; // enable counting // //} <file_sep>#include "HMC345.h" void HMC345_init(void) { RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Pin = HMC345_1_CTLA |HMC345_1_CTLB | HMC345_2_CTLA| HMC345_2_CTLB; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; GPIO_Init(GPIOE, &GPIO_InitStructure); } void HMC345_set_path(uint8_t path) { if((path & 0b00001000)>>3) GPIO_SetBits(GPIOE, HMC345_1_CTLA); else GPIO_ResetBits(GPIOE, HMC345_1_CTLA); if((path & 0b00000100)>>2) GPIO_SetBits(GPIOE, HMC345_1_CTLB); else GPIO_ResetBits(GPIOE, HMC345_1_CTLB); if((path & 0b00000010)>>1) GPIO_SetBits(GPIOE, HMC345_2_CTLA); else GPIO_ResetBits(GPIOE, HMC345_2_CTLA); if((path & 0b00000001)) GPIO_SetBits(GPIOE, HMC345_2_CTLB); else GPIO_ResetBits(GPIOE, HMC345_2_CTLB); } <file_sep>#include "HMC624.h" inline void HMC624_init(void) { RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Pin = HMC624_ATTEN_D2 |HMC624_ATTEN_D3 | HMC624_ATTEN_D4 | HMC624_ATTEN_D5; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = HMC624_ATTEN_D0 | HMC624_ATTEN_D1 ; GPIO_Init(GPIOC, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = HMC624_ATTEN_LE ; GPIO_Init(GPIOB, &GPIO_InitStructure); } //TODO: optimize this function inline void HMC624_set_attenuation(float attenuation) { uint8_t config_record = ((int)roundf((attenuation*2.0f))); GPIO_ResetBits(GPIOB,HMC624_ATTEN_LE); GPIO_SetBits(GPIOC,HMC624_ATTEN_D0 | HMC624_ATTEN_D1); GPIO_SetBits(GPIOA,HMC624_ATTEN_D2 |HMC624_ATTEN_D3 | HMC624_ATTEN_D4| HMC624_ATTEN_D5); if((config_record & 0b00100000)>>5) GPIO_ResetBits(GPIOA, HMC624_ATTEN_D5); if((config_record & 0b00010000)>>4) GPIO_ResetBits(GPIOA, HMC624_ATTEN_D4); if((config_record & 0b00001000)>>3) GPIO_ResetBits(GPIOA, HMC624_ATTEN_D3); if((config_record & 0b00000100)>>2) GPIO_ResetBits(GPIOA, HMC624_ATTEN_D2); if((config_record & 0b00000010)>>1) GPIO_ResetBits(GPIOC, HMC624_ATTEN_D1); if((config_record & 0b00000001) ) GPIO_ResetBits(GPIOC, HMC624_ATTEN_D0); GPIO_SetBits(GPIOB,HMC624_ATTEN_LE); }
a8a47daff7bb8fe06fdc44f41262d2ffacfb6dbd
[ "C" ]
14
C
kkasiabbartosik/GIT_GENER
682f99a20dea7954e300757052fee6a7cf3a6a70
819172488110211dfa9bb5b9640ef024734e01b4
refs/heads/master
<file_sep>import { Component, Input } from '@angular/core'; @Component({ selector: 'customInput', templateUrl: './customInput.component.html', }) export class CustomInputComponent { @Input() disabled = false; } <file_sep># Clase2 This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 11.2.10. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. ## Setup angular testing with Hest - Uninstall karma dependencies: `npm uninstall karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter` - Install jest dependencies: `npm install -D jest jest-preset-angular @types/jest jest-jasmine2` - Configure `setup-test.ts` and `jest.config.js` ``` //setup-jest.ts import 'jest-preset-angular/setup-jest'; //jest.config.js module.exports = { preset: "jest-preset-angular", setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"], coverageDirectory: "coverage", collectCoverageFrom: ["<rootDir>/src/app/**/*.ts"], coverageReporters: ["text", "text-summary", "html"], testRunner: "jest-jasmine2", }; ``` - Change package-json test task to use jest `"test": "jest",` - Create a coverage task `"test:coverage": "jest --coverage",` <file_sep>import { AfterViewInit, ComponentRef, Directive, ElementRef, HostListener, Optional, Self, } from '@angular/core'; import { FormGroupDirective, NgControl, ValidationErrors, } from '@angular/forms'; import { filter, map, tap } from 'rxjs/operators'; import { Overlay, OverlayRef } from '@angular/cdk/overlay'; import { ComponentPortal } from '@angular/cdk/portal'; import { ErrorMessageComponent } from '../../components/error-message/error-message.component'; import { Observable } from 'rxjs'; import { VALIDATORS_MESSAGES } from 'src/app/modules/form/validators/messages'; @Directive({ selector: '[controlError]' }) export class ControlErrorDirective implements AfterViewInit { private componentRef: ComponentRef<ErrorMessageComponent>; private overlayRef: OverlayRef; @HostListener('focus') focus(): void { this.showError(); } @HostListener('blur') blur(): void { this.hideMessage(); } constructor( @Self() @Optional() private control: NgControl, @Self() @Optional() private group: FormGroupDirective, private overlay: Overlay, private elementRef: ElementRef<HTMLElement> ) {} ngAfterViewInit() { this.subscribeToChanges(); } private getSubscriber(): Observable<any> { return this.getControl().valueChanges; } private getControl() { return this.control || this.group; } private getErrors(): ValidationErrors { return this.control?.errors || this.group?.errors; } private showError(): void { const errors = this.getControl().errors; if (!errors) { return; } this.createErrorComponent(); this.setError(errors); this.setErrorClass(); } private subscribeToChanges(): void { this.getSubscriber() .pipe( map(() => this.getErrors()), tap((errors: ValidationErrors) => this.checkError(errors)), filter((errors: ValidationErrors) => !!errors) ) .subscribe((errors: ValidationErrors) => { this.createErrorComponent(); this.setError(errors); this.setErrorClass(); }); } private checkError(errors: ValidationErrors): void { if (!errors && this.componentRef) { this.hideMessage(); this.removeErrorClass(); } } private setErrorClass() { this.elementRef.nativeElement.classList.add('form--error'); } private removeErrorClass() { this.elementRef.nativeElement.classList.remove('form--error'); } private hideMessage() { this.overlayRef.detach(); this.componentRef = null; } private createOverlay() { const positionStrategy = this.overlay .position() .flexibleConnectedTo(this.elementRef) .withPositions([ { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: 0, }, ]); this.overlayRef = this.overlay.create({ positionStrategy, panelClass: ['panel--error'], }); } private createErrorComponent(): void { if (this.componentRef) { return; } this.createOverlay(); const ref = new ComponentPortal(ErrorMessageComponent); this.componentRef = this.overlayRef.attach(ref); } private setError(errors: ValidationErrors): void { const [firstError] = Object.entries(errors); const error = VALIDATORS_MESSAGES[firstError[0]](firstError[1]); this.componentRef.instance.msg = error; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormArray, FormBuilder, Validators } from '@angular/forms'; import { Store } from '@ngxs/store'; import { FormStateModel, FormStore, SetAddressesData, } from '../../store/form.store'; @Component({ selector: '[addresses]', templateUrl: './addresses.component.html', }) export class AddressesComponent implements OnInit { addresses: FormArray; constructor(private fb: FormBuilder, private store: Store) {} ngOnInit() { const store: FormStateModel = this.store.selectSnapshot(FormStore); this.initializeAddresses(store.addresses.value); this.subscribeToChanges(); } addItem(address: any = null): void { const group = this.fb.group({ direction: [address?.direction, [Validators.required]], postalCode: [address?.postalCode], city: address?.city, country: address?.country, }); this.addresses.push(group); } onRemoveAddress(index: number) { this.addresses.removeAt(index); } private initializeAddresses(addresses: any[]): void { this.addresses = this.fb.array([]); addresses.forEach((address) => { this.addItem(address); }); } private subscribeToChanges() { this.addresses.valueChanges.subscribe((value) => { const valid = this.addresses.valid; this.store.dispatch( new SetAddressesData({ value, valid, }) ); }); } } <file_sep>import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { Store } from '@ngxs/store'; import { withLatestFrom } from 'rxjs/operators'; import { CreateProfile, FormStateModel, FormStore, } from '../../store/form.store'; @Component({ selector: '[form-page]', templateUrl: './form-page.component.html', }) export class FormPageComponent { constructor(private store: Store, private router: Router) {} onSubmit(): void { this.store .dispatch(new CreateProfile()) .pipe(withLatestFrom(this.store.select(FormStore))) .subscribe(([_, formStoreValue]: [any, FormStateModel]) => { this.router.navigate(['profile', formStoreValue.newProfileId]); }); } } <file_sep>import { Component, EventEmitter, OnInit, Output } from '@angular/core'; import { Select, Store } from '@ngxs/store'; import { Observable } from 'rxjs'; import { FormStore, SetNextStep, SetPreviousStep, StepName, } from '../../store/form.store'; @Component({ selector: '[profile-form]', templateUrl: './profile-form.component.html', }) export class ProfileFormComponent implements OnInit { @Output() submitForm = new EventEmitter<void>(); @Select(FormStore.formIsValid) formIsValid$: Observable<boolean>; @Select(FormStore.hasNextStep) hasNextStep$: Observable<boolean>; @Select(FormStore.hasPreviousStep) hasPreviousStep$: Observable<boolean>; @Select(FormStore.formStepIsValid) formStepIsValid$: Observable<boolean>; @Select(FormStore.currentStep) currentStep$: Observable<string>; private currentStep: string; StepName = StepName; constructor(private store: Store) {} ngOnInit(): void { this.currentStep$.subscribe( (currentStep) => (this.currentStep = currentStep) ); } onNext() { this.store.dispatch(new SetNextStep()); } onBack() { this.store.dispatch(new SetPreviousStep()); } isCurrentStep(step: string): boolean { return this.currentStep === step; } onSubmit(): void { this.submitForm.emit(); } canChangeStep(): boolean { return true; } } <file_sep>import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { InputsModule } from '@progress/kendo-angular-inputs'; import { AddressComponent } from './components/address/address.component'; import { CustomInputComponent } from './components/customInput/customInput.component'; import { ControlErrorDirective } from './directives/controlError/controlError.directive'; @NgModule({ imports: [CommonModule, InputsModule, ReactiveFormsModule], exports: [ CommonModule, ReactiveFormsModule, CustomInputComponent, AddressComponent, ControlErrorDirective, ], declarations: [AddressComponent, ControlErrorDirective, CustomInputComponent], providers: [], }) export class SharedModule {} <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { Profile } from '../models/profile.model'; export type ProfileEntity = Profile & { id: number }; const URL = 'https://profile-angular-course.free.beeceptor.com'; @Injectable() export class ProfileService { constructor(private http: HttpClient) {} createProfile(profile: Profile): Observable<{ id: number }> { return this.http.post<{ id: number }>(URL, profile); } getProfile(id: number): Observable<ProfileEntity> { return this.http.get<ProfileEntity>(URL); } } <file_sep>import { Injectable } from '@angular/core'; import { Action, Select, Selector, State, StateContext } from '@ngxs/store'; import { tap } from 'rxjs/operators'; import { Profile } from '../../core/models/profile.model'; import { ProfileService } from '../../core/services/profile.service'; export enum StepName { PERSONAL_DATA = 'personalData', PASSWORD = '<PASSWORD>', ADDRESSES = 'addresses', } export interface FormStateModel { personalData: { value: any; valid: boolean }; password: { value: any; valid: boolean }; addresses: { value: any; valid: boolean }; newProfileId: number; currentStep: string; } const DEFAULT_VALUES = { personalData: { value: null, valid: false, }, password: { value: null, valid: false, }, addresses: { value: [], valid: false, }, newProfileId: null, currentStep: StepName.PERSONAL_DATA, }; interface Step { next: string; previous: string; current: string; } export const Steps: { [key: string]: Step } = { [StepName.PERSONAL_DATA]: { current: StepName.PERSONAL_DATA, next: StepName.PASSWORD, previous: null, }, [StepName.PASSWORD]: { current: StepName.PASSWORD, next: StepName.ADDRESSES, previous: StepName.PERSONAL_DATA, }, [StepName.ADDRESSES]: { current: StepName.ADDRESSES, next: null, previous: StepName.PASSWORD, }, }; export class SetPasswordData { static readonly type = '[FORM STATE] Set password data'; constructor(public password: { value: any; valid: boolean }) {} } export class SetPersonalData { static readonly type = '[FORM STATE] Set personal data'; constructor(public personalData: { value: any; valid: boolean }) {} } export class SetAddressesData { static readonly type = '[FORM STATE] Set addresses data'; constructor(public addresses: { value: any[]; valid: boolean }) {} } export class CreateProfile { static readonly type = '[FORM STATE] Create a new profile'; } export class SetNextStep { static readonly type = '[FORM STATE] Set next step'; } export class SetPreviousStep { static readonly type = '[FORM STATE] Set previous step'; } export class SetFirstStep { static readonly type = '[FORM STATE] Set first step'; } @Injectable() @State<FormStateModel>({ name: 'FormStateModel', defaults: DEFAULT_VALUES, }) export class FormStore { @Selector() static formIsValid(ctx: FormStateModel): boolean { return ctx.addresses.valid && ctx.password.valid && ctx.personalData.valid; } @Selector() static formStepIsValid(ctx: FormStateModel): boolean { return ctx[ctx.currentStep].valid; } @Selector() static hasNextStep(ctx: FormStateModel): boolean { return !!Steps[ctx.currentStep].next; } @Selector() static hasPreviousStep(ctx: FormStateModel): boolean { return !!Steps[ctx.currentStep].previous; } @Selector() static currentStep(ctx: FormStateModel): string { return ctx.currentStep; } constructor(private profileService: ProfileService) {} @Action(SetPasswordData) setPasswordData( context: StateContext<FormStateModel>, { password }: SetPasswordData ) { context.patchState({ password }); } @Action(SetPersonalData) setPersonalData( context: StateContext<FormStateModel>, { personalData }: SetPersonalData ) { context.patchState({ personalData }); } setAddressesData( context: StateContext<FormStateModel>, { addresses }: SetAddressesData ) { context.patchState({ addresses }); } createProfile(context: StateContext<FormStateModel>) { const state = context.getState(); const profile = parseForm(state); return this.profileService.createProfile(profile).pipe( tap(({ id }) => context.patchState({ newProfileId: id, }) ), tap(() => context.dispatch(new SetFirstStep())) ); } @Action(SetNextStep) setNextStep(context: StateContext<FormStateModel>): void { const stepConfig = Steps[context.getState().currentStep]; context.patchState({ currentStep: stepConfig.next, }); } @Action(SetPreviousStep) setPreviousStep(context: StateContext<FormStateModel>): void { const stepConfig = Steps[context.getState().currentStep]; context.patchState({ currentStep: stepConfig.previous, }); } @Action(SetFirstStep) setFirstStep(context: StateContext<FormStateModel>): void { context.patchState({ currentStep: StepName.PERSONAL_DATA, }); } } function parseForm(formValue: FormStateModel): Profile { return { age: formValue.personalData.value.age, name: formValue.personalData.value.name, addresses: formValue.addresses.value, password: <PASSWORD>, }; } <file_sep>import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: '[buttons]', templateUrl: './buttons.component.html', }) export class ButtonsComponent implements OnInit { @Input() submitDisabled = false; @Input() nextDisabled = false; @Input() backDisabled = false; @Input() backButtonVisible = false; @Input() nextButtonVisible = false; @Input() submitButtonVisible = false; @Output() submit = new EventEmitter<void>(); @Output() next = new EventEmitter<void>(); @Output() back = new EventEmitter<void>(); constructor() {} ngOnInit() {} onNext() { this.next.emit(); } onBack() { this.back.emit(); } onSubmit() { this.submit.emit(); } } <file_sep>import { createComponentFactory, Spectator } from '@ngneat/spectator'; import { ButtonsComponent } from './buttons.component'; describe('ButtonsComponent', () => { let spectator: Spectator<ButtonsComponent>; const createHost = createComponentFactory({ component: ButtonsComponent, }); beforeEach(() => (spectator = createHost())); it('Should be created', () => expect(spectator).toBeDefined()); it('should click onNext and emit', () => { jest.spyOn(spectator.component.next, 'emit'); spectator.component.onNext(); expect(spectator.component.next.emit).toHaveBeenCalled(); }); it('should click onBack and emit', () => { jest.spyOn(spectator.component.back, 'emit'); spectator.component.onBack(); expect(spectator.component.back.emit).toHaveBeenCalled(); }); it('should click onSubmit and emit', () => { jest.spyOn(spectator.component.submit, 'emit'); spectator.component.onSubmit(); expect(spectator.component.submit.emit).toHaveBeenCalled(); }); }); <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Store } from '@ngxs/store'; import { FormStateModel, FormStore, SetPasswordData, } from '../../store/form.store'; import { VALIDATORS_MESSAGES } from '../../validators/messages'; import { passwordValidator } from '../../validators/password.validator'; @Component({ selector: '[password]', templateUrl: './password.component.html', }) export class PasswordComponent implements OnInit { password: FormGroup; constructor(private fb: FormBuilder, private store: Store) {} ngOnInit() { const store: FormStateModel = this.store.selectSnapshot(FormStore); this.password = this.fb.group( { password: [store.password.value?.password, [Validators.required]], confirmPassword: [ store.password.value?.confirmPassword, [Validators.required], ], }, { validators: [Validators.required, passwordValidator], } ); this.subscribeToChanges(); } private subscribeToChanges(): void { this.password.valueChanges.subscribe( (value: { password: string; confirmPassword: string }) => { const valid = this.password.valid; this.store.dispatch(new SetPasswordData({ value, valid })); } ); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ProfileEntity, ProfileService, } from '../../core/services/profile.service'; @Component({ selector: '[profile]', templateUrl: './profile-page.component.html', }) export class ProfilePageComponent implements OnInit { profile: ProfileEntity; profileId: number; constructor( private profileService: ProfileService, private route: ActivatedRoute, private router: Router ) {} ngOnInit() { this.getProfileId(); this.getProfile(); } goToForm() { this.router.navigate(['/']); } private getProfileId(): void { this.profileId = this.route.snapshot.params['id']; } private getProfile(): void { this.profileService.getProfile(this.profileId).subscribe({ next: (profile: ProfileEntity) => (this.profile = profile), }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Store } from '@ngxs/store'; import { FormStateModel, FormStore, SetPersonalData, } from '../../store/form.store'; import { minAgeValidator } from '../../validators/minAge/minAge.validator'; @Component({ selector: '[personalData]', templateUrl: './personalData.component.html', }) export class PersonalDataComponent implements OnInit { personalData: FormGroup; constructor(private fb: FormBuilder, private store: Store) {} ngOnInit() { const store: FormStateModel = this.store.selectSnapshot(FormStore); this.personalData = this.fb.group({ age: [ store.personalData.value?.age, { validators: [Validators.required, minAgeValidator(21)] }, ], name: [ store.personalData.value?.name, { validators: [Validators.required] }, ], }); this.subscribeToChanges(); } private subscribeToChanges() { this.personalData.valueChanges.subscribe((value) => { const valid = this.personalData.valid; this.store.dispatch( new SetPersonalData({ value, valid, }) ); }); } } <file_sep>export const VALIDATORS_MESSAGES = { minAge: ({ min }) => `La edad mínima són ${min} años`, required: () => 'El campo es obligatorio', password: () => 'Las contraseñas no coinciden', }; <file_sep>module.exports = { preset: "jest-preset-angular", setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"], coverageDirectory: "coverage", collectCoverageFrom: ["<rootDir>/src/app/**/*.ts"], coverageReporters: ["text", "text-summary", "html"], testRunner: "jest-jasmine2", }; <file_sep>import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: '[error]', template: `<p>{{ error }}</p>`, }) export class ErrorComponent implements OnInit { @Input() error = 'Hola'; constructor() {} ngOnInit() {} } <file_sep>import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: '[error-message]', template: '<p>{{msg}}</p>', }) export class ErrorMessageComponent implements OnInit { @Input() msg; constructor() {} ngOnInit() {} } <file_sep>import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { createComponentFactory, mockProvider, Spectator, } from '@ngneat/spectator'; import { Observable, of } from 'rxjs'; import { Profile } from 'src/app/modules/core/models/profile.model'; import { ProfileEntity, ProfileService, } from '../../../core/services/profile.service'; import { FormPageComponent } from './form-page.component'; const MOCK_PROFILE: Profile = { addresses: [ { city: 'Valencia', country: 'España', direction: 'Plaza del ayuntamiento', postalCode: 46006, }, ], age: 12, name: 'David', password: '12', }; describe('FormPageComponent', () => { let spectator: Spectator<FormPageComponent>; const createHost = createComponentFactory({ component: FormPageComponent, providers: [mockProvider(ProfileService)], imports: [RouterTestingModule], }); beforeEach(() => (spectator = createHost())); it('should be defined', () => expect(spectator.component).toBeDefined()); it('should call to onSubmit and call to service', () => { const id = 1; const service = spectator.inject(ProfileService); const navigateSpy = spyOn(spectator.inject(Router), 'navigate'); service.createProfile.and.returnValue(of({ id })); spectator.component.onSubmit(MOCK_PROFILE); expect(service.createProfile).toHaveBeenCalledWith(MOCK_PROFILE); expect(navigateSpy).toHaveBeenCalledWith(['profile', id]); }); }); <file_sep>export interface Profile { age: number; name: string; password: string; addresses: Address[]; } interface Address { direction: string; postalCode: number; country: string; city: string; } <file_sep>import { Component, EventEmitter, Input, Output } from '@angular/core'; import { FormGroup } from '@angular/forms'; @Component({ selector: '[address]', templateUrl: './address.component.html', }) export class AddressComponent { @Input() formGroup: FormGroup; @Input() index: number; @Output() removeAddress = new EventEmitter<number>(); removeItem() { this.removeAddress.emit(this.index); } } <file_sep>import { FormGroup } from '@angular/forms'; export function passwordValidator({ value }: FormGroup) { const { password, confirmPassword } = value; return password === confirmPassword ? null : { password: true }; } <file_sep>import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { ButtonsComponent } from './components/buttons/buttons.component'; import { ErrorComponent } from './components/error/error.component'; import { PasswordComponent } from './components/password/password.component'; import { ProfileFormComponent } from './components/profile-form/profile-form.component'; import { FormRouter } from './form-routing.module'; import { FormPageComponent } from './pages/form/form-page.component'; import { NgxsModule } from '@ngxs/store'; import { FormStore } from './store/form.store'; import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { PersonalDataComponent } from './components/personalData/personalData.component'; import { AddressesComponent } from './components/addresses/addresses.component'; @NgModule({ imports: [ FormRouter, SharedModule, NgxsReduxDevtoolsPluginModule.forRoot(), NgxsModule.forRoot([FormStore]), ], declarations: [ ProfileFormComponent, FormPageComponent, PasswordComponent, ErrorComponent, ButtonsComponent, PersonalDataComponent, AddressesComponent, ], }) export class FormModule {} <file_sep>import { FormControl } from '@angular/forms'; import { minAgeValidator } from './minAge.validator'; describe('MinAgeValidator', () => { it('should return false', () => { const control = { value: 22, } as FormControl; const result = minAgeValidator(18)(control); expect(result).toBeFalsy(); }); it('should return true', () => { const control = { value: 15, } as FormControl; const result = minAgeValidator(18)(control); expect(result).toBeTruthy(); }); }); <file_sep>import { NgModule } from '@angular/core'; import { ProfileService } from './services/profile.service'; @NgModule({ providers: [ProfileService], }) export class CoreModule {} <file_sep>import { createHttpFactory, HttpMethod, SpectatorHttp, } from '@ngneat/spectator/jest'; import { Profile } from '../models/profile.model'; import { ProfileService } from './profile.service'; const MOCK_PROFILE: Profile = { addresses: [ { city: 'Valencia', country: 'España', direction: 'Plaza del ayuntamiento', postalCode: 46006, }, ], age: 12, name: 'David', password: '12', }; const BASE_URL = 'https://profile-angular-course.free.beeceptor.com'; describe('ProfileService', () => { let spectator: SpectatorHttp<ProfileService>; const createService = createHttpFactory(ProfileService); beforeEach(() => (spectator = createService())); it('should be created', () => expect(spectator.service).toBeDefined()); describe('createProfile', () => { it('should call to the backend', () => { spectator.service.createProfile(MOCK_PROFILE).subscribe(); const reqUrl = `${BASE_URL}`; const req = spectator.expectOne(reqUrl, HttpMethod.POST); expect(req.request.url).toBe(BASE_URL); req.flush({ id: 10 }); }); }); describe('getProfile', () => { it('should call to the backend', () => { const id = 1; spectator.service.getProfile(id).subscribe(); const reqUrl = `${BASE_URL}`; const req = spectator.expectOne(reqUrl, HttpMethod.GET); expect(req.request.url).toBe(BASE_URL); req.flush({ id: 10, ...MOCK_PROFILE }); }); }); }); <file_sep>import { Form, FormControl } from '@angular/forms'; /* export function minAgeValidator(control: FormControl): { [key: string]: boolean; } { const age = 18 return value > min ? null : { minAge: { min } } } */ export function minAgeValidator(min: number) { return ({ value }: FormControl) => agnosticAgeValidator(value, min); } export function agnosticAgeValidator(value: number, min: number) { return value > min ? null : { minAge: { min } }; }
4bc50201a4b4cfd5d0a5acb32e5ac9fc7d8a01e9
[ "Markdown", "TypeScript", "JavaScript" ]
27
TypeScript
davidrivers93/angularCourseForm
7b1c2d9920ed6e21730aa078b9b4467893f7e0d6
d1f6ce0c5e3f9d3b6500aa51a913a9e9ef1206c4
refs/heads/master
<repo_name>UlfFildebrandt/k8s-eval<file_sep>/node-prime-service/create_postgres.sh cf cups -p '{ "url": "postgres://postgres:[email protected]:5432/prime" }' cf bs prime-service-broker postgres cf bs prime-service postgres cf restage prime-service-broker cf restage prime-service <file_sep>/node-prime-service/service/test/primeServiceAppTests.js "use strict"; var assert = require('assert'); var request = require('supertest'); var psa = require('../primeServiceApp'); //https://thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/ <file_sep>/node-prime-service/create_broker.sh cf create-service-broker prime admin admin http://prime-service-broker.bosh-lite.com cf enable-service-access prime <file_sep>/node-prime-service/create_docker_access_sec_group.sh cf create-security-group docker_access docker_access_sec_group cf bind-staging-security-group docker_access cf bind-running-security-group docker_access <file_sep>/node-prime-service/broker/primeServiceBroker.js "use strict"; var logger = require('./logger'); var cfenv = require('cfenv'); var appEnv = cfenv.getAppEnv(); var Promise = require('promise'); var co = require('co'); var pgp = require('pg-promise')(/*options*/); var db = null; var md5 = require('md5'); var uuid = require('uuid'); var pass = require('pwd'); var targetHost = process.env.TARGET_HOST || 'http://prime-service.bosh-lite.com'; function getDbConnStr() { if (appEnv && !appEnv.isLocal) { var postgresServiceCreds = appEnv.getServiceCreds('postgres'); logger.info('Postgres database:', postgresServiceCreds.url); return postgresServiceCreds.url; } else { logger.info('Postgres database:', process.env.POSTGRES_URL); return process.env.POSTGRES_URL; } } function *dbExists() { var sql = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'prime'`; var data = yield db.oneOrNone(sql); return !!data; } function *initDb() { logger.info('Initializing database...'); if (!db) { db = pgp(getDbConnStr()); } var exists = yield *dbExists(); logger.info(exists ? 'Database schema exists!' : 'Database schema does not exist!'); if (!exists) { logger.info('Creating database schema...'); yield db.none(`CREATE SCHEMA prime`); } logger.info('Setting default schema...'); yield db.none(`SET search_path = 'prime'`); if (!exists) { logger.info('Creating tables...'); yield db.none("CREATE TABLE number_store (id TEXT PRIMARY KEY, number INTEGER)"); yield db.none("CREATE TABLE cred_bindings (binding_id TEXT PRIMARY KEY, service_id TEXT, usr TEXT, pwd TEXT, salt TEXT)"); } } function closeDb() { logger.info('Closing database...'); // no-op at present logger.info("Database closed."); } function inDb(generator) { return function(/* arguments */) { var args = arguments; return co(function *() { try { yield *initDb(); var result = yield *generator.apply(this, args); } catch (e) { logger.error("Error while processing service broker request:", e); throw e; } finally { closeDb(); return result; } }); } } var provisionInstance = inDb(function *(instanceId) { logger.info(`Provisioning instance '${instanceId}'...`); yield db.none("INSERT INTO number_store VALUES ('" + instanceId + "', NULL)"); logger.info("Instance provisioned."); }); var createBinding = inDb(function *(instanceId, bindingId) { logger.info(`Creating service binding '${bindingId}' for service instance '${instanceId}'...`); const user = md5(bindingId); const password = <PASSWORD>().replace(/-/g, ''); const saltedHash = yield new Promise(function(resolve, reject) { pass.hash(password, function(err, salt, hash){ if (err) { return reject(err); } resolve({ salt: salt, hash: hash }); }); }); yield db.none(`INSERT INTO cred_bindings VALUES ('${bindingId}', '${instanceId}', '${user}', '${saltedHash.hash}', '${saltedHash.salt}')`); logger.info(`Service binding '${bindingId}' for service instance '${instanceId}' created.`); return { "url": `${targetHost}/${instanceId}`, "user": user, "password": <PASSWORD> }; }); var removeBinding = inDb(function *(instanceId, bindingId) { logger.info(`Removing service binding '${bindingId}' for service instance '${instanceId}'...`); yield db.none(`DELETE FROM cred_bindings WHERE binding_id = '${bindingId}'`); logger.info("Service binding removed."); }); var removeInstance = inDb(function *(instanceId) { logger.info(`Removing service instance '${instanceId}'...`); yield db.none(`DELETE FROM number_store WHERE id = '${instanceId}'`); logger.info("Service instance removed."); }); module.exports.provisionInstance = provisionInstance; module.exports.createBinding = createBinding; module.exports.removeBinding = removeBinding; module.exports.removeInstance = removeInstance; <file_sep>/node-prime-service/service/primeServiceApp.js "use strict"; var express = require('express'); var logger = require('./logger'); var cfenv = require('cfenv'); var appEnv = cfenv.getAppEnv(); var Promise = require('promise'); var auth = require('basic-auth'); var app = express(); var pgp = require('pg-promise')(/*options*/); var db = null; var pass = require('pwd'); var ps = require('./primeService'); function getDbConnStr() { if (appEnv && !appEnv.isLocal) { var postgresServiceCreds = appEnv.getServiceCreds('postgres'); logger.info('Postgres database:', postgresServiceCreds.url); return postgresServiceCreds.url; } else { logger.info('Postgres database:', process.env.POSTGRES_URL); return process.env.POSTGRES_URL; } } function checkAuth(req, res, next) { var serviceId = req.params.service_id; var credentials = auth(req); if (!credentials) { logger.warn("No credentials provided"); return setUnauthorized(null, res, serviceId); } initDb().then(function() { return getPasswordForServiceAndUser(serviceId, credentials['name']); }).then(function(data) { pass.hash(credentials['pass'], data.salt, function(err, hash){ if (err) { return setUnauthorized(err, res, serviceId); } if (data.pwd !== hash) { logger.warn(`Unauthorized access to prime service '${serviceId}' (wrong password)`); return setUnauthorized(null, res, serviceId); } else { return next(); } }) }).catch(function(err) { setUnauthorized(err, res, serviceId); }); } function setUnauthorized(err, res, serviceId) { err && logger.error(`Unauthorized access to prime service '${serviceId}':`, err); res.statusCode = 401; res.setHeader('WWW-Authenticate', `Basic realm="${serviceId}"`); res.end('Unauthorized'); } function initDb() { if (!db) { db = pgp(getDbConnStr()); } logger.info("Setting default schema..."); return db.none(`SET search_path = 'prime'`); } function getPasswordForServiceAndUser(serviceId, user) { logger.info(`Retrieving password for service instance '${serviceId}' AND user = '${user}'`); return db.one(`SELECT pwd, salt FROM cred_bindings WHERE service_id = '${serviceId}' AND usr = '${user}'`); } function getCurrentPrime(req, res) { var serviceId = req.params.service_id; ps.getCurrentPrime(serviceId).then(function(prime) { res.set('Content-Type', 'application/json') .send(JSON.stringify({ "prime": prime })); }).catch(function(err) { logger.error(`Error while retrieving current prime for service instance '${serviceId}':`, err); res.status(500) .send(""); }); } function getNextPrime(req, res) { var serviceId = req.params.service_id; ps.getNextPrime(serviceId).then(function(prime) { res.set('Content-Type', 'application/json') .send(JSON.stringify({ "prime": prime })); }).catch(function(err) { logger.error(`Error while retrieving next prime for service instance '${serviceId}':`, err); res.status(500) .send(""); }); } app.get('/:service_id', checkAuth, getCurrentPrime); app.put('/:service_id', checkAuth, getNextPrime); var server = app.listen(process.env.VCAP_APP_PORT || process.env.APP_PORT || 3000, function () { var host = server.address().address; var port = server.address().port; logger.info('Prime Service listening at http://%s:%s', host, port); }); <file_sep>/node-prime-service/create_service.sh cf cs prime free prime cf bs prime-client prime cf restage prime-client <file_sep>/node-prime-service/client/logger.js "use strict"; var cfenv = require('cfenv'); var appEnv = cfenv.getAppEnv(); var winston = require('winston'); var transports = []; if (appEnv && !appEnv.isLocal) { transports.push(new winston.transports.Console({ level: 'info' })); // error } else { transports.push(new winston.transports.Console({ level: 'info' })); } module.exports = new winston.Logger({ transports: transports }); <file_sep>/node-prime-service/broker/test/primeServiceBrokerTests.js "use strict"; var logger = require('../logger'); var assert = require("assert"); var Promise = require('promise'); var pgp = require('pg-promise')(/*options*/); var db = pgp(getDbConnStr()); var pass = require('pwd'); var psb = require('../primeServiceBroker'); function getDbConnStr() { logger.info('Postgres database:', process.env.POSTGRES_URL); return process.env.POSTGRES_URL; } function cleanUp(done) { db.none("DROP SCHEMA prime CASCADE").then(done).catch(done); } describe('Prime Service Broker', function(){ describe('#provisionInstance', function(){ it('should initialize the database if needed', function(done){ psb.provisionInstance("1234-2345-3456").then(function() { return db.one(`SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = 'prime' AND table_name = 'number_store' )`); }).then(function(data) { assert.equal(data.exists, true); done(); }).catch(done); }); it('should create an empty number record', function(done){ var id = "1a234f456"; psb.provisionInstance(id).then(function() { return db.one(`SELECT id, number FROM number_store WHERE id='${id}'`); }).then(function(data) { assert.equal(data.id, id); assert.equal(data.number, null); done(); }).catch(done); }); }); describe('#createBinding', function(){ it('should create credentials', function(done){ var serviceId = "1a234f456"; const bindingId = "2345"; var user = null; var password = null; psb.provisionInstance(serviceId).then(function() { return psb.createBinding(serviceId, bindingId); }).then(function(data) { user = data.user; password = data.password; return db.one(`SELECT service_id, usr, pwd, salt FROM cred_bindings WHERE binding_id='${bindingId}'`); }).then(function(data) { assert.equal(data.service_id, serviceId); assert.equal(data.usr, user); pass.hash(password, data.salt, function(err, hash){ if (err) { return done(err); } assert.equal(data.pwd, hash); done(); }) }).catch(done); }); }); afterEach(cleanUp); }); <file_sep>/node-prime-service/service/Dockerfile FROM node:6.9.5 # PROXY SETTINGS RUN echo "Acquire::http::proxy \"http://proxy.wdf.sap.corp:8080/\";" >> /etc/apt/apt.conf ENV HTTP_PROXY=http://proxy.wdf.sap.corp:8080 ENV HTTPS_PROXY=$HTTP_PROXY ENV NO_PROXY=.sap.corp,localhost ENV http_proxy=$HTTP_PROXY ENV https_proxy=$HTTP_PROXY ENV no_proxy=$NO_PROXY RUN echo "HTTP_PROXY=$HTTP_PROXY" >> /etc/environment RUN echo "HTTPS_PROXY=$HTTP_PROXY" >> /etc/environment RUN echo "NO_PROXY=$NO_PROXY" >> /etc/environment RUN echo "http_proxy=$HTTP_PROXY" >> /etc/environment RUN echo "https_proxy=$HTTP_PROXY" >> /etc/environment RUN echo "no_proxy=$NO_PROXY" >> /etc/environment ENV PROXY_HOST proxy.wdf.sap.corp ENV PROXY_PORT 8080 # Add package.json and get dependencies from SAP npm registry COPY package.json package.json RUN npm config set registry http://nexus.wdf.sap.corp:8081/nexus/content/groups/build.milestones.npm/ RUN npm install # Add your source files in a separate step to leverage layer caching - if dependencies don't change, we don't need to rebuild COPY . . CMD ["npm","start"]<file_sep>/node-prime-service/client/primeClientApp.js "use strict"; var express = require('express'); var logger = require('./logger'); var cfenv = require('cfenv'); var appEnv = cfenv.getAppEnv(); var amqp = require('amqplib/callback_api'); var q = 'tasks'; var tasks = []; var request = require('request'); ///// AMQP function bail(err) { logger.error(err); //process.exit(1); } // Consumer function consumer(conn) { var ok = conn.createChannel(on_open); function on_open(err, ch) { if (err != null) { return bail(err); } ch.assertQueue(q); ch.consume(q, function(msg) { if (msg !== null) { var task = msg.content.toString(); logger.info("Task:", task); tasks.push(task); ch.ack(msg); if (task === "task #9") { setTimeout(bail.bind(this, "Maximum number of messages reached."), 500); } } }); } } amqp.connect('amqp://192.168.50.100', function(err, conn) { if (err != null) { return bail(err); } consumer(conn); }); //// PRIME SERVICE function getPrimeServiceInfo() { if (appEnv && !appEnv.isLocal) { var creds = appEnv.getServiceCreds('prime'); logger.info('Prime service:', creds); return creds; } else { logger.info('Prime service:', process.env.PRIME_URL); return JSON.parse(process.env.PRIME_URL); } } function getPrimeServiceURL() { return getPrimeServiceInfo().url; } function getPrimeServiceCreds() { var creds = getPrimeServiceInfo(); return { username: creds.user, password: <PASSWORD> }; } function getCurrentPrime(req, res) { request({ url: getPrimeServiceURL(), auth: getPrimeServiceCreds() }, function (err, res2, body) { if (err || res2.statusCode !== 200) { logger.error("Current prime could not be retrieved:", err || res2.statusCode); return res.status(500).send(""); } res.status(200).send(body); }) } function getNextPrime(req, res) { request({ url: getPrimeServiceURL(), method: 'PUT', auth: getPrimeServiceCreds() }, function (err, res2, body) { if (err || res2.statusCode !== 200) { logger.error("Next prime could not be retrieved:", err || res2.statusCode); return res.status(500).send(""); } res.status(200).send(body); }) } ///// REST SERVICES var app = express(); app.use(express.static('static')); function serviceBindings(req, res) { res.set('Content-Type', 'application/json') .send(JSON.stringify( { "services": getPrimeServiceInfo(), "tasks": tasks })); } app.get('/service_bindings', serviceBindings); app.get('/prime', getCurrentPrime); app.put('/prime', getNextPrime); var server = app.listen(process.env.VCAP_APP_PORT || process.env.APP_PORT || 3666, function () { var host = server.address().address; var port = server.address().port; logger.info('Prime Client listening at http://%s:%s', host, port); }); <file_sep>/node-prime-service/service/test/primeServiceTests.js "use strict"; var logger = require('../logger'); var assert = require("assert"); var pgp = require('pg-promise')(/*options*/); var db = pgp(getDbConnStr()); var psb = require('../../broker/primeServiceBroker'); var prime = require('../primeGenerator'); var ps = require('../primeService'); function getDbConnStr() { logger.info('Postgres database:', process.env.POSTGRES_URL); return process.env.POSTGRES_URL; } function setUp(done) { psb.provisionInstance("4711").then(done.bind(this, null)).catch(done); } function cleanUp(done) { db.none("DROP SCHEMA prime CASCADE").then(done).catch(done); } describe('Prime Generator Function', function(){ describe('#prime', function(){ it('should yield prime 2 after 0', function(done){ assert.equal(prime(0), 2, "should be 2"); return done(); }); it('should yield prime 7 after 6', function(done){ assert.equal(prime(6), 7, "should be 7"); return done(); }); it('should yield prime 13 after 12', function(done){ assert.equal(prime(12), 13, "should be 13"); return done(); }); }); }); describe('Prime Service', function(){ describe('#getCurrentPrime', function(){ it('should yield 2 as first prime', function(done){ ps.getCurrentPrime(4711).then(function(res) { assert.equal(2, res, "should be 2"); return done(); }).catch(function(err) { return done(err); }); }); }); describe('#getNextPrime', function(){ it('should yield 2, 3, 5, 7, 11 for successive calls', function(done){ ps.getNextPrime(4711).then(function(res) { assert.equal(2, res, "should be 2"); return ps.getNextPrime(4711); }).then(function(res) { assert.equal(3, res, "should be 3"); return ps.getNextPrime(4711); }).then(function(res) { assert.equal(5, res, "should be 5"); return ps.getNextPrime(4711); }).then(function(res) { assert.equal(7, res, "should be 7"); return ps.getNextPrime(4711); }).then(function(res) { assert.equal(11, res, "should be 11"); return done(); }).catch(function(err) { return done(err); }); }); }); beforeEach(setUp) afterEach(cleanUp); });
9b37700e968c644ce21ef66a64304527b41f0e91
[ "JavaScript", "Dockerfile", "Shell" ]
12
Shell
UlfFildebrandt/k8s-eval
c6ecaf4dcb96c155dc93707ca349925366b989d0
b88f59fc9799353b5a45de1849646e03ca40467d
refs/heads/master
<file_sep># file=open('create.txt') # try: # finally: # file.close() #our filel should be in csv format import numpy as np def sigmoid(z): s=1/1+np.exp(-z) return s class neuralnetwork: def __init__(self,x,y): self.input=x self.input=y self.weigths1=1 self.weights2=2 def feedforward(self): self.layer1 = sigmoid(np.dot(self.input, self.weights1)) self.output = sigmoid(np.dot(self.layer1, self.weights2)) <file_sep># a simple layer of neurons, with 4 inputs. inputs = [1.0, 2.0, 3.0, 2.5] weights1 = [0.2, 0.8, -0.5, 1.0] weights2 = [0.5, -0.91, 0.26, -0.5] weights3 = [-0.26, -0.27, 0.17, 0.87] bias1 = 2.0 bias2 = 3.0 bias3 = 0.5 wgt=[] wgt.append(weights1) wgt.append(weights2) wgt.append(weights3) b=[] b.append(bias1) b.append(bias2) b.append(bias3) outputs=[0.0]*len(wgt); for i in range(len(outputs)): result=0.0; for j in range(len(inputs)): result+=inputs[j]*wgt[i][j] outputs[i]+=result+b[i] print(*outputs)<file_sep>import numpy as np np.random.seed(0) X = [[1, 2, 3, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]] class Dense_Layer(object): """docstring for Layer""" def __init__(self, n_inputs, n_neurons): self.wgts = 0.1*np.random.randn(n_inputs, n_neurons) self.bias = np.zeros((1, n_neurons)) def forward_pro(self, inputs): self.output = np.dot(inputs, self.wgts) + self.bias # here we did not took dot of wght*input to save the transpose step layer1 = Dense_Layer(4,5) layer2 = Dense_Layer(5,2) layer1.forward_pro(X) #print(layer1.output) layer2.forward_pro(layer1.output) print(layer2.output) """ Limitations Dense layers add an interesting non-linearity property, thus they can model any mathematical function. However, they are still limited in the sense that for the same input vector we get always the same output vector. They can’t detect repetition in time, or produce different answers on the same input. we can’t do that with dense layers easily (unless we increase dimensions which can get quite complicated and has its own limitations). That’s where we need recurrent layers. """<file_sep>import pygame import time import sys import random pygame.init() white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (130,255,110) display_width = 800 display_length = 800 gameDisplay = pygame.display.set_mode((display_width,display_length)) pygame.display.set_caption('slither') icon = pygame.image.load("snakiii.jpeg") # NO ICON DISPLAYING pygame.display.set_icon(icon) img = pygame.image.load('tr.png').convert_alpha() img = pygame.transform.scale(img, (35, 35)).convert_alpha() applesimg = pygame.image.load("apple.png") applesimg = pygame.transform.scale(applesimg, (35, 30)).convert_alpha() font = pygame.font.SysFont(None,35) smallfont = pygame.font.SysFont("comicsansms",35) middelfont = pygame.font.SysFont("comic sans ms",55) largefont = pygame.font.SysFont("comicsansms",85) clock = pygame.time.Clock() FPS = 12 direction = 'right' ##################################################################### class NodeType: empty, snake_head, food, wall = range(4) #Grid constants screen_size = (50,50) columns, rows = screen_size[0], screen_size[1]; def getGrid(): grid = [[0 for x in range(columns)] for y in range(rows)] for x in range(columns): grid[x][0] = NodeType.wall grid[x][columns-1] = NodeType.wall for y in range(rows): grid[0][y] = NodeType.wall grid[rows-1][y] = NodeType.wall return grid #################################################################### def appleGen(objectsize): randappleX = round(random.randrange(0,display_width - block_size))#/10.0)*10.0 randappleY = round(random.randrange(0,display_length - block_size))#/10.0)*10.0 def snake(gameDisplay, color,snakelist, block_size): if direction == 'right': head = pygame.transform.rotate(img, 270) if direction == 'left': head = pygame.transform.rotate(img, 90) if direction == 'up': head = img if direction == 'down': head = pygame.transform.rotate(img, 180) for x,y in snakelist: gameDisplay.blit(head,(snakelist[-1][0], snakelist[-1][1])) pygame.display.update() for x,y in snakelist[:-1]: pygame.draw.rect(gameDisplay,color,[x,y,block_size,block_size]) def text_objects(text,color,size): if size == 'small': textSurface = smallfont.render(text, True, color) if size == 'middel': textSurface = middelfont.render(text, True, color) if size == 'large': textSurface = largefont.render(text, True, color) return textSurface, textSurface.get_rect() #def message_to_screen(msg,color): # screen_text = font.render(msg,True,red) # gameDisplay.blit(screen_text, [150,50]) def message_to_screen(msg,color,y_displace=0,size='small'): textSurf, textRect = text_objects(msg,color,size) textRect.center = (display_width/2), (display_length/2)+y_displace gameDisplay.blit(textSurf, textRect) def text_screen(text,color,x,y): font = pygame.font.SysFont(None,50) screen_text = font.render(text,True,color) gameDisplay.blit(screen_text,[x,y]) def game_intro(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() quit() if event.key == pygame.K_c: gameLoop() gameDisplay.fill(white) message_to_screen("Welcome to Slither",green,-100,"large") message_to_screen("The objective of the game is to eat eat red apples",black,-30,) message_to_screen("The more apples you eat, the longer you get",black,10,) message_to_screen("If you run into yourself, or the edges, you die!",black,50,) message_to_screen("Press C to play or Q to quit.",black,180,) pygame.display.update() clock.tick(15) def gameLoop(): global direction global gameExit gameExit = False global gameOver gameOver = False Score = 0 block_size = 35 lead_x = display_length/2 lead_y = display_width/2 lead_x_change = 0 lead_y_change = 0 dx = 20 randappleX = round(random.randrange(0,display_width - block_size))#/10.0)*10.0 randappleY = round(random.randrange(0,display_length - block_size))#/10.0)*10.0 snakelist = [] snakelength = 1 while not gameExit: while gameOver == True: gameDisplay.fill(white) message_to_screen("Game Over !!!", red, -50, size = 'middel') message_to_screen("Press C to play again or Q to quit.", black, 50, size = 'small') text_screen("Score: " +str(Score),green,320,380) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True gameOver = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameExit = True gameOver = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): pygame.init() if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: direction = 'left' lead_x_change -= dx lead_y_change = 0 elif event.key == pygame.K_RIGHT: direction = 'right' lead_x_change += dx lead_y_change = 0 elif event.key == pygame.K_DOWN: direction = 'down' lead_y_change += dx lead_x_change = 0 elif event.key == pygame.K_UP: direction = 'up' lead_y_change -= dx lead_x_change = 0 elif event.key == pygame.K_RETURN: Score += 10 if lead_x < 0 or lead_x>= display_width or lead_y < 0 or lead_y>= display_length: gameOver = True lead_x += lead_x_change lead_y += lead_y_change gameDisplay.fill(white) text_screen("Score:"+str(Score),red,5,5) AppleThickness = 55 #pygame.draw.rect(gameDisplay, red, [randappleX, randappleY, AppleThickness, AppleThickness]) gameDisplay.blit(applesimg, (randappleX, randappleY)) snake(gameDisplay, green, snakelist, block_size) snakehead = [] snakehead.append(lead_x) snakehead.append(lead_y) snakelist.append(snakehead) if len(snakelist) > snakelength: del snakelist[0] for eachSegment in snakelist[:-1]: if eachSegment == snakehead: gameOver = True pygame.display.update() if (lead_x>randappleX and lead_x<randappleX+AppleThickness or lead_x+block_size>randappleX and lead_x+block_size<randappleX+AppleThickness): if lead_y > randappleY and lead_y < randappleY + AppleThickness: randappleX = round(random.randrange(0,display_width - AppleThickness))#/10.0)*10.0 randappleY = round(random.randrange(0,display_length - AppleThickness))#/10.0)*10.0 Score += 10 snakelength += 1 elif lead_y + block_size> randappleY and lead_y + block_size < randappleY + AppleThickness: randappleX = round(random.randrange(0,display_width - AppleThickness))#/10.0)*10.0 randappleY = round(random.randrange(0,display_length - AppleThickness))#/10.0)*10.0 Score += 10 snakelength += 1 clock.tick(FPS) network = fully_connected(network, 25, activation='relu') network = fully_connected(network, 1, activation='linear') network = regression(network,optimizer='adam', learning_rate=1e-2, loss='mean_square',name='target') model = tflearn.DNN(network) # sanke will be moving randomly through the help of random function # then store all the random moves if max_points>max_points=>max_points=max(max_points,points): # or just points>0=True: # then parameters will be # x,y data = pds.read_csv("Data.csv",usecols=[1,2,3,4,5]) labels = pds.read_csv("Data.csv",usecols=[0]) model = getTrainedModel(data,labels) pygame.quit() game_intro() gameLoop() <file_sep>import numpy as np from spiral_pattern import spiral_data X, y = spiral_data(100, 3) class Dense_Layer: def __init__(self, n_inputs, n_neurons): self.weights = 0.10 * np.random.randn(n_inputs, n_neurons) self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): self.output = np.dot(inputs, self.weights) + self.biases class Activation_ReLU: def forward(self, inputs): self.output = np.maximum(0, inputs) # y=max(0,x); layer1 = Dense_Layer(2,5) activation1 = Activation_ReLU() layer1.forward(X) #print(layer1.output) activation1.forward(layer1.output) print(activation1.output)<file_sep>import pygame import time import sys import random import os pygame.mixer.init() pygame.init() #initiate the function white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,155,0) display_width = 800 display_length = 800 gameDisplay = pygame.display.set_mode((display_width,display_length)) pygame.display.set_caption('slither') font = pygame.font.SysFont(None,35) clock = pygame.time.Clock() FPS = 30 #Background Image bgimg = pygame.image.load("snake.png").convert_alpha() bgimg = pygame.transform.scale(bgimg, (display_width,display_length)).convert_alpha() #endimg = pygame.image.load("images.jpeg").convert_alpha() #endimg = pygame.transform.scale(bgimg, (display_width,display_length)).convert_alpha() pygame.mixer.music.load("Home_Base_Groove.mp3") pygame.mixer.music.play() #import pygame #def plotsnake(gameWindow, color,snake_list, block_size): # for x,y in snake_list: # pygame.draw.rect(gameWindow, black, [snake_list, block_size, block_size]) #snake_list = [] #snake_head = [] #snake_head.append(lead_x) #snake_head.append(lead_y) #snake_list.append(snake_head) #snake_length = 1 #snake_length =+ 5 #if snake_list > snake_length: # del snake_list[0 def snake(gameDisplay, color,snakelist, block_size): for x,y in snakelist: pygame.draw.rect(gameDisplay,color,[x,y,block_size,block_size]) def message_to_screen(msg,color): screen_text = font.render(msg,True,red) gameDisplay.blit(screen_text, [150,50]) def text_screen(text,color,x,y): font = pygame.font.SysFont(None,50) screen_text = font.render(text,True,color) gameDisplay.blit(screen_text,[x,y]) def welcome(): gameExit = False while not gameExit: gameDisplay.fill((210,120,230)) text_screen("Welcome!!",black,300,280) text_screen("Press Space To Play",black,220,320) for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: pygame.mixer.music.load("Bomber_Sting.mp3") pygame.mixer.music.play() gameLoop() pygame.display.update() clock.tick(60) #def afterGame(): # # while gameOver == True: # gameDisplay.fill(black) # message_to_screen("Game over,press C to play again or Q to quit", red) # pygame.display.update() # # for event in pygame.event.get(): # if event.type == pygame.KEYDOWN: # if event.type == pygame.K_q: # gameExit = True # gameOver = False # if event.type == pygame.K_c: # pass def gameLoop(): #check if highscore file exists if(not os.path.exists("highscore.txt")): with open("highscore.txt", "w") as f: f.write("0") #reading of highscore with open("highscore.txt", "r") as f: hiscore = f.read() #gameExit is a variable created in game #we have a game loss and this is a game exit #gameExit = False #gameOver = False #we have a game loss and this is a game exit gameExit = False gameOver = False Score = 0 #variable for block leading the snake block_size = 10 lead_x = display_length/2 lead_y = display_width/2 lead_x_change = 0 lead_y_change = 0 dx = 10 #round off figure to match snake with apple completely - block_size)/10.0)*10.0 randappleX = round(random.randrange(0,display_width - block_size)/10.0)*10.0 randappleY = round(random.randrange(0,display_length - block_size)/10.0)*10.0 snakelist = [] snakelength = 1 while not gameExit: while gameOver == True: #gameDisplay.blit(endimg, (0, 0)) ----------------------------------problem #pygame.mixer.music.load("Choose_Your_Path_Sting.mp3") -------------problem #pygame.mixer.music.play() -----------------------------------------problem #writing of hisocre with open("highscore.txt", "w") as f: f.write(str(hiscore)) gameDisplay.fill(white) message_to_screen("Game Over, press C to play again or Q to quit.", white) text_screen("Score: " +str(Score),green,350,350) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: #pygame.quit() gameExit = True gameOver = False if event.key == pygame.K_c: #gameLoop() welcome() for event in pygame.event.get(): pygame.init() #print(event) if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: lead_x_change -= dx lead_y_change = 0 elif event.key == pygame.K_RIGHT: lead_x_change += dx lead_y_change = 0 elif event.key == pygame.K_DOWN: lead_y_change += dx lead_x_change = 0 elif event.key == pygame.K_UP: lead_y_change -= dx lead_x_change = 0 elif event.key == pygame.K_RETURN: Score += 10 #for stopping snake being unpressed and run for pressed buttons(lead_x_change = 0) #if event.type == pygame.KEYUP: # if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: # lead_x_change = 0 # if event.key == pygame.K_UP or event.key == pygame.K_DOWN: # lead_y_change = 0 #creating boundaries for snake. #condition to fail gameOver = True if lead_x < 0 or lead_x>= display_width or lead_y < 0 or lead_y>= display_length: #gameExit = True #guess why? because it will end ... #gameDisplay.blit(endimg, (0, 0)) #pygame.mixer.music.load("Choose_Your_Path_Sting.mp3") #pygame.mixer.music.play() gameOver = True lead_x += lead_x_change lead_y += lead_y_change #gameDisplay.fill(white) gameDisplay.blit(bgimg, (0, 0)) text_screen("Score:"+str(Score) + " Highscore:"+str(hiscore),red,5,5) #pygame.draw.rect() #draw a rectangle shape #rect(Surface, color, Rect, width=0) -> Rec #pygame.draw.rect(gameDisplay, green, [lead_x,lead_y,block_size,block_size]) pygame.draw.rect(gameDisplay, red, [randappleX, randappleY, block_size, block_size]) #draw a rect at x=200, y=200, and 50*50 pixels #gameDisplay.fill(red, rect = [200, 200, 50, 50]) snake(gameDisplay, green, snakelist, block_size) snakehead = [] snakehead.append(lead_x) snakehead.append(lead_y) snakelist.append(snakehead) print(snakelist) print(snakelength) if len(snakelist) > snakelength: del snakelist[0] for eachSegment in snakelist[:-1]: if eachSegment == snakehead: gameOver = True pygame.display.update() if lead_x == randappleX and lead_y == randappleY: #print("slither") randappleX = round(random.randrange(0,display_width - block_size)/10.0)*10.0 randappleY = round(random.randrange(0,display_length - block_size)/10.0)*10.0 Score += 10 snakelength += 1 if Score > int(hiscore): #int because highscore file is read in strings #print(hiscore) hiscore = Score clock.tick(FPS) #message_to_screen("You Lose, get outside you fool", red) #pygame.display.update() #time.sleep(2) pygame.quit() #gameLoop() welcome()<file_sep># game-bot a.i based model to control and play game Made a self playing game solver framework, to specify, design the game and solve it. In this AI tries to determines and go to the destination point based on apple location on the board using pygame module and linear regression <file_sep># Imports import pygame from random import randint,shuffle import numpy as np from math import pi, asin, sqrt, degrees, radians import pandas as pds from keras.models import Sequential from keras.layers import Dense import coremltools # Enums class Direction: left, right, up, down = range(4) class NodeType: empty, snake_head, food, wall = range(4) # Screen constants block_size = 10 screen_size = (50,50) screen_color = (0, 0, 0) wall_color = (128, 128, 128) snake_color = (0, 255, 255) food_color = (0, 255, 0) # Grid constants columns, rows = screen_size[0], screen_size[1]; # Snake constants snake_initial_size = 1 class SnakeNode: def __init__(self,x,y): self.x = x self.y = y def removeDuplicates(input_file_name,output_file_name): with open(input_file_name,"r") as input_file, open(output_file_name,"w") as output_file: output_file.writelines(unique_everseen(input_file)) def getGrid(): grid = [[0 for x in range(columns)] for y in range(rows)] for x in range(columns): grid[x][0] = NodeType.wall grid[x][columns-1] = NodeType.wall for y in range(rows): grid[0][y] = NodeType.wall grid[rows-1][y] = NodeType.wall return grid def getSnakeNodes(x,y,grid): # Create initial snake snake_nodes = [] for i in range(snake_initial_size): segment = SnakeNode(x+i, y) snake_nodes.append(segment) grid[x][y] = NodeType.snake_head for i in range(1,len(snake_nodes)): grid[snake_nodes[i].x][snake_nodes[i].y] = NodeType.wall return snake_nodes def getGrownSnake(snake_nodes,direction,grid): tail = snake_nodes[-1] if direction == Direction.right: new_tail = SnakeNode(tail.x-1, tail.y) elif direction == Direction.left: new_tail = SnakeNode(tail.x+1, tail.y) elif direction == Direction.up: new_tail = SnakeNode(tail.x, tail.y+1) else: new_tail = SnakeNode(tail.x, tail.y-1) grid[new_tail.x][new_tail.y] = NodeType.wall snake_nodes.append(new_tail) return snake_nodes,grid def drawNode(x,y,grid,screen): if grid[x][y] == NodeType.snake_head: color = snake_color elif grid[x][y] == NodeType.food: color = food_color elif grid[x][y] == NodeType.wall: color = wall_color else: color = screen_color pygame.draw.rect(screen,color,pygame.Rect(x*block_size,y*block_size,block_size,block_size)) def isGameOver(snake_nodes,grid): head = snake_nodes[0] return grid[head.x][head.y] == NodeType.wall\ or head.x == 0\ or head.y == 0\ or head.x == columns-1\ or head.y == rows-1 def advanceSnake(snake_nodes,direction,grid): head = snake_nodes[0] tail = snake_nodes.pop() grid[tail.x][tail.y] = NodeType.empty if direction == Direction.up: tail.x = head.x tail.y = head.y - 1 elif direction == Direction.down: tail.x = head.x tail.y = head.y + 1 elif direction == Direction.left: tail.x = head.x - 1 tail.y = head.y elif direction == Direction.right: tail.x = head.x + 1 tail.y = head.y snake_nodes.insert(0,tail) if grid[tail.x][tail.y] != NodeType.food and grid[tail.x][tail.y] != NodeType.wall: grid[tail.x][tail.y] = NodeType.snake_head for i in range(1,len(snake_nodes)): grid[snake_nodes[i].x][snake_nodes[i].y] = NodeType.wall return snake_nodes def drawNodes(grid,screen): for x in range(columns): for y in range(rows): drawNode(x,y, grid,screen) def getNeighboringNodes(snake_nodes,direction,grid): # Left, forward, right nodes of snake head = snake_nodes[0] if direction == Direction.right: return (grid[head.x][head.y-1],grid[head.x+1][head.y],grid[head.x][head.y+1]) elif direction == Direction.left: return (grid[head.x][head.y+1],grid[head.x-1][head.y],grid[head.x][head.y-1]) elif direction == Direction.up: return (grid[head.x-1][head.y],grid[head.x][head.y-1],grid[head.x+1][head.y]) else: return (grid[head.x+1][head.y],grid[head.x][head.y+1],grid[head.x-1][head.y]) def areNeighboringNodesBlocked(left,forward,right): return (int(left == NodeType.wall),int(forward == NodeType.wall),int(right == NodeType.wall)) def isAnyNeighboringNodesBlocked(left,forward,right): return left == NodeType.wall or forward == NodeType.wall or right == NodeType.wall def distanceBetweenSnakeAndFood(snake_nodes,food_position): head = snake_nodes[0] food_x,food_y = food_position base = abs(food_x - head.x) perpendicular = abs(food_y - head.y) hypotenuse = sqrt(base**2 + perpendicular**2) return hypotenuse def getOrthogonalAngle(snake_nodes,food_position,absolute_direction): head = snake_nodes[0] food_x,food_y = food_position base = food_x - head.x perpendicular = food_y - head.y hypotenuse = sqrt(base**2 + perpendicular**2)+0.00001 angle = degrees(asin(perpendicular/hypotenuse))%90 if absolute_direction == Direction.right: if base >= 0 and perpendicular <= 0: angle = angle + 0 elif base <= 0 and perpendicular <= 0: angle = angle + 90 elif base <= 0 and perpendicular >= 0: angle = angle + 90 else: angle = angle + 0 elif absolute_direction == Direction.up: if base >= 0 and perpendicular <= 0: angle = angle + 0 elif base <= 0 and perpendicular <= 0: angle = angle + 0 elif base <= 0 and perpendicular >= 0: angle = angle + 90 else: angle = angle + 90 elif absolute_direction == Direction.left: if base >= 0 and perpendicular <= 0: angle = angle + 90 elif base <= 0 and perpendicular <= 0: angle = angle + 0 elif base <= 0 and perpendicular >= 0: angle = angle + 0 else: angle = angle + 90 else: if base >= 0 and perpendicular <= 0: angle = angle + 90 elif base <= 0 and perpendicular <= 0: angle = angle + 90 elif base <= 0 and perpendicular >= 0: angle = angle + 0 else: angle = angle + 0 return radians(angle-90)/(pi/2) def neuralInputs(snake_nodes,grid,absolute_direction,food_position): return (areNeighboringNodesBlocked(*getNeighboringNodes(snake_nodes,absolute_direction,grid)), getOrthogonalAngle(snake_nodes,food_position,absolute_direction)) def getTrainedModel(data, labels): model = Sequential() model.add(Dense(5,input_shape=(5,),activation="relu")) model.add(Dense(25,activation="relu")) model.add(Dense(25,activation="relu")) model.add(Dense(1,activation="linear")) model.summary() model.compile(loss="mean_squared_error",optimizer="adam",metrics=["accuracy"]) model.fit(data,labels,epochs=1) return model def getRelativeDirection(current_direction,next_direction): if current_direction == Direction.right: if next_direction == Direction.up: return -1 elif next_direction == Direction.right: return 0 else: return 1 elif current_direction == Direction.left: if next_direction == Direction.down: return -1 elif next_direction == Direction.left: return 0 else: return 1 elif current_direction == Direction.up: if next_direction == Direction.left: return -1 elif next_direction == Direction.up: return 0 else: return 1 else: if next_direction == Direction.right: return -1 elif next_direction == Direction.down: return 0 else: return 1 def getPredictedDirection(snake_nodes,absolute_direction,model,inputs,grid,shuffle_predictions): head = snake_nodes[0] relative_directions = [-1,0,1] if shuffle_predictions == True: shuffle(relative_directions) no_match_found = False for relative_direction in relative_directions: prediction = model.predict(np.array([[inputs[0][0],inputs[0][1],inputs[0][2],inputs[1],relative_direction]])) if prediction > 0.9: break no_match_found = True if no_match_found == True and shuffle_predictions == True: for relative_direction in relative_directions: prediction = model.predict(np.array([[inputs[0][0],inputs[0][1],inputs[0][2],inputs[1],relative_direction]])) if prediction >= 0: break if absolute_direction == Direction.right: if relative_direction == -1: return Direction.up,relative_direction elif relative_direction == 0: return Direction.right,relative_direction else: return Direction.down,relative_direction elif absolute_direction == Direction.left: if relative_direction == -1: return Direction.down,relative_direction elif relative_direction == 0: return Direction.left,relative_direction else: return Direction.up,relative_direction elif absolute_direction == Direction.up: if relative_direction == -1: return Direction.left,relative_direction elif relative_direction == 0: return Direction.up,relative_direction else: return Direction.right,relative_direction else: if relative_direction == -1: return Direction.right,relative_direction elif relative_direction == 0: return Direction.down,relative_direction else: return Direction.left,relative_direction def getOutputForTraining(target_output,inputs,snake_nodes,relative_direction): return "\n{},{},{},{},{},{}".format(target_output, inputs[0][0], inputs[0][1], inputs[0][2], inputs[1], relative_direction) def generateFood(grid): food_position = (randint(1, columns-snake_initial_size-1),randint(1, rows-snake_initial_size-1)) grid[food_position[0]][food_position[1]] = NodeType.food return food_position def checkForFoodCollision(snake_nodes,grid): head = snake_nodes[0] return grid[head.x][head.y] == NodeType.food def resetStuckPosition(): return [[0 for x in range(columns)] for y in range(rows)] def runGame(death_count,font,model): # Game objects score_count = 0 grid = getGrid() directions = [Direction.right,Direction.left,Direction.up,Direction.down] direction = directions[randint(0,len(directions)-1)] snake_position = (randint(1, columns-snake_initial_size-1),randint(1, rows-snake_initial_size-1)) food_position = generateFood(grid) snake_nodes = getSnakeNodes(snake_position[0], snake_position[1], grid) screen = pygame.display.set_mode((screen_size[0]*block_size, screen_size[1]*block_size)) stuck_position = resetStuckPosition() # Game loop while not isGameOver(snake_nodes,grid): # Update score game_stats_label = font.render("Deaths: {} Score: {}".format(death_count,score_count), 1, (255,255,0)) for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True # Drawing screen.fill(screen_color) drawNodes(grid,screen) screen.blit(game_stats_label, (0, 0)) pygame.display.flip() # Clock ticking pygame.time.Clock().tick(999999999999) # If snake gets stuck in the same position for too long (5 times), shuffle the predictions stuck_position[snake_nodes[0].x][snake_nodes[0].y] += 1 shuffle_predictions = (stuck_position[snake_nodes[0].x][snake_nodes[0].y] > 5) # Manual controls # pressed = pygame.key.get_pressed() # if pressed[pygame.K_UP] and direction!=Direction.down: direction = Direction.up # elif pressed[pygame.K_DOWN] and direction!=Direction.up: direction = Direction.down # elif pressed[pygame.K_LEFT] and direction!=Direction.right: direction = Direction.left # elif pressed[pygame.K_RIGHT] and direction!=Direction.left: direction = Direction.right # Random controls # pressed = randint(0, 3) # if pressed == 0 and direction!=Direction.down: direction = Direction.up # elif pressed == 1 and direction!=Direction.up: direction = Direction.down # elif pressed == 2 and direction!=Direction.right: direction = Direction.left # elif pressed == 3 and direction!=Direction.left: direction = Direction.right # AI controls current_direction = direction inputs = neuralInputs(snake_nodes,grid,direction,food_position) direction,relative_direction = getPredictedDirection(snake_nodes,direction,model,inputs,grid,shuffle_predictions) previous_distance_between_snake_and_food = distanceBetweenSnakeAndFood(snake_nodes,food_position) snake_nodes = advanceSnake(snake_nodes,direction,grid) current_distance_between_snake_and_food = distanceBetweenSnakeAndFood(snake_nodes,food_position) # If game is over, target output is -1 # If snake has moved away from the goal, target output is 0 # If snake has moved closer to the goal, target output is 1 if isGameOver(snake_nodes,grid): target_output = -1 elif current_distance_between_snake_and_food >= previous_distance_between_snake_and_food: target_output = 0 else: target_output = 1 output = getOutputForTraining(target_output,inputs,snake_nodes,getRelativeDirection(current_direction,direction)) # file = open("Data.csv","a") # file.write(output) # file.close() if checkForFoodCollision(snake_nodes,grid): score_count += 1 food_position = generateFood(grid) shuffle_predictions = False stuck_position = resetStuckPosition() snake_nodes,grid = getGrownSnake(snake_nodes,direction,grid) # Load CSV file, indicate that the first column represents labels data = pds.read_csv("Data.csv",usecols=[1,2,3,4,5]) labels = pds.read_csv("Data.csv",usecols=[0]) model = getTrainedModel(data,labels) # coreml_model = coremltools.converters.keras.convert(model) # coreml_model.save("SnakeModel.mlmodel") death_count = 0 pygame.init() font = pygame.font.SysFont("monospace", 50) while True: death_count += 1 runGame(death_count,font,model)
eb4cf44fd6b37b47134e4dd75cabf2a51b55f3de
[ "Markdown", "Python" ]
8
Python
Sahilamin219/game-bot
4e138c3ffea0e3b0b288a3a37d57731f0f29f3a9
8a8d95d4e4f4379cd853ae428ca5237e54f60e09
refs/heads/master
<file_sep>require 'pry' def generatePaths(pebblePath) pattern = "" frogCurrent = 0 while frogCurrent <= (pebblePath.length - 2) decision = whatToDo(pebblePath, frogCurrent) frogCurrent = frogCurrent + 1 if decision == 'A' frogCurrent = frogCurrent + 2 if decision == 'B' pattern << decision end return pattern end private def whatToDo(pebblePath, frogCurrent) pebblePath[frogCurrent + 1] == ' ' ? 'B' : 'A' end path = generatePaths('pp pp pppp') puts path
1282dd3cd70fd74b29ab495654d7af4bd56cee84
[ "Ruby" ]
1
Ruby
sriharshakappala/path-finder
2a2417a7384bc13b776ba3c6255d33485787249b
b9a97806da0837332d682d4ca59959dd5062a672
refs/heads/master
<file_sep>require 'pry' # A method to reverse each word in a sentence, in place. def reverse_words(my_words) return nil if my_words == nil return my_words if my_words.length == 1 index = 0 while index < my_words.length while my_words[index] == " " index += 1 end j = index while my_words[j] != " " && j < my_words.length - 1 j += 1 end n = index m = j while n < m while my_words[n] == " " n += 1 end while my_words[m] == " " m -= 1 end temp = my_words[n] my_words[n] = my_words[m] my_words[m] = temp n += 1 m -= 1 end index = j + 1 end return my_words end
2eb64c100887a13cc0563eb737872008b3896b9e
[ "Ruby" ]
1
Ruby
diklaaharoni/reverse_words
728999d884407cced6d955cf5d9923dec728ab1e
1e4c0d7645b79d090fcdbb93cfc5dc4d1339b45c
refs/heads/master
<file_sep>'use strict'; import assert from "assert"; describe("Test placeholder", () => { it("should pass", done => { assert.equal(true, true); done(); }); });<file_sep># node-vagrant-babel Node babel development environment with Vagrant <file_sep>#!/bin/bash # Syncronizes project on vagrant with host rsync -avh --include=".babelrc" --include=".gitignore" --exclude="node_modules" --exclude=".*" --exclude="dist" --delete /vagrant/ /home/vagrant<file_sep>#!/bin/bash # Development Environment Provisioning Script set -e # Exit script immediately on first error. echo "Updating..." sudo apt-get update echo "Installing GIT..." sudo apt-get install -y git libkrb5-dev echo "Installing Nodejs and NPM..." curl --silent --location https://deb.nodesource.com/setup_6.x | sudo -E bash - sudo apt-get install -y build-essential g++ nodejs echo "Installing PM2 server manager..." sudo npm install pm2 -g echo "rsyncing synced folder to vagrant user directory..." rsync -avh --include=".babelrc" --include=".gitignore" --exclude="node_modules" --exclude=".*" --exclude="dist" --delete /vagrant/ /home/vagrant echo "Installing dependencies..." npm install # add environment variables to .profile echo "export PROJECT_HOME=/home/vagrant" >> /home/vagrant/.profile<file_sep>'use strict'; export var appName = "Hapi Server"; export var glueComposeOptions = { relativeTo: process.env.PROJECT_HOME+"/lib" || __dirname };<file_sep>'use strict'; import Glue from "glue"; import {appName, glueComposeOptions} from "./config"; import manifest from "./manifest"; Glue.compose(manifest, glueComposeOptions, (err, server) => { if(err){ throw err; } server.start(() => { console.log(appName + " online!"); }); });
f4e6077eef68263cbd8c12dff46630ffc08afd7e
[ "JavaScript", "Markdown", "Shell" ]
6
JavaScript
acoulon99/node-vagrant-babel
dc4920d960254ff8e5298260df8487539fe1b54d
080d78d20859c310961c77228afb2cb91ecee0ad
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # @Time: 2020/11/11 14:32 # @Author: Rollbear # @Filename: antColony.py import numpy as np import random from entity.roulette import Roulette class AntColony: def __init__(self, alpha, beta, rho, m, num_iter): # 算法参数 self.alpha = alpha # 权重alpha self.beta = beta # 权重beta self.rho = rho # 信息素更新权重 self.m = m # 族群规模 self.num_iter = num_iter # 迭代次数 # 维护的数据结构 self.taboo = None # 禁忌表,路径记忆向量 self.tau = None # 信息素表 self.paths = None # 路径长度表(邻接表) self.ant_tract = None # 记录蚂蚁走过的路径 # self.global_shortest = None # 全局最短路径 self.iter_shortest = [] # 记录每轮迭代的局部最优路径 def run(self, adj_mat, debug=False): self.paths = np.array(adj_mat) # 使用贪婪法初始化信息素 self.alg_init(debug) # 执行num iter次迭代 for i_iter in range(self.num_iter): # 在每轮迭代,重新初始化禁忌表与蚂蚁路径 self.taboo = {} self.ant_tract = {} if debug: print("\n" + "=" * 10 + f"iter {i_iter + 1}" + "=" * 10) self.run_iter(debug) def run_iter(self, debug): # 为每只蚂蚁随机选取出发城市 ant_cur_cities = random.choices(range(len(self.paths)), k=self.m) # 保存蚂蚁的出发城市,在遍历其他城市后需要回来 ant_start_cities = ant_cur_cities.copy() if debug: self.print_title("Set Off City") for i_ant, city in enumerate(ant_cur_cities): print(f"Ant{i_ant}: {city}") end = False # 算法到某个蚂蚁的禁忌表满(没有可用城市)时停止 while not end: # 为每只蚂蚁选择下一城市 for i_ant, cur_city in enumerate(ant_cur_cities): # 当前城市(已到达过的城市)加入禁忌表 if i_ant not in self.taboo: self.taboo[i_ant] = [cur_city] else: self.taboo[i_ant].append(cur_city) # 计算每个允许前往的城市的路径权重 city_weight = {} avail_cities = [i_city for i_city, _ in enumerate(self.paths[cur_city]) if i_city not in self.taboo.get(i_ant, [])] if len(avail_cities) == 0: end = True break for avail_city in avail_cities: # 计算访问某个城市的概率(权重) city_weight[avail_city] = self.probability(cur_city, avail_city) # 轮盘赌选择下一城市 next_city = Roulette(city_weight).roll() # 蚂蚁前往了下一城市,更新记录蚂蚁当前位置的表ant_cur_cities ant_cur_cities[i_ant] = next_city # 在蚂蚁路径记录中添加这条记录 if i_ant not in self.ant_tract: self.ant_tract[i_ant] = [(cur_city, next_city)] else: self.ant_tract[i_ant].append((cur_city, next_city)) if debug: self.print_title("Ant Report") print(f"Ant {i_ant}: {city_weight}") print(f"next city: {next_city}") # 每只蚂蚁回到出发的城市 for i_ant in range(self.m): cur_city = ant_cur_cities[i_ant] next_city = ant_start_cities[i_ant] self.ant_tract[i_ant].append((cur_city, next_city)) if debug: self.print_title("Ant Report") print(f"Ant {i_ant}: back to start city.") print(f"next city: {next_city}") # 本轮迭代结束,更新信息素,并计算本次迭代的局部最优 local_shortest = self.update_tau(debug) # 存储本轮迭代的局部最优路径 self.iter_shortest.append(local_shortest) def alg_init(self, debug): """初始化信息素:首先使用贪婪法计算次短路径信息素""" self.tau = np.zeros(shape=self.paths.shape) greed_taboo = [] cur_city = 0 path_length = 0 if debug: self.print_title("Alg Init") print("Greedy Path:", end=" ") while True: greed_taboo.append(cur_city) # 走过的城市加入禁忌表(局部变量) if debug: print(cur_city, end=" ") next_city_cluster = sorted([(i, elem) for i, elem in enumerate(self.paths[cur_city]) if i not in greed_taboo], key=lambda item: item[1]) if len(next_city_cluster) == 0: break next_city = sorted([(i, elem) for i, elem in enumerate(self.paths[cur_city]) if i not in greed_taboo], key=lambda item: item[1])[0][0] path_length += self.paths[cur_city, next_city] cur_city = next_city path_length += self.paths[cur_city, 0] tau_0 = self.m / path_length # 使用贪婪最短路径计算初始信息素浓度 if debug: print() print(f"τ0: {tau_0}") self.tau[:, :] = tau_0 # 所有路径上的信息素浓度初始化为tau0 def update_tau(self, debug): """更新信息素,并返回本次迭代的局部最优路径""" if debug: self.print_title("Updating tau") ant_path_length = [] ant_delta_tau = {} # 存储每只蚂蚁对每条路径的信息素增量 # 计算每只蚂蚁在一轮迭代中走过的路径长度,计算信息素更新量 for i_ant, tracts in self.ant_tract.items(): # 计算蚂蚁在这次迭代走过的路径长 path_length = sum([self.paths[tract[0], tract[1]] for tract in tracts]) if debug: print(f"Ant {i_ant} path length: {path_length}") ant_path_length.append(path_length) # 信息素增量等于蚂蚁这次迭代走过的路径长的倒数 delta_tau = {(i, j): 1 / path_length for i, j in tracts} ant_delta_tau[i_ant] = delta_tau # 更新信息素 for i in range(len(self.tau)): for j in range(len(self.tau[0])): # 计算所有蚂蚁对这条边的更新量 delta_sum = sum([delta.get((i, j), 0) for delta in ant_delta_tau.values()]) self.tau[i, j] = (1 - self.rho) * self.tau[i, j] + delta_sum if debug: print("tau:") print(self.tau) # 返回局部最优路径 return min(ant_path_length) def eta(self, i, j): """以路径距离的倒数作为η(课本方法)""" return 1 / self.paths[i, j] def probability(self, cur_city, target_city): """计算蚂蚁从城市A前往城市B的概率""" return (self.tau[cur_city, target_city] ** self.alpha) * \ (self.eta(cur_city, target_city) ** self.beta) @staticmethod def print_title(message): print("-" * 10 + message + "-" * 10) <file_sep># -*- coding: utf-8 -*- # @Time: 2020/11/11 14:22 # @Author: Rollbear # @Filename: roulette.py import random class Roulette: def __init__(self, weight: dict): items = [(key, value) for key, value in weight.items()] self.index = [elem[0] for elem in items] self.weight_lt = [elem[1] for elem in items] def roll(self): hit = None volume = sum(self.weight_lt) key = random.random() * volume for i, sample in enumerate(self.weight_lt): if sum(self.weight_lt[:i + 1]) >= key: hit = i return self.index[hit]
ba5f66db022e5bfd095da189099aa871ef2b8835
[ "Python" ]
2
Python
Rollbear-bot/AntColony
5f7bce3975dee63a28d9ebaa7bc02bf17290af1b
d22450913fb6a68693744d56481c44f02b48d417
refs/heads/master
<file_sep>#!/bin/sh $SNAP/bin/dogecoin-qt -datadir=$SNAP_USER_COMMON "$@"
447d2543d88fbf6657d3828315307ed9be8fc825
[ "Shell" ]
1
Shell
barryprice/dogecoin
d090e5f66f929df3c4fb51ebd9137d59dd6e17ab
48c077d82be44d291a98732958f383e1535a9aaa
refs/heads/master
<repo_name>tomgk/health-check<file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/LinkBuilder.java package org.exolin.health.servlets; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * * @author tomgk */ public class LinkBuilder { private final String url; private final boolean json; public LinkBuilder(String url, boolean json) { this.url = url; this.json = json; } public String link(String type, String name) { String serviceId = type+":"+name; try{ return url+"?"+(json?"type=json&":"")+"service="+URLEncoder.encode(serviceId, "UTF-8"); }catch(UnsupportedEncodingException e){ throw new RuntimeException(e); } } } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/html/Formatter.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.exolin.health.servlets.html; import java.io.PrintWriter; import java.time.LocalDateTime; import java.time.ZoneOffset; /** * * @author tomgk */ public class Formatter { static void writeException(PrintWriter out, Throwable e) { out.print("<pre>"); e.printStackTrace(out); out.print("</pre>"); } static String formatTimestamp(Long timestamp) { if(timestamp == null) return "NULL"; return LocalDateTime.ofEpochSecond(timestamp/1000, (int)(timestamp%1000*1000000), ZoneOffset.UTC).toString()+" UTC"; } static String formatDuration(Long duration) { if(duration == null) return "NULL"; if(duration < 1000) return duration+" ms"; else return duration/1000+" s, "+duration%1000+" ms"; } } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/json/ValueWrapper.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.exolin.health.servlets.json; import org.exolin.health.servlets.Value; /** * * @author tomgk */ public class ValueWrapper { private final Value value; public ValueWrapper(Value value) { this.value = value; } public String getValue() { return value.getValue(); } public EceptionWrapper getException() { return EceptionWrapper.wrap(value.getException()); } } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/json/EceptionWrapper.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.exolin.health.servlets.json; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * * @author tomgk */ @JsonPropertyOrder({ "name", "message" }) public class EceptionWrapper { private final Throwable exception; private EceptionWrapper(Throwable exception) { this.exception = exception; } static EceptionWrapper wrap(Throwable exception) { return exception != null ? new EceptionWrapper(exception) : null; } public String getType() { return exception.getClass().getName(); } public String getMessage() { return exception.getMessage(); } } <file_sep>/health-servlets/src/test/java/org/exolin/health/servlets/FinderTest.java package org.exolin.health.servlets; import java.util.Arrays; import java.util.List; import org.junit.Test; import static org.junit.Assert.*; /** * Tests für {@link Finder} * * @author tomgk */ public class FinderTest { static class HealthComponentImpl implements HealthComponent { private final String type; private final String name; private final List<HealthComponent> subComponents; public HealthComponentImpl(String type, String name, HealthComponent...subComponents) { this.type = type; this.name = name; this.subComponents = Arrays.asList(subComponents); } @Override public String getType() { return type; } @Override public Status getStatus() { return Status.OK; } @Override public String getName() { return name; } @Override public List<HealthComponent> getSubComponents() { return subComponents; } } HealthComponentImpl sub1, sub2; HealthComponentImpl root = new HealthComponentImpl("root", "xyz", sub1 = new HealthComponentImpl("sub", "name1", sub2 = new HealthComponentImpl("sub", "name2"), new HealthComponentImpl("sub", null) //Namenslose sollten zu keinem Problem führen ) ); @Test public void testFind_Root() { assertSame(root, Finder.find(root, "root", "xyz")); } @Test public void testFind_Level1() { assertSame(sub1, Finder.find(root, "sub", "name1")); } @Test public void testFind_Level2() { assertSame(sub2, Finder.find(root, "sub", "name2")); } @Test public void testFind_NotFound() { assertNull(Finder.find(root, "sub", "name3")); } } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/json/HealthComponentShortInfo.java package org.exolin.health.servlets.json; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.exolin.health.servlets.HealthComponent; import org.exolin.health.servlets.LinkBuilder; /** * * @author tomgk */ @JsonPropertyOrder({ "type", "name", "url" }) public class HealthComponentShortInfo { private final HealthComponent component; private final LinkBuilder linkBuilder; public HealthComponentShortInfo(HealthComponent component, LinkBuilder linkBuilder) { this.component = component; this.linkBuilder = linkBuilder; } public String getType() { return component.getType(); } public String getName() { return component.getName(); } public String getUrl() { String name = component.getName(); if(name == null) return null; return linkBuilder.link(component.getType(), name); } } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/html/HealthComponentWithParent.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.exolin.health.servlets.html; import org.exolin.health.servlets.HealthComponent; /** * * @author tomgk */ public class HealthComponentWithParent { private final HealthComponent parent; private final HealthComponent component; public HealthComponentWithParent(HealthComponent parent, HealthComponent component) { this.parent = parent; this.component = component; } public HealthComponent getComponent() { return component; } public HealthComponent getParent() { return parent; } } <file_sep>/README.md # health-check [![Build Status](https://travis-ci.com/tomgk/health-check.svg?branch=master)](https://travis-ci.com/tomgk/health-check) Utilities for health checks in websites/-services <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/json/HealthJSON.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.exolin.health.servlets.json; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.Writer; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.exolin.health.servlets.HealthComponent; import org.exolin.health.servlets.LinkBuilder; import org.exolin.health.servlets.Status; import org.exolin.health.servlets.Visualizer; /** * * @author tomgk */ public class HealthJSON implements Visualizer { private static final ObjectMapper mapper = new ObjectMapper(); static { mapper.setSerializationInclusion(Include.NON_NULL); } @Override public void write(String url, HealthComponent component, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json;charset=UTF-8"); write(url, response.getWriter(), component); } static void write(String url, Writer out, HealthComponent component) throws IOException { LinkBuilder linkBuilder = new LinkBuilder(url, true); mapper.writeValue(out, new HealthComponentWrapper(component, linkBuilder)); } @Override public void writeNotFound(String url, String type, String name, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); mapper.writeValue(response.getWriter(), Collections.singletonMap("error", "not found: service[type="+type+", name="+name+"]")); } @Override public void showStatusAggregate(String url, Map<Status, Map<String, List<HealthComponent>>> aggregated, HttpServletRequest request, HttpServletResponse response) throws IOException { LinkBuilder linkBuilder = new LinkBuilder(url, true); Map<String, Map<String, List<HealthComponentShortInfo>>> shortInfoOfStatus = new LinkedHashMap<>(); for(Map.Entry<Status, Map<String, List<HealthComponent>>> ofStatus: aggregated.entrySet()) { Map<String, List<HealthComponentShortInfo>> shortInfoOfSpecificStatus = new LinkedHashMap<>(); for(Map.Entry<String, List<HealthComponent>> ofSpecificStatus: ofStatus.getValue().entrySet()) { shortInfoOfSpecificStatus.put( ofSpecificStatus.getKey(), ofSpecificStatus.getValue() .stream() .map(c -> new HealthComponentShortInfo(c, linkBuilder)) .collect(Collectors.toList()) ); } shortInfoOfStatus.put(ofStatus.getKey().name().toLowerCase(), shortInfoOfSpecificStatus); } mapper.writeValue(response.getWriter(), shortInfoOfStatus); } } <file_sep>/health-servlets/src/test/java/org/exolin/health/servlets/json/HealthJSONTest.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.exolin.health.servlets.json; import java.io.StringWriter; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.exolin.health.servlets.HealthComponent; import org.exolin.health.servlets.Status; import org.exolin.health.servlets.Value; import static org.junit.Assert.*; import org.junit.Test; /** * * @author tomgk */ public class HealthJSONTest { private static final String URL = "http://exolin.test/status"; static class HealthComponentRoot implements HealthComponent { @Override public String getType() { return "root"; } @Override public Status getStatus() { return Status.OK; } } @Test public void testWriteMinimal() throws Exception { StringWriter out = new StringWriter(); HealthJSON.write(URL, out, new HealthComponentRoot()); assertEquals("{\"type\":\"root\",\"status\":\"ok\"}", out.toString()); } static class HealthComponentRoot2 implements HealthComponent { @Override public String getType() { return "root"; } @Override public String getName() { return "a name"; } @Override public String getVersion() { return "3.2"; } @Override public String getSubType() { return "rooty"; } @Override public Status getStatus() { return Status.OK; } @Override public String getSpecificStatus() { return "running"; } @Override public Long getStartTime() { return 1234l; } @Override public Long getStartDuration() { return 5678l; } @Override public Throwable getStartupException() { return null; } @Override public List<HealthComponent> getSubComponents() { return Arrays.asList(new HealthComponent() { @Override public String getType() { return "sub-thingy"; } @Override public Status getStatus() { return Status.OK; } }); } @Override public Map<String, Value> getProperties() { return Collections.singletonMap("something", Value.value("value of it")); } } @Test public void testWriteAll() throws Exception { StringWriter out = new StringWriter(); HealthJSON.write(URL, out, new HealthComponentRoot2()); assertEquals("{" + "\"type\":\"root\"," + "\"name\":\"a name\"," + "\"version\":\"3.2\"," + "\"subType\":\"rooty\"," + "\"url\":\"http://exolin.test/status?type=json&service=root%3Aa+name\"," + "\"status\":\"ok\"," + "\"specificStatus\":\"running\"," + "\"properties\":{\"something\":{\"value\":\"value of it\"}}," + "\"startTime\":1234," + "\"startDuration\":5678," + "\"subComponents\":[{\"type\":\"sub-thingy\",\"status\":\"ok\"}" + "]}", out.toString()); } } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/Constants.java package org.exolin.health.servlets; /** * * @author tomgk */ public class Constants { public static final String VERSION = "1.3"; } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/Value.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.exolin.health.servlets; /** * * @author tomgk */ public class Value { private final String value; private final Throwable exception; public Value(String value, Throwable exception) { this.value = value; this.exception = exception; } public static Value value(String value) { return new Value(value, null); } public static Value failed(Throwable exception) { return new Value(null, exception); } public String getValue() { return value; } public Throwable getException() { return exception; } } <file_sep>/health-servlets/src/main/java/org/exolin/health/servlets/Status.java package org.exolin.health.servlets; /** * * @author tomgk */ public enum Status { OK, ERROR }
306427172e21155f98052288a72ed9a1bbd30de4
[ "Markdown", "Java" ]
13
Java
tomgk/health-check
c048ba83746a059e0d469f3d13f1873d65cee446
be35560336dc46233f78e8e72026dc30350b7b2a
refs/heads/master
<repo_name>bonebox/DATASource<file_sep>/Podfile use_frameworks! link_with 'Tests', 'CollectionSwift', 'CollectionObjC', 'TableSwift', 'TableObjC', 'InfiniteTableSwift', 'InfiniteCollectionSwift' pod 'DATASource', path: "." pod 'DATAStack'
768c8fa8d82e06d359e20a765176b978a19ff34c
[ "Ruby" ]
1
Ruby
bonebox/DATASource
993e816aeb5dc593adf5334aa61885a907d39f78
63f220622fb121fef4e492ce519d197a47d108fa
refs/heads/main
<file_sep># blockchain-training-urcet The training codes used in Blockchain Training for URCET 2021 Batch
10b27c8c0a34c3c9b4723a51ce9fa38c7fcea59d
[ "Markdown" ]
1
Markdown
madblocksgit/blockchain-training-urcet
59c93de8a097e938ebc72afc02fea727b618cd9c
4d5f5b7e84f9fc9dc92122ab325ba9c7e4445120
refs/heads/master
<repo_name>B4lto/TestProject<file_sep>/Assets/Scripts/GameEventArgs/BuildingTypeEventArgs.cs using System; using Assets.Scripts.Enums; namespace Assets.Scripts.GameEventArgs { public class BuildingTypeEventArgs :EventArgs { public BuildingType Type { get; private set; } public BuildingTypeEventArgs(BuildingType type) { Type = type; } } } <file_sep>/Assets/Scripts/Components/InputHandler.cs using System; using Assets.Scripts.Components.Buildings; using Assets.Scripts.Enums; using Assets.Scripts.GameEventArgs; using Assets.Scripts.Helpers; using Assets.Scripts.Managers; using Assets.Scripts.Models; using UnityEngine; using UnityEngine.UI; namespace Assets.Scripts.Components { public class InputHandler : MonoBehaviour { [SerializeField] private Button _buildButton; [SerializeField] private GameObject _constructionSubMenuContainer; [SerializeField] private Button _buildSmallButton; [SerializeField] private Button _buildMediumButton; [SerializeField] private Button _buildLargeButton; [SerializeField] private GameObject _buildingsSubMenuContainer; [SerializeField] private Button _buildingInfo; [SerializeField] private Button _destroyBuilding; [SerializeField] private GameObject _infoContainer; [SerializeField] private Text _infoText; [SerializeField] private Text _gameMessages; private const string TerrainLayerName = "Terrain"; private const string BuildingsLayerName = "Building"; private const string InfoFormat = "Info: size = {0}"; private const int CameraSensitivity = 2; public event EventHandler<PositionEventArgs> TerrainClickedEvent; public event EventHandler NonUIClickEvent; public event EventHandler BuildMenuButtonClickedEvent; public event EventHandler<BuildingTypeEventArgs> BuildBuildingButtonClickedEvent; public event EventHandler<PositionEventArgs> BuildingClickedEvent; public event EventHandler DestroyBuildingEvent; private void Update() { if (Input.GetMouseButtonDown(0)) { if (!IsUIClick() && NonUIClickEvent != null) { NonUIClickEvent.Invoke(this, null); CheckBuildingHit(); CheckTerrainHit(); } } HandleCameraInput(); } public void Init() { _buildButton.onClick.AddListener(BuildButtonHandler); _buildSmallButton.onClick.AddListener(BuildSmallButtonHandler); _buildMediumButton.onClick.AddListener(BuildMediumButtonHandler); _buildLargeButton.onClick.AddListener(BuildLargeButtonHandler); _buildingInfo.onClick.AddListener(BuildingInfoButtonHandler); _destroyBuilding.onClick.AddListener(DestroyBuildingButtonHandler); } public void Dissmiss() { _buildButton.onClick.RemoveListener(BuildButtonHandler); _buildSmallButton.onClick.RemoveListener(BuildSmallButtonHandler); _buildMediumButton.onClick.RemoveListener(BuildMediumButtonHandler); _buildLargeButton.onClick.RemoveListener(BuildLargeButtonHandler); _buildingInfo.onClick.RemoveListener(BuildingInfoButtonHandler); _destroyBuilding.onClick.RemoveListener(DestroyBuildingButtonHandler); } private void CheckTerrainHit() { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, float.MaxValue, LayerMask.GetMask(TerrainLayerName))) { //I want my game coordinates to start from left bottom edge and match cells indexes. int x = -1; int y = -1; CoordinatesHelper.ConvertWorldCoordinatesToGame(hit.point, out x, out y); var gameCoord = new Vector2(x, y); //Debug.Log("worldX = " + hit.point.x + " worldZ = " + hit.point.z); //Debug.Log("gameCordX = " + gameCord.x + " gameCordY = " + gameCord.y); if (TerrainClickedEvent != null) { TerrainClickedEvent.Invoke(this, new PositionEventArgs(gameCoord)); } } } private void CheckBuildingHit() { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, float.MaxValue, LayerMask.GetMask(BuildingsLayerName))) { var buildingView = hit.transform.parent.GetComponent<BuildingView>(); if (buildingView != null && BuildingClickedEvent != null) { var centerOffset = buildingView.Size * 0.5f; int x = -1; int y = -1; var cellPosition = new Vector3(buildingView.transform.position.x - centerOffset, 0, buildingView.transform.position.z - centerOffset); CoordinatesHelper.ConvertWorldCoordinatesToGame(cellPosition, out x, out y); var gameCoord = new Vector2(x,y); BuildingClickedEvent.Invoke(this, new PositionEventArgs(gameCoord)); } } } private bool IsUIClick() { return UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(); } #region Menu Controls public void DisplayConstructionMenu() { _infoContainer.SetActive(false); _buildingsSubMenuContainer.SetActive(false); _constructionSubMenuContainer.SetActive(true); } public void HideConstructionMenu() { _constructionSubMenuContainer.SetActive(false); } public void DisplayBuildingsMenu() { _buildingsSubMenuContainer.SetActive(true); } public void HideBuildingsMenu() { _buildingsSubMenuContainer.SetActive(false); } public void DisplayBuildingInfo(Building selectedBuilding) { if (selectedBuilding != null) { _infoContainer.SetActive(true); _infoText.text = string.Format(InfoFormat, selectedBuilding.Size); } } public void HideBuildingInfo() { _infoContainer.SetActive(false); } public void CloseAllSubMenus() { HideBuildingsMenu(); HideBuildingInfo(); HideConstructionMenu(); SetGameMessage(""); } public void SetGameMessage(string message) { _gameMessages.text = message; } #endregion #region Camera Controls private void HandleCameraInput() { if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) { MoveCamera(Vector2.up); } if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) { MoveCamera(Vector2.down); } if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) { MoveCamera(Vector2.left); } if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) { MoveCamera(Vector2.right); } } private void MoveCamera(Vector2 direction) { var currentPos = Camera.main.transform.position; Camera.main.transform.position = new Vector3(currentPos.x + direction.x * CameraSensitivity, currentPos.y, currentPos.z + direction.y * CameraSensitivity); } #endregion #region ButtonsHandlers private void BuildButtonHandler() { if (BuildMenuButtonClickedEvent != null) { BuildMenuButtonClickedEvent.Invoke(this, null); } } private void BuildSmallButtonHandler() { if (BuildBuildingButtonClickedEvent != null) { BuildBuildingButtonClickedEvent.Invoke(this, new BuildingTypeEventArgs(BuildingType.Small)); } } private void BuildMediumButtonHandler() { if (BuildBuildingButtonClickedEvent != null) { BuildBuildingButtonClickedEvent.Invoke(this, new BuildingTypeEventArgs(BuildingType.Medium)); } } private void BuildLargeButtonHandler() { if (BuildBuildingButtonClickedEvent != null) { BuildBuildingButtonClickedEvent.Invoke(this, new BuildingTypeEventArgs(BuildingType.Large)); } } private void BuildingInfoButtonHandler() { DisplayBuildingInfo(GameManager.Instance.SelectedBuilding); } private void DestroyBuildingButtonHandler() { if (DestroyBuildingEvent != null) { DestroyBuildingEvent.Invoke(this, null); } } #endregion } } <file_sep>/Assets/Scripts/Helpers/RandomHelper.cs using System; namespace Assets.Scripts.Helpers { public static class RandomHelper { private static readonly Random _random = new Random(); public static Random Random { get { return _random; } } public static int Roll(int max) { return Random.Next(max); } } } <file_sep>/Assets/Scripts/Enums/TerrainCellType.cs namespace Assets.Scripts.Enums { public enum TerrainCellType { Free = 0, NotAvailiable = 1, HasBuilding = 2 } } <file_sep>/Assets/Scripts/Models/Building.cs using Assets.Scripts.Enums; using UnityEngine; namespace Assets.Scripts.Models { public class Building { public BuildingType Type { get; private set; } public Vector2 Position { get; set; } public int Size { get { switch (Type) { case BuildingType.Small: return 1; case BuildingType.Medium: return 2; case BuildingType.Large: return 3; default: Debug.LogError("Trying to get size of undefined type"); return 0; } } } public Building(BuildingType type) { Type = type; } } } <file_sep>/Assets/Scripts/Managers/TerrainManager.cs using Assets.Scripts.Components.Surface; using Assets.Scripts.Enums; using Assets.Scripts.Helpers; using UnityEngine; using Debug = System.Diagnostics.Debug; namespace Assets.Scripts.Managers { public class TerrainManager { private static readonly TerrainManager _instance = new TerrainManager(); public static TerrainManager Instance { get { return _instance; } } private TerrainManager() { Terrain = new TerrainCellType[MapSize * MapSize]; } private const int MapSize = 100; private const int BadSurfaceCellsCount = 100; //10% of all surface is not available for construction private TerrainCellType[] Terrain { get; set; } public void GenerateTerrainSurface() { var cellsCount = MapSize*MapSize; for (var i = 0; i < BadSurfaceCellsCount; i++) { var rand = RandomHelper.Roll(cellsCount); while (Terrain[rand] != TerrainCellType.Free) { rand = RandomHelper.Roll(cellsCount); } CreateInvalidSurface(rand); } } private void CreateInvalidSurface(int index) { Terrain[index] = TerrainCellType.NotAvailiable; var gameObj = new GameObject(typeof(InvalidSurfaceViewController).Name); var surfaceVC = gameObj.AddComponent<InvalidSurfaceViewController>(); surfaceVC.Init(GetPosition(index)); } public void PlaceBuilding(int posX, int posY, int sizeX, int sizeY) { for (var i = 0; i < sizeX; i++) { for (var j = 0; j < sizeY; j++) { var index = GetIndex(posX + i, posY + j); Debug.Assert(!IsCellFree(index), "Construction on non acceptable place"); Terrain[index.Value] = TerrainCellType.HasBuilding; } } } public void RemoveBuilding(int posX, int posY, int sizeX, int sizeY) { for (var i = 0; i < sizeX; i++) { for (var j = 0; j < sizeY; j++) { var index = GetIndex(posX + i, posY + j); Debug.Assert(!index.HasValue, "Removing from bad cell"); Terrain[index.Value] = TerrainCellType.Free; } } } public bool CanPlaceBuilding(int posX, int posY, int sizeX, int sizeY) { //if building is larger than 1x1 we place it right bottom from cursor for (var i = 0; i < sizeX; i++) { for (var j = 0; j < sizeY; j++) { if (!IsCellFree(posX + i, posY + j)) { return false; } } } return true; } #region Helpers private int? GetIndex(int x, int y) { var index = x * 100 + y; if (index > MapSize*MapSize || index < 0) { return null; } return index; } private Vector2 GetPosition(int index) { int x = index/100; int y = index - 100*x; return new Vector2(x,y); } private bool IsCellFree(int x, int y) { var index = GetIndex(x, y); return IsCellFree(index); } private bool IsCellFree(int? index) { if (!index.HasValue) { return false; } return Terrain[index.Value] == TerrainCellType.Free; } #endregion } } <file_sep>/Assets/Scripts/Components/Surface/InvalidSurfaceViewController.cs using Assets.Scripts.Helpers; using UnityEngine; namespace Assets.Scripts.Components.Surface { public class InvalidSurfaceViewController : MonoBehaviour { private const string PrefabPath = "InvalidSurface"; private InvalidSurfaceView View { get; set; } public void Init(Vector2 position) { var prefab = Resources.Load(PrefabPath) as GameObject; Vector3 worldPos; CoordinatesHelper.ConvertGameCoordinatesToWorld((int)position.x, (int)position.y, out worldPos); worldPos.x += 0.5f; worldPos.z += 0.5f; worldPos.y += 0.01f; View = Instantiate(prefab, worldPos, Quaternion.identity, transform).GetComponent<InvalidSurfaceView>(); } } } <file_sep>/Assets/Scripts/Managers/ConstructionManager.cs using System.Collections.Generic; using Assets.Scripts.Components.Buildings; using Assets.Scripts.Constants; using Assets.Scripts.Enums; using Assets.Scripts.Models; using UnityEngine; namespace Assets.Scripts.Managers { public class ConstructionManager { private static readonly ConstructionManager _instance = new ConstructionManager(); public static ConstructionManager Instance { get { return _instance; } } private ConstructionManager() { BuildingsVCs = new List<BuildingViewController>(); } private List<BuildingViewController> BuildingsVCs; public void ConstructBuilding(Building building, Vector2 position) { if (TerrainManager.Instance.CanPlaceBuilding((int) position.x, (int) position.y, building.Size, building.Size)) { building.Position = position; var gameObj = new GameObject(typeof(BuildingViewController).Name); var buildingVC = gameObj.AddComponent<BuildingViewController>(); buildingVC.Init(building); BuildingsVCs.Add(buildingVC); TerrainManager.Instance.PlaceBuilding((int) position.x, (int) position.y, building.Size, building.Size); } else { GameManager.Instance.DisplayGameMessage(GameMessages.CantPlaceBuilding); } } public void RemoveBuilding(Building building) { var buildingVC = BuildingsVCs.Find(vc => vc.Building.Position == building.Position); Debug.Assert(buildingVC != null, "Trying to remove null building"); buildingVC.RemoveBuilding(); BuildingsVCs.Remove(buildingVC); TerrainManager.Instance.RemoveBuilding((int)building.Position.x, (int)building.Position.y, building.Size, building.Size); } public Building GetBuildingAtPosition(Vector2 position) { var buildingVC = BuildingsVCs.Find(vc => vc.Building.Position == position); return buildingVC != null ? buildingVC.Building : null; } } } <file_sep>/Assets/Scripts/Components/Buildings/BuildingViewController.cs using Assets.Scripts.Enums; using Assets.Scripts.Helpers; using Assets.Scripts.Models; using UnityEngine; namespace Assets.Scripts.Components.Buildings { public class BuildingViewController : MonoBehaviour { private const string PrefabsPath = "Buildings/"; public Building Building { get; private set; } private BuildingView View { get; set; } public void Init(Building building) { Building = building; InstantiateView(); } public int Size { get { return Building.Size; } } public void RemoveBuilding() { //Better solution - hide object instance from scene, put reference to a pool and reuse it later, avoiding multiply instantiation and destroyong. View.Destroy(); } private void InstantiateView() { var prefabName = ""; //game coordinates correspond to left bottom edge of cell var offset = 0f; switch (Building.Type) { case BuildingType.Small: prefabName = "BuildingSmallView"; offset = 0.5f; break; case BuildingType.Medium: prefabName = "BuildingMediumView"; offset = 1f; break; case BuildingType.Large: prefabName = "BuildingLargeView"; offset = 1.5f; break; } var prefab = Resources.Load(PrefabsPath + prefabName) as GameObject; Debug.Assert(prefab != null, "Trying to create null object"); if (prefab == null) { return; } Vector3 worldPos; CoordinatesHelper.ConvertGameCoordinatesToWorld((int)Building.Position.x, (int)Building.Position.y, out worldPos); worldPos.x += offset; worldPos.z += offset; View = Instantiate(prefab, worldPos, Quaternion.identity).GetComponent<BuildingView>(); View.Size = Size; } } } <file_sep>/Assets/Scripts/Helpers/CoordinatesHelper.cs using System; using UnityEngine; namespace Assets.Scripts.Helpers { public static class CoordinatesHelper { public static void ConvertGameCoordinatesToWorld(int gameX, int gameY, out Vector3 worldCoord) { worldCoord = new Vector3(gameX - 50, 0 , gameY - 50); } public static void ConvertWorldCoordinatesToGame(Vector3 worldCoord, out int gameX, out int gameY) { gameX = (int) Math.Floor(worldCoord.x) + 50; gameY = (int) Math.Floor(worldCoord.z) + 50; } } } <file_sep>/Assets/Scripts/Components/Buildings/BuildingView.cs using Assets.Scripts.Helpers; using UnityEngine; namespace Assets.Scripts.Components.Buildings { public class BuildingView : MonoBehaviour { [SerializeField] GameObject _model; public int Size { get; set; } public void Destroy() { Destroy(_model); } } } <file_sep>/Assets/Scripts/Constants/GameMessages.cs namespace Assets.Scripts.Constants { public static class GameMessages { public const string CantPlaceBuilding = "Can't place building here"; public const string ChooseBuilding = "Choose building type"; } } <file_sep>/Assets/Scripts/Enums/GameState.cs namespace Assets.Scripts.Enums { public enum GameState { Invalid = 0, FreeRunning = 1, Constructing = 2 } } <file_sep>/Assets/Scripts/Managers/GameManager.cs using System; using System.Collections; using Assets.Scripts.Components; using Assets.Scripts.Constants; using Assets.Scripts.Enums; using Assets.Scripts.GameEventArgs; using Assets.Scripts.Models; using UnityEngine; namespace Assets.Scripts.Managers { public class GameManager : MonoBehaviour { //I want to have entry point here, so this is MonoBehaviour class and not a standard singleton. public static GameManager Instance { get; private set; } private GameState CurrentState { get; set; } private InputHandler GameMenu { get; set; } public Building SelectedBuilding { get; private set; } private void Awake() { Instance = this; StartGame(); } public void StartGame() { LoadUI(); TerrainManager.Instance.GenerateTerrainSurface(); CurrentState = GameState.FreeRunning; } private void LoadUI() { var menuUI = Resources.Load("Buildings/MenuUI") as GameObject; if (menuUI == null) { Debug.LogError("Can't create Game Menu"); CurrentState = GameState.Invalid; return; } GameMenu = Instantiate(menuUI).GetComponent<InputHandler>(); GameMenu.Init(); RegisterInputEventsHandlers(); } public void DisplayGameMessage(string message) { GameMenu.SetGameMessage(message); } private void EndGame() { UnregisterInputEventsHandlers(); GameMenu.Dissmiss(); GameMenu = null; CurrentState = GameState.Invalid; } private void RegisterInputEventsHandlers() { GameMenu.BuildMenuButtonClickedEvent += BuildMenuButtonClickedEventHandler; GameMenu.BuildBuildingButtonClickedEvent += BuildingButtonClickedEventHandler; GameMenu.NonUIClickEvent += NonUIClickedEventHandler; GameMenu.TerrainClickedEvent += TerrainClickedEventHandler; GameMenu.BuildingClickedEvent += BuildingHitEventHandler; GameMenu.DestroyBuildingEvent += DestroyBuildingEventHandler; } private void UnregisterInputEventsHandlers() { GameMenu.BuildMenuButtonClickedEvent -= BuildMenuButtonClickedEventHandler; GameMenu.BuildBuildingButtonClickedEvent -= BuildingButtonClickedEventHandler; GameMenu.NonUIClickEvent -= NonUIClickedEventHandler; GameMenu.TerrainClickedEvent -= TerrainClickedEventHandler; GameMenu.BuildingClickedEvent -= BuildingHitEventHandler; GameMenu.DestroyBuildingEvent -= DestroyBuildingEventHandler; } private void SetState(GameState newState) { if (CurrentState == newState) { return; } CurrentState = newState; if (CurrentState == GameState.Constructing) { GameMenu.HideConstructionMenu(); } } private void BuildMenuButtonClickedEventHandler(object sender, EventArgs args) { GameMenu.DisplayConstructionMenu(); } private void BuildingButtonClickedEventHandler(object sender, BuildingTypeEventArgs args) { SelectedBuilding = new Building(args.Type); SelectedBuilding.Position = new Vector2(-1, -1); SetState(GameState.Constructing); } private void NonUIClickedEventHandler(object sender, EventArgs args) { GameMenu.CloseAllSubMenus(); } private void TerrainClickedEventHandler(object sender, PositionEventArgs args) { if (CurrentState == GameState.Constructing) { if (SelectedBuilding != null && SelectedBuilding.Type != BuildingType.NotSpecified) { ConstructionManager.Instance.ConstructBuilding(SelectedBuilding, args.Position); SelectedBuilding = null; SetState(GameState.FreeRunning); } else { DisplayGameMessage(GameMessages.ChooseBuilding); } } } private void BuildingHitEventHandler(object sender, PositionEventArgs args) { if (CurrentState != GameState.Constructing) { SelectedBuilding = ConstructionManager.Instance.GetBuildingAtPosition(args.Position); if (SelectedBuilding != null) { GameMenu.DisplayBuildingsMenu(); } } } private void DestroyBuildingEventHandler(object sender, EventArgs args) { ConstructionManager.Instance.RemoveBuilding(GameManager.Instance.SelectedBuilding); SelectedBuilding = null; GameMenu.CloseAllSubMenus(); } } } <file_sep>/Assets/Scripts/Components/Surface/InvalidSurfaceVIew.cs using UnityEngine; namespace Assets.Scripts.Components.Surface { public class InvalidSurfaceView : MonoBehaviour { [SerializeField] GameObject _invalidSurface; } } <file_sep>/Assets/Scripts/Enums/BuildingType.cs namespace Assets.Scripts.Enums { public enum BuildingType { NotSpecified = 0, Small = 1, Medium = 2, Large = 3 } } <file_sep>/Assets/Scripts/GameEventArgs/PositionEventArgs.cs using System; using UnityEngine; namespace Assets.Scripts.GameEventArgs { public class PositionEventArgs : EventArgs { public Vector2 Position { get; private set; } public PositionEventArgs(Vector2 position) { Position = position; } } }
77f5cd61f84133c5616cbdc9dfa3b9a6390c76da
[ "C#" ]
17
C#
B4lto/TestProject
9799822d9697639d19fb77921216c8d9040e9a4a
a4772be9916ef96e4fadaa8f435e26a0688bbbe3
refs/heads/master
<file_sep>import {Component} from '@angular/core'; import {environment} from '../environments/environment'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'angular demo'; api = environment.apiUrl; alerts = [{ type: 'success', message: 'Welcome to the demo!', }]; close(alert: { type: string; message: string }) { this.alerts.splice(this.alerts.indexOf(alert), 1); } } <file_sep>import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {GameRoutingModule} from './game-routing.module'; import {GameComponent} from './game.component'; import {GameBoardComponent} from './game-board/game-board.component'; import {SquareComponent} from './square/square.component'; import {GameService} from './game.service'; @NgModule({ declarations: [GameComponent, GameBoardComponent, SquareComponent], imports: [ CommonModule, GameRoutingModule ], providers: [GameService] }) export class GameModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; import { HerosRoutingModule } from './heros-routing.module'; import { HerosComponent } from './heros/heros.component'; import { HeroListComponent } from './hero-list/hero-list.component'; import { HeroDetailsComponent } from './hero-details/hero-details.component'; @NgModule({ declarations: [HerosComponent, HeroListComponent, HeroDetailsComponent], imports: [ NgbModule, CommonModule, HerosRoutingModule ] }) export class HerosModule { } <file_sep># Angulardemo This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.24. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build ``` ng build --configuration=production ``` Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). ### Add module ng g module heros --route=heros --module=app ### ngnix settings ngnix need to forward all urls to index.html to let angular handle the routing. Otherwise, will trigger 404. * nginx.conf ``` location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } ``` ### docker ``` npx lite-server --baseDir="dist/angulardemo" ng build --configuration=production docker build -t frankye2099/angular-demo:0.0.1 . docker run -p 80:80 frankye2099/angular-demo:0.0.1 docker push frankye2099/angular-demo:0.0.1 ``` ### kubernetes deployment.yaml ```$xslt kubectl create deployment demoui --image=frankye2099/angular-demo:0.0.1 --dry-run -o=yaml > deployment.yaml echo --- >> deployment.yaml kubectl create service loadbalancer demoui --tcp=80:80 --dry-run -o=yaml >> deployment.yaml ``` deploy ```$xslt kubectl apply -f deployment.yaml http://localhost ``` <file_sep>import {Component, Input, OnInit} from '@angular/core'; import {GameService} from '../game.service'; @Component({ selector: 'app-square', templateUrl: './square.component.html', styleUrls: ['./square.component.scss'] }) export class SquareComponent implements OnInit { @Input() id: number; @Input() value: string; constructor(private game: GameService) { } ngOnInit() { } click() { this.value = this.game.go(this.id); } } <file_sep>import {Injectable} from '@angular/core'; import {Observable, BehaviorSubject} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class GameService { private winLines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; squares: string[]; private xIsNext: boolean; private winnerSubject = new BehaviorSubject(null); winner = this.winnerSubject.asObservable(); private nextSubject = new BehaviorSubject(null); next = this.nextSubject.asObservable(); constructor() { this.reset(); } reset() { this.squares = ['', '', '', '', '', '', '', '', '']; this.xIsNext = true; this.winnerSubject.next(null); this.nextSubject.next('X'); } go(index) { const winner = this.calculateWinner(this.squares); if (!winner && this.squares[index] === '') { const next = this.getNext(); this.squares[index] = next; this.xIsNext = !this.xIsNext; this.nextSubject.next(this.getNext()); this.calculateWinner(this.squares); } return this.squares[index]; } getNext() { return this.xIsNext ? 'X' : 'O'; } calculateWinner(squares) { for (const line of this.winLines) { const [a, b, c] = line; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { this.winnerSubject.next(squares[a]); return squares[a]; } } return null; } } <file_sep>import {TestBed} from '@angular/core/testing'; import {GameService} from './game.service'; describe('GameService', () => { let service: GameService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.get(GameService); }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('go and getNext', () => { it('should return X/O alternately', () => { expect(service.getNext()).toEqual('X'); expect(service.go(0)).toEqual('X'); expect(service.getNext()).toEqual('O'); expect(service.go(1)).toEqual('O'); expect(service.getNext()).toEqual('X'); }); }); describe('calculateWinner', () => { it('should return null', () => { const squares = ['X', 'O', '', '', '', '', '', '', '']; expect(service.calculateWinner(squares)).toEqual(null); }); it('should return X', () => { const squares = ['X', 'X', 'X', 'O', 'O', '', '', '', '']; expect(service.calculateWinner(squares)).toEqual('X'); }); it('should return O', () => { const squares = ['O', 'X', 'X', 'X', 'O', 'O', 'X', 'X', 'O']; expect(service.calculateWinner(squares)).toEqual('O'); }); }); }); <file_sep>import { Component, OnInit, OnDestroy } from '@angular/core'; import {GameService} from '../game.service'; import {Subscription} from 'rxjs'; @Component({ selector: 'app-game-board', templateUrl: './game-board.component.html', styleUrls: ['./game-board.component.scss'] }) export class GameBoardComponent implements OnInit, OnDestroy { next: string; winner: string; square: string[]; private subscription: Subscription; constructor(private game: GameService) { } ngOnInit() { this.reset(); const nextSub = this.game.next.subscribe(value => this.next = value); const winnerSub = this.game.winner.subscribe(value => this.winner = value); this.subscription = nextSub; this.subscription.add(winnerSub); } ngOnDestroy(): void { this.subscription.unsubscribe(); } reset() { this.game.reset(); this.square = this.game.squares; } }
973c513248e1cce0adfd92dc7e6537389f40bead
[ "Markdown", "TypeScript" ]
8
TypeScript
frankye2099/angulardemo
12ea13da2d574fa7239399f647ac3f13f3c706c4
9db468769b261ba26dd2f8dae2adb06f6790ac36
refs/heads/main
<repo_name>Mitchellhogue0/maven-exercises<file_sep>/src/main/java/ApacheString.java //import com.sun.tools.jdeprscan.scan.Scan; import org.apache.commons.lang3.StringUtils; import java.util.Scanner; public class ApacheString { public static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println("Please enter a string :)"); String input = sc.nextLine(); StringTest(input); } public static void StringTest (String input) { System.out.println("This is a number? " + StringUtils.isNumeric(input)); System.out.println("This is the string with flipped casing: " + StringUtils.swapCase(input)); System.out.println("This is the string reversed: " + StringUtils.reverse(input)); } }
624352a928ed7be4b9e65a20f22deda6f6ce8952
[ "Java" ]
1
Java
Mitchellhogue0/maven-exercises
3d565d8b228822c47546a04bc63c2a5c1f8c5ed6
acb8143492aaacca0e58c444969707dcd038f681
refs/heads/master
<file_sep>Assignee: <NAME> EMAIL: <EMAIL> Language used: Java TASK ACHIEVED: 1. Read the data from the weather.dat file 2. Calculate the temperature spread for each day 3. Get the maximum spread and day of the month Assumptions Made: 1. Code to be view on developing IDE using JDK 1.7 and 1.8 JDK 2. The weather.dat file to be located in the project folder 3. The executable jar will remain the dist folder during execution 4. The asterisk in the values 32* and 97* removed using regex to eliminate the error: java.lang.NumberFormatException: For input string: "97*" 5. The file name and extension (weather.dat) to be maintained for the file to be scanned How to run the application: Requirements: > JDK/JRE 1.7 and above > JAVA_HOME environment variable set on OS (Linux/Windows) test: on terminal/commandline type "java -version" 1. Windows > Navigate to the project directory on file explorer > double click the "fileScanner.bat" or on command line type "start fileScanner.bat" 2. Linux > On Terminal navigate to the project directory. > grant execution privileges to file "fileScanner.sh": command: "chmod +x fileScanner.sh" > commands available "start: > then, type "./fileScanner start" <file_sep>======================== BUILD OUTPUT DESCRIPTION ======================== Assignee: <NAME> EMAIL: <EMAIL> Language used: Java TASK ACHIEVED: 1. Read the data from the weather.dat file 2. Calculate the temperature spread for each day 3. Get the maximum spread and day of the month Assumptions Made: 1. Code to be view on developing IDE using JDK 1.7 and 1.8 JDK 2. The weather.dat file to be located in the project folder 3. The executable jar will remain the dist folder during execution 4. The asterisk in the values 32* and 97* removed using regex to eliminate the error: java.lang.NumberFormatException: For input string: "97*" 5. The file name and extension (weather.dat) to be maintained for the file to be scanned How to run the application: Requirements: > JDK/JRE 1.7 and above > JAVA_HOME environment variable set on OS (Linux/Windows) test: on terminal/commandline type "java -version" 1. Windows > Navigate to the project directory on file explorer > double click the "fileScanner.bat" or on command line type "start fileScanner.bat" 2. Linux > On Terminal navigate to the project directory. > grant execution privileges to file "fileScanner.sh": command: "chmod +x fileScanner.sh" > commands available "start: > then, type "./fileScanner start" <file_sep>compile.on.save=true user.properties.file=C:\\Users\\<NAME>\\AppData\\Roaming\\NetBeans\\8.2\\build.properties <file_sep>#!/bin/sh DIR="$( cd "$( DIR "${BASH_SOURCE[0]}" )" && pwd )" JARNAME=$DIR/dist/FileScanner.jar start() { echo "Starting File scanner for weather.dat" #forward all logs to the files stated....needs file permissions 777 java -jar $JARNAME } case "$1" in start) start ;; *) echo "Usage: fileScanner {start}" exit 1 ;; esac exit $?
81bb06908a4c699e5638bff0cef0296134e3855e
[ "Markdown", "Shell", "Text", "INI" ]
4
Markdown
AlexKimani/WeatherDATTask
1947e522192fea5df3f149ac010b4bb6acc33a4c
46eb1be3fab645f9e4e3858a4b4c6704488057de
refs/heads/master
<repo_name>CristobalM/pisa_formatter<file_sep>/util.hpp // // Created by <NAME>, 2019 // #ifndef PISA_FORMATTER_UTIL_HPP #define PISA_FORMATTER_UTIL_HPP #include <string> #include <memory> #include <vector> #include "cxxopts/cxxopts.hpp" struct summary_opts { std::string option, description; std::shared_ptr<cxxopts::Value> value; }; using vsopts = std::vector<summary_opts>; inline void check_missing_opts(cxxopts::ParseResult &result_opt, vsopts &vso){ for(auto &so : vso){ if (result_opt[so.option].count() < 1) { throw std::runtime_error("--" + so.option + " option is missing: " + so.description); } } } std::unique_ptr<cxxopts::ParseResult> parse_input_cline(cxxopts::Options &options, std::vector<summary_opts> &opts, int argc, char **argv){ auto acc_opts = options.add_options(); for (auto &opt : opts) { acc_opts(opt.option, opt.description, opt.value); } std::unique_ptr<cxxopts::ParseResult> result_opt_ptr; try { result_opt_ptr = std::make_unique<cxxopts::ParseResult>(options.parse(argc, argv)); } catch (const cxxopts::argument_incorrect_type &e) { throw std::runtime_error("Invalid input: type error\nReason: " + std::string(e.what())); } check_missing_opts(*result_opt_ptr, opts); return result_opt_ptr; } #endif //PISA_FORMATTER_UTIL_HPP <file_sep>/query_transformer.cpp // // Created by <NAME>, 2019 // #include <cassert> #include <string> #include <fstream> #include <regex> #include "cxxopts/cxxopts.hpp" #include "terms_reader.hpp" #include "util.hpp" int main(int argc, char **argv){ static const std::string terms_idxes_file_label = "terms"; static const std::string queries_file_label = "queries"; static const std::string output_file_label = "output"; cxxopts::Options options("query_transformer", "converts query file with terms to indexes query file"); std::vector<summary_opts> opts = { {terms_idxes_file_label, "path to terms binary file", cxxopts::value<std::string>()}, {queries_file_label, "path to queries file", cxxopts::value<std::string>()}, {output_file_label, "path to output file", cxxopts::value<std::string>()} }; auto result_opt_ptr = parse_input_cline(options, opts, argc, argv); auto &result_opt = *result_opt_ptr; auto terms_file_name = result_opt[terms_idxes_file_label].as<std::string>(); auto queries_file_name = result_opt[queries_file_label].as<std::string>(); auto output_file_name = result_opt[output_file_label].as<std::string>(); terms_reader tr(terms_file_name); std::ifstream queries_file(queries_file_name); std::ofstream output_file(output_file_name); static const std::string word_regex_str = "([^\\s]+)"; std::regex word_regex(word_regex_str); std::string line; while(std::getline(queries_file, line)){ std::vector<std::string> words(std::sregex_token_iterator(line.begin(),line.end(), word_regex), std::sregex_token_iterator()); if(words.empty()){ continue; } std::stringstream ss; uint32_t counter = 0; for(const auto &word : words){ if(!tr.term_exists(word)){ throw std::runtime_error("Term '" + word + "' not found on terms file: " + terms_file_name); } auto term_id = tr.get_term_id(word); ss << term_id; if(counter < words.size() - 1){ ss << " "; } else{ ss << "\n"; } counter++; } output_file << ss.str(); } return 0; }<file_sep>/pisa_formatter.cpp #include <cassert> #include <algorithm> #include <fstream> #include <regex> #include <iostream> #include <vector> #include "cxxopts/cxxopts.hpp" #include "docs_parser.hpp" #include "util.hpp" int main(int argc, char **argv) { static const std::string word_regex = "([^\\s]+)"; static const std::string input_file_optid = "input_file"; static const std::string basename = "basename"; cxxopts::Options options("pisa_formatter", "converts input documents into pisa format"); std::vector<summary_opts> opts = { {input_file_optid, "path to the documents file", cxxopts::value<std::string>()}, {basename, "output basename", cxxopts::value<std::string>()} }; auto result_opt_ptr = parse_input_cline(options, opts, argc, argv); auto &result_opt = *result_opt_ptr; docs_parser dp(result_opt[input_file_optid].as<std::string>(), result_opt[basename].as<std::string>()); dp.parse(); return 0; }<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.14) project(pisa_formatter) set(CMAKE_CXX_STANDARD 17) if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() set(CMAKE_CXX_FLAGS "-Wall -Wextra") set(CMAKE_CXX_FLAGS_DEBUG "-g") set(CMAKE_CXX_FLAGS_RELEASE "-O3") include_directories(${CMAKE_SOURCE_DIR}/lib) add_library(docs_parser docs_parser.hpp docs_parser.cpp) add_library(terms_reader terms_reader.hpp terms_reader.cpp) add_executable(pisa_formatter pisa_formatter.cpp util.hpp) add_executable(query_transformer query_transformer.cpp util.hpp) add_executable(print_terms print_terms.cpp util.hpp) target_link_libraries(pisa_formatter docs_parser) target_link_libraries(query_transformer terms_reader) target_link_libraries(print_terms terms_reader) <file_sep>/print_terms.cpp // // Created by <NAME>, 2019 // #include <string> #include "cxxopts/cxxopts.hpp" #include "util.hpp" #include "terms_reader.hpp" int main(int argc, char **argv) { static const std::string word_regex = "([^\\s]+)"; static const std::string terms_idxes_file_label = "terms"; cxxopts::Options options("query_transformer", "converts query file with terms to indexes query file"); std::vector<summary_opts> opts = { {terms_idxes_file_label, "path to terms binary file", cxxopts::value<std::string>()} }; auto result_opt_ptr = parse_input_cline(options, opts, argc, argv); auto &result_opt = *result_opt_ptr; auto terms_file_name = result_opt[terms_idxes_file_label].as<std::string>(); terms_reader tr(terms_file_name); tr.debug_read_terms(); return 0; }<file_sep>/terms_reader.hpp // // Created by <NAME>, 2019 // #ifndef PISA_FORMATTER_TERMS_READER_HPP #define PISA_FORMATTER_TERMS_READER_HPP #include <string> #include <vector> #include <unordered_map> class terms_reader { std::string terms_file_name; std::vector<const std::string*> terms; std::unordered_map<std::string, uint32_t> term_map_idx; void read_file(); public: explicit terms_reader(std::string terms_file_name); bool term_exists(const std::string &term); uint32_t get_term_id(const std::string &term); void debug_read_terms(); }; #endif //PISA_FORMATTER_TERMS_READER_HPP <file_sep>/docs_parser.cpp // // Created by <NAME>, 2019 // #include <memory> #include <fstream> #include <vector> #include <unordered_map> #include <sstream> #include <utility> #include <regex> #include "docs_parser.hpp" docs_parser::docs_parser(std::string input_file_name, std::string basename) : input_file_name(std::move(input_file_name)), basename(std::move(basename)) { } void docs_parser::parse() { static const std::string word_regex = "([^\\s]+)"; static const std::regex word_regex_load(word_regex); std::ifstream file(input_file_name); std::unordered_map<std::string, uint32_t> terms_indexes; std::vector<std::string> terms_strings; std::unordered_map<std::string, uint32_t> docs_indexes; std::unordered_map<uint32_t, std::vector<std::pair<uint32_t, uint32_t>>> terms_to_docs_freq; std::vector<uint32_t> doc_sizes; std::string line; uint32_t term_counter = 0; uint32_t doc_counter = 0; while(std::getline(file, line)){ std::vector<std::string> words(std::sregex_token_iterator(line.begin(),line.end(), word_regex_load), std::sregex_token_iterator()); if(words.empty()){ continue; } std::unordered_map<uint32_t, uint32_t> term_freq_current_doc; doc_sizes.push_back(words.size()); auto &doc_name = words[0]; uint32_t doc_idx; if(docs_indexes.find(doc_name) == docs_indexes.end()){ doc_idx = doc_counter++; docs_indexes[doc_name] = doc_idx; } else{ doc_idx = docs_indexes[doc_name]; } for(auto i = 1ul; i < words.size(); i++){ const auto &current_word = words[i]; uint32_t current_word_index; if(terms_indexes.find(current_word) == terms_indexes.end()){ current_word_index = term_counter++; terms_strings.push_back(current_word); auto &word_ = terms_strings[terms_strings.size()-1]; terms_indexes[word_] = current_word_index; } else{ current_word_index = terms_indexes[current_word]; } if(term_freq_current_doc.find(current_word_index) == term_freq_current_doc.end()){ term_freq_current_doc[current_word_index] = 0; } term_freq_current_doc[current_word_index]++; } for(const auto &tfcd_it : term_freq_current_doc){ const auto word_idx = tfcd_it.first; const auto freq = tfcd_it.second; terms_to_docs_freq[word_idx].emplace_back(doc_idx, freq); } } std::ofstream docs_file(basename + ".docs", std::ios::binary); std::ofstream freqs_file(basename + ".freqs", std::ios::binary); std::ofstream sizes_file(basename + ".sizes", std::ios::binary); std::ofstream terms_file(basename + ".terms", std::ios::binary); auto docs_qty = (uint32_t)docs_indexes.size(); constexpr auto u32_sz = sizeof(uint32_t); constexpr auto one_sz = static_cast<uint32_t>(1); docs_file.write((char *)&one_sz, u32_sz); docs_file.write((char *)&docs_qty, u32_sz); terms_file.write((char *)&term_counter, u32_sz); for(auto i = 0ul; i < term_counter; i++){ const auto word_list = terms_to_docs_freq[i]; const auto word_docs_qty = static_cast<uint32_t>(word_list.size()); docs_file.write((char *)&word_docs_qty, u32_sz); freqs_file.write((char *)&word_docs_qty, u32_sz); for(const auto &w_p : word_list){ const auto doc_id = w_p.first; const auto term_freq_in_doc = w_p.second; docs_file.write((char *)&doc_id, u32_sz); freqs_file.write((char *)&term_freq_in_doc, u32_sz); } const auto &current_term = terms_strings[i]; const auto term_sz = (uint32_t)current_term.size(); const auto *c_str = current_term.c_str(); terms_file.write((char *)&term_sz, u32_sz); terms_file.write(c_str, term_sz * sizeof(char)); } sizes_file.write((char *)&docs_qty, u32_sz); for(auto doc_size : doc_sizes){ sizes_file.write((char *)&doc_size, u32_sz); } } uint32_t docs_parser::count_file_lines(std::ifstream &file) { uint32_t counter = 0; file.clear(); file.seekg(0, std::ios::beg); std::string line; while(std::getline(file, line)){ counter++; } file.clear(); file.seekg(0, std::ios::beg); return counter; } <file_sep>/README.md # Pisa formatter ### Executables **pisa_formatter**: converts list of documents to the [pisa-engine](https://github.com/pisa-engine/pisa) binary format: {.docs, .freqs, .sizes}. Its input should be a text file where each line is a document. Each document starts with the document name (which should not have whitespaces) followed by a list of ascii terms separated by whitespaces which define the document. This also generates a binary .terms file which has the information to convert from term to index and is used by the query_transformer executable. This file stores all the unique terms from all the documents. Usage: ``` ./pisa_formatter --input_file="INPUT_FILE_PATH" --basename="PATH_TO_BASENAME/BASENAME" ``` Here basename is the prefix for each of the files generated. **query_transformer**: transforms a list of queries, separated by line breaks, with terms contained in the .terms binary file. The output is a text file Usage: ``` ./query_transformer --queries="PATH_TO_QUERIES_FILE" --terms="PATH_TO_TERMS_FILE" --output="PATH_TO_OUTPUT_FILE" ``` **print_terms**: This reads a .terms file and prints the list of terms by the order of their index Usage: ``` ./print_terms --terms="PATH_TO_TERMS_FILE" ``` ### Build ``` mkdir -p build cd build cmake .. make ```<file_sep>/terms_reader.cpp #include <utility> #include <fstream> #include <iostream> #include <memory> // // Created by <NAME>, 2019 // #include "terms_reader.hpp" terms_reader::terms_reader(std::string terms_file_name) : terms_file_name(std::move(terms_file_name)) { read_file(); } void terms_reader::read_file() { std::ifstream file(terms_file_name, std::ios::binary); constexpr auto u32_sz = sizeof(uint32_t); { file.seekg(0, std::ifstream::end); uint32_t file_length = file.tellg(); if(file_length < u32_sz){ throw std::runtime_error("Can't read the number of terms in file " + terms_file_name); } file.seekg(0, std::ifstream::beg); } uint32_t nof_terms; file.read((char *)&nof_terms, u32_sz); for(uint32_t i = 0; i < nof_terms; i++){ uint32_t term_length; file.read((char *)&term_length, u32_sz); std::string term(term_length, 0); file.read(term.data(), term_length * sizeof(char)); auto insert_r = term_map_idx.insert({term, i}); terms.push_back(&((*insert_r.first).first)); // to save space it only stores a pointer to the string, not the string itself } } bool terms_reader::term_exists(const std::string &term) { return term_map_idx.find(term) != term_map_idx.end(); } void terms_reader::debug_read_terms() { for(const auto *s : terms){ std::cout << *s << std::endl; } } uint32_t terms_reader::get_term_id(const std::string &term) { return term_map_idx[term]; } <file_sep>/docs_parser.hpp // // Created by <NAME>, 2019 // #ifndef PISA_FORMATTER_DOCS_PARSER_HPP #define PISA_FORMATTER_DOCS_PARSER_HPP #include <string> class docs_parser { std::string input_file_name; std::string basename; public: explicit docs_parser(std::string input_file_name, std::string basename); void parse(); static uint32_t count_file_lines(std::ifstream &file); }; #endif //PISA_FORMATTER_DOCS_PARSER_HPP
e92bc012fea5defa4cba84d0b7c10f64ce3818a0
[ "Markdown", "CMake", "C++" ]
10
C++
CristobalM/pisa_formatter
93bc4e47c4da86620bc97dbfa395a63b7442f72a
f0fb0727f32a385f4acfe6a9357ea5525603ca88
refs/heads/master
<file_sep>#!/bin/sh #autopep8 --ignore=W602,E501,E301,E309 -i *.py source ~/.bash_profile p2 yapf --style "pep8" -i *.py <file_sep>#!/usr/bin/env python class config(object): def __init__(self, *args, **kwargs): print("config __init__") # def __new__(cls, *args, **kwargs): # print("config __new__") class server(config): def __init__(self, ip, host): self.ip = ip self.host = host print("server __init__") # def __new__(cls, *args, **kwargs): # print("server __new__") c = config() s = server("192.168.241.12", "invoker") print(s.ip, s.host) class A(object): __impl_class = None __impl_kwargs = None def __new__(cls, *args, **kwargs): print("A __new__") base = cls.config_base() init_kwargs = {} if cls is base: impl = cls.config_class() if base.__impl_kwargs: init_kwargs.update(base.__impl_kwargs) else: impl = cls init_kwargs.update(kwargs) instance = super(A, cls).__new__(impl) instance.initialize(*args, **init_kwargs) return instance @classmethod def config_base(cls): raise NotImplementedError() @classmethod def config_default(cls): raise NotImplementedError() @classmethod def config_class(cls): base = cls.config_base() if cls.__impl_class is None: base.__impl_class = cls.config_default() return base.__impl_class class B(A): def __init__(self, *args, **kwargs): print("B __init__") pass # def __new__(cls, *args, **kwargs): # print("B __new__") def initialize(self, name, gender, age): self.name = name self.gender = gender self.age = age @classmethod def config_base(cls): return B @classmethod def config_default(cls): return B u = B() u.initialize("fzeng","male", 23) print(u.name) <file_sep>#!/usr/bin/env python class A(): def __init__(self, *args, **kwargs): print("init A") class B(A): def __init__(self, *args, **kwargs): print("init B") u = B() print(u) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import tornado.httpserver import tornado.web import tornado.httpclient from uuid import uuid4 from tornado.options import define, options define("port", default=8000, help="run on given port", type=int) REMOTE_URL = "http://www.5eplay.com/" class ShoppingCart(object): totalInventory = 10 callbacks = [] carts = {} def register(self, callback): self.callbacks.append(callback) def moveItemToCart(self, session): if session in self.carts: return self.carts[session] = True self.notifyCallbacks() def removeFromCart(self, session): if session not in self.carts: return del(self.carts[session]) self.notifyCallbacks() def notifyCallbacks(self): for c in self.callbacks: self.callbackHelper(c) self.callbacks = [] def callbackHelper(self, callback): callback(self.getInventoryCount()) def getInventoryCount(self): return self.totalInventory - len(self.carts) class DetailHandler(tornado.web.RequestHandler): def get(self): session = uuid4() count = self.application.shoppingCart.getInventoryCount() self.render("index.html", session=session, count=count) class CartHandler(tornado.web.RequestHandler): def post(self): action = self.get_argument('action') session = self.get_argument('session') if not session: self.set_status(400) return if action == 'add': self.application.shoppingCart.moveItemToCart(session) elif action == 'remove': self.application.shoppingCart.removeItemToCart(session) else: self.set_status(400) class StatusHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): self.application.shoppingCart.register(self.async_callback(self.on_message)) def on_message(self, count): self.write('{"inventoryCount":"%d"}' % count) self.finish() class Application(tornado.web.Application): def __init__(self): self.shoppingCart = ShoppingCart() handlers = [ (r'/', DetailHandler), (r'/cart', CartHandler), (r'/cart/status', StatusHandler), ] settings = { 'debug': True, 'template_path': 'templates', 'static_path': 'statics' } tornado.web.Application.__init__(self, handlers, **settings) class Index(tornado.web.RequestHandler): @tornado.web.asynchronous @tornado.gen.engine def get(self): client = tornado.httpclient.AsyncHTTPClient() response = yield tornado.gen.Task(client.fetch, REMOTE_URL) body = response.body now = datetime.datetime.utcnow() self.write(""" <div style="text-align: center"> <div style="font-size: 72px">%s</div> </div>. <div>%s</div> """ % (body, now)) self.finish() def post(self, data): pass if __name__ == "__main__": tornado.options.parse_command_line() settings = dict( auto_reload = True, ) # app = tornado.web.Application([ # (r'/', Index) # ], **settings) # app = Application() http_sever = tornado.httpserver.HTTPServer(app) http_sever.listen(options.port) tornado.ioloop.IOLoop.current().start() <file_sep><head> <title>{{ welcome }}</title> </head> {% if error %} <span sytle="color: red"> Error: {{ error }} </span><p> {% end %} <form action="/login" method="POST"> user:<input name="user", type="text"><br> password:<input name="<PASSWORD>", type="<PASSWORD>"><br> {% module xsrf_form_html() %} <input type="submit"> <input type="hidden" name="next" value="/uimodule"> </form> <file_sep>#!/usr/bin/env python # vim: set fileencoding=utf-8 : import tornado.ioloop import tornado.web import tornado.httpclient import tornado.escape import tornado.gen import tornado.escape import logging import os import uimodules logging.basicConfig( level=logging.DEBUG, format= '%(asctime)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d %(message)s', ) class MainHandler(tornado.web.RequestHandler): def get(self): self.write( '<html><body>' '<br><a href="/msg">Message</a>' '<br><a href="/fetch_async">API @tornado.web.asynchronous</a>' '<br><a href="/fetch_coro">API @tornado.gen.coroutine</a>' '<br><a href="/temp">Template</a>' '<br><a href="/uimodule">uimodule</a>' '</body></html>') class MyFormHandler(tornado.web.RequestHandler): def get(self): self.write('<html><body><form action="/msg" method="POST">' '<input type="text" name="message">' '<input type="submit" value="Submit">' '</form></body></html>') def post(self): self.set_header("Content-Type", "text/plain") self.write("You wrote " + self.get_body_argument("message")) class FakeJsonAPI(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): feng = dict(name="<NAME>", gender="male", age=28, ) sky = dict(name="<NAME>", gender="female", age=26, ) users = (feng, sky) json = tornado.escape.json_encode(users) self.write(json) class WebSpiderHandler_Async(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch("http://192.168.56.111:8888/api", callback=self.on_response) def on_response(self, response): if response.error: raise tornado.web.HTTPError(500) json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(json) + " name" "from our own api") self.finish() class WebSpiderHandler_coroutine(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch("http://192.168.56.111:8888/api") json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(json) + "from fake API") class TemplateHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch("http://192.168.56.111:8888/api") json = tornado.escape.json_decode(response.body) #userlist = [ "Hello" , "hellO", "aaa" , "bbbb" ] self.render("index.html", title="Very first template demo", userlist=json) class UIModuleHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch("http://192.168.56.111:8888/api") user1 = User(name="许其亮", age=24, gender="男") user2 = User(name="杨雪", age=23, gender="女") profiles = [user1, user2] self.render("uimodule.html", title="Yet Another Template", profiles=profiles) class User(object): def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender class LoginHandler(tornado.web.RequestHandler): def get(self): print escape.xhtml_escape(self.xsrf_token) self.render("login.html", welcome="Demo of tornado login", error = None) @tornado.gen.coroutine @tornado.web.authenticated def post(self): user = self.get_argument("user") password = <PASSWORD>(self.get_argument("password")) if user == "feng" and password == "111": self.set_secure_cookie("feng", str("feng")) self.redirect(self.get_argument("next")) else: self.render("login.html", welcome="Something is wrong", error="username or password wrong") class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), (r"/msg", MyFormHandler), (r"/fetch_async", WebSpiderHandler_Async), (r"/api", FakeJsonAPI), (r"/fetch_coro", WebSpiderHandler_coroutine), (r"/temp", TemplateHandler), (r"/uimodule", UIModuleHandler), (r"/login", LoginHandler), ] settings = dict(autoreload=True, debug=True, compress_response=True, template_path=os.path.join( os.path.dirname(__file__), "templates"), compiled_template_cache=False, cookie_secret="__suning_secret__", login_url="/login", xsrf_cookies=True, ui_modules=uimodules, ) super(Application, self).__init__(handlers, **settings) def make_app(): return Application() if __name__ == "__main__": app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import tornado.httpserver import tornado.web import tornado.httpclient from tornado.options import define, options define("port", default=8000, help="run on given port", type=int) REMOTE_URL="http://www.sina.com.cn/" class Base(tornado.web.RequestHandler): pass class Index(Base): @tornado.web.asynchronous @tornado.gen.engine def get(self): client = tornado.httpclient.AsyncHTTPClient() response = yield tornado.gen.Task(client.fetch, REMOTE_URL) body = response.body now = datetime.datetime.utcnow() self.write(""" <div style="text-align: center"> <div style="font-size: 72px">%s</div> </div>. <div>%s</div> """ % (body, now)) self.finish() def post(self, data): pass if __name__ == "__main__": tornado.options.parse_command_line() settings = dict( auto_reload = True, ) app = tornado.web.Application([ (r'/', Index) ], **settings) http_sever = tornado.httpserver.HTTPServer(app) http_sever.listen(options.port) tornado.ioloop.IOLoop.current().start() <file_sep># Introduction This is a demo of my attempt to master tornado <file_sep># -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import re import json import base64 import binascii import rsa import requests import logging logging.basicConfig(level=logging.DEBUG) WBCLIENT = 'ssologin.js(v1.4.5)' user_agent = ( 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) ' 'Chrome/20.0.1132.57 Safari/536.11' ) session = requests.session() session.headers['User-Agent'] = user_agent def encrypt_passwd(passwd, pubkey, servertime, nonce): key = rsa.PublicKey(int(pubkey, 16), int('10001', 16)) message = str(servertime) + '\t' + str(nonce) + '\n' + str(passwd) passwd = rsa.encrypt(message.encode('utf-8'), key) return binascii.b2a_hex(passwd) def wblogin(username, password): resp = session.get( 'http://login.sina.com.cn/sso/prelogin.php?' 'entry=sso&callback=sinaSSOController.preloginCallBack&' 'su=%s&rsakt=mod&client=%s' % (base64.b64encode(username.encode('utf-8')), WBCLIENT) ) pre_login_str = re.match(r'[^{]+({.+?})', resp.text).group(1) pre_login = json.loads(pre_login_str) pre_login = json.loads(pre_login_str) data = { 'entry': 'weibo', 'gateway': 1, 'from': '', 'savestate': 7, 'userticket': 1, 'ssosimplelogin': 1, 'su': base64.b64encode(requests.utils.quote(username).encode('utf-8')), 'service': 'miniblog', 'servertime': pre_login['servertime'], 'nonce': pre_login['nonce'], 'vsnf': 1, 'vsnval': '', 'pwencode': 'rsa2', 'sp': encrypt_passwd(password, pre_login['pubkey'], pre_login['servertime'], pre_login['nonce']), 'rsakv' : pre_login['rsakv'], 'encoding': 'UTF-8', 'prelt': '115', 'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.si' 'naSSOController.feedBackUrlCallBack', 'returntype': 'META' } resp = session.post( 'http://login.sina.com.cn/sso/login.php?client=%s' % WBCLIENT, data=data ) login_url = re.search(r'replace\([\"\']([^\'\"]+)[\"\']', resp.text).group(1) resp = session.get(login_url) login_str = re.match(r'[^{]+({.+?}})', resp.text).group(1) return json.loads(login_str) if __name__ == '__main__': print(json.dumps(wblogin('<EMAIL>', 'XXXXXXXX'), ensure_ascii=False)) # timeline print(session.get('http://weibo.com/').text <file_sep>#!/usr/bin/env python import tornado class Profile(tornado.web.UIModule): def render(self, profile): return self.render_string("user.html", profile=profile) <file_sep><html> <head> <title>{{ title }}</title> </head> <body> <ul> <table border = "2"> {% module Template("profile.html", profiles=profiles) %} </table> {% module xsrf_form_html() %} </ul> </body> </html>
de0df97bed9c275b7386c86e73e2c96e391d579f
[ "Markdown", "Python", "HTML", "Shell" ]
11
Shell
lvfeng1130/tornado
d923ac123acca554350355b36a19aad4ab9c58ea
b9c0f19b8f7a5354a13b8c230ca6d9aa361e0cf7
refs/heads/master
<repo_name>Digitalni-akademie-Web-Jaro-2020-Praha/ukol-ukolnicek-VFryzlova<file_sep>/index.js 'use strict'; let tasks = [ "Zalít květiny", "Vyprat prádlo", "Vynést koš", "Vyluxovat", ]; const addBtn = document.querySelector(".btn-add"); const newTask = document.querySelector(".new-task"); const updateTasks = () => { const taskElm = document.querySelector(".todo__tasks"); taskElm.innerHTML = ""; for (let i = 0; i < tasks.length; i ++){ taskElm.innerHTML += `<div class="task">${tasks[i]}</div>`; } } updateTasks(); const addTask = () =>{ const newTask = document.querySelector(".new-task"); if(newTask.value !== ""){ tasks.push(newTask.value); updateTasks(tasks); newTask.value = ""; } else { alert("Nezadána hodnota"); } } addBtn.addEventListener("click", addTask); updateTasks(tasks);
566eb8888d0e572d47e84def3acdd28af9978b58
[ "JavaScript" ]
1
JavaScript
Digitalni-akademie-Web-Jaro-2020-Praha/ukol-ukolnicek-VFryzlova
54566822d16d439cc46c33959ac8607cbfe55656
1377bc338bec3f9dd25e961ae0fa0a36ee7c55ec
refs/heads/main
<repo_name>wilhemparaclet/TP_<file_sep>/todo/models.py from django.db import models class Task(models.Model): content = models.CharField(max_length=200) is_done = models.BooleanField() created_date = models.DateTimeField()
4afb3b5a2d6512ff53f836e59f406f04d1e31142
[ "Python" ]
1
Python
wilhemparaclet/TP_
cced05b32853ec844c95ab099b0d00c77c159414
cb178db1a54ecbdda05235fafbe7e0976b97538e
refs/heads/main
<repo_name>RodolfoXV/ReactBioarkePage<file_sep>/src/config/Config.js import firebase from 'firebase/app' import 'firebase/auth'; import 'firebase/firestore'; import 'firebase/storage'; const firebaseConfig = { apiKey: "<KEY>", authDomain: "bioarke-react.firebaseapp.com", projectId: "bioarke-react", storageBucket: "bioarke-react.appspot.com", messagingSenderId: "1036778769320", appId: "1:1036778769320:web:eac4115e0713072c08ab9d", measurementId: "G-M1N1MXJBK3" }; firebase.initializeApp(firebaseConfig); const auth = firebase.auth(); const db = firebase.firestore(); const storage = firebase.storage(); export { auth, db, storage} <file_sep>/src/components/NotFound.js import React from 'react' export const NotFound = () => { return ( <div> Error 404 Page not Found or not Exist </div> ) } <file_sep>/src/components/AddProducts.js import React,{useState} from 'react'; import {storage, db } from '../config/Config' export const AddProducts = () => { const [productName, setProductName] = useState(''); const [productPrice, setProductPrice] = useState(0); const [productStock, setProductStock] = useState(0); const [productImg, setProductImg] = useState(null); const [error, setError] = useState(''); const types = ['image/png', 'image/jpeg'] const productImgHandler = (e) =>{ let selectedFile = e.target.files[0]; if (selectedFile && types.includes(selectedFile.type)){ setProductImg(selectedFile); setError('') } else{ setProductImg(null) setError("Por favor seleciona un tipo de archivo valido (png o jpeg)") } } const addproducts = (e) =>{ e.preventDefault(); const uploadTask = storage.ref(`product-images/${productImg.name}`).put(productImg); uploadTask.on('state_changed', snapshot => { const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log(progress); }, err => setError(err.message) , () => { storage.ref('product-images').child(productImg.name).getDownloadURL().then(url => { db.collection('Products').add({ ProductName: productName, ProductPrice: Number(productPrice), ProductStock: Number(productStock), ProductImg: url }).then(() => { setProductName(''); setProductPrice(0) setProductStock(0) setProductImg(''); setError(''); document.getElementById('file').value = ''; }).catch(err => setError(err.message)) }) }) } return ( <div className='container'> <br/> <h2>Agregar Productos</h2> <hr/> <form autoComplete='off' className='form-group container' onSubmit={addproducts}> <label htmlFor='product-name'>Nombre del Producto</label> <br/> <input type='text' className='form-control' required onChange={(e)=>setProductName(e.target.value)} value={productName}/> <br/> <label htmlFor='product-price'>Precio de Producto</label> <br/> <input type='number' className='form-control' required onChange={(e)=>setProductPrice(e.target.value)} value={productPrice}/> <br/> <label htmlFor='product-stock'>Stock del Producto</label> <br/> <input type='number' className='form-control' required onChange={(e)=>setProductStock(e.target.value)} value={productStock}/> <br/> <label htmlFor='product-img'>Imagen del Producto</label> <br/> <input type='file' className='form-control' onChange={productImgHandler}/> <br/> <hr/> <button className='btn btn-success btn-md mybtn'>Agregar a Inventario</button> </form> <br/> {error&& <span className='error-msg'>{error}</span>} </div> ); };
8ee5b4152613ffff096b73f9afee6576dba3d7a6
[ "JavaScript" ]
3
JavaScript
RodolfoXV/ReactBioarkePage
6974a69a2c500c21976a08a2763e088bb96ec462
c179ee257eda03d23460c610517388938323acda
refs/heads/master
<file_sep>/** * Copyright 2012-2013 University Of Southern California * * 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 org.workflowsim; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.cloudbus.cloudsim.Cloudlet; import org.cloudbus.cloudsim.Consts; import org.cloudbus.cloudsim.UtilizationModelFull; import org.cloudbus.cloudsim.core.CloudSim; import org.workflowsim.scheduling.WorkGivingSchedulingAlgorithm; /** * Task is an extention to Cloudlet in CloudSim. It supports the implementation * of dependencies between tasks, which includes a list of parent tasks and a * list of child tasks that it has. In WorkflowSim, the Workflow Engine assure * that a task is released to the scheduler (ready to run) when all of its * parent tasks have completed successfully * * @author <NAME> * @since WorkflowSim Toolkit 1.0 * @date Apr 9, 2013 */ public class Task extends Cloudlet { public static final double HEART_BEAT_EXPIRATION_PERIOD = 125; public static int maxNumBackup = 2; private static long maxDur; private long earlyStart; private long earlyFinish; private long latestStart; private long latestFinish; private long criticalPath; // New Scheduler properties private double heartBeat; private double startPeriodExpiration = CloudSim.clock() + HEART_BEAT_EXPIRATION_PERIOD; private Set<Integer> boundNodes = new TreeSet<Integer>(); private int numBackup = Math.max(0, maxNumBackup); public boolean startPeriodExpired() { return startPeriodExpiration < CloudSim.clock(); } public boolean heartBeatExpired() { return heartBeat < CloudSim.clock(); } public void heartbeat() { heartBeat = CloudSim.clock() + HEART_BEAT_EXPIRATION_PERIOD; } public boolean hasBeenPolledByOwner() { return heartBeat > 0; } public boolean bind(Integer nodeId) { if(getVmId() >= 0 && !isBound(getVmId())) boundNodes.add(getVmId()); if(isBound(nodeId)) return true; if(isBindable()) { boundNodes.add(nodeId); return true; } return false; } public boolean isBindable() { return boundNodes.size() < numBackup+1; } public boolean isBound(Integer nodeId) { return boundNodes.contains(nodeId); } public boolean isOwner(int nodeId) { return nodeId == getVmId(); } public Set<Integer> getBoundNodes(){ return boundNodes; } boolean running = false; public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } public void setLatest() { latestStart = maxDur - criticalPath; latestFinish = latestStart + getCloudletLength(); } public String[] toStringArray() { String criticalCond = earlyStart == latestStart ? "Yes" : "No"; String[] toString = { "" + getCloudletId(), earlyStart + 1 + "", earlyFinish + "", latestStart + 1 + "", latestFinish + "", latestStart - earlyStart + "", criticalCond , getType()}; return toString; } public static long getMaxDur() { return maxDur; } public long getEarlyStart() { return earlyStart; } public long getEarlyFinish() { return earlyFinish; } public long getLatestStart() { return latestStart; } public long getLatestFinish() { return latestFinish; } public long getCriticalPath() { return criticalPath; } public static void setMaxDur(long maxDur) { Task.maxDur = maxDur; } public void setEarlyStart(long earlyStart) { this.earlyStart = earlyStart; } public void setEarlyFinish(long earlyFinish) { this.earlyFinish = earlyFinish; } public void setCriticalPath(long criticalPath) { this.criticalPath = criticalPath; } /* * The list of parent tasks. */ private List<Task> parentList; /* * The list of child tasks. */ private List<Task> childList; /* * The list of all files (input data and ouput data) */ private List<FileItem> fileList; /* * The priority used for research. Not used in current version. */ private int priority; /* * The depth of this task. Depth of a task is defined as the furthest path * from the root task to this task. It is set during the workflow parsing * stage. */ private int depth; /* * The impact of a task. It is used in research. */ private double impact; /* * The type of a task. */ private String type; /** * The finish time of a task (Because cloudlet does not allow WorkflowSim to * update finish_time) */ private double taskFinishTime; /** * Allocates a new Task object. The task length should be greater than or * equal to 1. * * @param taskId the unique ID of this Task * @param taskLength the length or size (in MI) of this task to be executed * in a PowerDatacenter * @pre taskId >= 0 * @pre taskLength >= 0.0 * @post $none */ public Task( final int taskId, final long taskLength) { /** * We do not use cloudletFileSize and cloudletOutputSize here. We have * added a list to task and thus we don't need a cloudletFileSize or * cloudletOutputSize here The utilizationModelCpu, utilizationModelRam, * and utilizationModelBw are just set to be the default mode. You can * change it for your own purpose. */ super(taskId, taskLength, 1, 0, 0, new UtilizationModelFull(), new UtilizationModelFull(), new UtilizationModelFull()); this.childList = new ArrayList<>(); this.parentList = new ArrayList<>(); this.fileList = new ArrayList<>(); this.impact = 0.0; this.taskFinishTime = -1.0; } /** * Sets the type of the task * * @param type the type */ public void setType(String type) { this.type = type; } /** * Gets the type of the task * * @return the type of the task */ public String getType() { return type; } /** * Sets the priority of the task * * @param priority the priority */ public void setPriority(int priority) { this.priority = priority; } /** * Sets the depth of the task * * @param depth the depth */ public void setDepth(int depth) { this.depth = depth; } /** * Gets the priority of the task * * @return the priority of the task * @pre $none * @post $none */ public int getPriority() { return this.priority; } /** * Gets the depth of the task * * @return the depth of the task */ public int getDepth() { return this.depth; } /** * Gets the child list of the task * * @return the list of the children */ public List<Task> getChildList() { return this.childList; } /** * Sets the child list of the task * * @param list, child list of the task */ public void setChildList(List<Task> list) { this.childList = list; } /** * Sets the parent list of the task * * @param list, parent list of the task */ public void setParentList(List<Task> list) { this.parentList = list; } /** * Adds the list to existing child list * * @param list, the child list to be added */ public void addChildList(List<Task> list) { this.childList.addAll(list); } /** * Adds the list to existing parent list * * @param list, the parent list to be added */ public void addParentList(List<Task> list) { this.parentList.addAll(list); } /** * Gets the list of the parent tasks * * @return the list of the parents */ public List<Task> getParentList() { return this.parentList; } /** * Adds a task to existing child list * * @param task, the child task to be added */ public void addChild(Task task) { this.childList.add(task); } /** * Adds a task to existing parent list * * @param task, the parent task to be added */ public void addParent(Task task) { this.parentList.add(task); } /** * Gets the list of the files * * @return the list of files * @pre $none * @post $none */ public List<FileItem> getFileList() { return this.fileList; } /** * Adds a file to existing file list * * @param file, the file to be added */ public void addFile(FileItem file) { this.fileList.add(file); } /** * Sets a file list * * @param list, the file list */ public void setFileList(List<FileItem> list) { this.fileList = list; } /** * Sets the impact factor * * @param impact, the impact factor */ public void setImpact(double impact) { this.impact = impact; } /** * Gets the impact of the task * * @return the impact of the task * @pre $none * @post $none */ public double getImpact() { return this.impact; } /** * Sets the finish time of the task (different to the one used in Cloudlet) * * @param time finish time */ public void setTaskFinishTime(double time) { this.taskFinishTime = time; } /** * Gets the finish time of a task (different to the one used in Cloudlet) * * @return */ public double getTaskFinishTime() { return this.taskFinishTime; } /** * Gets the total cost of processing or executing this task The original * getProcessingCost does not take cpu cost into it also the data file in * Task is stored in fileList <tt>Processing Cost = input data transfer + * processing cost + output transfer cost</tt> . * * @return the total cost of processing Cloudlet * @pre $none * @post $result >= 0.0 */ @Override public double getProcessingCost() { // cloudlet cost: execution cost... double cost = getCostPerSec() * getActualCPUTime(); // ...plus input data transfer cost... long fileSize = 0; for (FileItem file : getFileList()) { fileSize += file.getSize() / Consts.MILLION; } cost += costPerBw * fileSize; return cost; } } <file_sep>package simulation; /** * Copyright 2012-2013 University Of Southern California * * 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. */ import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.nio.file.Paths; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.ConsoleHandler; import java.util.Map.Entry; import org.cloudbus.cloudsim.CloudletSchedulerSpaceShared; import org.cloudbus.cloudsim.DatacenterCharacteristics; import org.cloudbus.cloudsim.HarddriveStorage; import org.cloudbus.cloudsim.Host; import org.cloudbus.cloudsim.Log; import org.cloudbus.cloudsim.ParameterException; import org.cloudbus.cloudsim.Pe; import org.cloudbus.cloudsim.Storage; import org.cloudbus.cloudsim.VmAllocationPolicySimple; import org.cloudbus.cloudsim.VmSchedulerTimeShared; import org.cloudbus.cloudsim.core.CloudSim; import org.cloudbus.cloudsim.lists.HostList; import org.cloudbus.cloudsim.provisioners.BwProvisionerSimple; import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple; import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple; import org.workflowsim.ClusterRamDiskStorage; import org.workflowsim.ClusterStorage; import org.workflowsim.CondorVM; import org.workflowsim.Job; import org.workflowsim.Task; import org.workflowsim.WorkflowDatacenter; import org.workflowsim.WorkflowEngine; import org.workflowsim.WorkflowPlanner; import org.workflowsim.scheduling.WorkGivingSchedulingAlgorithm; import org.workflowsim.utils.ClusteringParameters; import org.workflowsim.utils.OverheadParameters; import org.workflowsim.utils.Parameters; import org.workflowsim.utils.Parameters.ClassType; import org.workflowsim.utils.Parameters.PlanningAlgorithm; import org.workflowsim.utils.Parameters.SchedulingAlgorithm; import org.workflowsim.utils.ReplicaCatalog; import readycli.Command; import readycli.Option; import utilpack.TableView; import utilpack.TableView.Row; import utilpack.Tuple; import utilpack.logging.Logger; import utilpack.logging.Loggers; import utilpack.logging.handler.text.ConsoleLogHandler; import utilpack.logging.handler.text.SimpleLogFormatter; import utilpack.logging.handler.text.TextLogHandler; import utilpack.parsing.CSVReader; import utilpack.parsing.CSVWriter; import utilpack.parsing.arguments.ArgumentParser; import utilpack.parsing.arguments.ExpectedArgumentException; import utilpack.parsing.arguments.ExpectedOptionParameterException; import utilpack.parsing.arguments.UnexpectedArgumentException; /** * This WorkflowSimExample creates a workflow planner, a workflow engine, and * one schedulers, one data centers and 20 vms. You should change daxPath at * least. You may change other parameters as well. * * @author <NAME> * @since WorkflowSim Toolkit 1.0 * @date Apr 9, 2013 */ public class Simulation { private static Logger logger = Loggers.getLogger("WorkflowSim");; private static int vmNum = 100;//number of vms; private static SchedulingAlgorithm scheduling = SchedulingAlgorithm.WORKGIVING; private static PlanningAlgorithm planning = PlanningAlgorithm.RANDOM; private static String daxPath = "./config/dax/Montage_1000.xml"; private static String logPath = "./log"; private static long bandwidth = 1000; private static double finishTime; private static int nodeMips = 2000; private static int nodeRam = 8192; private static int nodeCores = 4; protected static List<CondorVM> createVM(int userId, int vms, int vmIdBase) { //Creates a container to store VMs. This list is passed to the broker later LinkedList<CondorVM> list = new LinkedList<>(); //VM Parameters long size = 10000; //image size (MB) int ram = nodeRam; //vm memory (MB) int mips = nodeMips; long bw = bandwidth; int pesNumber = nodeCores; //number of cpus String vmm = "Xen"; //VMM name LinkedList<Storage> storageList = new LinkedList<>(); double interBandwidth = 1000; double intraBandwidth = interBandwidth * 2; //create VMs CondorVM[] vm = new CondorVM[vms]; for (int i = 0; i < vms; i++) { vm[i] = new CondorVM(vmIdBase + i, userId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerSpaceShared()); list.add(vm[i]); String name = "vm_" + (vmIdBase+i); ClusterStorage s1 = null; ClusterRamDiskStorage s2 = null; try { s1 = new ClusterStorage(name, 1e6); s2 = new ClusterRamDiskStorage(name, 6200); s1.setBandwidth("local", intraBandwidth); s2.setBandwidth("local", intraBandwidth); s1.setBandwidth("source", interBandwidth); s2.setBandwidth("source", interBandwidth); } catch (ParameterException e) { e.printStackTrace(); } storageList.add(s1); storageList.add(s2); vm[i].setStorage(storageList); } return list; } private static WorkflowDatacenter createDatacenter(String name) { // Here are the steps needed to create a PowerDatacenter: // 1. We need to create a list to store one or more // Machines List<Host> hostList = new ArrayList<>(); // 2. A Machine contains one or more PEs or CPUs/Cores. Therefore, should // create a list to store these PEs before creating // a Machine. int hostId = 0; for (int i = 1; i <= vmNum; i++) { List<Pe> peList1 = new ArrayList<>(); int mips = nodeMips; // 3. Create PEs and add these into the list. //for a quad-core machine, a list of 4 PEs is required: for(int core=0; core<nodeCores; core++) peList1.add(new Pe(core, new PeProvisionerSimple(mips))); int ram = nodeRam; //host memory (MB) long storage = 1000000; //host storage long bw = bandwidth; hostList.add( new Host( hostId, new RamProvisionerSimple(ram), new BwProvisionerSimple(bw), storage, peList1, new VmSchedulerTimeShared(peList1))); // This is our first machine hostId++; } // 4. Create a DatacenterCharacteristics object that stores the // properties of a data center: architecture, OS, list of // Machines, allocation policy: time- or space-shared, time zone // and its price (G$/Pe time unit). String arch = "x86"; // system architecture String os = "Linux"; // operating system String vmm = "Xen"; double time_zone = 10.0; // time zone this resource located double cost = 3.0; // the cost of using processing in this resource double costPerMem = 0.05; // the cost of using memory in this resource double costPerStorage = 0.1; // the cost of using storage in this resource double costPerBw = 0.1; // the cost of using bw in this resource LinkedList<Storage> storageList = new LinkedList<>(); //we are not adding SAN devices by now WorkflowDatacenter datacenter = null; logger.info("numberOfPes=%d", HostList.getNumberOfPes(hostList)); DatacenterCharacteristics characteristics = new DatacenterCharacteristics( arch, os, vmm, hostList, time_zone, cost, costPerMem, costPerStorage, costPerBw); // 5. Finally, we need to create a storage object. /** * The bandwidth within a data center in MB/s. */ int maxTransferRate = 15;// the number comes from the futuregrid site, you can specify your bw try { // Here we set the bandwidth to be 15MB/s HarddriveStorage s1 = new HarddriveStorage(name, 1e12); s1.setMaxTransferRate(maxTransferRate); storageList.add(s1); datacenter = new WorkflowDatacenter(name, characteristics, new VmAllocationPolicySimple(hostList), storageList, 0); } catch (Exception e) { e.printStackTrace(); } return datacenter; } /** * Prints the job objects * * @param list list of jobs * @throws FileNotFoundException */ private static void printJobList(List<Job> list) throws FileNotFoundException { TableView table = new TableView(); table.row("Job ID", "Task IDs", "STATUS", "Data center ID", "VM ID", "Time", "Start Time", "Finish Time", "Depth"); DecimalFormat dft = new DecimalFormat("###.##"); for (Job job : list) { Row row = table.row(); row.add(job.getCloudletId()); if (job.getClassType() == ClassType.STAGE_IN.value) row.add("Stage-in"); else { List<Integer> taskIds = new LinkedList<Integer>(); for (Task task : job.getTaskList()) taskIds.add(task.getCloudletId()); row.add(taskIds); } row.add(job.getCloudletStatusString()); row.add(job.getResourceId(), job.getVmId(), dft.format(job.getActualCPUTime())); row.add(dft.format(job.getExecStartTime()),dft.format(job.getFinishTime()),job.getDepth()); } logger.info(table.toString()); } ////////////////////////// STATIC METHODS /////////////////////// /** * Creates main() to run this example This example has only one datacenter * and one storage * @throws UnexpectedArgumentException * @throws ExpectedArgumentException * @throws ExpectedOptionParameterException */ public static void main(String[] args) throws ExpectedOptionParameterException, ExpectedArgumentException, UnexpectedArgumentException { Command.defaultDocs("", "Simulation - Performs a single workflow simulation with the given parameters") .addRequiredArgument("dax", "path to the DAX file that contains the workflow to simulate on") .addOption(Option.create("nodes", "specify the number of virtual machines") .addParameter("value", "integer value", ""+vmNum) .build()) .addOption(Option.create("wgmode", "specify the execution mode for the work-giving scheduler") .addParameter("value", "-1=DM only; 0=no replication; 1,2,3,.. = 1,2,3,.. task replicas", ""+2) .build()) .addOption(Option.create("seed", "specify the seed used for the random generator") .addParameter("value", "long value, set to 'null' to use a random seed", "null") .build()) .addOption(Option.create("log", "output directory for log file. The name of the file is given by the parameters of the simulation") .addParameter("value", "path to the log directory", logPath) .build()) .addOption(Option.create("bw", "bandwith of each virtual machine") .addParameter("value", "integer value in MB/s", ""+bandwidth) .build()) .addOption(Option.create("sched", "the scheduling strategy to simulate. " + "Possible values are: " + Arrays.toString(SchedulingAlgorithm.values())) .addParameter("value", "name of the scheduling strategy", scheduling.toString()) .build()) .addOption(Option.create("plan", "the planning algorithm to simulate. " + "Possible values are: " + Arrays.toString(PlanningAlgorithm.values())) .addParameter("value", "name of the scheduling strategy", planning.toString()) .build()) .build(ctx->{ daxPath = ctx.getArgument("dax"); vmNum = Integer.valueOf(ctx.getOption("nodes").get("value")); int wgMode = Integer.valueOf(ctx.getOption("wgmode").get("value")); switch(wgMode) { case -1: WorkGivingSchedulingAlgorithm.workgivingActive = false; break; case 0: WorkGivingSchedulingAlgorithm.workgivingActive = true; WorkGivingSchedulingAlgorithm.replicationActive = false; break; default: WorkGivingSchedulingAlgorithm.workgivingActive = true; WorkGivingSchedulingAlgorithm.replicationActive = true; Task.maxNumBackup = Math.max(1, Math.abs(wgMode)); break; } String seed = ctx.getOption("seed").get("value"); if(seed.equals("null")) System.setProperty("simulation.seed", ""+System.currentTimeMillis()); else System.setProperty("simulation.seed", seed); logPath=ctx.getOption("log").get("value"); bandwidth=Integer.valueOf(ctx.getOption("bw").get("value")); scheduling=SchedulingAlgorithm.valueOf(ctx.getOption("sched").get("value")); planning=PlanningAlgorithm.valueOf(ctx.getOption("plan").get("value")); }) .execute(args); if(scheduling == SchedulingAlgorithm.WORKGIVING) { logger.info("using Work Giving strategy"); logger.info("work giving active: %s", WorkGivingSchedulingAlgorithm.workgivingActive); logger.info("replication active: %s", WorkGivingSchedulingAlgorithm.replicationActive); } System.setProperty("simulation.seed", "0"); //System.out.println("Bandwidth="+bandwidth); new File(logPath).mkdirs(); File daxFile = new File(daxPath); try { String logName = String.format("%s.%s.nodes_%d.bw_%d.file_%s", scheduling, planning, vmNum, bandwidth, daxFile.getName()); File logFile = Paths.get(logPath, logName + ".log").toFile(); PrintStream logStream = new PrintStream(logFile); logger.attachLogHandler(new TextLogHandler(logStream, new SimpleLogFormatter())); //logger.attachLogHandler(ConsoleLogHandler.getInstance()); // First step: Initialize the WorkflowSim package. /** * However, the exact number of vms may not necessarily be vmNum If * the data center or the host doesn't have sufficient resources the * exact vmNum would be smaller than that. Take care. */ /** * Should change this based on real physical path */ logger.info("starting simulation..."); if (!daxFile.exists()) { Log.printLine("Warning: Please replace daxPath with the physical path in your working environment!"); return; } /** * Since we are using MINMIN scheduling algorithm, the planning * algorithm should be INVALID such that the planner would not * override the result of the scheduler */ Parameters.SchedulingAlgorithm sch_method = scheduling; Parameters.PlanningAlgorithm pln_method = planning; ReplicaCatalog.FileSystem file_system = ReplicaCatalog.FileSystem.SHARED; /** * No overheads */ OverheadParameters op = new OverheadParameters(0, null, null, null, null, 0); /** * No Clustering */ ClusteringParameters.ClusteringMethod method = ClusteringParameters.ClusteringMethod.NONE; ClusteringParameters cp = new ClusteringParameters(0, 0, method, null); /** * Initialize static parameters */ Parameters.init(vmNum, daxPath, null, null, op, cp, sch_method, pln_method, null, 0); ReplicaCatalog.init(file_system); // before creating any entities. int num_user = 1; // number of grid users Calendar calendar = Calendar.getInstance(); boolean trace_flag = false; // mean trace events // Initialize the CloudSim library CloudSim.init(num_user, calendar, trace_flag); WorkflowDatacenter datacenter0 = createDatacenter("Datacenter_0"); /** * Create a WorkflowPlanner with one schedulers. */ WorkflowPlanner wfPlanner = new WorkflowPlanner("planner_0", 1); /** * Create a WorkflowEngine. */ WorkflowEngine wfEngine = wfPlanner.getWorkflowEngine(); /** * Create a list of VMs.The userId of a vm is basically the id of * the scheduler that controls this vm. */ List<CondorVM> vmlist0 = createVM(wfEngine.getSchedulerId(0), Parameters.getVmNum(), 0); /** * Submits this list of vms to this WorkflowEngine. */ wfEngine.submitVmList(vmlist0, 0); /** * Binds the data centers with the scheduler. */ wfEngine.bindSchedulerDatacenter(datacenter0.getId(), 0); CloudSim.startSimulation(); List<Job> outputList = wfEngine.getJobsReceivedList(); CloudSim.stopSimulation(); printJobList(outputList); /*tasks completion times*/ { TreeMap<Double, Integer> reduceMap = new TreeMap<>(); int numCompleted=0; for(Job job : outputList) reduceMap.put(job.getFinishTime(), ++numCompleted); try(CSVWriter csv = new CSVWriter(Paths.get(logPath, "tasks-" + logName + ".csv").toFile(), ';', false)){ csv.write(Tuple.ofObjects("time","tasks")); for(Entry<Double, Integer> e : reduceMap.entrySet()) { csv.write(Tuple.ofObjects( String.format("%1.3f", e.getKey()), e.getValue().toString() )); } } } for(Job job : outputList) finishTime = Math.max(finishTime, job.getFinishTime()); // dax-file, scheduling, planning, bandwidth, nodes, finish-time String csvLine = String.format("%s; %s; %s; %d; %d; %1.3f\n", daxFile.getName(), scheduling, planning, vmNum, bandwidth, finishTime); logger.info(csvLine); logStream.close(); logger.info("simulation ended"); System.out.printf("%s;%s;%s", finishTime, WorkGivingSchedulingAlgorithm.backupCounter, WorkGivingSchedulingAlgorithm.nonBackupCounter); System.exit(0); } catch (Exception e) { Log.printLine("The simulation has been terminated due to an unexpected error"); e.printStackTrace(); System.exit(-1); } } } <file_sep>package simulation; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Paths; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import readycli.Command; import readycli.Option; import utilpack.Tuple; import utilpack.parsing.CSVReader; import utilpack.parsing.CSVWriter; import utilpack.parsing.arguments.ArgumentParser; import utilpack.parsing.arguments.ExpectedArgumentException; import utilpack.parsing.arguments.ExpectedOptionParameterException; import utilpack.parsing.arguments.UnexpectedArgumentException; public class Transform { private static final Tuple labels = Tuple.ofStrings("File", "Scheduler", "Planner", "Bandwidth", "Nodes", "Simulation Time"); //key: (simulation name, workflow name, nodes, bandwidth); value: (medium execution time) private static Map<Tuple, Double> results = new TreeMap<>(); private static File resultsDir = new File("./sim-dataset/Sipht"); private static File resultsFile = new File("./Sipht-times.csv"); private static Set<String> daxFiles = new TreeSet<>(); private static Set<Tuple> strategies = new HashSet<>(); private static Set<Integer> bandwidths = new TreeSet<>(); private static Set<Integer> numbersOfNodes = new TreeSet<>(); private static Set<String> appNames = new TreeSet<>(); private static Set<Integer> taskNums = new TreeSet<>(); public static void main(String[] args) throws FileNotFoundException, IOException, ExpectedOptionParameterException, ExpectedArgumentException, UnexpectedArgumentException { Command.defaultDocs("", "Transforms collected simulations data to interesting datasets. This command allows to build the node-variation and the task-variation datasets.") .addRequiredArgument("results-file", "the CSV file containing the collected simulations data") .addOption(Option.create("output", "The directory where the output transformed results are stored") .addAlias("o") .addParameter("value", "directory path", resultsDir.toString()) .build()) .build(ctx->{ resultsFile=new File(ctx.getArgument("results-file")); resultsDir=new File(ctx.getOption("output").get("value")); }) .execute(args); System.out.println("Transform"); resultsDir.mkdirs(); try (CSVReader csvReader = new CSVReader(resultsFile, ';')){ if(csvReader.hasNextTuple()) csvReader.read(); while(csvReader.hasNextTuple()) { Tuple tuple = csvReader.read(); results.put(tuple.head(), Double.parseDouble(tuple.getLast().toString().replace(",", "."))); } } for(Tuple simKey : results.keySet()) { Iterator<Object> it = simKey.iterator(); String daxFile = (String) it.next(); Tuple strategy = Tuple.ofObjects((String) it.next(), (String) it.next()); String bw = (String) it.next(); String nodes = (String) it.next(); daxFiles.add(daxFile); strategies.add(strategy); bandwidths.add(Integer.parseInt(bw)); numbersOfNodes.add(Integer.parseInt(nodes)); if(daxFile.matches(".+_[0-9]+(\\..*)?")) { String[] workflow = daxFile.split("\\.")[0].split("_"); String appName = workflow[0]; String taskNum = workflow[1]; appNames.add(appName); taskNums.add(Integer.parseInt(taskNum)); } } createNodeVariationDataset(); createTaskVariationDataset(); } static void createNodeVariationDataset() throws FileNotFoundException, IOException { // dataset id: (daxFile, bandwidth) // columns: nodes, matrix, albatross, workgiving Tuple labels = Tuple.ofObjects("nodes"); for(Tuple s : strategies) labels = labels.add(s.<String>get(0)); for(String appName : appNames) for(Integer taskNum : taskNums) for(Integer bandwidth : bandwidths) { File csvFile = Paths.get(resultsDir.getName(), appName, "nodevar", "nodevar_"+appName+"_"+taskNum+".xml_bw"+bandwidth+".csv").toFile(); csvFile.getParentFile().mkdirs(); try(CSVWriter csvWriter = new CSVWriter(csvFile, ';', false)){ csvWriter.write(labels); for(Integer nodes : numbersOfNodes) { List<String> tuple = new LinkedList<>(); tuple.add(""+nodes); for(Tuple strategy : strategies) { Tuple simKey = Tuple.ofStrings(appName + "_"+taskNum+".xml", strategy.get(0), strategy.get(1), bandwidth, nodes); if(results.containsKey(simKey)) { double simTime = results.get(simKey); tuple.add(String.format("%1.3f",simTime)); } else tuple.add("<unknown>"); } Tuple datasetTuple = Tuple.ofStrings(tuple); csvWriter.write(datasetTuple); } } } } static void createTaskVariationDataset() throws FileNotFoundException, IOException { // dataset id: (appName, nodes, bandwidth) // columns: tasks, matrix, albatross, workgiving Tuple labels = Tuple.ofObjects("tasks"); for(Tuple s : strategies) labels = labels.add(s.<String>get(0)); for(String appName : appNames) { //System.out.println(appName); for(Integer nodes : numbersOfNodes) { for(Integer bandwidth : bandwidths) { File csvFile = Paths.get(resultsDir.getName(), appName, "taskvar", "taskvar_"+appName+"_nodes"+nodes+"_bw"+bandwidth+".csv").toFile(); csvFile.getParentFile().mkdirs(); try(CSVWriter csvWriter = new CSVWriter(csvFile, ';', false)){ csvWriter.write(labels); for(Integer taskNum : taskNums) { //System.out.println(taskNum); String daxFile = appName+"_"+taskNum+".xml"; if(daxFiles.contains(daxFile)) { List<String> tuple = new LinkedList<>(); tuple.add(String.valueOf(taskNum)); for(Tuple strategy : strategies) { Tuple simKey = Tuple.ofStrings(daxFile, strategy.get(0), strategy.get(1), bandwidth, nodes); if(results.containsKey(simKey)) { //System.out.println(simKey); double simTime = results.get(simKey); tuple.add(String.format("%1.3f",simTime)); } else tuple.add("<unknown>"); } Tuple datasetTuple = Tuple.ofStrings(tuple); csvWriter.write(datasetTuple); } } } } } } } }
3ab8ce3c3941e62bf882ffcc010a14e72deef12f
[ "Java" ]
3
Java
SCAlabUnical/ADAGE
063fa27d0eb0f90d123f917d7c51fd76eb153476
eab0a8d6200df6c98475ec2c13b24eb3c9dd42b5
refs/heads/master
<repo_name>timsterzel/Cloud-Gallery<file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/ui/com_interfaces/OnChangeActionBarTitle.java package org.tmcrafz.cloudgallery.ui.com_interfaces; public interface OnChangeActionBarTitle { void OnChangActionbarTitle(String title); } <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/ui/home/HomeFragment.java package org.tmcrafz.cloudgallery.ui.home; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import com.owncloud.android.lib.resources.files.model.RemoteFile; import org.tmcrafz.cloudgallery.R; import org.tmcrafz.cloudgallery.datahandling.DataHandlerSql; import org.tmcrafz.cloudgallery.web.nextcloud.NextcloudOperationReadFolder; import org.tmcrafz.cloudgallery.web.nextcloud.NextcloudWrapper; import java.util.ArrayList; public class HomeFragment extends Fragment implements NextcloudOperationReadFolder.OnReadFolderFinishedListener { private static String TAG = HomeFragment.class.getCanonicalName(); private EditText mEditTextPath; private HomeViewModel homeViewModel; private DataHandlerSql mDataHandlerSql; private NextcloudWrapper mNextCloudWrapper; // Store the folder structure as with path as key and another map with the same data as value //private HashMap<String, Object> m_FolderStructure = null; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class); View root = inflater.inflate(R.layout.fragment_home, container, false); mEditTextPath = root.findViewById(R.id.editText_path); mEditTextPath.setText("/Test1/"); Button buttonShow = root.findViewById(R.id.button_show); /* buttonShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // String path = mEditTextPath.getText().toString(); // //downloadAndShowPicture(path); // loadContentOfFolder(path); String path = mEditTextPath.getText().toString(); Intent intent = new Intent(getActivity(), ShowPicturesActivity.class); intent.putExtra(ShowPicturesActivity.EXTRA_PATH_TO_SHOW, path); startActivity(intent); } }); */ // mDataHandlerSql = new DataHandlerSql(getActivity()); // mDataHandlerSql.deleteDatabase(getActivity()); mDataHandlerSql = new DataHandlerSql(getActivity()); mDataHandlerSql.insertMediaPath("/Test1/", true); mDataHandlerSql.insertMediaPath("/Test2/", false); // mMediaPaths = mDataHandlerSql.getAllPaths(); // for (RemotePath remotePath : mMediaPaths) { // Log.d(TAG, "->Path: " + remotePath.path + " show: " + remotePath.show); // } return root; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // ToDO: TMP. // Load folder structure SharedPreferences prefs = getActivity().getSharedPreferences(getString(R.string.key_preference_file_key), 0); String serverUrl = prefs.getString(getString(R.string.key_preference_server_url), ""); String username = prefs.getString(getString(R.string.key_preference_username), ""); String password = prefs.getString(getString(R.string.key_preference_password), ""); if (serverUrl != "" && username != "" && password != "") { mNextCloudWrapper = new NextcloudWrapper(serverUrl); mNextCloudWrapper.connect(username, password, getActivity()); } else { Log.d(TAG, "mNextCloudWrapper Cannot connect to Nextcloud. Server, username or password is not set"); } loadCompleteFolderStructure(); } // ToDo: TMP. private void loadCompleteFolderStructure() { if (mNextCloudWrapper == null) { return; } mNextCloudWrapper.startReadFolder("/", "/", new Handler(), this); } @Override public void onReadFolderFinished(String identifier, boolean isSuccesfull, ArrayList<Object> files) { // Load dir and sub dirs recursively if (isSuccesfull) { Log.d(TAG, "--------------Identifier: " + identifier + "----------------"); for(Object fileTmp: files) { RemoteFile file = (RemoteFile) fileTmp; String mimetype = file.getMimeType(); //Log.d(TAG, remotePath + ": " + mimetype); if (mimetype.equals("DIR")) { String remotePath = file.getRemotePath(); //Log.d(TAG, "---DIR"); Log.d(TAG, remotePath + ": " + mimetype); // Dont proceed with current path to avoid unlimited recursion if (!remotePath.equals(identifier)) { mNextCloudWrapper.startReadFolder(remotePath, remotePath, new Handler(), this); } } } } else { Log.e(TAG, "Could not read remote folder with identifier: " + identifier); } mNextCloudWrapper.cleanOperations(); } } <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/web/nextcloud/NextcloudWrapper.java package org.tmcrafz.cloudgallery.web.nextcloud; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Handler; import android.util.Log; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClientFactory; import com.owncloud.android.lib.common.OwnCloudCredentialsFactory; import org.tmcrafz.cloudgallery.R; import java.util.ArrayList; import java.util.Iterator; public class NextcloudWrapper { private static String TAG = NextcloudWrapper.class.getCanonicalName(); public static NextcloudWrapper wrapper; private OwnCloudClient mClient; private String mServerUrl; private ArrayList<NextcloudOperation> mRunningOperations; public NextcloudWrapper(String serverUrl) { mServerUrl = serverUrl; mRunningOperations = new ArrayList<>(); } public static boolean initializeWrapperWhenNecessary(String serverUrl, String username, String password, Context context) { if (wrapper == null) { if (serverUrl != "" && username != "" && password != "") { wrapper = new NextcloudWrapper(serverUrl); wrapper.connect(username, password, context); return true; } else { Log.d(TAG, "mNextCloudWrapper Cannot connect to Nextcloud. Server, username or password is not set"); return false; } } return true; } public void connect(String username, String password, Context context) { Uri serverUri = Uri.parse(mServerUrl); mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, context, true); mClient.setCredentials(OwnCloudCredentialsFactory.newBasicCredentials(username, password)); } public void startReadFolder(String path, String identifier, Handler handler, NextcloudOperationReadFolder.OnReadFolderFinishedListener listener) { NextcloudOperationReadFolder operation = new NextcloudOperationReadFolder(identifier, handler, listener); mRunningOperations.add(operation); operation.readFolder(path, mClient); } public void startDownload(String remoteFilePath, String targetDirectory, String identifier, Handler handler, NextcloudOperationDownloadFile.OnDownloadFileFinishedListener listener) { NextcloudOperationDownloadFile operation = new NextcloudOperationDownloadFile(identifier, handler, listener); mRunningOperations.add(operation); operation.downloadFile(remoteFilePath, targetDirectory, mClient); } public void startThumbnailDownload(Activity context, String remoteFilePath, String targetDirectory, int size, String identifier, NextcloudOperationDownloadThumbnail.OnDownloadThumbnailFinishedListener listener) { NextcloudOperationDownloadThumbnail operation = new NextcloudOperationDownloadThumbnail(identifier, listener); mRunningOperations.add(operation); operation.downloadThumbnail(context, remoteFilePath, targetDirectory, size, mClient); } // Delete all finished operations public void cleanOperations() { Iterator<NextcloudOperation> operationIterator = mRunningOperations.iterator(); while (operationIterator.hasNext()) { NextcloudOperation operation = operationIterator.next(); if (operation.isFinished()) { operationIterator.remove(); } } } }<file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/datahandling/RemotePath.java package org.tmcrafz.cloudgallery.datahandling; public class RemotePath { public String path; public boolean show; } <file_sep>/README.md # Cloud-Gallery Android app which will show your Nextcloud photos <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/ui/cloud_folders/CloudFolderViewModel.java package org.tmcrafz.cloudgallery.ui.cloud_folders; import androidx.lifecycle.ViewModel; public class CloudFolderViewModel extends ViewModel { // TODO: Implement the ViewModel } <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/ui/settings/SettingsFragment.java package org.tmcrafz.cloudgallery.ui.settings; import androidx.lifecycle.ViewModelProviders; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.tmcrafz.cloudgallery.R; public class SettingsFragment extends Fragment { private static String TAG = SettingsFragment.class.getCanonicalName(); private SettingsViewModel mViewModel; private EditText mEditTextServer; private EditText mEditTextUsername; private EditText mEditTextPassword; private SharedPreferences mSavedSettings; public static SettingsFragment newInstance() { return new SettingsFragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mSavedSettings = getActivity().getSharedPreferences(getString(R.string.key_preference_file_key), 0); mViewModel = ViewModelProviders.of(this).get(SettingsViewModel.class); return inflater.inflate(R.layout.fragment_settings, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel.serverUrl = mSavedSettings.getString(getString(R.string.key_preference_server_url), ""); mViewModel.username = mSavedSettings.getString(getString(R.string.key_preference_username), ""); mViewModel.password = mSavedSettings.getString(getString(R.string.key_preference_password), ""); mEditTextServer = (EditText) getActivity().findViewById(R.id.edit_text_server); mEditTextServer.setText(mViewModel.serverUrl); mEditTextUsername = (EditText) getActivity().findViewById(R.id.edit_text_username); mEditTextUsername.setText(mViewModel.username); mEditTextPassword = (EditText) getActivity().findViewById(R.id.edit_text_password); mEditTextPassword.setText(mViewModel.password); Button btnSave = getActivity().findViewById(R.id.button_save_settings); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String serverUrl = mEditTextServer.getText().toString(); String username = mEditTextUsername.getText().toString(); String password = mEditTextPassword.getText().toString(); SharedPreferences.Editor editor = mSavedSettings.edit(); editor.putString(getString(R.string.key_preference_server_url), serverUrl); editor.putString(getString(R.string.key_preference_username), username); editor.putString(getString(R.string.key_preference_password), password); editor.commit(); Toast toast = Toast.makeText(getActivity(), R.string.settings_toast_saved ,Toast.LENGTH_SHORT); toast.show(); } }); } } <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/web/nextcloud/NextcloudOperation.java package org.tmcrafz.cloudgallery.web.nextcloud; import android.os.Handler; public class NextcloudOperation { private static String TAG = NextcloudOperation.class.getCanonicalName(); protected String mIdentifier; protected Handler mHandler; protected boolean mIsFinished; public NextcloudOperation(String identifier, Handler handler) { mIdentifier = identifier; mHandler = handler; mIsFinished = false; } public NextcloudOperation(String identifier) { mIdentifier = identifier; mIsFinished = false; } protected String getIdentifier() { return mIdentifier; } protected Handler getHandler() { return mHandler; } protected boolean isFinished() { return mIsFinished; } } <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/ui/show_photo/ShowPhotoActivity.java package org.tmcrafz.cloudgallery.ui.show_photo; import android.annotation.SuppressLint; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import org.tmcrafz.cloudgallery.R; import org.tmcrafz.cloudgallery.adapters.GalleryItem; import org.tmcrafz.cloudgallery.datahandling.StorageHandler; import org.tmcrafz.cloudgallery.web.nextcloud.NextcloudOperationDownloadFile; import org.tmcrafz.cloudgallery.web.nextcloud.NextcloudWrapper; import java.io.File; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ public class ShowPhotoActivity extends AppCompatActivity implements NextcloudOperationDownloadFile.OnDownloadFileFinishedListener { private static String TAG = ShowPhotoActivity.class.getCanonicalName(); public final static String EXTRA_REMOTE_PATH_TO_IMAGE = "remote_path_to_image"; /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * Some older devices needs a small delay between UI widget updates * and a change of the status and navigation bar. */ private static final int UI_ANIMATION_DELAY = 300; private final Handler mHideHandler = new Handler(); private View mContentView; private final Runnable mHidePart2Runnable = new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { // Delayed removal of status and navigation bar // Note that some of these constants are new as of API 16 (Jelly Bean) // and API 19 (KitKat). It is safe to use them, as they are inlined // at compile-time and do nothing on earlier devices. mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } }; private View mControlsView; private final Runnable mShowPart2Runnable = new Runnable() { @Override public void run() { // Delayed display of UI elements ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.show(); } //mControlsView.setVisibility(View.VISIBLE); } }; private boolean mVisible; private final Runnable mHideRunnable = new Runnable() { @Override public void run() { hide(); } }; /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ private String mNextcloudUrl; private String mNextcloudUsername; private String mNextcloudPassword; private ImageView mImageView; private String mRemotePath; // ToDo: Remote Folder, to swipe to next picture (pre loading next and before last picture? private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } break; case MotionEvent.ACTION_UP: view.performClick(); break; default: break; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences prefs = getSharedPreferences(getString(R.string.key_preference_file_key), 0); mNextcloudUrl = prefs.getString(getString(R.string.key_preference_server_url), ""); mNextcloudUsername = prefs.getString(getString(R.string.key_preference_username), ""); mNextcloudPassword = prefs.getString(getString(R.string.key_preference_password), ""); NextcloudWrapper.initializeWrapperWhenNecessary( mNextcloudUrl, mNextcloudUsername, mNextcloudPassword, getApplicationContext()); setContentView(R.layout.activity_show_photo); //supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle(""); getWindow().setStatusBarColor(Color.TRANSPARENT); mVisible = true; //mControlsView = findViewById(R.id.fullscreen_content_controls); mContentView = findViewById(R.id.fullscreen_content); // Set up the user interaction to manually show or hide the system UI. mContentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggle(); } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. //findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); mImageView = findViewById(R.id.imageView_picture); Intent intent = getIntent(); if (intent != null) { mRemotePath = intent.getStringExtra(EXTRA_REMOTE_PATH_TO_IMAGE); Log.d(TAG, "RemotePath: " + mRemotePath); // ToDo: Use real pricture Data (online this one when nothing else is available until better resolution is loaded) String previewTmpPath = StorageHandler.getThumbnailDir(this) + mRemotePath; Log.d(TAG, "PreviewPath: " + previewTmpPath); // ToDo: Thumbnail resoultion seem to differ from full picture, find way to make loading more smooth mImageView.setImageBitmap(BitmapFactory.decodeFile(previewTmpPath)); // Load full picture to show String localFileDir = StorageHandler.getMediaDir(getApplicationContext()); String identifier = localFileDir + mRemotePath; NextcloudWrapper.wrapper.startDownload( mRemotePath, localFileDir, identifier, new Handler(), this); // ToDo: load smaller pictures first when big (and dont load full size picture when in Datamode and too big?) } } @Override protected void onResume() { super.onResume(); NextcloudWrapper.initializeWrapperWhenNecessary( mNextcloudUrl, mNextcloudUsername, mNextcloudPassword, getApplicationContext()); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } private void toggle() { if (mVisible) { hide(); } else { show(); } } private void hide() { // Hide UI first ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } //mControlsView.setVisibility(View.GONE); mVisible = false; // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable); mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); } private void show() { // Show the system bar mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); mVisible = true; // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable); mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); } /** * Schedules a call to hide() in delay milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.show_photo_menu, menu); return true; } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onBackPressed() { super.onBackPressed(); finish(); } @Override public void onDownloadFileFinished(String identifier, boolean isSuccessful) { if (isSuccessful) { Log.d(TAG, "Identifier: " + identifier); String localFilePath = identifier; Log.d(TAG, "onDownloadFileFinished successful, local path: " + localFilePath); File file = new File(localFilePath); if (file.exists() && file.isFile()) { // ToDo: handle picture orientation mImageView.setImageBitmap(BitmapFactory.decodeFile(localFilePath)); } } } }<file_sep>/Cloud-Gallery/settings.gradle rootProject.name='Cloud Gallery' include ':app' <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/web/nextcloud/NextcloudOperationDownloadFile.java package org.tmcrafz.cloudgallery.web.nextcloud; import android.os.Handler; import android.util.Log; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.network.OnDatatransferProgressListener; import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.resources.files.DownloadFileRemoteOperation; import java.io.File; public class NextcloudOperationDownloadFile extends NextcloudOperation implements OnRemoteOperationListener, OnDatatransferProgressListener { private static String TAG = NextcloudOperationDownloadFile.class.getCanonicalName(); public interface OnDownloadFileFinishedListener { void onDownloadFileFinished(String identifier, boolean isSuccessful); } private OnDownloadFileFinishedListener mListener; public NextcloudOperationDownloadFile(String identifier, Handler handler, OnDownloadFileFinishedListener listener) { super(identifier, handler); mListener = listener; } // File is saved in targetDirectory + filePath (location on Server) public void downloadFile(String remoteFilePath, String targetDirectory, OwnCloudClient client) { File targetDirFile = new File(targetDirectory); Log.d(TAG, "TargetFileDir: " + targetDirFile); DownloadFileRemoteOperation downloadOperation = new DownloadFileRemoteOperation(remoteFilePath, targetDirFile.getAbsolutePath()); downloadOperation.addDatatransferProgressListener(this); downloadOperation.execute(client, this, mHandler); } @Override public void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result) { if (caller instanceof DownloadFileRemoteOperation) { mListener.onDownloadFileFinished(mIdentifier, result.isSuccess()); } mIsFinished = true; } @Override public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileAbsoluteName) { } } <file_sep>/Cloud-Gallery/app/src/main/java/org/tmcrafz/cloudgallery/web/nextcloud/NextcloudOperationReadFolder.java package org.tmcrafz.cloudgallery.web.nextcloud; import android.os.Handler; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation; import java.util.ArrayList; public class NextcloudOperationReadFolder extends NextcloudOperation implements OnRemoteOperationListener { public interface OnReadFolderFinishedListener { void onReadFolderFinished(String identifier, boolean isSuccesfull, ArrayList<Object> files); } private static String TAG = NextcloudOperationReadFolder.class.getCanonicalName(); private OnReadFolderFinishedListener mListener; public NextcloudOperationReadFolder(String identifier, Handler handler, OnReadFolderFinishedListener listener) { super(identifier, handler); mListener = listener; } public void readFolder(String path, OwnCloudClient client) { ReadFolderRemoteOperation refreshOperation = new ReadFolderRemoteOperation(path); refreshOperation.execute(client, this, mHandler); } @Override public void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result) { if (caller instanceof ReadFolderRemoteOperation) { mListener.onReadFolderFinished(mIdentifier, result.isSuccess(), result.getData()); } mIsFinished = true; } }
ffd70defd436c757dc5db620fccc975a3c38295e
[ "Markdown", "Java", "Gradle" ]
12
Java
timsterzel/Cloud-Gallery
5a5040a8b23735648d93c727ce1ad8d9d14b9ef7
7223b91ec658eb497821f597a58c6b628ae68efe
refs/heads/master
<file_sep>export const installed_blueprints = [ //@BlueprintInsertion { name: 'UserProfile58078', human_name: 'User Profile', access_route: 'UserProfile58078'}, { name: 'Tutorial58077', human_name: 'Tutorial', access_route: 'Tutorial58077', icon: 'question-circle'}, { name: 'NotificationList58049', human_name: 'Notification List', access_route: 'NotificationList58049'}, { name: 'Settings58048', human_name: 'Settings', access_route: 'Settings58048'}, { name: 'Settings58040', human_name: 'Settings', access_route: 'Settings58040'}, { name: 'UserProfile58038', human_name: 'User Profile', access_route: 'UserProfile58038'}, { name: 'Messenger', human_name: 'Messenger', access_route: 'Messenger', icon: 'comments'}, { name: 'Tutorial', human_name: 'Tutorial', access_route: 'Tutorial', icon: 'question-circle'}, { name: 'Maps', human_name: 'Maps', access_route: 'Maps', icon: 'map'}, { name: 'Calendar', human_name: 'Calendar', access_route: 'Calendar', icon: 'calendar'}, { name: 'Camera', human_name: 'Camera', access_route: 'Camera', icon: 'camera'}, { name: 'EmailAuth', human_name: 'EmailAuth', access_route: 'EmailAuth', icon: 'envelope-o'}, // you can add more installed blueprints here // access route is the route nate given to navigator ]; <file_sep>import { createAppContainer } from 'react-navigation'; import { createStackNavigator } from 'react-navigation-stack'; import {createDrawerNavigator} from 'react-navigation-drawer'; import SplashScreen from "../features/SplashScreen"; import SideMenu from './sideMenu'; //@BlueprintImportInsertion import UserProfile58078Navigator from '../features/UserProfile58078/navigator'; import Tutorial58077Navigator from '../features/Tutorial58077/navigator'; import NotificationList58049Navigator from '../features/NotificationList58049/navigator'; import Settings58048Navigator from '../features/Settings58048/navigator'; import Settings58040Navigator from '../features/Settings58040/navigator'; import UserProfile58038Navigator from '../features/UserProfile58038/navigator'; import MessengerNavigator from '../features/Messenger/navigator'; import TutorialNavigator from '../features/Tutorial/navigator'; import MapsNavigator from '../features/Maps/navigator'; import CalendarNavigator from '../features/Calendar/navigator'; import CameraNavigator from '../features/Camera/navigator'; import EmailAuthNavigator from '../features/EmailAuth/navigator'; /** * new navigators can be imported here */ const AppNavigator = { SplashScreen: { screen: SplashScreen }, //@BlueprintNavigationInsertion UserProfile58078: { screen: UserProfile58078Navigator }, Tutorial58077: { screen: Tutorial58077Navigator }, NotificationList58049: { screen: NotificationList58049Navigator }, Settings58048: { screen: Settings58048Navigator }, Settings58040: { screen: Settings58040Navigator }, UserProfile58038: { screen: UserProfile58038Navigator }, Messenger: { screen: MessengerNavigator }, Tutorial: { screen: TutorialNavigator }, Maps: { screen: MapsNavigator }, Calendar: { screen: CalendarNavigator }, Camera: { screen: CameraNavigator }, EmailAuth: { screen: EmailAuthNavigator }, /** new navigators can be added here */ }; const DrawerAppNavigator = createDrawerNavigator( { ...AppNavigator, }, { contentComponent: SideMenu, initialRouteName: 'SplashScreen', }, ); const AppContainer = createAppContainer(DrawerAppNavigator); export default AppContainer;
49ad4facf3668e4bf2d33dc853f2023ffd15983b
[ "JavaScript" ]
2
JavaScript
peachseemz/taskapp-17702
baae0150a010fe93415b2f0d0a4ac45b71220489
99037d565a325c1083a06ceedfe9f06431771e0a
refs/heads/master
<file_sep>package com.leyou.item.bean; import io.swagger.annotations.ApiOperation; import lombok.Data; import javax.persistence.*; @Table(name = "tb_brand") @Entity @Data public class Brand { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String image; private Character letter; } <file_sep>package com.ly.common.exception; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @AllArgsConstructor @NoArgsConstructor public enum ExceptionEnum { PRICE_CANNOT_BE_NULL(400, "价格不能为空"); private int code; private String message; } <file_sep>package com.ly.common.advice; import com.ly.common.exception.ExceptionEnum; import com.ly.common.exception.LyException; import com.ly.common.vo.ResponseResult; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class CommonExceptionHandler { @ExceptionHandler(LyException.class) public ResponseEntity<ResponseResult> handlerRuntimeException(LyException e) { ExceptionEnum exceptionEnum = e.getExceptionEnum(); return ResponseEntity.status(exceptionEnum.getCode()).body(new ResponseResult(exceptionEnum)); } } <file_sep>添加hosts映射: 127.0.0.1 manage.leyou.com <br> 127.0.0.1 api.leyou.com <br>
9b1b7287ddc9b2cf7065548479115762a363926c
[ "Markdown", "Java" ]
4
Java
AmberBar/LEI-YOU
2afa16b10941b1d4aeb757fa17fbb186abdbc625
2cfa20a7264472d014522d0367d38f14b1137988
refs/heads/master
<file_sep># Vue Void Before `[email protected]`, the following code: ```html <template slot="..."></template> ``` ...results in clearing the slot content. But in later versions this will reveal the fallback content instead. To clear the fallback content of a predefined slot, the quickest way seem to be [using a zero-width space (`&#8203;`)](https://github.com/vuejs/vue/issues/7064#issuecomment-344798116) in the template. But it does look hacky. Let's hide the hack under the hood and use a more semantic approach, which doesn't even need an extra character here. This component renders absolutely nothing except a comment node (which won't appear in DOM tree so that CSS selectors like `:first-child` will not be affected) so you can now clear a slot like this: ```html <template slot="..."><v-void/></template> ``` It'll be more ideal if Vue can support this with a native custom component like `<transition>`/`<keep-alive>`: ```html <template slot="..."><void/></template> ``` <file_sep>import { mount } from '@vue/test-utils' import VVoid from '@/components/VVoid' describe('VVoid.vue', () => { it('renders only an empty string', () => { const wrapper = mount(VVoid) expect(wrapper.vnode.tag).toBe(undefined) expect(wrapper.vnode.children).toBe(undefined) expect(wrapper.vnode.data).toBe(undefined) expect(wrapper.vnode.text).toBe('') }) }) <file_sep>const vue = require('rollup-plugin-vue') const buble = require('rollup-plugin-buble') const uglify = require('rollup-plugin-uglify') export default { input: 'src/components/VVoid.js', external: [ 'vue' ], output: { format: 'umd', file: 'dist/VVoid.js', name: 'VVoid' }, plugins: [ vue(), buble(), uglify() ] }
787ae0d9620a64f5c833b4e7a55df7941e68993c
[ "Markdown", "JavaScript" ]
3
Markdown
Justineo/vue-void
a2deeab710bd723f7311afb8b1504f2b21746319
fd761e2f15e92e79507c270a18bd7746b4170fd6
refs/heads/master
<file_sep>package server_tcp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; class ERunnable implements Runnable { // Thread Ŭ���� // ������ �־���ϴ� Field�� ������ �־���ϰ� �������κ��� ��Dz,�ƿ�Dz ��Ʈ���� �̾Ƴ�����. Socket socket; // Ŭ���̾�Ʈ�� ����� ���� BufferedReader br; // �Է��� ���� ��Ʈ�� PrintWriter out; // ����� ���� ��Ʈ�� // CarinfoVO car = new CarinfoVO(); Connection conn = null; String carnum = null; public ERunnable(Socket socket) { super(); this.socket = socket; try { this.br = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("�Է¹�����"); carnum = br.readLine(); System.out.println(carnum); this.out = new PrintWriter(socket.getOutputStream()); // ���̵� �����ɷ� ���� �ٲ��; // String carinfostr = carinfo(carnum); // // // out.println(carinfostr); // out.flush(); // System.out.println(out.toString()); } catch (IOException e) { e.printStackTrace(); } } public static Connection getConnection() { // oracle ���� String jdbcUrl = "jdbc:oracle:thin:@172.16.58.3:1521:xe"; String userId = "SCOTT"; String userPw = "<PASSWORD>"; Connection conn = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { conn = DriverManager.getConnection(jdbcUrl, userId, userPw); // System.out.println("���Ἲ��, ȣ�⼺��"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public String carupdate(String carnum) throws SQLException { PreparedStatement pstmt0 = null; PreparedStatement pstmt3 = null; ResultSet rs = null; String returns = null; try { String sql0 = "SELECT A3.B1, A3.B2, A3.B3, A3.B4, A3.B5" + " FROM A2" + " join A1 ON A1.ROUTE = A2.ROUTE" + " JOIN A3 ON A2.CARNUM = A3.CARNUM" + " WHERE A1.ID = ?"; // String sql0 = "SELECT B1,B2 FROM A3 WHERE CARNUM = ?"; // b1 = pstmt0 = getConnection().prepareStatement(sql0); // pstmt0.setString(1, carnum); pstmt0.setString(1, "1234"); rs = pstmt0.executeQuery(); System.out.println("carnum�� ? : @" + carnum); } catch (Exception e) { e.printStackTrace(); }finally { if (pstmt3 != null) try { pstmt3.close(); } catch (SQLException ex) { } if (pstmt0 != null) try { pstmt0.close(); } catch (SQLException ex) { } if (getConnection() != null) try { getConnection().close(); } catch (SQLException ex) { } } return returns; } public String carinfo(String carnum) throws SQLException { PreparedStatement pstmt0 = null; PreparedStatement pstmt3 = null; ResultSet rs = null; JSONArray ja = new JSONArray(); String returns = null; try { String sql0 = "SELECT A3.B1, A3.B2, A3.B3, A3.B4, A3.B5" + " FROM A2" + " join A1 ON A1.ROUTE = A2.ROUTE" + " JOIN A3 ON A2.CARNUM = A3.CARNUM" + " WHERE A1.ID = ?"; // String sql0 = "SELECT B1,B2 FROM A3 WHERE CARNUM = ?"; // b1 = pstmt0 = getConnection().prepareStatement(sql0); // pstmt0.setString(1, carnum); pstmt0.setString(1, "1234"); rs = pstmt0.executeQuery(); System.out.println("carnum�� ? : @" + carnum); while (rs.next()) { JSONObject jo = new JSONObject(); jo.put("B1", rs.getString("B1")); jo.put("B2", rs.getString("B2")); jo.put("B3", rs.getString("B3")); jo.put("B4", rs.getString("B4")); jo.put("B5", rs.getString("B5")); ja.add(jo); } returns = ja.toJSONString(); } catch (Exception e) { e.printStackTrace(); } finally { if (pstmt3 != null) try { pstmt3.close(); } catch (SQLException ex) { } if (pstmt0 != null) try { pstmt0.close(); } catch (SQLException ex) { } if (getConnection() != null) try { getConnection().close(); } catch (SQLException ex) { } } return returns; } @Override public void run() { // Ŭ���̾�Ʈ�� echoó�� ���� // Ŭ���̾�Ʈ�� ���ڿ��� ������ �ش� ���ڿ��� �޾Ƽ� �ٽ� Ŭ���̾�Ʈ���� ����. // �ѹ��ϰ� �����ϴ°� �ƴ϶� Ŭ���̾�Ʈ�� "/EXTI"��� ���ڿ��� // ���� ������ ����. String line = ""; try { for (int i = 0; i < 1; i++) { // ������ ������ ������? ��� �Ǵ��� �ϰ� �� Thread.sleep(300); // ��񰡼� �����Ϳ� // �����°� ����.. String carinfostr = carinfo(carnum); out.println(carinfostr); out.flush(); System.out.println(out.toString()); } // while((line = br.readLine()) != null) { // ������ ������ ������? ��� �Ǵ��� �ϰ� �� // if(line.equals("/EXIT/")) { // break; // ���� ������ loop�� Ż��! // } // else { // out.println(line); // out.flush(); // } // } } catch (Exception e) { e.printStackTrace(); } } } public class TCPserver extends Application { TextArea textarea; // �޽��� â �뵵�� ��� Button startbtn, closebtn; // ���� ����, ���� ���� ��ư ExecutorService executorservice = Executors.newCachedThreadPool(); // Cached : �ɵ������� �þ��� �پ���. // ServerSocket server = new ServerSocket(7777); // Ŭ���̾�Ʈ�� ������ �޾Ƶ��̴� ���� ����. but ����ó���� �ʿ��ϱ� ������ �ʵ忡�� ���� �����ϱ� ���Ѵ�. ���� ���� ���ְ� // �Ʒ� �����Ҷ� ����ó���� �ϸ鼭 �����Ѵ�. ServerSocket server; private void printMsg(String msg) { Platform.runLater(() -> { textarea.appendText(msg + "\n"); }); } @Override public void start(Stage primaryStage) throws Exception { // ȭ�鱸���ؼ� window ���� �ڵ� // ȭ��⺻ layout�� ���� => ȭ���� ���������߾�(5���� ����)���� �и� BorderPane root = new BorderPane(); // BorderPane�� ũ�⸦ ���� => ȭ�鿡 ���� window�� ũ�� ���� root.setPrefSize(700, 500); // Component �����ؼ� BorderPane�� ���� textarea = new TextArea(); root.setCenter(textarea); startbtn = new Button("Echo ���� ����!!"); startbtn.setPrefSize(250, 50); startbtn.setOnAction(t -> { // ��ư���� Action�� �߻�(Ŭ��)���� �� ȣ��! // ���� ���α׷� ���� ��ư // Ŭ���̾�Ʈ ������ ��ٷ���! => ������ �Ǹ� Thread�� �ϳ� ���� // => Thread�� �����ؼ� Ŭ���̾�Ʈ�� Thread�� ����ϵ��� ������ // ������ �ٽ� �ٸ� Ŭ���̾�Ʈ�� ������ ��ٷ���! Runnable runnable = () -> { try { server = new ServerSocket(8090); int flag = 0; printMsg("Echo Server ���� 111!! "); // Socket s = server.accept(); // ���� ��� �κ�. ���ٸ� ������ �Ѹ��� Ŭ���̾�Ʈ�� ���� while (true) { printMsg("Ŭ���̾�Ʈ ���� ���"); Socket s = server.accept(); // ���� ��� �κ�. �������� ������ ���� ���� ������ �̿� // accept ������ javaFX�� ����. �׷��� Thread�� ������ �������� System.out.println(s); printMsg("Ŭ���̾�Ʈ ���� ����"); ERunnable r = new ERunnable(s); // Ŭ���̾�Ʈ�� ���������� Thread����� �����ؿ�! executorservice.execute(r); // thread ���� // Thread t2 = new Thread(r); } } catch (Exception e) { e.printStackTrace(); } }; executorservice.execute(runnable); }); closebtn = new Button("Echo ���� ���� !!"); closebtn.setPrefSize(250, 50); closebtn.setOnAction(t -> { // ��ư���� Action�� �߻�(Ŭ��)���� �� ȣ��! // ���ӹ�ư }); FlowPane flowpane = new FlowPane(); flowpane.setPrefSize(700, 50); // flowpane�� ��ư�� �÷���! flowpane.getChildren().add(startbtn); flowpane.getChildren().add(closebtn); root.setBottom(flowpane); // Scene ��ü�� �ʿ��ؿ�. Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.setTitle("Thread �����Դϴ�."); primaryStage.show(); } public static void main(String[] args) { launch(); } }<file_sep> package can; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import java.util.Enumeration; public class SerialTest implements SerialPortEventListener { //String[] str = null; //int i = 0; SerialPort serialPort; CarLattePanda car; private static final String PORT_NAMES[] = { "COM8", // Windows }; private InputStream input; private OutputStream output; private static final int TIME_OUT = 2000; private static final int DATA_RATE = 9600; public void initialize(CarLattePanda carr) { car = carr; CommPortIdentifier portId = null; Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); while (portEnum.hasMoreElements()) { CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement(); for (String portName : PORT_NAMES) { if (currPortId.getName().equals(portName)) { portId = currPortId; break; } } } if (portId == null) { System.out.println("Could not find COM port."); return; } try { serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT); serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); input = serialPort.getInputStream(); output = serialPort.getOutputStream(); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); } catch (Exception e) { System.err.println(e.toString()); } } public synchronized void close() { if (serialPort != null) { serialPort.removeEventListener(); serialPort.close(); } } // public synchronized void serialEvent(SerialPortEvent oEvent) { // if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { // String sCommand = ""; // int cTemp; // try { // String[] str = null; // int i = 0; // while (input.available() > 0) { // try { // int available = input.available(); // byte chunk[] = new byte[available]; // input.read(chunk, 0, available); // //System.out.print(new String(chunk)); // // CarLattePanda car = new CarLattePanda(); // str[i] = new String(chunk); // i++; // // // //car.sendData("rfid"); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // System.out.println(str[0].toString()); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } public synchronized void serialEvent(SerialPortEvent oEvent) { if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { byte chunk[] = new byte[1]; int len = -1; String str = ""; StringBuilder sb = new StringBuilder(); int idx = 0; try { while (idx < 110) { len = this.input.read(chunk); String ss = new String(chunk,0,len); ss = ss.replaceAll("(\r\n|\r|\n|\n\r)", " "); String t = ""; for(int i=0; i<ss.length(); i++) { t += ss.charAt(i); } sb.append(t); //System.out.println(sb.toString()); idx += 1; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(sb.toString()); String sooy = sb.toString(); if(sooy.contains("D6 2C 4B 54")) { //RFID KEY Dex값 car.sendData("start"); } } } }
aed467a2185cb5faf1c4e1aa03afffdad8c95915
[ "Java" ]
2
Java
ehsehs90/SafeBusfinalProject_JAVA
45747e85252eec50b41b2dde2f9746418f78e388
944018162e286621031ca4126f137493dee1273e
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // initial variables Rigidbody playerBody; Camera playerCam; public float sensitivity = 10; public float constRotX = 60; public float speed = 5; float rotY = 0f; // Awake is called when the object is activated void Awake () { playerBody = GetComponent<Rigidbody>(); playerCam = GetComponentInChildren<Camera>(); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { float rotX = Input.GetAxis("Mouse X") * sensitivity + transform.localEulerAngles.y; rotY += Input.GetAxis("Mouse Y") * sensitivity; rotY = Mathf.Clamp(rotY, -constRotX, constRotX); if (Input.GetKey(KeyCode.W)) { playerBody.velocity = transform.forward * speed; } else if (Input.GetKey(KeyCode.A)) { playerBody.velocity = -transform.right * speed; } else if (Input.GetKey(KeyCode.S)) { playerBody.velocity = -transform.forward * speed; } else if (Input.GetKey(KeyCode.D)) { playerBody.velocity = transform.right * speed; } else { playerBody.velocity = new Vector3(0, playerBody.velocity.y, 0); } transform.localEulerAngles = new Vector3(0, rotX, 0); playerCam.transform.localEulerAngles = new Vector3(-rotY, 0, 0); } }<file_sep># dontblink KTH Computer Game Design course Fall 2016 <file_sep>using System; using UnityEngine; public class StraightPiece: PuzzlePiece { public StraightPiece(Transform transform, Material activeWireMaterial, Material inactiveWireMaterial): base(transform, activeWireMaterial, inactiveWireMaterial) { } public override void setActivated(bool activated, Direction source) { Transform wire = transform.Find ("wire"); if (activated) { wire.GetComponent<Renderer>().sharedMaterial = activeWireMaterial; } else { wire.GetComponent<Renderer>().sharedMaterial = inactiveWireMaterial; } } public override bool isValid(Direction source) { if (rotation == 0 || rotation == 2) { return source == Direction.UP || source == Direction.DOWN; } else { return source == Direction.LEFT || source == Direction.RIGHT; } } public override Direction getNext(Direction source) { return source; } } <file_sep>using System; public enum Direction { NONE, LEFT, UP, RIGHT, DOWN } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; public class SplashScreenController : MonoBehaviour { CanvasGroup canvasGroup; float progress = 0f; bool fading = false; public float speed = 2f; float target = 0f; public float Alpha { get { return canvasGroup.alpha; } } public void Fade (float par) { if (!fading) { fading = true; target = par; progress = 0f; } } // Use this for initialization void Awake () { canvasGroup = GetComponent<CanvasGroup>(); canvasGroup.alpha = 1; } // Update is called once per frame void Update () { /*if (Input.GetKeyDown(KeyCode.RightArrow)){ fading = true; }*/ if (fading) { progress += Time.deltaTime * speed; if (target == 0) { canvasGroup.alpha = Mathf.Lerp(1, 0, progress); } else { canvasGroup.alpha = Mathf.Lerp(0, 1, progress); } if (canvasGroup.alpha == target) fading = false; } } } <file_sep>using UnityEngine; using System.Collections; public abstract class PuzzlePiece { protected Transform transform; protected int rotation = 0; protected Material activeWireMaterial; protected Material inactiveWireMaterial; bool highlighted = false; float interpolation = 0.0f; float angle = 0; Vector3 unhighlightedPos; Vector3 highlightedPos; public PuzzlePiece(Transform transform, Material activeWireMaterial, Material inactiveWireMaterial) { this.transform = transform; this.activeWireMaterial = activeWireMaterial; this.inactiveWireMaterial = inactiveWireMaterial; highlightedPos = transform.position - transform.forward * 0.05f; unhighlightedPos = transform.position; } public void setHighlighted(bool highlighted) { this.highlighted = highlighted; } public void rotate() { rotation += 1; if (rotation > 3) { rotation -= 4; angle -= 360.0f; } } public void Update() { if (highlighted) { if (interpolation < 1.0f) { interpolation += Mathf.Min(10.0f * Time.deltaTime, 1.0f); transform.position = Vector3.Slerp(unhighlightedPos, highlightedPos, interpolation); } } else if (!highlighted) { if (interpolation > 0.0f) { interpolation -= Mathf.Max(10.0f * Time.deltaTime, 0.0f); transform.position = Vector3.Slerp(unhighlightedPos, highlightedPos, interpolation); } } if (angle < rotation * 90.0f) { float deltaAngle = 1000.0f * Time.deltaTime; if (angle + deltaAngle > rotation * 90.0f) { deltaAngle = rotation * 90.0f - angle; } angle += deltaAngle; transform.RotateAround (transform.position, transform.forward, deltaAngle); } } public abstract void setActivated (bool activated, Direction source); public abstract bool isValid (Direction source); public abstract Direction getNext (Direction source); } <file_sep>using System; public class PuzzlePieceIndex { int i = 0; int j = 0; public PuzzlePieceIndex (int i, int j) { this.i = i; this.j = j; } public int getI() { return i; } public int getJ() { return j; } } <file_sep>using UnityEngine; using System.Collections; using System; public class PuzzleInteract : MonoBehaviour { public Material activeWireMaterial; public Material inactiveWireMaterial; public Material solvedLightMaterial; public Material unsolvedLightMaterial; public TextAsset puzzleConfigurationFile; public AudioClip doorOpenClip; public AudioClip doorCloseClip; public AudioClip markerMoveClip; public AudioClip markerRotateClip; public AudioClip activatedSound; public Transform puzzleScreen; public Transform puzzleStraight; public Transform puzzleCurve; public Transform puzzleDouble; AudioSource doorAudioSource; AudioSource activatedAudioSource; Transform puzzleDoor; Transform puzzleFinishWire; Transform solvedLight; int w = 7; int h = 7; PuzzlePiece[,] puzzlePieces; bool puzzleMode = false; bool solved = false; float interpolation = 0.0f; float doorAngle = 0; int markerX = 3; int markerY = 3; Vector3 interpolationFrom; Vector3 interpolationTo; Collider interactor = null; ArrayList activeWires; // Use this for initialization void Start () { puzzleDoor = puzzleScreen.Find ("puzzle_frame/door"); puzzleFinishWire = puzzleScreen.Find ("puzzle_frame/output_wire"); solvedLight = puzzleScreen.Find ("puzzle_frame/light"); AudioSource[] audioSources = puzzleScreen.GetComponents <AudioSource> (); doorAudioSource = audioSources[0]; activatedAudioSource = audioSources[1]; Debug.Log (doorAudioSource); puzzlePieces = new PuzzlePiece[w, h]; activeWires = new ArrayList (); Array values = Enum.GetValues(typeof(Piece)); System.Random random = new System.Random (); string puzzleConfiguration = puzzleConfigurationFile.text; int row = 0; int column = 0; for (int i = 0; i < puzzleConfiguration.Length; i++) { if (puzzleConfiguration [i] == '\n') { row++; column = 0; } else if (puzzleConfiguration [i] == '\r') { // Do nothing }else { switch (puzzleConfiguration [i]) { case '1': instantiatePiece (Piece.STRAIGHT, column, row); break; case '2': instantiatePiece (Piece.CURVE, column, row); break; case '3': instantiatePiece (Piece.DOUBLE, column, row); break; default: instantiatePiece ((Piece)values.GetValue (random.Next (values.Length)), column, row); break; } column++; } } for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int rotations = random.Next (4); for (int r = 0; r < rotations; r++) { rotatePuzzlePiece (i, j); } } } } void instantiatePiece (Piece piece, int i, int j) { Vector3 origin = puzzleScreen.transform.position + puzzleScreen.transform.up * 0.075f + puzzleScreen.transform.forward * 0.30f + puzzleScreen.transform.right * 0.30f; Vector3 position = origin - (puzzleScreen.transform.forward * i + puzzleScreen.transform.right * j) * 0.1f; Transform transform; switch (piece) { case Piece.STRAIGHT: transform = (Transform) Instantiate (puzzleStraight, position, this.transform.rotation); puzzlePieces [i, j] = new StraightPiece (transform, activeWireMaterial, inactiveWireMaterial); break; case Piece.CURVE: transform = (Transform) Instantiate (puzzleCurve, position, this.transform.rotation); puzzlePieces [i, j] = new CurvedPiece (transform, activeWireMaterial, inactiveWireMaterial); break; case Piece.DOUBLE: transform = (Transform) Instantiate (puzzleDouble, position, this.transform.rotation); puzzlePieces [i, j] = new DoublePiece (transform, activeWireMaterial, inactiveWireMaterial); break; }; } bool lookingAtPuzzle(Collider other) { return Vector3.Angle (other.transform.forward, puzzleScreen.transform.position - other.transform.position) < 20.0f; } void OnTriggerEnter(Collider other) { if (!puzzleMode) { if ((other.tag == "Player" || other.tag == "Safe Player") && lookingAtPuzzle(other)) { interactor = other; } } } void OnTriggerStay(Collider other) { if (!puzzleMode) { if ((other.tag == "Player" || other.tag == "Safe Player") && lookingAtPuzzle(other)) { interactor = other; } } } void moveMarkerLeft() { if (markerX > 0) { puzzlePieces [markerX, markerY].setHighlighted (false); markerX -= 1; puzzlePieces [markerX, markerY].setHighlighted (true); doorAudioSource.PlayOneShot (markerMoveClip, 0.5f); } } void moveMarkerRight() { if (markerX < w - 1) { puzzlePieces [markerX, markerY].setHighlighted (false); markerX += 1; puzzlePieces [markerX, markerY].setHighlighted (true); doorAudioSource.PlayOneShot (markerMoveClip, 0.5f); } } void moveMarkerUp() { if (markerY > 0) { puzzlePieces [markerX, markerY].setHighlighted (false); markerY -= 1; puzzlePieces [markerX, markerY].setHighlighted (true); doorAudioSource.PlayOneShot (markerMoveClip, 0.5f); } } void moveMarkerDown() { if (markerY < h - 1) { puzzlePieces [markerX, markerY].setHighlighted (false); markerY += 1; puzzlePieces [markerX, markerY].setHighlighted (true); doorAudioSource.PlayOneShot (markerMoveClip, 0.5f); } } void breakActiveWires(int i, int j) { Direction source = Direction.DOWN; int index; for (index = 0; index < activeWires.Count; index++) { PuzzlePieceIndex piece = (PuzzlePieceIndex) activeWires [index]; if (piece.getI() == i && piece.getJ() == j) { break; } source = puzzlePieces [piece.getI (), piece.getJ ()].getNext (source); } for (int k = index; k < activeWires.Count; k++) { PuzzlePieceIndex piece = (PuzzlePieceIndex) activeWires[k]; puzzlePieces [piece.getI(), piece.getJ()].setActivated (false, source); source = puzzlePieces [piece.getI (), piece.getJ ()].getNext (source); } activeWires.RemoveRange (index, activeWires.Count - index); } void updateActiveWires() { solved = false; Direction source = Direction.DOWN; if (activeWires.Count == 0) { if (puzzlePieces [0, 0].isValid (Direction.DOWN)) { puzzlePieces [0, 0].setActivated (true, Direction.DOWN); activeWires.Add (new PuzzlePieceIndex(0, 0)); } } for (int i = 0; i < activeWires.Count; i++) { PuzzlePieceIndex x = (PuzzlePieceIndex) activeWires[i]; puzzlePieces [x.getI(), x.getJ()].setActivated (true, source); source = puzzlePieces [x.getI (), x.getJ ()].getNext (source); } if (activeWires.Count > 0) { bool finished = false; while (!finished) { PuzzlePieceIndex x = (PuzzlePieceIndex)activeWires [activeWires.Count - 1]; int i = x.getI (); int j = x.getJ (); if (source == Direction.NONE) { finished = true; } switch (source) { case Direction.DOWN: if (j < h - 1 && puzzlePieces [i, j + 1].isValid (source)) { puzzlePieces [i, j + 1].setActivated (true, source); activeWires.Add (new PuzzlePieceIndex (i, j + 1)); source = puzzlePieces [i, j + 1].getNext (source); } else { finished = true; } break; case Direction.LEFT: if (i > 0 && puzzlePieces [i - 1, j].isValid (source)) { puzzlePieces [i - 1, j].setActivated (true, source); activeWires.Add (new PuzzlePieceIndex (i - 1, j)); source = puzzlePieces [i - 1, j].getNext (source); } else { finished = true; } break; case Direction.RIGHT: if (i < w - 1 && puzzlePieces [i + 1, j].isValid (source)) { puzzlePieces [i + 1, j].setActivated (true, source); activeWires.Add (new PuzzlePieceIndex (i + 1, j)); source = puzzlePieces [i + 1, j].getNext (source); } else { if (j == h - 1 && i == w - 1) { solved = true; puzzleFinishWire.GetComponent<Renderer>().sharedMaterial = activeWireMaterial; solvedLight.GetComponent<Renderer>().sharedMaterial = solvedLightMaterial; activatedAudioSource.Play(); } finished = true; } break; case Direction.UP: if (j > 0 && puzzlePieces [i, j - 1].isValid (source)) { puzzlePieces [i, j - 1].setActivated (true, source); activeWires.Add (new PuzzlePieceIndex (i, j - 1)); source = puzzlePieces [i, j - 1].getNext (source); } else { finished = true; } break; } } } if (!solved) { puzzleFinishWire.GetComponent<Renderer>().sharedMaterial = inactiveWireMaterial; solvedLight.GetComponent<Renderer>().sharedMaterial = unsolvedLightMaterial; activatedAudioSource.Stop (); } } void rotatePuzzlePiece(int i, int j) { breakActiveWires (i, j); puzzlePieces [i, j].rotate(); updateActiveWires (); } private void updatePuzzlePieces() { for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { puzzlePieces [i, j].Update (); } } } public bool isSolved() { return solved; } public bool isPuzzleMode() { return puzzleMode; } // Update is called once per frame void Update () { if (!puzzleMode) { if (doorAngle > 0.0f) { float deltaAngle = 500.0f * Time.deltaTime; if (doorAngle - deltaAngle < 0) { deltaAngle = doorAngle; } doorAngle -= deltaAngle; puzzleDoor.RotateAround (puzzleDoor.transform.position - puzzleDoor.transform.up * 0.36f, puzzleDoor.transform.right, -deltaAngle); } if (interactor != null && Input.GetKeyDown (KeyCode.E)) { puzzleMode = true; interpolation = 0.0f; interpolationFrom = interactor.transform.position; interpolationTo = transform.position; interpolationTo.y = interpolationFrom.y; puzzlePieces [markerX, markerY].setHighlighted (true); doorAudioSource.PlayOneShot (doorOpenClip); } else { interactor = null; } } else { if (doorAngle < 160.0f) { float deltaAngle = 500.0f * Time.deltaTime; if (doorAngle + deltaAngle > 160.0f) { deltaAngle = 160.0f - doorAngle; } doorAngle += deltaAngle; puzzleDoor.RotateAround (puzzleDoor.transform.position - puzzleDoor.transform.up * 0.36f, puzzleDoor.transform.right, deltaAngle); } if (interpolation < 1.0f) { interactor.transform.position = Vector3.Slerp(interpolationFrom, interpolationTo, interpolation); interpolation += 5.0f * Time.deltaTime; } else { if (Input.GetKeyDown (KeyCode.E)) { puzzleMode = false; puzzlePieces [markerX, markerY].setHighlighted (false); doorAudioSource.PlayOneShot (doorCloseClip); } else if (Input.GetKeyDown (KeyCode.A)) { moveMarkerLeft (); } else if (Input.GetKeyDown (KeyCode.D)) { moveMarkerRight (); } else if (Input.GetKeyDown (KeyCode.W)) { moveMarkerUp (); } else if (Input.GetKeyDown (KeyCode.S)) { moveMarkerDown (); } else if (Input.GetKeyDown (KeyCode.Space)) { rotatePuzzlePiece (markerX, markerY); doorAudioSource.PlayOneShot (markerRotateClip, 0.5f); } interactor.transform.position = interpolationTo; } } updatePuzzlePieces (); } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class GameEnd : MonoBehaviour { public CanvasGroup gameOverCanvas; bool gameDone = false; float gameDoneTimer = 8.0f; // Use this for initialization void Start () { gameOverCanvas.alpha = 0.0f; } void OnTriggerEnter(Collider other) { if (other.tag == "Player") { gameDone = true; } } void Update() { if (gameDone) { gameOverCanvas.alpha += 0.5f * Time.deltaTime; if (gameOverCanvas.alpha > 1.0f) { gameOverCanvas.alpha = 1.0f; } gameDoneTimer -= Time.deltaTime; if (gameDoneTimer < 0.0f) { SceneManager.LoadScene ("MainMenu"); } } } } <file_sep>using UnityEngine; using System.Collections; public class LightFlicker : MonoBehaviour { Light shinyLight; public float timeToFade = 5f; public float cheatVar = 0f; public float incCheatVar = 1f; float firstStop = 3f * 50; float stayOff = 2f * 50; float secondStop = 3.5f * 50; // Use this for initialization void Awake () { shinyLight = GetComponent<Light>(); } // Update is called once per frame void FixedUpdate () { // shinyLight.intensity = Mathf.Lerp(shinyLight.intensity, 0, timeToFade * Time.deltaTime); //if (shinyLight.intensity > 0) { // shinyLight.intensity -= timeToFade * Time.deltaTime; //}else { // shinyLight.intensity += timeToFade * 2 * Time.deltaTime; //} if (cheatVar == 500) { cheatVar = 0; } if (cheatVar == 0 || cheatVar == firstStop || cheatVar == secondStop) { shinyLight.intensity = 0f; } if (((cheatVar > firstStop + stayOff && cheatVar < secondStop) || cheatVar < firstStop || cheatVar > 150) && shinyLight.intensity < 5) { shinyLight.intensity += 1.2f * 2 * Time.deltaTime; } cheatVar += incCheatVar; } } <file_sep>using UnityEngine; using System.Collections; public class OpenDoor : MonoBehaviour { public float maxRotation = -90f; float opening = 0; public float degreesPerUpdate = -1f; public PuzzleInteract puzzle = null; bool canOpenDoor = false; bool openingDoor = false; Rigidbody door; float doorY = 0; void Awake() { door = GetComponentInParent<Rigidbody>(); doorY = door.transform.localEulerAngles.y; } void OnTriggerEnter(Collider other) { if (other.tag == "Player") { canOpenDoor = true; } } void OnTriggerStay(Collider other) { if (other.tag == "Player") { canOpenDoor = true; } } void OnTriggerExit(Collider other) { if (other.tag == "Player") { canOpenDoor = false; } } // Update is called once per frame public void openDoor () { if (canOpenDoor) { if (puzzle == null || puzzle.isSolved ()) { openingDoor = true; } } if (openingDoor && opening > maxRotation) { opening += degreesPerUpdate; openingDoor = opening > maxRotation; }else if (opening < 0) { opening -= degreesPerUpdate; } door.transform.localEulerAngles = new Vector3(door.transform.localEulerAngles.x, doorY + opening, door.transform.localEulerAngles.z); Debug.Log ("open door"); } } <file_sep>using UnityEngine; using System.Collections; public class InmateAnimation : MonoBehaviour { public float blend; private Animator animator; // Use this for initialization void Start () { animator = GetComponent<Animator> (); animator.SetFloat ("Blend", blend); animator.speed = Random.Range (0.9f, 1.1f); } // Update is called once per frame void Update () { } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class ChangeLevel : MonoBehaviour { public void toSecondLevel() { SceneManager.LoadScene ("testingScene"); } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class MainMenuManager : MonoBehaviour { public void playButton () { SceneManager.LoadScene("firstLevelScene"); } public void exitGame () { SceneManager.LoadScene("MainMenu"); } public void replayFirstLevel(){ SceneManager.LoadScene("firstLevelScene"); } public void replaySecondLevel(){ SceneManager.LoadScene("testingScene"); } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; public class Interact : MonoBehaviour { public string interactButton; public float interactDistance = 3f; public LayerMask interactLayer; //Filter public Image interactIcon; // Picture to show if you can interact or not public bool isInteracting; public GameObject OpenDoorHintCanvas; public GameObject OpenCameraHintCanvas; // Use this for initialization void Start () { // set interact icon invisible if (interactIcon != null && OpenDoorHintCanvas != null && OpenCameraHintCanvas != null) { interactIcon.enabled = false; OpenDoorHintCanvas.SetActive(false); OpenCameraHintCanvas.SetActive(false); } } // Update is called once per frame void Update () { // shoot a ray Ray ray = new Ray (transform.position, transform.forward); RaycastHit[] hits = Physics.RaycastAll (ray, interactDistance, interactLayer); // check if we are not interacting foreach (RaycastHit hit in hits) { if (!isInteracting) { if (interactIcon != null) { interactIcon.enabled = true; // show door hint if (hit.collider.gameObject.CompareTag ("Door") == true) { if (OpenDoorHintCanvas != null) { OpenDoorHintCanvas.SetActive(true); } } /* if (hit.collider.gameObject.CompareTag ("Puzzle") == true) { if (OpenDoorHintCanvas != null) { OpenDoorHintCanvas.SetActive(true); } }*/ // show open TV hint if (hit.collider.gameObject.CompareTag ("TV") == true) { if (OpenCameraHintCanvas != null) { OpenCameraHintCanvas.SetActive(true); } } // if press the interact button "E" if (Input.GetButtonDown (interactButton)) { if (hit.collider.gameObject.CompareTag ("Door") == true) { hit.collider.GetComponent<Door> ().ChangeDoorState (); } } if (Input.GetButtonDown (interactButton)) { if (hit.collider.gameObject.CompareTag ("DoorSuccess") == true) { if (GameObject.FindGameObjectWithTag ("TV").GetComponent<SecurityCameraController> ().SecondMaterial == true) { hit.collider.GetComponent<ChangeLevel> ().toSecondLevel(); } } } } } } if (hits.Length == 0) { interactIcon.enabled = false; if (OpenCameraHintCanvas != null) { OpenDoorHintCanvas.SetActive (false); } if (OpenCameraHintCanvas != null) { OpenCameraHintCanvas.SetActive (false); } } } } <file_sep> public enum Piece { STRAIGHT, CURVE, DOUBLE, };<file_sep>using System; using UnityEngine; public class DoublePiece: PuzzlePiece { public DoublePiece(Transform transform, Material activeWireMaterial, Material inactiveWireMaterial): base(transform, activeWireMaterial, inactiveWireMaterial) { } public override void setActivated(bool activated, Direction source) { String name = "wire_bend1"; switch (source) { case Direction.DOWN: if (rotation == 0 || rotation == 1) { name = "wire_bend2"; } break; case Direction.UP: if (rotation == 2 || rotation == 3) { name = "wire_bend2"; } break; case Direction.RIGHT: if (rotation == 1 || rotation == 2) { name = "wire_bend2"; } break; case Direction.LEFT: if (rotation == 0 || rotation == 3) { name = "wire_bend2"; } break; } Transform wire = transform.Find (name); if (activated) { wire.GetComponent<Renderer>().sharedMaterial = activeWireMaterial; } else { wire.GetComponent<Renderer>().sharedMaterial = inactiveWireMaterial; } } public override bool isValid(Direction source) { return true; } public override Direction getNext(Direction source) { if (rotation == 0 || rotation == 2) { switch (source) { case Direction.DOWN: return Direction.RIGHT; case Direction.RIGHT: return Direction.DOWN; case Direction.UP: return Direction.LEFT; case Direction.LEFT: return Direction.UP; } } else { switch (source) { case Direction.DOWN: return Direction.LEFT; case Direction.LEFT: return Direction.DOWN; case Direction.UP: return Direction.RIGHT; case Direction.RIGHT: return Direction.UP; } } return Direction.NONE; } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class CameraPath : MonoBehaviour { public List<CameraWaypoint> waypointList; public Camera mainCamera; SplashScreenController splashController; public float speed; float startTime; float distance; bool active = false; int waypointIndex = 0; KeyCode lastKeycode; Transform origin, destiny; void Awake() { if (waypointList.Count > 1) { mainCamera.transform.position = waypointList[0].transform.position; mainCamera.transform.rotation = waypointList[0].transform.rotation; } splashController = FindObjectOfType<SplashScreenController>(); } void OnDrawGizmos () { Gizmos.color = Color.red; if (waypointList.Count > 1) { int i = 1; for(i = 1; i < waypointList.Count; i++) { Gizmos.DrawLine(waypointList[i-1].transform.position, waypointList[i].transform.position); } } } void NextWaypoint (int dir) { origin = waypointList[waypointIndex].transform; waypointIndex += dir; if (waypointIndex < waypointList.Count && waypointIndex >= 0) { destiny = waypointList[waypointIndex].transform; distance = Vector3.Distance(origin.position, destiny.position); startTime = Time.time; active = true; } else { //active = false; splashController.Fade(1); waypointIndex -= dir; } } // Update is called once per frame void Update() { if (active) { if (Input.GetKeyDown(lastKeycode)) { active = false; if (waypointList[waypointIndex].ending) { mainCamera.transform.position = destiny.position; mainCamera.transform.rotation = destiny.rotation; }else { if (lastKeycode == KeyCode.RightArrow) { for (int i = waypointIndex; i < waypointList.Count; i++) { if (waypointList[i].ending) { mainCamera.transform.position = waypointList[i].transform.position; mainCamera.transform.rotation = waypointList[i].transform.rotation; waypointIndex = i; break; } } } else { for (int i = waypointIndex; i >= 0; i--) { if (waypointList[i].ending) { mainCamera.transform.position = waypointList[i].transform.position; mainCamera.transform.rotation = waypointList[i].transform.rotation; waypointIndex = i; break; } } } } } else { float distCovered = (Time.time - startTime) * speed; float fracJourney = distCovered / distance; mainCamera.transform.position = Vector3.Lerp(origin.position, destiny.position, fracJourney); mainCamera.transform.rotation = Quaternion.Lerp(origin.rotation, destiny.rotation, fracJourney); if (Vector3.Distance(mainCamera.transform.position, destiny.position) < 0.01f) { if(waypointList[waypointIndex].ending) active = false; else { if (lastKeycode == KeyCode.RightArrow) NextWaypoint(1); else NextWaypoint(-1); } } } } else { if (Input.GetKeyDown(KeyCode.LeftArrow)) { if (splashController.Alpha == 1) { splashController.Fade(0); }else { lastKeycode = KeyCode.LeftArrow; NextWaypoint(-1); } } else if (Input.GetKeyDown(KeyCode.RightArrow)) { if (splashController.Alpha == 1) { splashController.Fade(0); } else { lastKeycode = KeyCode.RightArrow; NextWaypoint(1); } } } } } <file_sep>using UnityEngine; using System.Collections; public class Door : MonoBehaviour { public bool open = false; public float DoorOpenAngle = 90f; public float DoorCloseAngle = 180f; public float Smooth = 2f; public PuzzleInteract puzzle; AudioSource doorOpenSound; public Light doorLight; public void ChangeDoorState(){ if (puzzle == null || puzzle.isSolved()) { open = !open; doorOpenSound.Play (); } } // Use this for initialization void Start () { doorOpenSound = GetComponent<AudioSource> (); } // Update is called once per frame void Update () { if (puzzle != null && !puzzle.isSolved()) { if (doorLight != null) { doorLight.color = Color.red; } } else { if (doorLight != null) { doorLight.color = Color.green; } } if (open) { // open the door Quaternion targetRotationOpen = Quaternion.Euler (0, DoorOpenAngle, 0); transform.localRotation = Quaternion.Slerp (transform.localRotation, targetRotationOpen, Smooth * Time.deltaTime); } else { // close the door Quaternion targetRotationClose = Quaternion.Euler (0, DoorCloseAngle, 0); transform.localRotation = Quaternion.Slerp (transform.localRotation, targetRotationClose, Smooth * Time.deltaTime); } } } <file_sep>using UnityEngine; using System.Collections; public class SecurityCameraController : MonoBehaviour { // put the first material here. public Material material1; // put the second material here. public Material material2; public Camera securitycamera; public PuzzleInteract puzzle = null; public Light cameraLight = null; float turnSpeed = 4.0f; // Speed of camera turning when mouse moves in along an axis private Vector3 mouseOrigin; // Position of cursor when mouse dragging starts private bool isRotating; // Is the camera being rotated? bool FirstMaterial = true; public bool SecondMaterial = false; void Start () { if (securitycamera != null) { securitycamera.enabled = false; } GetComponent<Renderer>().material = material1; } void Update() { if (Input.GetKey("o")) { if (puzzle == null || puzzle.isSolved ()) { GetComponent<Renderer> ().material = material2; SecondMaterial = true; FirstMaterial = false; if (cameraLight != null) { cameraLight.intensity = 3; } if (securitycamera != null) { securitycamera.enabled = true; } } } // Get the left mouse button if(SecondMaterial) { // Get mouse origin Debug.Log(Input.mousePosition); isRotating = true; } // Rotate camera along X and Y axis if (isRotating) { //Vector3 pos = Input.mousePosition - mouseOrigin ; if(Input.GetKey("right")){ securitycamera.transform.parent.parent.parent.Rotate (Vector3.up * turnSpeed); } else if(Input.GetKey("left")){ securitycamera.transform.parent.parent.parent.Rotate (Vector3.down * turnSpeed); } // if(Input.GetKey("l")){ // securitycamera.transform.Rotate (Vector3.right * turnSpeed); // } // else if(Input.GetKey("j")){ // securitycamera.transform.Rotate (Vector3.left * turnSpeed); // } } } } <file_sep>using System; using UnityEngine; using System.Collections; namespace UnityStandardAssets.Characters.ThirdPerson { public class basicAI : MonoBehaviour { NavMeshAgent agent; //handles the level positions for movement ThirdPersonCharacter character; //handles the ai functions CheckForObservers checkForObservers; AudioSource audioSource; bool initialized; float patrolTick = 0.0f; public enum State { PATROL, CHASE, OBSERVED } public State state; private bool alive; public bool playerAlive = true; // Varaibles for patrolling public GameObject[] waypoints; int waypointInd = 0; public float patrolSpeed = 0.5f; //Variables for chasing public float chaseSpeed = 0.5f; Vector3 target; // Initialization void Start () { agent = GetComponent<NavMeshAgent> (); character = GetComponent<ThirdPersonCharacter> (); checkForObservers = GetComponent<CheckForObservers> (); audioSource = GetComponent <AudioSource> (); audioSource.pitch = UnityEngine.Random.Range (0.8f, 1.2f); initialized = false; agent.updatePosition = true; agent.updateRotation = false; state = State.PATROL; alive = true; playerAlive = true; StartCoroutine ("FSM"); } // runs while ai is alive and keeps updating ai behaviour by checking current ai state IEnumerator FSM() { while (alive) { if (checkForObservers.IsObserved ()) { state = State.OBSERVED; } else if (state == State.OBSERVED) { state = State.PATROL; } switch (state) { case State.OBSERVED: Freeze (); break; case State.PATROL: Patrol (); break; case State.CHASE: Chase (); break; } yield return null; } } // runs if player location is unknown and ai not observed void Patrol() { patrolTick += Time.deltaTime; if (patrolTick > 5.0f) { patrolTick = 0.0f; float angle = UnityEngine.Random.Range (0.0f, 2 * Mathf.PI); Vector3 direction = new Vector3 (Mathf.Cos(angle), 0.0f, Mathf.Sin(angle)); agent.SetDestination(transform.position + direction * 10.0f); } agent.speed = patrolSpeed; character.Move(agent.desiredVelocity, false, false); if (!audioSource.isPlaying) { audioSource.Play(); } if (audioSource.volume < 1.0f) { audioSource.volume += Time.deltaTime; } } // runs if play location is known and ai not observed void Chase() { agent.speed = chaseSpeed; agent.SetDestination (target); character.Move(agent.desiredVelocity, false, false); if (!audioSource.isPlaying) { audioSource.Play(); } if (audioSource.volume < 1.0f) { audioSource.volume += Time.deltaTime; } } // runs if ai is observed void Freeze() { agent.speed = 0; agent.SetDestination (character.transform.position); character.Move(agent.desiredVelocity, false, false); if (audioSource.volume > 0.0f) { audioSource.volume -= 2.0f * Time.deltaTime; } else { audioSource.Stop (); } } // runs if player is within ai awareness radius // has no effect if ai is observed void OnTriggerStay (Collider coll) { if (coll.tag == "Player") { state = State.CHASE; target = coll.gameObject.transform.position; } else if (coll.tag == "Safe Player") { state = State.PATROL; } } // Checks if player is touching the ai void OnCollisionEnter (Collision coll) { if (coll.collider.tag == "Player") { if (coll.collider is CapsuleCollider) { //Enter code for game over here Debug.Log ("You are Dead"); playerAlive = false; } } } void OnTriggerExit (Collider coll) { if (coll.tag == "Player") { state = State.PATROL; } } } } <file_sep>using UnityEngine; using System.Collections; public class CameraWaypoint : MonoBehaviour { public bool ending = true; // Use this for initialization void OnDrawGizmos () { if (ending) { Gizmos.color = Color.cyan; Gizmos.DrawSphere(transform.position, 0.1f); }else { Gizmos.color = Color.yellow; Gizmos.DrawSphere(transform.position, 0.05f); } Gizmos.color = Color.magenta; Gizmos.DrawLine(transform.position, transform.position + transform.forward * 1.5f); } } <file_sep>using System; using UnityEngine; public class CurvedPiece: PuzzlePiece { public CurvedPiece(Transform transform, Material activeWireMaterial, Material inactiveWireMaterial): base(transform, activeWireMaterial, inactiveWireMaterial) { } public override void setActivated(bool activated, Direction source) { Transform wire = transform.Find ("wire_bend"); if (activated) { wire.GetComponent<Renderer>().sharedMaterial = activeWireMaterial; } else { wire.GetComponent<Renderer>().sharedMaterial = inactiveWireMaterial; } } public override bool isValid(Direction source) { switch (rotation) { case 0: return source == Direction.UP || source == Direction.RIGHT; case 1: return source == Direction.LEFT || source == Direction.UP; case 2: return source == Direction.DOWN || source == Direction.LEFT; case 3: return source == Direction.RIGHT || source == Direction.DOWN; } return false; } public override Direction getNext(Direction source) { switch (source) { case Direction.DOWN: switch (rotation) { case 2: return Direction.RIGHT; case 3: return Direction.LEFT; } break; case Direction.LEFT: switch (rotation) { case 1: return Direction.DOWN; case 2: return Direction.UP; } break; case Direction.RIGHT: switch (rotation) { case 0: return Direction.DOWN; case 3: return Direction.UP; } break; case Direction.UP: switch (rotation) { case 0: return Direction.LEFT; case 1: return Direction.RIGHT; } break; } return Direction.NONE; } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; /** * Behaviour model for checking if the object is seen by an enabled camera. */ public class CheckForObservers : MonoBehaviour { private bool isObserved = false; public bool inDarkness = true; private int lastCalculation = -1; // Use this for initialization void Start () { } /** * Determines if the given point is inside the field of the given camera. * This method does not take into consideration that the visibility of this * point may be obscured by another object (like a wall) */ private bool PointInCameraFOV(Camera camera, Vector3 point) { Vector3 viewPos = camera.WorldToViewportPoint (point); double x = viewPos.x; double y = viewPos.y; double z = viewPos.z; return x >= 0.0 && x <= 1.0 && y >= 0.0 && y <= 1.0 && z >= 0.0; } /** * Determines if there is a wall between the two given points. * * A wall has layerMask 10000000 (binary) */ private bool WallBetween(Vector3 a, Vector3 b) { int layerMask = 1 << 10; return Physics.Raycast (a, (b - a).normalized, (b - a).magnitude, layerMask); } /** * Determines if the given point is lit by a light source. * * Should only be done in dark levels. */ private bool PointIsLit (Vector3 point) { Light[] lights = FindObjectsOfType (typeof(Light)) as Light[]; foreach (Light light in lights) { if ((light.transform.position - point).magnitude <= light.range) { return true; } } return false; } /** * Determines if the given point is observed by one of the (enabled) cameras in the * scene. */ private bool PointObserved (Vector3 point) { if (inDarkness && !PointIsLit (point)) { return false; } foreach (Camera camera in Camera.allCameras) { Vector3 cameraPosition = camera.transform.position; if (PointInCameraFOV(camera, point) && !WallBetween(cameraPosition, point)) { return true; } } return false; } /** * Returns a in Iterator of all corners of the bounding box of this object. */ private IEnumerable<Vector3> IterateAllCorners() { Bounds bounds = GetComponent<Collider> ().bounds; Vector3 c = bounds.center; Vector3 e = bounds.extents; yield return new Vector3(c.x - e.x, c.y - e.y, c.z - e.z); yield return new Vector3(c.x - e.x, c.y - e.y, c.z + e.z); yield return new Vector3(c.x - e.x, c.y + e.y, c.z - e.z); yield return new Vector3(c.x - e.x, c.y + e.y, c.z + e.z); yield return new Vector3(c.x + e.x, c.y - e.y, c.z - e.z); yield return new Vector3(c.x + e.x, c.y - e.y, c.z + e.z); yield return new Vector3(c.x + e.x, c.y + e.y, c.z - e.z); yield return new Vector3(c.x + e.x, c.y + e.y, c.z + e.z); yield break; } /** * Determines if the object is observed by an enabled camera. */ private bool DetermineIsObserved() { // Note (2016-11-08): // This is a rather cheap way to determine the visibility of // the object. What this method does is to check if any of the corners // are visible from any camer. It might be possible that all corners are // obscured by other objects in the scene, but parts of the object are // visible. // // I think for now it is better to design the levels to prevent these // kind of cases, and ensure that the object is visible only if any of // the corners are visible. foreach (Vector3 corner in IterateAllCorners()) { if (PointObserved (corner)) { return true; } } return false; } /** * Returns true if this object is observed by an enabled camera. */ public bool IsObserved() { if (lastCalculation != Time.frameCount) { isObserved = DetermineIsObserved(); lastCalculation = Time.frameCount; } return isObserved; } // Update is called once per frame void Update () { if (IsObserved ()) { } else { } } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameLogicUI : MonoBehaviour { public GameObject GameStartCanvas; public GameObject LookEnemyHint; public GameObject GameOverCanvas; public GameObject PuzzleHintCanvas; private GameObject[] enemies; private bool alive; // Use this for initialization void Start () { StartCoroutine (hideUI (GameStartCanvas, 3.0f)); //Wait 2 seconds then hide UI alive = true; GameOverCanvas.SetActive (false); } // Update is called once per frame void Update () { enemies = GameObject.FindGameObjectsWithTag ("Enemy"); if (alive) { Cursor.visible = false; } else { Cursor.visible = true; } bool showEnemyHint = false; foreach (GameObject enemy in enemies) { if (!enemy.GetComponent<CheckForObservers> ().IsObserved ()) { showEnemyHint = true; } if (enemy.GetComponent<UnityStandardAssets.Characters.ThirdPerson.basicAI> ().playerAlive == false) { alive = false; } } GameObject[] puzzles = GameObject.FindGameObjectsWithTag ("Puzzle"); bool showPuzzleHint = false; foreach (GameObject puzzle in puzzles) { if (puzzle.GetComponent<PuzzleInteract> ().isPuzzleMode ()) { showPuzzleHint = true; } } if (alive == false) { if (GameObject.FindGameObjectWithTag ("TV") == true) { if (GameObject.FindGameObjectWithTag ("TV").GetComponent<SecurityCameraController> ().SecondMaterial == false) { GameOverCanvas.SetActive (true); } } else { GameOverCanvas.SetActive (true); } }else if (showEnemyHint) { /* if (LookEnemyHint.activeSelf == false) { LookEnemyHint.SetActive (true); StartCoroutine (hideUI (LookEnemyHint, 3.0f)); }*/ } if (PuzzleHintCanvas != null) { if (showPuzzleHint) { if (PuzzleHintCanvas.activeSelf == false) { PuzzleHintCanvas.SetActive (true); } } else { PuzzleHintCanvas.SetActive (false); } } } IEnumerator hideUI (GameObject guiParentCanvas, float secondsToWait,bool show = false) { yield return new WaitForSeconds (secondsToWait); guiParentCanvas.SetActive (show); } }
439520d9d85ccfe0af0e06416f04cf74a2815398
[ "Markdown", "C#" ]
25
C#
alicenara/dontblink
2b6da7d4f7b937d607c767860ffbc3b39860609f
ee30d411a1a14dc5947ce96ed829b0d7e8bfe37a
refs/heads/master
<file_sep>package MikkelSorensen; public class Args { public static void main(String[] args) { System.out.println("Skriv de 3 værdier: " + args[0] + args[1] + args[2]); double v1 = Double.parseDouble(args[0]); double v2 = Double.parseDouble(args[2]); double sum = 0; String ope = args[1]; switch (ope) { case "+": sum = v1 + v2; break; case "-": sum = v1 - v2; break; case "*": sum = v1 * v2; break; case "/": sum = v1 / v2; break; } System.out.println("Resultatet er: " + sum); } } <file_sep>package MikkelSorensen; public class Kortspil { public static void main(String[] args) { //Hele kortspillet med 52 kort, 4 klasser og 13 kort. int[] deck = new int[52]; String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"}; String[] ranks = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; //Initialisere kortene for (int i = 0; i < deck.length; i++) { deck[i] = i; } //Her blandes kortene ved brug af Math.random, så kortene er tilfædige. //Deck[i] bliver til den tilfældige variabel, som der bruges til at vise det tilfældige kort. for (int i = 0; i < deck.length; i++) { int index =(int)(Math.random()*deck.length); int temp = deck[i]; deck[i] = deck[index]; deck[index] = temp; } //Her bliver der tilfældigt trukket 4 kort, og der vises de 4 kort i en println. for (int i = 0; i < 4; i++) { String suit = suits[deck[i] / 13]; String rank = ranks[deck[i] % 13]; System.out.println("Card number " + deck[i] + " is: " + rank + " of " + suit); } } }
cfb96546a94248de297f51e9989262ddbcda07d8
[ "Java" ]
2
Java
Mikk4211/Array
0da6b14a930897d1350d0f47ea90b7274af1829e
a47557708f36fc756d2d475f849a060b0530b938
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule } from '@angular/router'; import { ServiceWorkerModule } from '@angular/service-worker'; import { environment } from '../environments/environment'; import { AppComponent } from './app.component'; import { CartDetailComponent } from './store/cartDetail.component'; import { CheckoutComponent } from './store/checkout.component'; import { StoreComponent } from './store/store.component'; import { StoreModule } from './store/store.module'; import { StoreFirstGuard } from './storeFirst.guard'; @NgModule({ declarations: [ AppComponent ], imports: [BrowserModule, StoreModule, RouterModule.forRoot([ {path: 'store', component: StoreComponent, canActivate: [StoreFirstGuard]}, {path: 'cart', component: CartDetailComponent, canActivate: [StoreFirstGuard]}, {path: 'checkout', component: CheckoutComponent, canActivate: [StoreFirstGuard]}, { path: 'admin', loadChildren: './admin/admin.module#AdminModule', canActivate: [StoreFirstGuard] }, {path: '**', redirectTo: '/store'} ]), ServiceWorkerModule.register('ngsw-worker.js', {enabled: environment.production})], providers: [StoreFirstGuard], bootstrap: [AppComponent] }) export class AppModule { /** * That’s because the root module only really exists to provide information through the @NgModule decorator. The imports property tells * Angular that it should load the BrowserModule feature module, which contains the core Angular features required for a web application. * * The declarations property tells Angular that it should load the root component, the providers property tells Angular about the * shared objects used by the application, and the bootstrap property tells Angular that the root component is the AppModule class. * I’ll add information to this decorator’s properties as I add features to the SportsStore application, but this basic configuration * is enough to start the application. */ } <file_sep>import { Component } from '@angular/core'; import { NgForm } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { Product } from '../model/product.model'; import { ProductRepository } from '../model/product.repository'; @Component({ templateUrl: 'productEditor.component.html' }) export class ProductEditorComponent { editing: boolean = false; product: Product = new Product(); /** Angular will provide an ActivatedRoute object as a constructor argument when it creates a new instance of the component class and that can be used to inspect the activated route. In this case, the component works out whether it should be editing or creating a product and, if editing, retrieves the current details from the repository. There is also a save method, which uses the repository to save changes that the user has made. **/ constructor(private repository: ProductRepository, private router: Router, activeRoute: ActivatedRoute) { this.editing = activeRoute.snapshot.params['mode'] == 'edit'; if (this.editing) { Object.assign(this.product, repository.getProduct(activeRoute.snapshot.params['id'])); } } save(form: NgForm) { this.repository.saveProduct(this.product); this.router.navigateByUrl('/admin/main/products'); } }
309b18a9c46a17cf6675f1f355939c00f94cb64e
[ "TypeScript" ]
2
TypeScript
oguiller/sports-store
d357e90da5c4e03adbb32df089d335fc3031a9cf
f9584de7c3312a4ecb2253885c52988e49f4488a
refs/heads/master
<file_sep>export default { route: { ads:'广告', manageAgency: '管理Agency', manageBrands: '管理Brands', manageCampaigns: '管理Campaigns', manageChannels: '管理Channels', dashboard: '仪表盘', retail:'迪士尼门票兑换订单', regularTickets:'平日票', peakTickets:'高峰票', historyOrders:'历史订单', queryOrders:'订单查询', }, } <file_sep>export default { route: { ads:'ads', manageAgency: 'Manage Agency', manageBrands: 'Manage Brands', manageCampaigns: 'Manage Campaigns', manageChannels: 'Manage Channels', dashboard: 'Dashboard', retail:'迪士尼门票兑换订单', regularTickets:'平日票', peakTickets:'高峰票', historyOrders:'历史订单', queryOrders:'订单查询', csb:'兄弟塑业', goods:'商品信息管理', orders:'订单管理', }, } <file_sep>import axios from 'axios'; import $ from "jquery"; import config from '../config/config'; // let base = 'http://172.16.58.3:9090/adsManagement'; let base = config.serviceUrl; // axios.defaults.withCredentials = true export const requestLogin = params => { return $.ajax({ type: 'post', url: `${base}/login`, contentType: "application/json;charset=UTF-8", data: JSON.stringify(params), xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json' }).then(res => res); }; export const uploadImg = (params,config) => { return axios.post(`${base}/csb/uploadImg`, params,config).then(res => res.data); }; export const saveOrUpdateGoods = params => { return $.ajax({ type: 'post', url: `${base}/csb/saveOrUpdateGoods`, contentType: "application/json;charset=UTF-8", data: JSON.stringify(params), xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json' }).then(res => res); }; export const saveGoods = params => { return $.ajax({ type: 'post', url: `${base}/csb/saveGoods`, contentType: "application/json;charset=UTF-8", data: JSON.stringify(params), xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json' }).then(res => res); }; export const updateGoods = params => { return $.ajax({ type: 'post', url: `${base}/csb/updateGoods`, contentType: "application/json;charset=UTF-8", data: JSON.stringify(params), xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json' }).then(res => res); }; export const queryGoodsInfo = params => { return $.ajax({ type: 'get', url: `${base}/csb/queryGoodsInfo`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const queryGoodsInfosLike = params => { return $.ajax({ type: 'get', url: `${base}/csb/queryGoodsInfosLike`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const deleteGoods = params => { return $.ajax({ type: 'get', url: `${base}/csb/deleteGoods`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const updateOrder = params => { return $.ajax({ type: 'post', url: `${base}/csb/updateOrder`, contentType: "application/json;charset=UTF-8", data: JSON.stringify(params), xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json' }).then(res => res); }; export const queryOrders = params => { return $.ajax({ type: 'get', url: `${base}/csb/queryOrders`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const queryOrdersLike = params => { return $.ajax({ type: 'get', url: `${base}/csb/queryOrdersLike`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const queryOrderAndInfosByOrderNo = params => { return $.ajax({ type: 'get', url: `${base}/csb/queryOrderAndInfosByOrderNo`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const queryOrderInfos = params => { return $.ajax({ type: 'get', url: `${base}/csb/queryOrderInfos`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const getLoginCode = params => { return $.ajax({ type: 'post', url: `${base}/getLoginCode`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; // export const getLoginCode = params => { return axios.post(`${base}/getLoginCode`, params).then(res => res.data); }; // export const requestLogin = params => { return axios.post(`${base}/login`, params).then(res => res.data); }; export const queryRetailOrders = params => { return $.ajax({ type: 'get', url: `${base}/retail/queryRetailOrders`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const queryRetailOrdersNoOrder = params => { return $.ajax({ type: 'get', url: `${base}/retail/queryRetailOrdersNoOrder`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; export const queryRetailOrdersByEnterTime = params => { return $.ajax({ type: 'get', url: `${base}/retail/queryRetailOrdersByEnterTime`, data: params, xhrFields: { withCredentials: true }, dataType: 'json', crossDomain: true }).then(res => res); }; // export const queryOrders = params => { // return $.ajax({ // type: 'get', // url: `${base}/retail/queryOrders`, // data: params, // xhrFields: { // withCredentials: true // }, // dataType: 'json', // crossDomain: true // }).then(res => res); // }; export const updateRetailOrderById = params => { return $.ajax({ type: 'post', url: `${base}/retail/updateRetailOrderById`, contentType: "application/json;charset=UTF-8", data: JSON.stringify(params), xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json' }).then(res => res); }; export const updateRetailOrderByIdNotSendSms = params => { return $.ajax({ type: 'post', url: `${base}/retail/updateRetailOrderByIdNotSendSms`, contentType: "application/json;charset=UTF-8", data: JSON.stringify(params), xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json' }).then(res => res); };
cd671e81703669d8595b435a36072cfd1dbcbdba
[ "JavaScript" ]
3
JavaScript
daiagou/csbAdmin
2396d1c3a8ade45e5228c606f9eab12343d77bd3
d8386e560e08faa7539587154d1ab420a4fac24b
refs/heads/master
<file_sep>class Joke < ActiveRecord::Base attr_accessible :author, :date, :joke, :title end <file_sep>Given /^I have jokes titled (.+)$/ do |titles| titles.split(', ').each do |title| Joke.create!(:title => title) end end Given /^I have no jokes/ do Joke.delete_all end Then /^I should have ([0-9]+) articles?$/ do |count| Joke.count.should == count.to_i end When /^I follow "([^\"]*)" and accept alert$/ do |link| click_link(link) page.driver.browser.switch_to.alert.accept end <file_sep>Given /^I create user as (.+) with (.+)$/ do |email, password| visit new_user_registration_path fill_in "Email", with: email fill_in "Password", with: <PASSWORD> fill_in "Password confirmation", with: <PASSWORD> click_button "Sign up" end Given /^I sign user as (.+) with (.+)$/ do |email, password| visit new_user_session_path fill_in "Email", with:email fill_in "Password", with: <PASSWORD> click_button "Sign in" end Given /^I sign out$/ do visit new_user_session_path end
dfb85ca2a3da9ccdace535054bf3cef3a64e121c
[ "Ruby" ]
3
Ruby
VictorMarques/blog
94f7918b7b7978ac52e1a0a68fe2c150a2262f08
378c048a377f7fb2ebceb779180328d85ca87344
refs/heads/master
<repo_name>ChChCheeeeo/TDDWP<file_sep>/lists_app/templates/home.html {% extends 'base.html' %} {% block header_text %}Start a new To-Do list{% endblock %} <!-- { % block form_action % }/lists/new{ % endblock % }--> <!-- You can replace the hardcoded URL with a Django template tag which refers to the URL’s "name" url(r'^new$', views.new_list, name='new_list'), --> {% block form_action %}{% url 'new_list' %}{% endblock %}<file_sep>/lists_app/models.py from django.db import models from django.core.urlresolvers import reverse from django.conf import settings class List(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) shared_with = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='shared_lists' ) def get_absolute_url(self): # use it in the view—the redirect function just takes the object we # want to redirect to, and it uses get_absolute_url under the hood # automagically return reverse('view_list', args=[self.id]) @property def name(self): return self.item_set.first().text @staticmethod def create_new(first_item_text, owner=None): list_ = List.objects.create(owner=owner) Item.objects.create(text=first_item_text, list=list_) return list_ class Item(models.Model): # to get it deliberately wrong, include the unique constraint text = models.TextField(default='')#, unique=True) list = models.ForeignKey(List, default=None) class Meta: ordering = ('id',) unique_together = ('list', 'text') def __str__(self): return self.text <file_sep>/accounts_app/tests/test_authentication.py from unittest.mock import patch from django.conf import settings from django.test import TestCase from django.contrib.auth import get_user_model User = get_user_model() from accounts_app.authentication import ( PERSONA_VERIFY_URL, PersonaAuthenticationBackend ) import logging # You can apply a patch at the class level as well, # and that has the effect that every test method in the class will # have the patch applied, and the mock injected. @patch('accounts_app.authentication.requests.post') class AuthenticateTest(TestCase): # use the setUp function to prepare any useful variables # to use in all of the tests. def setUp(self): self.backend = PersonaAuthenticationBackend() user = User(email='<EMAIL>') # By default, Django’s users have a username attribute, # which has to be unique, so this value is just a placeholder # to allow us to create multiple users. Later on, get rid of # usernames in favour of using emails as the primary key. user.username = 'otheruser' user.save() def test_sends_assertion_to_mozilla_with_domain(self, mock_post): self.backend.authenticate('an assertion') mock_post.assert_called_once_with( PERSONA_VERIFY_URL, data={'assertion': 'an assertion', 'audience': settings.DOMAIN} ) def test_returns_none_if_response_errors(self, mock_post): # Now each test is only adjusting the setup variables it needs, # rather than setting up a load of duplicated boilerplate, # it’s more readable. mock_post.return_value.ok = False mock_post.return_value.json.return_value = {} user = self.backend.authenticate('an assertion') self.assertIsNone(user) def test_returns_none_if_status_not_okay(self, mock_post): # Now each test is only adjusting the setup variables it needs, # rather than setting up a load of duplicated boilerplate, # it’s more readable. mock_post.return_value.json.return_value = {'status': 'not okay!'} user = self.backend.authenticate('an assertion') self.assertIsNone(user) def test_finds_existing_user_with_email(self, mock_post): mock_post.return_value.json.return_value = {'status': 'okay', 'email': '<EMAIL>'} actual_user = User.objects.create(email='<EMAIL>') found_user = self.backend.authenticate('an assertion') self.assertEqual(found_user, actual_user) def test_creates_new_user_if_necessary_for_valid_assertion(self, mock_post): mock_post.return_value.json.return_value = {'status': 'okay', 'email': '<EMAIL>'} found_user = self.backend.authenticate('an assertion') new_user = User.objects.get(email='<EMAIL>') self.assertEqual(found_user, new_user) def test_logs_non_okay_responses_from_persona(self, mock_post): response_json = { 'status': 'not okay', 'reason': 'eg, audience mismatch' } # set up test with some data that should cause some logging mock_post.return_value.ok = True mock_post.return_value.json.return_value = response_json # retrieve the actual logger for the module being tested logger = logging.getLogger('accounts_app.authentication') # use patch.object to temporarily mock out its warning function, # by using with to make it a context manager around the function # being tested with patch.object(logger, 'warning') as mock_log_warning: self.backend.authenticate('an assertion') # then it’s available to make assertions against mock_log_warning.assert_called_once_with( 'Persona says no. Json was: {}'.format(response_json) ) class GetUserTest(TestCase): def test_gets_user_by_email(self): backend = PersonaAuthenticationBackend() other_user = User(email='<EMAIL>') other_user.username = 'otheruser' other_user.save() desired_user = User.objects.create(email='<EMAIL>') found_user = backend.get_user('<EMAIL>') self.assertEqual(found_user, desired_user) def test_returns_none_if_no_user_with_that_email(self): backend = PersonaAuthenticationBackend() self.assertIsNone( backend.get_user('<EMAIL>') )<file_sep>/functional_tests/server_tools.py from os import path import subprocess THIS_FOLDER = path.dirname(path.abspath(__file__)) def reset_database(host): subprocess.check_call( ['fab', 'reset_database', '--host={}'.format(host)], cwd=THIS_FOLDER ) # use the subprocess module to call some Fabric functions using the fab command. def create_session_on_server(host, email): return subprocess.check_output( [ 'fab', # command-line syntax for arguments to fab functions 'create_session_on_server:email={}'.format(email), '--host={}'.format(host), '--hide=everything,status', ], cwd=THIS_FOLDER # be quite careful about extracting the session key as a string from the # output of the command as it gets run on the server. ).decode().strip()<file_sep>/superlists_project/settings/base.py """ Django settings for superlists_project project. Generated by 'django-admin startproject' using Django 1.8.4. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os # from django.core.exceptions import ImproperlyConfigured # def get_env_variable(var_name): # try: # return os.environ[var_name] # except KeyError: # error_msg = "Set the %s environment variable" % var_name # raise ImproperlyConfigured(error_msg) # SECRET_KEY = get_env_variable('SECRET_KEY') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # DJANGO_SETTINGS_MODULE='superlists_project.settings.development' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY='<KEY>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # This setting is changed by the deploy script DOMAIN = "localhost" ALLOWED_HOSTS = [DOMAIN] # Application definition INSTALLED_APPS = ( # default # 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party # my apps 'lists_app', 'accounts_app', # for management commands 'functional_tests', ) # why not accounts_app.models.User? AUTH_USER_MODEL = 'accounts_app.User' AUTHENTICATION_BACKENDS = ( 'accounts_app.authentication.PersonaAuthenticationBackend', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'superlists_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'superlists_project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, '../../database/db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' # static files folder shouldn’t be a part of your repository—we don’t want to put # it under source control, because it’s a duplicate of all the files that are # inside lists/static. # STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, '../../static')) # Make site-wide static files STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, '../static')) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), # I don't know #'superlists_project', 'static'), ) # Logging configuration is hierarchical, so you can define "parent" loggers for # top-level modules, and all the Python modules inside them will inherit # that config. # Now accounts_app.models, accounts_app.views, accounts_a[[.authentication, # and all the others will inherit the logging.StreamHandler from the parent # accounts_app logger. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], }, 'accounts_app': { 'handlers': ['console'], }, 'lists_app': { 'handlers': ['console'], }, }, 'root': {'level': 'INFO'}, }<file_sep>/functional_tests/home_and_list_pages.py # Page patterns involves having objects represent different pages on # your site, and to be the single place to store information about how # to interact with them. # The idea behind the Page pattern is that it should capture all the # information about a particular page in your site, so that if, later, you want # to go and make changes to that page—even just simple tweaks to its HTML layout # for example—you have a single place to go and look for to adjust your functional # tests, rather than having to dig through dozens of FTs. ITEM_INPUT_ID = 'id_text' class HomePage(object): # Page objects for the home page def __init__(self, test): # initialize with an object that represents the current test. # so it can make assertions, access the browser instance via # self.test.browser, and use the wait_for function. self.test = test def go_to_home_page(self): # Most Page objects have a "go to this page" function. # It implements the interaction/wait pattern # First get the page URL # then wait for a known element on the home page. self.test.browser.get(self.test.server_url) self.test.wait_for(self.get_item_input) # Returning self is just a convenience. # It enables method chaining return self def get_item_input(self): return self.test.browser.find_element_by_id(ITEM_INPUT_ID) def start_new_list(self, item_text): # Function starts a new list. # Go to the home page # find the input box # send the new item text to it and a carriage return. # Use a wait to check that the interaction has completed # but the wait is actually on a different Page object (ListPage) self.go_to_home_page() inputbox = self.get_item_input() inputbox.send_keys(item_text + '\n') list_page = ListPage(self.test) # Use ListPage'swait_for_new_item_in_list and specify the expected # text of the item, and its expected position in the list list_page.wait_for_new_item_in_list(item_text, 1) # return the list_page object to the caller # because they will probably find it useful return list_page def go_to_my_lists_page(self): self.test.browser.find_element_by_link_text('My lists').click() self.test.wait_for(lambda: self.test.assertEqual( self.test.browser.find_element_by_tag_name('h1').text, 'My Lists' )) class ListPage(object): def __init__(self, test): self.test = test def get_list_table_rows(self): return self.test.browser.find_elements_by_css_selector( '#id_list_table tr' ) def wait_for_new_item_in_list(self, item_text, position): expected_row = '{}: {}'.format(position, item_text) self.test.wait_for(lambda: self.test.assertIn( expected_row, [row.text for row in self.get_list_table_rows()] )) def get_share_box(self): return self.test.browser.find_element_by_css_selector( 'input[name=email]' ) def get_shared_with_list(self): return self.test.browser.find_elements_by_css_selector( '.list-sharee' ) def share_list_with(self, email): self.get_share_box().send_keys(email + '\n') self.test.wait_for(lambda: self.test.assertIn( email, [item.text for item in self.get_shared_with_list()] )) def get_item_input(self): return self.test.browser.find_element_by_id(ITEM_INPUT_ID) def add_new_item(self, item_text): current_pos = len(self.get_list_table_rows()) self.get_item_input().send_keys(item_text + '\n') self.wait_for_new_item_in_list(item_text, current_pos + 1) def get_list_owner(self): return self.test.browser.find_element_by_id('id_list_owner').text<file_sep>/accounts_app/tests/test_views.py # from django.http import HttpRequest # from accounts_app.views import persona_login from django.contrib.auth import get_user_model, SESSION_KEY from django.test import TestCase from unittest.mock import patch # Here get_user_model from django.contrib.auth finds the project’s user model # and it works whether you’re using the standard user model or a custom one, User = get_user_model() class LoginViewTest(TestCase): # patch is a bit like the Sinon mock function. # It lets you specify an object you want to "mock out". # In this case it's mocking out the authenticate function, # which we expect to be using in accounts/views.py @patch('accounts_app.views.authenticate') def test_calls_authenticate_with_assertion_from_post( self, mock_authenticate ): # The decorator adds the mock object as an additional argument to the # function it’s applied to. # It can then onfigure the mock so that it has certain behaviours. # Having authenticate return None is the simplest, set the special # .return_value attribute. Otherwise it would return another mock, # and that would probably confuse our view. mock_authenticate.return_value = None self.client.post('/accounts/login', {'assertion': 'assert this'}) # Mocks can make assertions. In this case, they can check whether # they were called, and what with. mock_authenticate.assert_called_once_with(assertion='assert this') @patch('accounts_app.views.authenticate') def test_returns_OK_when_user_found( self, mock_authenticate ): user = User.objects.create(email='<EMAIL>') user.backend = '' # required for auth_login to work mock_authenticate.return_value = user response = self.client.post('/accounts/login', {'assertion': 'a'}) self.assertEqual(response.content.decode(), 'OK') @patch('accounts_app.views.authenticate') def test_gets_logged_in_session_if_authenticate_returns_a_user( self, mock_authenticate ): user = User.objects.create(email='<EMAIL>') user.backend = '' # required for auth_login o work mock_authenticate.return_value = user self.client.post('/accounts/login', {'assertion': 'a'}) # The Django test client keeps track of the session for its user. # For the case where the user gets authenticated successfully, # check that their user ID (the primary key, or pk) is associated # with their session. self.assertEqual(self.client.session[SESSION_KEY], str(user.pk)) # An alternative way of testing that the Django login function # was called correctly would be to mock it out too # @patch('accounts_app.views.login') # @patch('accounts_app.views.authenticate') # #def test_calls_auth_login_if_authenticate_returns_a_user( # # self, mock_authenticate, mock_login # #): # def test_calls_auth_login_if_authenticate_returns_a_user( # self, mock_authenticate): # request = HttpRequest() # request.POST['assertion'] = 'asserted' # mock_user = mock_authenticate.return_value # persona_login(request) # mock_login.assert_called_once_with(request, mock_user) @patch('accounts_app.views.authenticate') def test_does_not_get_logged_in_if_authenticate_returns_None( self, mock_authenticate ): mock_authenticate.return_value = None self.client.post('/accounts/login', {'assertion': 'a'}) # In the case where the user should not be authenticated, # the SESSION_KEY should not appear in their session. self.assertNotIn(SESSION_KEY, self.client.session)<file_sep>/deploy_tools/fabfile.py from fabric.contrib.files import append, exists, sed from fabric.api import env, local, run import random env.key_filename = "~/.ssh/id_rsa" #REPO_URL = 'https://github.com/hjwp/book-example.git' REPO_URL = 'https://github.com/ChChCheeeeo/TDDWP.git' def deploy(): # env.host will contain the address of the server we've specified at the # command line, eg, superlists.ottg.eu # tmpdomain-staging.tmpdomain.xyz # tmpdomain.xyz # env.user will contain the username you're using to log in to the server site_folder = '/home/%s/sites/%s' % (env.user, env.host) source_folder = site_folder + '/source' _create_directory_structure_if_necessary(site_folder) _get_latest_source(source_folder) _update_settings(source_folder, env.host) _update_virtualenv(source_folder) _update_static_files(source_folder) _update_database(source_folder) def _create_directory_structure_if_necessary(site_folder): # build directory struction, in a way that doesn't fall down # if it already exists for subfolder in ('database', 'static', 'virtualenv', 'source'): # fabric command - run this shell command on the server run('mkdir -p %s/%s' % (site_folder, subfolder)) def _get_latest_source(source_folder): # look for the .git hidden folder to check whether the repo has # already been cloned in that folder. if exists(source_folder + '/.git'): # Fabric doesn't have any state, so it doesn't remember what # directory you're in from one run to the next. # pull down all the latest commits run('cd %s && git fetch' % (source_folder,)) else: # Alternatively use git clone with the repo URL to bring down # a fresh source tree run('git clone %s %s' % (REPO_URL, source_folder)) # Fabric's local command runs a command on your local machine-it's # just a wrapper around subpreoces.Popen really, but it's quite # convenient. Here we capture the output from that git log # invocation to get the hash of the current commit that's in your # local tree. That means the server will end up with whatever code # is currently checked out on your machine (as long as you're pushed # it up to the server). current_commit = local("git log -n 1 --format=%H", capture=True) # reset --hard to that commit, which will blow away any current # changess in the server's code directory. run('cd %s && git reset --hard %s' % (source_folder, current_commit)) def _update_settings(source_folder, site_name): # update the settings file, to set the ALLOWED_HOSTS and DEBUG, # and to create a new secret key settings_path = source_folder + '/superlists_project/settings/base.py'#settings.py' sed(settings_path, "DEBUG = True", "DEBUG = False") sed(settings_path, 'DOMAIN = "localhost"', 'DOMAIN = "%s"' % (site_name,)) # sed(settings_path, # 'ALLOWED_HOSTS =.+$', # 'ALLOWED_HOSTS = ["%s"]' % (site_name,) # ) secret_key_file = source_folder + '/superlists_project/settings/secret_key.py' # It's good practice to make sure the secret key on the server # is different from the one in your (possibly public) source code # repo. This coe will generate a new key to import into settings, # if there isnt' one there already (once you have a secret key, it # shuld stay the same between deploys). if not exists(secret_key_file): chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' key = ''.join(random.SystemRandom().choice(chars) for _ in range(50)) append(secret_key_file, "SECRET_KEY = '%s'" % (key,)) append(settings_path, '\nfrom .secret_key import SECRET_KEY') def _update_virtualenv(source_folder): # decide not to use venv_tdd_droplet_production as it don't know how to get # it to run virtualenvwrapper's workon command source_folder = source_folder + '/requirements' # craete or update the virtualenv virtualenv_folder = source_folder + '/../virtualenv' # look inside the virtualenv folder for the pip executable as a way of # checking whether it already exists if not exists(virtualenv_folder + '/bin/pip'): run('virtualenv --python=python3 %s' % (virtualenv_folder,)) run('%s/bin/pip install -r %s/base.txt' % ( #requirements.txt' % ( virtualenv_folder, source_folder )) def _update_static_files(source_folder): # Updating static files is a single comand # We use the virtualenv binaries foler whenever we need to run a Django # manage.py command, to make sure we get the virtualenv version of Django, # not the system one. run('cd %s && ./virtualenv/bin/python3 manage.py collectstatic --noinput' % ( # 1 source_folder, )) def _update_database(source_folder): # update the database with manage.py migrate run('cd %s && ./virtualenv/bin/python3 manage.py migrate --noinput' % ( source_folder, ))
35270d72194a0152a614cc2a2587f7745a44f91f
[ "Python", "HTML" ]
8
HTML
ChChCheeeeo/TDDWP
761062a207d9b53dd14a16f970a828cd489e5bf1
f97b936fefa7ffaff7e2b94c7282a0c72c0148fc
refs/heads/master
<file_sep>import numpy as np # Function that takes the true annotation files and retrieves the uniprotKBs + GO-terms dictionary def gaf_parse(annotation_lines): # Create dictionary for the annotation annotation_dict = dict() # Loop through the annotation file for line in annotation_lines: # Check which line is a documentation line # Split the line into sections line_items = line.split("\t") # Check if there is a UniProtKB link in the section if the GO-term is valid if line_items[3] == "": # Get the UniprotKB code for the protein protein = line_items[1] # Check whether protein code is already in the dictionaire if protein not in annotation_dict.keys(): # Create a empty list for the GO-terms if so. annotation_dict[protein] = [] # If not, add the go-annotation to the protein in question. annotation_dict[protein].append(line_items[4]) return annotation_dict <file_sep>import itertools import numpy as np import sys """ Class: To perform the PLST method. """ class call_PLST: """ Function: To transform the annotation matrix. self.transformed_matrix: the transformed matrix. """ def train(self, train_matrix, plst, PLST_class): self.train_matrix = train_matrix self.plst = plst self.transformed_matrix, self.transform = self.call(PLST_class) return self.transformed_matrix """ Function: to transform the matrix transformed_matrix: The transformed matrix transform: The PLST class """ def call(self, PLST_class): transform = PLST_class() doorgaan = True while doorgaan: try: transformed_matrix = transform.fit(self.train_matrix, ndims=round(self.train_matrix.shape[1] / self.plst)) doorgaan = False except: print("SVD error, conversion runs again ") return transformed_matrix, transform """ Function: To convert the transformed matrix back to get the original values. inversed_matrix: The matrix which is transformed back """ def inverse(self, matrix): inversed_matrix = self.transform.inverseMap(matrix) return inversed_matrix <file_sep>import random class Splitter: def __init__(self, fraction, input_file): self.fraction = fraction self.input_file = input_file def splitter(self): """ Depending on the percentage and the amount of lines in the file it will split the data and saves the test data into a seperate file. """ opslag = {} for id, term in self.input_file.items(): sample_size = len(term) * self.fraction // 100 sample = random.sample(term, int(sample_size)) opslag[id] = sample return opslag<file_sep>import numpy as np from scipy.sparse import * from scipy import * class Dict2Array: def __init__(self, x, y, dtype): self.dtype = dtype x = sorted(list(set(x))) y = sorted(list(set(y))) self.x_pos = {} self.y_pos = {} self.x_size = len(x) self.y_size = len(y) pos = 0 for key in x: self.x_pos[key] = pos pos += 1 pos = 0 for key in y: self.y_pos[key] = pos pos += 1 def make_array(self, data, func): for value in data.values(): if value != []: t = value[0][0] break if type(t) == tuple: t = type(t[1]) else: t = bool res = lil_matrix((self.y_size, self.x_size), dtype=t) for key in data: if func != None: vals = func(data[key]) else: vals = data[key] for value in vals: if not type(value) == tuple: value = (value, True) if not key in self.y_pos: continue if not value[0] in self.x_pos: print("Err value '%s' not in x index." % value[0]) continue res[self.y_pos[key], self.x_pos[value[0]]] = value[1] return res if __name__ == "__main__": x = ["GO:1", "GO:2", "GO:3"] y = ["PROT1", "PROT2", "PROT3"] data = {"PROT1": ["GO:1", "GO:3"], "PROT2": ["GO:2"], "PROT3": ["GO:3"]} arrmaker = Dict2Array(x, y, 1) array = arrmaker.make_array(data) <file_sep>import warnings import numpy as np import sklearn.metrics as metrics from sklearn.exceptions import UndefinedMetricWarning warnings.filterwarnings("ignore", category=UndefinedMetricWarning) """ Evaluator Class: The Evaluator class takes the predicted go-terms predicted by the Predictor class and the true go-terms taken from a gaf-file and evaluates the prediction performance of each predicted annotation by looking at the true annotation found in the gaf-file. The evaluator only calculates metrics specified by the user in the command line. The Evaluator will return the mean of the specified metric for each predicted annotation. """ class Evaluator: """ Parameters: - true_annotation: 2D-numpy array [proteins; go-terms] with the protein annotations taken from the gaf file. - pred_annotation: 2D-numpy array [proteins; go-terms] with the predicted protein annotations from the predictor - evaluators: list of the specified performance metrics as specified by the user. The initiator function takes the predicted annotation, the true annotation and the specified evaluation metrics. The function then determines the number of go-terms and proteins in each set by looking at the vector shape of the annotation variables. (number of rows: number of proteins, number of columns: number of go-terms) The function continues by making an empty numpy-array which is as long as the number of proteins in the true annotation. This empty array is saved in the class variables for each metric that can be calculated by the evaluator. The performance metric for each protein prediction will be saved in these empty arrays. """ def __init__(self, true_annotation, pred_annotation, evaluators): # Set the input files/lists # True (Y_true), pred (Y_pred) > Need to be in np vector format. self.true_annotation = true_annotation self.pred_annotation = pred_annotation self.evaluators = evaluators # Determine number of terms and proteins. (self.num_of_pred_proteins, self.num_of_pred_go_terms) = self.pred_annotation.shape (self.num_of_true_proteins, self.num_of_true_go_terms) = self.true_annotation.shape # Set empty np-arrays which should be determined by the class methods. empty_array = np.empty((self.num_of_true_proteins)) # F1-scores self.f1 = empty_array # Precision-scores self.prec = empty_array # Average precision scores self.avprec = empty_array """ The get_evaluation function makes a dictionary of the specified evaluation performance metrics as keys and checks which metrics are in this dictionary. If a given metric is in the dictionary, the function will call the function for this metric and the mean score will be saved as a value for the metric key. The function will return the dictionary which now contain the metrics as keys and the mean performance scores as values. returns: - evaluaton_dict: dictionary with specified metrics as keys and mean performance scores as values. """ def get_evaluation(self): evaluation_dict = dict.fromkeys(self.evaluators) if 'precision' in self.evaluators: evaluation_dict['precision'] = self.get_precision() if 'average_precision' in self.evaluators: evaluation_dict['average_precision'] = self.get_average_precision() if 'f-score' in self.evaluators: evaluation_dict['f-score'] = self.get_f1() return evaluation_dict """ The get_precision function will loop through the proteins in the true annotation dataset and take the true annotation- and the predicted annotation for a protein at a certain index position. The function calculates the precision score for this protein and saved it in the protein index position in the empty array initialized in the initializer function of the Evaluator class. After looping through the proteins, the function will return the mean of the calculated precision scores. returns: - self.prec.mean(): mean of the precision scores calculated for each protein (each index) of the true annotation dataset. """ def get_precision(self): for index in range(self.num_of_true_proteins): true_row = self.true_annotation[index].toarray()[0] pred_row = self.pred_annotation[index].toarray()[0] self.prec[index] = metrics.precision_score(true_row, pred_row) return self.prec.mean() """ The get_average_precision function will loop through the proteins in the true annotation dataset and take the true annotation- and the predicted annotation for a protein at a certain index position. The function calculates the average precision score for this protein and saved it in the protein index position in the empty array initialized in the initializer function of the Evaluator class. After looping through the proteins, the function will return the mean of the calculated average precision scores. returns: - self.avprec.mean(): mean of the average precision scores calculated for each protein (each index) of the true annotation dataset. """ def get_average_precision(self): for index in range(self.num_of_true_proteins): true_row = self.true_annotation[index].toarray()[0] pred_row = self.pred_annotation[index].toarray()[0] self.avprec[index] = metrics.average_precision_score(true_row, pred_row) return self.avprec.mean() """ The get_f1 function loops through the proteins (indexes) in the true annotation dataset and takes the predicted- and true annotation for a protein at an index. It then feeds these annotations to the f1_score function which calculates the f1-score for the protein prediction at the index. The f1-score is saved at the protein index in the f1-array initialized as an empty array in the initializer function. The function returns the mean of the calculated f1-scores. returns: - f1.mean(): mean of the calculated f1-scores of all the protein predictions. """ def get_f1(self): for index in range(self.num_of_true_proteins): true_row = self.true_annotation[index].toarray()[0] pred_row = self.pred_annotation[index].toarray()[0] prot_f1 = metrics.f1_score(true_row, pred_row) self.f1[index] = prot_f1 return self.f1.mean()<file_sep>import sys from classes.plotter import Plotter import datetime def interpfile(filename): title = "" try: file = open(filename, "r") except: print("Could not open file") lines = file.readlines() file.close() legends = [] plotconfig = [] data = [] for line in lines: sp = line.split() key = sp[0].strip(":") if len(sp) > 1: if key == "title": title = sp[1].strip() if key == "legend": legends.append(":".join(sp[1:]).strip()) plotconfig.append(["", ""]) if key == "linetype": plotconfig[-1][1] = sp[1].strip() if key == "color": plotconfig[-1][0] = sp[1].strip() if sp[0].isnumeric(): speval = line.split(";") evals = {} frac = 0 for spe in speval: spesp = spe.strip().split("\t") if len(spesp) > 1: frac = int(spesp[0]) evals[spesp[1]] = float(spesp[2]) data.append((frac, evals)) return title, plotconfig, legends, data def plot(title, plotconfig, legends, data): plotter = Plotter() for frac in data: plotter.add_score(frac[0], frac[1]) extrastring = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") plotter.plot_performance(title, legends, plotconfig, extrastring) if __name__ == "__main__": if len(sys.argv) > 1: filename = sys.argv[1] else: print("Give results file") exit() title, plotconfig, legends, data = interpfile(filename) print("title:", title) print("plotconfig:", plotconfig) print("legends:", legends) for frac in data: print(frac[0], frac[1]) plot(title, plotconfig, legends, data) <file_sep>class Predictor: def __init__(self, traindata): self.traindata = {} for line in traindata: line = line.split("\t") if len(line) > 1: self.traindata[line[0]] = line[1] def set_trainclass(self, trainclass): global train train = trainclass self.trainclass = trainclass def get_predictions(self, testdata): predictions = {} for protein in testdata: protein = protein.strip() if protein in self.traindata: protein_class = self.traindata[protein].strip() if protein_class in self.trainclass: predictions[protein] = self.trainclass[protein_class] #else: #print("PROTEIN_CLASS not in trainclass", protein_class) #predictions[protein] = [] else: print("PROTEIN NOT IN traindata", protein) predictions[protein] = [] return predictions <file_sep>#!/usr/bin/env python3 import time import os import importlib import re import datetime from multiprocessing import Process, Queue from classes.arguments import * from classes.fix_go import Go_Fixer from classes.gaf_parser import gaf_parse from classes.Evaluator import Evaluator from classes.plotter import Plotter from classes.Dict2Array import Dict2Array from classes.filter_gaf import filter_gaf from classes.splitter import split from classes.lsdr import PLST as PLST_class from classes.call_PLST import call_PLST from classes.train_matrix import train_matrix class thread_print: def __init__(self): self.q = Queue() def print(self, toprint): self.q.put(toprint) def display(self): if self.q.qsize() > 0: print(self.q.get()) class tprint: def print(self, toprint): print(toprint) def step(requests, results, predictor, testdata, traindata, testclass_array, trainclass, arraymaker, gofixer, gofix, evaluators, t, plst): while requests.qsize() > 0: #t.print("START") fraction = requests.get() sample = split(trainclass, fraction) train = train_matrix() matrix, go_index_reverse, rat_index = train.convert(gaf_parse(sample)) #t.print("AFTER TRAIN CONVERT") if plst > 0: #t.print("STARTING a.train") a = call_PLST() matrix = a.train(matrix, plst, PLST_class) #t.print("RAN a.train") #t.print("STARTING PREDICTION") matrix, rat_index = predictor.get_predictions(testdata, matrix, rat_index) if plst > 0: #t.print("STARTING a.inverse") matrix = a.inverse(matrix) del a #t.print("RAN a.inverse") #t.print("STARTING backconvert") predictions = train.back_convert(matrix, rat_index, go_index_reverse, predictor.get_train()) del matrix, rat_index, go_index_reverse, train #t.print("STARTING GOFIX") if gofix: pred_array = arraymaker.make_array(predictions, gofixer.fix_go, predictor.get_dtype(), t) else: pred_array = arraymaker.make_array(predictions, gofixer.replace_obsolete_terms, predictor.get_dtype(), t) #t.print("STARTING EVAL") evaluator = Evaluator(testclass_array, pred_array, evaluators) evaluation = evaluator.get_evaluation() results.put((fraction, evaluation)) def main(): title, multargs = get_args() plotter = Plotter() methodlist = [] plotconfig = [] number = 0 extrastring = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") file = open(title + extrastring,"w") file.write("title: " + title + "\n") for legend in multargs: if len(multargs) > 1: print("\nRUN:", legend) methodlist.append(legend) args = multargs[legend] plotconfig.append((args["color"], args["linetype"])) #print(plotconfig) argname = re.split('/|\.', args["predictor"])[-2] modname = args["predictor"].split(".")[0].replace("/", ".") print("Using predictor:", modname) Predictor = importlib.import_module(modname).Predictor gofix = not "nogofix" in args threads = args["threads"] if threads == "*": threads = os.sysconf("SC_NPROCESSORS_ONLN") print("Using %s threads"%threads) print("Loading input files") testclass_file = open(args["testgaf"], "r") trainclass_file = open(args["traingaf"], "r") traindata_file = open(args["traindata"], "r") testdata_file = open(args["testdata"], "r") testclass = testclass_file.readlines() trainclass = trainclass_file.readlines() traindata = traindata_file.readlines() testdata = testdata_file.readlines() testclass_file.close() trainclass_file.close() traindata_file.close() testdata_file.close() t = tprint() print("Parsing annotation") testclass = gaf_parse(filter_gaf(testclass, args["evidence"], args["domain"])) trainclass = filter_gaf(trainclass, args["evidence"], args["domain"]) print("Reading GO-tree") gofixer = Go_Fixer("files/go-basic.obo") print("Indexing all GO-terms") allterms = [] for terms in list(gaf_parse(trainclass).values()) + \ list(testclass.values()): if gofix: terms = gofixer.fix_go(terms, t) allterms.extend(terms) if "predargs" in args: predictor = Predictor(traindata, args["predargs"]) else: predictor = Predictor(traindata, None) arraymaker = Dict2Array(allterms, testclass) if gofix: testclass_array = arraymaker.make_array(testclass, gofixer.fix_go, bool, t) else: testclass_array = arraymaker.make_array(testclass, gofixer.replace_obsolete_terms, bool, t) print("\nSTARTING") requests = Queue() for fraction in range(100, 0, -args["stepsize"]): for r in range(0, args["repeats"]): requests.put(fraction) total = requests.qsize() processes = [] results = Queue() t = thread_print() done = 0 print("Progress: 0%") for x in range(threads): p = Process(target = step, args = (requests, results, predictor, testdata, traindata, testclass_array, trainclass, arraymaker, gofixer, gofix, args["evaluator"], t, args["plst"])) p.start() processes.append(p) file.write("legend: " + legend + "\nlinetype: " + args["linetype"] + "\ncolor: " + args["color"] + "\n" ) file.write("fraction\tmetric\tresult\n") reslist = [] while total - done > 0: t.display() if results.qsize() > 0: r = results.get() done += 1 print("Progress:", str(round(100 - (total - done) / total * 100)) + "%") reslist.append(r) time.sleep(0.1) for r in sorted(reslist, key=lambda x: x[0]): for metric, evaluation in r[1].items(): print("Fraction:", r[0], "Metric:", metric, "Evaluation:", evaluation) file.write(str(r[0]) + "\t" + str(metric) + "\t" + str(evaluation) + ";\t") plotter.add_score(r[0], r[1]) file.write("\n") file.close() plotter.plot_performance(title, methodlist, plotconfig, extrastring) main() <file_sep>import numpy as np import scipy.linalg as la class PLST: #Principle label space transformation, <NAME> 2010 def __init__(self): #transformation matrix self.w = np.array([]) #inverse map self.winv = np.array([]) self.bias = np.array([]) self.sigma = np.array([]) self.varianceExplained = 0.0 def fit(self, Y, **kwargs): #Y: #objects x #labels try: var_correction = kwargs.pop('var_correction') except KeyError: var_correction = False try: ndims = kwargs.pop('ndims') dim = True if kwargs: raise TypeError('Unexpected **kwargs: %r' % kwargs) except KeyError: var = kwargs.pop('var') dim = False if kwargs: raise TypeError('Unexpected **kwargs: %r' % kwargs) if dim and ndims > Y.shape[1]: raise ValueError('Invalid number of dimensions specified') if not dim and (var < 0.0 or var > 1.0): raise ValueError('Invalid variance fraction specified') self.bias = np.mean(Y, axis=0) Y = Y - np.tile(self.bias, [Y.shape[0], 1]) if var_correction: self.sigma = np.std(Y, axis=0) for i in range(self.sigma.shape[0]): if self.sigma[i] == 0: self.sigma[i] = 1 Y = Y / np.tile(self.sigma, (Y.shape[0],1)) else: self.sigma = np.ones((Y.shape[1],)) #print np.sum(np.isnan(Y).astype(int)) [U, s, VT] = la.svd(Y) totalVariance = np.sum(s) if dim: self.w = VT[:ndims,:].T self.winv = self.w.T self.varianceExplained = np.sum(s[:ndims]) / totalVariance else: variances = np.cumsum(s) / totalVariance found = False i = 0 ndims = -1 while not found and i != variances.shape[0]: if variances[i] > var: found = True ndims = i + 1 i += 1 if not found: ndims = Y.shape[1] self.w = VT[:ndims,:].T self.winv = self.w.T self.varianceExplained = np.sum(s[:ndims]) / totalVariance return Y.dot(self.w) def inverseMap(self, Yprime): Yrec = Yprime.dot(self.winv) * np.tile(self.sigma, [Yprime.shape[0], 1]) Yrec = Yrec + np.tile(self.bias, [Yprime.shape[0], 1]) return Yrec <file_sep>""" Filtergaf removes the header of a gaf file (lines starting with !) Also removes lines from the gaf file if it doesnt have an evidence code or domain. """ def filter_gaf(gaf_lines, evidence_codes, domains): number=0 for determineheader in gaf_lines[0:200]: if determineheader[0] == "!": number += 1 headfiltered_gaf = gaf_lines[number:] for index, line in enumerate(headfiltered_gaf): line_items = line.split("\t") if line_items[3] != "" or line_items[6] not in evidence_codes or line_items[8] not in domains: del headfiltered_gaf[index] return headfiltered_gaf <file_sep>import time class Go_Fixer: def fix_go(self, termlist, t): pos = 0 if len(termlist) > 0: fnum = type(termlist[0]) == tuple t0 = time.time() uniqc = set([x[0] for x in termlist]) for term in termlist: if fnum: term, conf = term try: parents = self.go_tree[term] while type(parents) == str: termlist[pos] = parents parents = self.go_tree[parents] except KeyError: continue for pterm in parents: if fnum: if not pterm in uniqc and pterm != '': termlist.append((pterm, conf)) uniqc.add(pterm) else: if not pterm in termlist and pterm != '': termlist.append(pterm) pos += 1 t0 = time.time() return termlist """ Parameters: self (class), term (String). This function replaces obsolete terms which aren't recognized as obsolete by the gaf file. A dictionary with obsolete terms and the replacement terms is made. If the term given to the function is a key in the dictionary, the term variable is replaced by the replacement term. The replacement term is returned. Returns: term (String) """ def replace_obsolete_term(self, term): if term in self.obsolete_terms.keys(): term = self.obsolete_terms[term] return term def replace_obsolete_terms(self, terms): for i in range(len(terms)): terms[i] = self.replace_obsolete_term(terms[i]) return terms def __init__(self, filename): self.go_tree = {} self.obsolete_terms = {} with open(filename) as file: id, name, term, replace, obsolete, relation = "", \ "", [], "", False, [] lines = file.readlines() for line in lines: line = line.split(": ") if line[0] == "id": id = line[1].strip() if line[0] == "replaced_by": replace = line[1].strip() self.obsolete_terms[id] = replace if line[0] == "alt_id": self.obsolete_terms[line[1].strip()] = id obsolete = True replace = line[1].strip() if line[0] == 'namespace': name = line[1].strip() if line[0] == "is_obsolete" and line[1].strip() == "true": obsolete = True if line[0] == "is_a": if len(line[1].split("!")[0].strip().split(":")) > 1: term.append(line[1].split("!")[0].strip()) if line[0] == "relationship": rel = line[1].strip().split(" ") if rel[0] in ["part_of", "negatively_regulates", "positively_regulates", "regulates"]: term.append(rel[1]) if line[0] == "\n" and name != "": if replace != "": if id in self.go_tree: self.go_tree[id] = self.go_tree[id] + term else: self.go_tree[id] = term elif not obsolete: if id in self.go_tree: self.go_tree[id] = self.go_tree[id] + term else: self.go_tree[id] = term id, name, term, replace, obsolete = "", "", [], "", False del lines def get_go_tree(self): return self.go_tree <file_sep># Get input: # Obo file download: wget -q http://current.geneontology.org/ontology/go-basic.obo # Rat gaf download ebi: wget ftp://ftp.ebi.ac.uk/pub/databases/GO/goa/UNIPROT/goa_uniprot_all.gz -O goa_mouse.gaf # Mouse gaf download ebi: wget ftp://ftp.ebi.ac.uk/pub/databases/GO/goa/UNIPROT/goa_uniprot_all.gz -O goa_rat.gaf # Organism rattus Download from uniprot: wget -q ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000002494_10116.fasta.gz -O rat.fa.gz gunzip rat.fa.gz # Organism mouse download from uniprot wget -q ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000000589_10090.fasta.gz -O mouse.fa.gz gunzip mouse.fa.gz # Create db for rat makeblastdb -in rat.fa -dbtype 'prot' -out rat # Blast proteins mouse against the rat db blastp -query mouse.fa -db rat -outfmt "6 qseqid score sseqid" -out out.txt <file_sep>import numpy as np import matplotlib.pyplot as plt import datetime import collections from random import randint import pandas as pd """ The Plotter class will plot the metrics generated by the Evaluator class on all specified missing data fractions. The class requires an array containing the missing data fractions and an array containing the average IC-scores (or other scores?) for each missing data fraction. """ class Plotter: def __init__(self): self.frac_of_miss_array = [] self.dictarray = [] """ Add_score will add fraction data to the frac_of_miss_array list Add score will also add a dictionary with the technique as key and corresponding value used for plotting. For example{'f1-score',10} to the dictarray, this will be used in plot performance. """ def add_score(self, fraction, mean): self.frac_of_miss_array.append(fraction) self.dictarray.append(mean) """ Plot_performance is able to plot multiple times depending on the amount of unique keys in the dict_array This will count the amount of fractions and plot the mean and standard deviation for each fraction Plotter will also give the corresponding x-as and y-axis names to the corresponding technique used This plotter is able to combine results from multiple techniques. Implemented line-type and line coloring with config file 7pm 13-06-2019 """ def plot_performance(self, title, totalruns, extrainfo,date): uniquelist = [] for key in self.dictarray[0]: if key not in uniquelist: uniquelist.append(key) totallist = np.array_split(self.frac_of_miss_array, len(totalruns)) extratotallist = np.array_split(self.dictarray, len(totalruns)) color = [x[0] for x in extrainfo] type = [y[1] for y in extrainfo] for value in uniquelist: dataframeus = pd.DataFrame(columns=['means', 'stdevs', 'methods', 'fractions']) for (i, firstfrac, firstdict) in zip(totalruns, totallist, extratotallist): newarray = [d[value] for d in firstdict] fractions = sorted(set(firstfrac)) listf = list(firstfrac) amount_of_runs = listf.count(100) means = {} stdevs = {} for round in range(0,len(firstfrac),amount_of_runs): acround = firstfrac[round] means[acround] = np.mean(newarray[round:round+amount_of_runs]) stdevs[acround] = np.std(newarray[round:round+amount_of_runs]) means = collections.OrderedDict(sorted(means.items())) stdevs = collections.OrderedDict(sorted(stdevs.items())) vs = [{'means': mean, 'stdevs': stdev, 'fractions':fraction, 'methods': i} for mean, stdev, fraction in zip(list(means.values()), list(stdevs.values()), fractions)] dataframeus = dataframeus.append(vs, ignore_index=True) reformed = dataframeus.pivot('fractions','methods') for number, valueas in enumerate(totalruns): if color[number] != '*': plt.errorbar(reformed.index,reformed['means'][valueas],yerr=reformed['stdevs'][valueas], color=color[number],fmt='',linestyle=type[number], capsize=4) else: plt.errorbar(reformed.index, reformed['means'][valueas], yerr=reformed['stdevs'][valueas], capsize=4) plt.legend(totalruns) plt.xticks(fractions) # location, labels plt.xlim(fractions[0]-0.5, fractions[-1]+0.5) plt.title(title) plt.ylabel(value.replace("_", " ")) plt.xlabel('fractions of data') plt.gca().invert_xaxis() plt.grid(True) writeout = title + date + value plt.savefig(writeout) plt.close() <file_sep>import numpy as np from scipy.sparse import * from scipy import * # This class has been made to create a matrix from the input data(test and train set). class Dict2Array: # The x: all go terms, y: All protein ids, dtype: Defining type array, must be imported. # All data from the x, y will be saved in a dictionairy assigned with a position. # Also, the size of each dictionairy will be defined. def __init__(self, x, y): self.dtype = dtype x = sorted(list(set(x))) y = sorted(list(set(y))) self.x_pos = {key:getal for getal, key in enumerate(x)} self.y_pos = {key:getal for getal, key in enumerate(y)} self.x_size = len(x) self.y_size = len(y) # This function creates the matrix with the data(train or prediction data). Also the go term tree must # be imported to get all go terms for a specific go term. # First, the matrix will be defined. # Second, for all ids the go terms will be specified. # Thirdly, if the go term in the go term dictionry and protein id in protein dictionairy defined above, then # fill the matrix. def make_array(self, data, func): res = lil_matrix((self.y_size, self.x_size), dtype=self.dtype) #file = open("print", "a") #file.write("Print\n") #file.close() def make_array(self, data, func, dtype, t): res = lil_matrix((self.y_size, self.x_size), dtype=dtype) for key in data: #t.print("KEY:" + str(key)) if func != None: vals = func(data[key], t) else: vals = data[key] #file = open("print", "a") #file.write("TUPLE:" + str(data[key])) #if type(data[key][0]) == tuple: # file.write("BEFORE GOFIX:"+ str(data[key]) + "\n") # file.write("AFTER GOFIX:" + str(vals) + "\n") #file.close() for value in vals: if not type(value) == tuple: value = (value, True) if not key in self.y_pos: continue if not value[0] in self.x_pos: # print("Err value '%s' not in x index." % value[0]) continue res[self.y_pos[key], self.x_pos[value[0]]] = value[1] return res def get_index(self): return self.x_pos, self.y_pos <file_sep>import random def split(lines, size): """ Depending on the percentage and the amount of lines in the file it will split the data and saves the test data into a seperate file. """ return random.sample(lines, int(len(lines) * (size / 100))) <file_sep>import itertools import numpy as np import sys """This class can predict the best blasthit or more blast hits, whereby the used best" hits are checked if they are annotated""" class Predictor: """ constructor: to save the blast results in a dictionaire. self.traindata: dictionaire with the blast results. self.besthits: Specifies how many blast hits are taken. self.only_annotate: Specifies if only annotated proteins must be used for the prediction.""" def __init__(self, traindata, args): self.traindata = {} self.besthits = int(args[0]) self.only_annotate = args[1] self.only_annotate = self.only_annotate.lower() == 'true' for id in traindata: id = id.split("\t") input = id[0].strip() output = id[1].strip() if input in self.traindata: self.traindata[input].append(output) elif input not in self.traindata: self.traindata[input] = [] self.traindata[input].append(output) """ Function: To get the right number of blast hits for each subject. The results are saved in the traindata dictionaire. """ def correct_traindata(self, rat_index): traindata = {} if self.only_annotate: for keys, val in self.traindata.items(): traindata[keys] = [] getal = 0 for values in val: if values in rat_index and getal < self.besthits: getal += 1 traindata[keys].append(values) else: for keys, val in self.traindata.items(): traindata[keys] = [] getal = 0 for values in val: if getal < self.besthits: getal += 1 traindata[keys].append(values) return traindata """ Function: To get the matrix with the go terms of all predicted proteins. 1. At first, the traindata needs to be corrected for the number of hits for each subject. index: To get the index of the predicted matrix according to the predictions. rat: To save the genes in the rat in a dictionaire. """ def get_predictions(self, testdata, matrix, rat_index): self.traindata = self.correct_traindata(rat_index) self.prediction_data = {} index = [] rat = {} getal = 0 for protein in testdata: protein = protein.strip() if protein in self.traindata: if len(self.traindata[protein]) > 0: for prot in self.traindata[protein]: if prot not in rat: if prot in rat_index: index.append(rat_index[prot]) rat[prot] = getal getal += 1 if prot in rat_index: if protein not in self.prediction_data: self.prediction_data[protein] = [] self.prediction_data[protein].append(prot) elif prot not in rat_index and protein in self.prediction_data: self.prediction_data[protein].append("not annotated") return matrix[index], rat """ Function: Determine the type of prediction array needs to be made. hits > 1 == float anders == bool. """ def get_dtype(self): if self.besthits > 1: return float return bool """ Function to get the traindata """ def get_train(self): return self.prediction_data <file_sep>import sys import os EVC = ("EXP","IDA","IPI","IMP","IGI","IEP","HTP","HTP","HDA","HMP", "HGI","HEP","IBA","IBD","IKR","IRD","ISS","ISO","ISA","ISM", "IGC","RCA","TAS","NAS","IC","ND","IEA","IEA") DOMAINS = ("C", "F", "P") EVAL = ('f-score', 'precision', 'average_precision') def check_stepsize(key, arg): text = "" if arg.isnumeric(): arg = int(arg) else: text = "The argument 'stepsize' or 's' was not numeric." return text, arg def check_evidence(key, arg): arg = arg.split(",") text = "" res = [] for i in range(len(arg)): if arg[i] in EVC: res.append(arg[i]) else: text = "'%s' is not a valid evidence code."%arg[i] return text , res def check_file(key, arg): text = "" if not os.path.exists(arg): text = "The file '%s' does not exist."%arg return text, arg def check_domain(key, arg): text = "" res = [] domains = arg.split(",") if arg == "*": res = DOMAINS else: for domain in domains: if domain in DOMAINS: res.append(domain) else: text = "Domain '%s' is not valid."%domain break return text, res def check_repeats(key, arg): text = "" if not arg.isnumeric(): text = "Repeat input '%s' is not numeric."%arg else: arg = int(arg) if arg > 100 or arg < 0: text = "Repeat input has to be a number between 100 and 0." return text, arg def check_threads(key, arg): text = "" if arg.isnumeric(): arg = int(arg) if arg < 1: text = "Threads has to be higher than 0." else: text = "Threads has to be a number." return text, arg def check_evaluator(key, arg): arg = arg.split(",") text = "" res = [] for i in range(len(arg)): if arg[i] in EVAL: res.append(arg[i]) else: text = "'%s' is not a valid evaluator."%arg[i] return text , res def check_predargs(key, arg): text = "" arg = arg.split(",") return text, arg def plst_check(key, arg): text = "" if arg.isnumeric(): arg = int(arg) if arg < 1: text = "Argument plst or P shoud be a number above 0." else: text = "Argument plst or P should be a number." return text, arg HELP = "====GOA_PREDICTION FRAMEWORK====\n"\ "Tests different GO-prediction algorithms "\ "by removing values incrementally from the "\ "input dataset." LETTERS = {"p":"predictor", "e":"evaluator", "l":"plotter", "s":"stepsize", "E":"evidence", "t":"traindata", "g":"traingaf", "T":"testdata", "G":"testgaf", "d":"domain", "r":"repeats", "n":"threads", "f":"nogofix", "a":"predargs", "P":"plst", "h":"plotheader", "A":"argfile", "c":"color", "L":"linetype", "h":"help"} ARGS = {"predictor":{ "required":False, "default":"blast", "check":check_file, "help":"What predictor to use. Can be one of: 'predictors/blast' or a custom module in the blast directory. " }, "predargs":{ "required":False, "default":"blast", "check":check_predargs, "help":"Extra arguments to pass to the predictor separated by comma without spaces." }, "evaluator":{ "required":False, "default":["f-score"], "check":check_evaluator, "help":"What evaluator to use. Can be one of: 'f-score', 'precision', 'average_precision'." }, "plotter":{ "required":False, "default":"line", "check":("line"), "help":"What plotter to use. Can be one of: 'line'." }, "stepsize":{ "required":False, "default":5, "check":check_stepsize, "help":"Percentage decrease of dataset sample per round. Should be a number from 0 to 100." }, "evidence":{ "required":False, "default":EVC, "check":check_evidence, "help":"Evidence codes to use. Should be multiple seperated by comma without spaces or * for all." }, "traindata":{ "required":True, "default":False, "check":check_file, "help":"Filename of traindata." }, "traingaf":{ "required":True, "default":False, "check":check_file, "help":"Filename of traingaf." }, "testdata":{ "required":True, "default":False, "check":check_file, "help":"Filename of testdata." }, "testgaf":{ "required":True, "default":False, "check":check_file, "help":"Filename of testgaf." }, "domain":{ "required":False, "default":DOMAINS, "check":check_domain, "help":"Domains to use. Should be multiple seperated by comma without spaces or * for all." }, "repeats":{ "required":False, "default":1, "check":check_repeats, "help":"Amount of repeats per step. Should be a positive number." }, "threads":{ "required":False, "default":"*", "check":check_threads, "help":"Amount of processing threads to use. Should be a positive number." }, "nogofix":{ "required":False, "default":False, "check":None, "help":"Skip GO-TREE completing the GO terms." }, "plst":{ "required":False, "default":-1, "check":plst_check, "help":"Use PLST to reduce input traindata. Give the amount of dimensions to reduce to." }, "argfile":{ "required":False, "default":None, "check":False, "help":"Give arguments file." }, "plotheader":{ "required":False, "default":"Plot Title", "check":False, "help":"title of the plot." }, "color":{ "required":False, "default":"*", "check":("b", "g", "r", "c", "m", "y", "k", "w"), "help":"Color of the line in the plot. Can be one of: b, g, r, c, m, y, k, w." }, "linetype":{ "required":False, "default":"-", "check":("-", "--", "-.", ":"), "help":"Linetype can be one of: -, --, -., :." }, "help":{ "required":False, "default":False, "check":False, "help":"Display this help." }} def show_help(): print(HELP) print("Arguments:") for letter in LETTERS: inf = ARGS[LETTERS[letter]] print("\t -%s --%s\t%s"%(letter, LETTERS[letter], inf["help"])) def finish_arg(argstore, lnum): for arg in ARGS: #print(arg) if arg in argstore: content = argstore[arg] #print(content) inf = ARGS[arg] text = "" if inf["check"] != False: if type(inf["check"]) == tuple: if not content in inf["check"]: if lnum != 0: print("Line:", lnum) print("'%s' not allowed for argument '%s'.\n"%( content, arg) + "Allowed: %s."%", ".join(inf["check"])) exit() elif inf["check"] != None: text, content = inf["check"](arg, content) if text != "": if lnum != 0: print("Line:", lnum) print("Error:" + text) exit() argstore[arg] = content else: if ARGS[arg]["required"]: if lnum != 0: print("Line:", lnum) print("Error: Required argument '%s' not given."%arg) exit() if ARGS[arg]["default"] != False: argstore[arg] = ARGS[arg]["default"] return argstore def parse_args(argv, lnum = 0): argstore = {} #print(argv) for i in range(0, len(argv)): word = False arg = argv[i] if arg[0] != "-" or arg[len(arg)-1].isnumeric()\ or arg in ("--", "-." , "-"): continue if arg[1] != "-": if arg[1:] in LETTERS: arg = LETTERS[arg[1:]] else: arg = arg[2:] if arg not in ARGS: if lnum != 0: print("Line", lnum) print("Argument '%s' is not a valid argument."%arg) exit() if arg in ARGS: if arg == "help": show_help() exit() content = "" if len(argv) > i + 1: content = argv[i + 1] argstore[arg] = content return finish_arg(argstore, lnum) def get_args(): argv = sys.argv if "-A" in argv or "--argfile" in argv: filename = "" for i in range(len(argv)): if argv[i] in ["-A", "--argfile"]: if len(argv) > i+1: filename = argv[i+1] else: print("Give argfile filename.") exit() if filename != "": try: argfile = open(filename, "r") except Exception as ass: print(ass) print("Could not open argfile") exit() lines = argfile.readlines() argfile.close() args = {} title = lines[0].split(":")[1].strip() lnum = 1 for line in lines[1:]: lnum += 1 lsplit = line.split(":") if len(lsplit) > 1: legend = lsplit[0] line = ":".join(lsplit[1:]).strip().split() args[legend] = parse_args(line, lnum) else: args = {"Default":parse_args(argv[1:])} title = args["Default"]["plotheader"] return title, args if __name__ == "__main__": os.chdir("..") print("RES:", get_args()) <file_sep># ProtPred Framework The ProtPred Framework is a python framework for testing protein function prediction under varying fractions of missing protein annotation. The framework uses a command-line interface in which the user is able to specify a lot of different prediction parameters. The framework allows for different prediction methods to be implemented. These methods can be specified by the user in the command-line interface. The ProtPred Framework takes proteomes and Gene Ontology annotations as input and outputs a prediction performance plot showing how the chosen prediction performs under varying amounts of missing annotation data. ## Gene Function Prediction with Missing Data The ProtPred Framework has been built for the Gene Function Prediction with Missing Data Project at TU Delft by 3rd year bioinformatics students from Hogeschool Leiden. ## Implemented protein prediction methods A BLAST-based protein prediction method which couples the annotation from the best BLAST-hit of a protein in one organism to the BLAST query protein which has no annotation (BLAST-tophit). A similar method taking the annotation from the 20 best hits of a protein has also been implemented. (BLAST-top20) Thirdly, a variation on the BLAST-tophit method has been implemented which discards proteins for which there is no annotation. ## Python packages required by the framework The following packages are required in order to run the ProtPred Framework: * Numpy (v1.16.2) * Matplotlib (v3.0.3) * Pandas (v0.24.2) * Scikit-learn (v0.20.3) * Scipy (v1.2.1) ## Input required by the framework The following input files are required in order to run the ProtPred Framework: * traindata : A file containing the file the prediction method uses to make predictions (in a BLAST-method, this would be the BLAST-results (query, hits)) * traingaf : A Gene Ontology annotation file containing annotation for the proteins in the traindata-file. * testdata : A proteome file which should containing proteins the prediction methods should predict the annotation for. * testgaf : A Gene Ontology annotation file containing annotation for the proteome in the testdata-file. Files need to be put into the files directory and will be specified as 'files/**_filename_**' ### Example of input data For testing the framework we used the proteomes and GO-annotation from Mouse and Rat: * traindata : _blast_besthit_traindata_mouserat_ This file contains rows consisting of a query protein-id followed by the best blast hit protein-id. * traingaf : _goa_rat.gaf_ This file contains Gene Ontology annotations for the proteome of Rat. * testdata : _blast_besthit_testdata_mouse_ This file contains all the protein-id's present in Mouse (one protein in each row) * testgaf : _goa_mouse.gaf_ This file contains Gene Ontology annotations for the proteome of Mouse. ## Specifiable parameters in the framework The user is able to specify the following options as arguments in the command line interface of the framework: * -p or --predictor (Predictor script to use, default: blast) * -e or --evaluator (Evaluator metric to use, default: f-score) * -l or --plotter (Type of plotter to use, default: line) * -s or --stepsize (Missing data fraction step-size to use, default: 5) * -E or --evidence (Annotation evidence codes to use, default: all, these need to be comma-separated) * -t or --traindata (Training data to use, must be specified) * -g or --testgaf (Test annotation to use, must be specified) * -d or --domains (Annotation domains to use, default: all, these need to be comma-separated) * -r or --repeats (Amount of repeats for each missing data fraction, default: 1) * -n or --threads (Amount of threads to use, default: all threads available) * -f or --nogofix (Whether to not add parent GO-terms to the annotation, default: False) * -a or --predargs (Extra arguments to give to the Predictor, these need to be comma-separated) * -P or --plst (The amount of PLST-dimensions to use, when using -1, PLST is disabled, default: -1) * -A or --argfile (A config file to give to the framework, default: None) * -h or --plotheader (A title for the prediction performance plot, default: Plot Title) * -c or --color (Color for the line in the performance plot, default: all) * -L or --linetype (Linetype to use in the performance plot, default: all) * -h or --help (Display help) ### Example of using different parameters As an example, the following bash code would run the Framework with a BLAST-tophit prediction method and predict the annotation of mouse proteins based on rat annotation. The user wants to see the f-score and precision scores in the performance plot which the framework builds. As a stepsize for the fractions of missing data a size of 5 was chosen. Also, to look at the deviation between different annotation samples, the user wants to have each fraction repeated five times. Lastly, in order to speed up the prediction process, the user wants to use 4 threads. ```bash python3 protpred.py -t files/blast_besthit_traindata_mouserat -g files/goa_rat.gaf -T files/blast_besthit_testdata_mouse -G files/goa_mouse.gaf -p predictors/pred_blast_besthit.py -e f-score,precision -s 5 -r 5 -n 4 ``` ## User-specifiable prediction methods A user of the framework can add different prediction methods to the framework, by adding a python-script containing a _Predictor_ class to the _predictors_ directory in the framework. The prediction method can then by specified by using the _-p_ command line argument, as is shown in the parameter example. If additional files are required by the predictor these files can be given to the predictor script using the argfile argument in the command line: _-a_. Files specified by the argfile argument will directly be given to the predictor class in the python-script. ## Usage of a config-file As an easy way to compare multiple different framework runs with each other, a config file can be used. In this file, the same arguments as in the regular command-line can be used. The top row of the file should containg the title of the plot which will contain all the framework runs. The rows below should contain the options for the runs itself, using the same arguments as in the command-line. ### Example of a config-file As an example, the following config file would result in a plot titled _Blastmethod comparison domain F_ which draws a line for the BLAST-tophit prediction method, the BLAST-top20 method and the BLAST-tophit only using annotated proteins using annotation in the Molecular Function Gene Ontology domain. ``` Title: Blastmethod comparison domain F TopBlast: --stepsize 5 --traindata ./files/blast_besthit_traindata_mouserat --traingaf ./files/goa_rat.gaf --testdata ./files/blast_besthit_testdata_mouse --testgaf ./files/goa_mouse.gaf --predictor predictors/blast.py --evaluator average_precision --predargs 1,false --evidence EXP,IDA,IPI,IMP,IGI,IEP,HTP,HTP,HDA,HMP,HGI,HEP,IBA,IBD,IKR,IRD,ISS,ISO,ISA,ISM,IGC,RCA,TAS,NAS,IC,ND,IEA,IEA --domain F --repeats 1 --threads 3 20Blast: --stepsize 5 --traindata ./files/blast_top20_traindata_mouserat --traingaf ./files/goa_rat.gaf --testdata ./files/blast_top20_testdata_mouse --testgaf ./files/goa_mouse.gaf --predictor predictors/blast.py --evaluator average_precision --predargs 20,false --evidence EXP,IDA,IPI,IMP,IGI,IEP,HTP,HTP,HDA,HMP,HGI,HEP,IBA,IBD,IKR,IRD,ISS,ISO,ISA,ISM,IGC,RCA,TAS,NAS,IC,ND,IEA,IEA --domain F --repeats 1 --threads 3 Annotated: --stepsize 5 --traindata ./files/blast_onlyannotated_traindata_rat --traingaf ./files/goa_rat.gaf --testdata ./files/blast_onlyannotated_testdata_mouse --testgaf ./files/goa_mouse.gaf --predictor predictors/blast.py --evaluator average_precision --predargs 1,true --evidence EXP,IDA,IPI,IMP,IGI,IEP,HTP,HTP,HDA,HMP,HGI,HEP,IBA,IBD,IKR,IRD,ISS,ISO,ISA,ISM,IGC,RCA,TAS,NAS,IC,ND,IEA,IEA --domain F --repeats 1 --threads 3 ``` The config file can be specified in the following command line argument: _--argfile_ An example is shown below: ```bash python3 protpred.py --argfile config.txt ``` ## The results file When running the framework the resulting data will be saved into a results file. This file will have the same name as the plot image without the image file extention (png). Below an example of the file is shown. The file contains the configuration of the plot and the data generated for each line. If any mistakes have been made while configuring the plot in the main script this can be corrected in this file. The parameters title (plot title), legend (legend name per line), linetype (what type of matplotlib line to use per line ':', '-.' or '--') and color (the color per line). To replot the data the script plotdata.py can be called with as first argument the filename of the results. For example: 'plotdata.py \<result filename\>'. ``` title: Blastmethod comparison domain C legend: TopBlast linetype: : color: b fraction metric result 50 average_precision 0.2901349170500518; 50 f-score 0.3858185665480277; 100 average_precision 0.48503347213182757; 100 f-score 0.5778911642896822; legend: Annotated linetype: -- color: g fraction metric result 50 average_precision 0.36315102835979096; 50 f-score 0.4930496427412165; 100 average_precision 0.5545653869694926; 100 f-score 0.668769573566121; ``` ### Example of a framework run resulting in a perfomance plot A run using the config file below will result in the plot shown further below: Config (go_fix_domain_c.txt): ``` Title: Tophit-BLAST with and without adding GO-parents (Domain C) topBLAST with gofix: --stepsize 5 --traindata ./files/blast_besthit_traindata_mouserat --traingaf ./files/goa_rat.gaf --testdata ./files/blast_besthit_testdata_mouse --testgaf ./files/goa_mouse.gaf --predictor predictors/blast.py --evaluator f-score --predargs 1,false --evidence EXP,IDA,IPI,IMP,IGI,IEP,HTP,HTP,HDA,HMP,HGI,HEP,IBA,IBD,IKR,IRD,ISS,ISO,ISA,ISM,IGC,RCA,TAS,NAS,IC,ND,IEA,IEA --domain C --repeats 10 --threads 1 topBLAST without gofix: --stepsize 5 --traindata ./files/blast_beshit_traindata_mouserat --traingaf ./files/goa_rat.gaf --testdata ./files/blast_beshit_testdata_mouse --testgaf ./files/goa_mouse.gaf --predictor predictors/blast.py --evaluator f-score --predargs 1,false --evidence EXP,IDA,IPI,IMP,IGI,IEP,HTP,HTP,HDA,HMP,HGI,HEP,IBA,IBD,IKR,IRD,ISS,ISO,ISA,ISM,IGC,RCA,TAS,NAS,IC,ND,IEA,IEA --domain C --repeats 10 --threads 1 --nogofix ``` Calling the framework using this config: ```bash python3 protpred.py --argfile go_fix_domain_c.txt ``` Resulting plot: ![alt text](https://github.com/Sbrussee/GenePredMissData/blob/master/sample_plot.png) <file_sep>import numpy as np import itertools """ Class: To create a matrix and a index for the gaf file. """ class train_matrix: """ Function: To create the matrix and an index. self.trainclass: All annotation information for the train gaf file. go_termen_train: A list of all unique go terms in the train gaf. go_index: To index all the go terms in a dictionaire. matrix: To create a matrix with on the y-axis the train genes and on the x-axis the go terms. return: The matrix with the go termen en gen index. """ def convert(self, train_class): self.trainclass = train_class go_termen_train = [go for go in self.trainclass.values()] go_termen_train = list(itertools.chain.from_iterable(go_termen_train)) go_termen_train = np.unique(go_termen_train) go_index = {a: getal for getal, a in enumerate(np.unique(go_termen_train))} go_index_reverse = {getal: a for getal, a in enumerate(np.unique(go_termen_train))} # Step 2: Create matrix from all unique go terms in gaf file matrix = np.zeros(((len(self.trainclass), len(go_termen_train))), dtype="int") rat_index = {} getal = 0 for rat, go_terms in self.trainclass.items(): rat_index[rat] = getal for go in go_terms: index = go_index[go] matrix[getal, index] = 1 getal += 1 return matrix, go_index_reverse, rat_index """ function: To put the predicted matrix into a dictionaire. predicitions: To put the matrix in a dictionaire. 1. The function iterate over the train data. 2. if the protein occurs in the prediction then the protein with go terms are stored in the matrix. """ def back_convert(self, matrix, rat_index, go_index_reverse, traindata): predictions = {} for mouse, rat in traindata.items(): go = [] for protein in rat: if protein in rat_index: matrix_index = rat_index[protein] i = np.where(matrix[matrix_index] > 0.3)[0] for go_terms in i: go.append(go_index_reverse[go_terms]) if len(rat) == 1: predictions[mouse] = go elif len(rat) > 1: unique, counts = np.unique(go, return_counts=True) predictions[mouse] = list(zip(unique, counts / len(rat))) return predictions
91e458227fb9e334d3ca34a0b167101317809615
[ "Markdown", "Python", "Shell" ]
19
Python
Sbrussee/GenePredMissData
2e5e8ccbc17fea6650a2b00b463ed25e89bf94ab
b34dfd1457a4d41b202666ae05463dba59b5a625
refs/heads/master
<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_admin_categoriesHandler { var $id; function initialize(&$render) { $uid = pnUserGetVar('uid'); $yesno_items = array ( array('text' => _LOBBY_YES, 'value' => 1), array('text' => _LOBBY_NO, 'value' => 0), ); $render->assign('yesno_items', $yesno_items); // load existing categories $categories = pnModAPIFunc('lobby','categories','get'); $render->assign('categories',$categories); // load category that should be edited? $id = (int)FormUtil::getPassedValue('id'); if ($id > 0) { $category = pnModAPIFunc('lobby','categories','get',array('id' => $id)); $render->assign($category); $this->id = $id; } return true; } function handleCommand(&$render, &$args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) { return LogUtil::registerPermissionError(); } if ($args['commandName']=='update') { // get the pnForm data and do a validation check $obj = $render->pnFormGetValues(); if (!$render->pnFormIsValid()) return false; if ($this->id > 0) { if ($obj['delete'] == 1) { $obj['id'] = $this->id; $result = DBUtil::deleteObject($obj,'lobby_categories'); if ($result) { LogUtil::registerStatus(_LOBBY_CATEGORY_DELETED); } else { LogUtil::registerError(_LOBBY_CATEGORY_DELETEERROR); } } else { // update object $obj['id'] = $this->id; $result = DBUtil::updateObject($obj,'lobby_categories'); if ($result) { LogUtil::registerStatus(_LOBBY_CATEGORY_UPDATED); } else { LogUtil::registerError(_LOBBY_CATEGORY_STOREFAILURE); } } } else { // store new object $result = DBUtil::insertObject($obj,'lobby_categories'); if ($result) { LogUtil::registerStatus(_LOBBY_CATEGORY_INSERTED); } else { LogUtil::registerError(_LOBBY_CATEGORY_STOREFAILURE); } } } return $render->pnFormRedirect(pnModURL('lobby','admin','categories')); } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * switch memnbers into form pulldown format * */ function lobby_membersToPullDown($users) { $result = array(); foreach ($users as $user) { $result[] = array ('text' => (string)$user['uname'], 'value' => $user['uid']); } return $result; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ define('_LOBBY_TABTITLE', 'Groups'); define('_LOBBY_NOUSERSPECIFIED', 'No user selected'); define('_LOBBY_GROUP_MEMBERSHIPS', 'The user %username% has active memberships'); define('_LOBBY_IS_OWNER', '%username% is the creator of this group'); define('_LOBBY_IS_MODERATOR', '%username% is a moderator in this group'); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ // general define('_LOBBY_DEAR', 'Liebe(r)'); define('_LOBBY_GROUP_INVITATION_FOR', 'Einladung zur Gruppe'); define('_LOBBY_FROM', 'von'); // new group define('_LOBBY_EMAIL_NEW_GROUP', 'Eine neue Gruppe wurde registriert'); define('_LOBBY_EMAIL_PENDING_NOW', 'Die Gruppe muss freigeschalten werden, da sie in einer offiziellen Kategorie eingeordnet ist'); define('_LOBBY_EMAIL_NEW_GROUP_FOR', 'Gruppenregistrierung auf'); define('_LOBBY_EMAIL_VIEW_GROUP', 'Gruppe anzeigen'); define('_LOBBY_EMAIL_VIEW_PENDING', 'Auf Freischaltung wartende Gruppen verwalten'); // new join define('_LOBBY_EMAIL_NEW_REQUEST_FOR_GROUP','Mitgliedsantrag für Gruppe'); define('_LOBBY_EMAIL_NEW_GROUP_MEMBER_FOR', 'Neues Mitglied in Gruppe'); define('_LOBBY_EMAIL_AT', 'auf'); define('_LOBBY_EMAIL_NEW_MEMBER', 'Folgender Benutzername hat sich für die Gruppe beworben'); define('_LOBBY_EMAIL_PENDING_USER', 'Der Benuzter wartet nun auf Freischaltung für die Gruppe'); define('_LOBBY_EMAIL_PENDING_USERS', 'Wartende Benutzer der Gruppe verwalten'); define('_LOBBY_EMAIL_USER_ADDED', 'Der Benutzer wurde hinzugefügt und ist nun Mitglied der Gruppe'); // membership ended define('_LOBBY_EMAIL_MEMBERSHIP_ENDED', 'Ein Benutzer hat seine Mitgliedschaft gekündigt in'); define('_LOBBY_EMAIL_MEMBERSHIP_QUIT', 'Folgender Benutzer hat die Gruppe verlassen'); define('_LOBBY_EMAIL_QUIT_TEXT', 'Folgenden Text hat er als Kündigungsgrund hinterlassen'); // group accepted define('_LOBBY_EMAIL_ACCEPTED_AT', 'wurde freigeschalten auf'); define('_LOBBY_EMAIL_GROUP_ACCEPTED', 'Die Gruppe wurde vom Seitenbetreiber akzeptiert und freigeschalten'); // membership request rejected define('_LOBBY_MEMBERSHIP_REQUEST_FOR', 'Antrag auf Mitgliedschaft in'); define('_LOBBY_WAS_REJECTED', 'wurde zurückgewiesen'); define('_LOBBY_CONTACT_OWNER_FOR_DETAILS', 'Leider können wir keinen genauen Grund für diese Aktion nennen, weswegen wir Dich bitten, bei Rückfragen mit dem Verantwortlichen der Gruppe in Verbindung zu treten'); // membership request accepted define('_LOBBY_WAS_ACCEPTED', 'wurde akzeptiert'); // new topic notification define('_LOBBY_EMAIL_NEWTOPIC_GROUP', 'Neues Thema in Gruppe'); define('_LOBBY_NEW_TOPIC_POSTED', 'Neue erstelltes Thema'); define('_LOBBY_POSTER', 'Autor'); // new reply to a topic notification define('_LOBBY_EMAIL_NEWREPLY', 'Neue Antwort'); define('_LOBBY_IN_GROUP', 'in Gruppe'); define('_LOBBY_TO_TOPIC_OF', 'Zu dem Thema von'); define('_LOBBY_WAS_REPLY_POSTED', 'wurde folgende Antwort geschrieben'); // invitation define('_LOBBY_GROUP_INVITATION_FOR', 'Du wurdest in folgende Gruppe eingeladen'); define('_LOBBY_GROUP_INVITATION_OF', 'Die Einladung wurde ausgesprochen vom Benutzer'); define('_LOBBY_GROUP_INVITATION_TEXT', 'Folgender Einladungstext wurde zusätzlich verfasst'); define('_LOBBY_GROUP_HOMEPAGE', 'Link zur Internetseite dieser Gruppe'); define('_LOBBY_GROUP_JOINPAGE', 'Mitglied in der Gruppe werden'); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ define('_LOBBY_GROUP_NEWS_ALL', 'Neuigkeiten (News) aller Gruppen'); define('_LOBBY_GROUP_NEWS_AL_TEXT', 'Integration der von den Gruppen veröffentlichten News unter berücksichtigung des individuellen Rechtesystems des Moduls lobby. Parameter: category=CATEGORYID für Filter auf spezielle Kategorie.'); define('_LOBBY_NO_NEW_ARTICLES', 'Keine Neuigkeiten im Zeitraum veröffentlicht'); define('_LOBBY_FROM_GROUP', 'in der Gruppe'); define('_LOBBY_READ_ARTICLE', 'Artikel lesen'); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { var $fid; var $gid; function initialize(&$render) { $gid = (int)FormUtil::getPassedValue('id'); $fid = (int)FormUtil::getPassedValue('fid'); $sync = (int)FormUtil::getPassedValue('sync'); $this->gid = $gid; if ($fid > 0) { // load forum $forum = pnModAPIFunc('lobby','forums','get',array('id' => $fid, 'gid' => $gid)); if ($forum['gid'] == $forum['gid']) { $render->assign($forum); $this->fid = $fid; // should forum be synced? if ($sync == 1) { // Get Topics and sync them $topics = pnModAPIFunc('lobby','forumtopics','get',array('fid' => $fid)); $counter = 0; foreach ($topics as $topic) { pnModAPIFunc('lobby','forumtopics','sync',array('id' => $topic['id'])); $counter++; } LogUtil::registerStatus($counter.' '._LOBBY_TOPICS_SYNCED_IN.' '.$forum['title']); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $gid, 'do' => 'forummanagement'))); } } } $public_status_items = array ( array('text' => _LOBBY_ALL, 'value' => 0), array('text' => _LOBBY_SITEMEMBERS, 'value' => 1), array('text' => _LOBBY_GROUPMEMBERS, 'value' => 2) ); $render->assign('public_status_items', $public_status_items); $forums = pnModAPIFunc('lobby','forums','get',array('gid' => $this->gid)); // we need to re-work at the sort_nr's $c = 0; $changes = false; $farray = array(); $ffarray = array(); $narray = array(); foreach ($forums as $f) { $c++; if ($f['sort_nr'] != $c) { $f['sort_nr'] = $c; DBUtil::updateObject($f,'lobby_forums'); $changes = true; } $narray[$previous] = $f['id']; $f['previous'] = $previous; $previous = $f['id']; $farray[] = $f; } foreach ($farray as $f) { $f['next'] = $narray[$f['id']]; $ffarray[] = $f; } // get "next" entry for each forum if ($changes) { return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'forummanagement'))); } // Has the sort order changed? $switch = (int) FormUtil::getPassedValue('switch'); if ($switch == 1) { $f1 = (int)FormUtil::getPassedValue('forum1'); $f2 = (int)FormUtil::getPassedValue('forum2'); $o1 = DBUtil::selectObjectByID('lobby_forums',$f1); $o2 = DBUtil::selectObjectByID('lobby_forums',$f2); if (($o2['gid'] == $o1['gid']) && ($o1['gid'] == $this->gid)) { $dummy = $o1['sort_nr']; $o1['sort_nr'] = $o2['sort_nr']; $o2['sort_nr'] = $dummy; DBUtil::updateObject($o1,'lobby_forums'); DBUtil::updateObject($o2,'lobby_forums'); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'forummanagement'))); } } $render->assign('forums', $ffarray); // Set page title PageUtil::setVar('title', _LOBBY_FORUM_MANAGEMENT); return true; } function handleCommand(&$render, &$args) { if ($args['commandName']=='update') { // get the form data and do a validation check $obj = $render->pnFormGetValues(); // Create forum or update existing forum information if ($this->fid > 0) { // Delete Forum? if ($obj['delete'] == 1) { $result = pnModAPIFunc('lobby','forums','del',array('id' => $this->fid)); if ($result) { LogUtil::registerStatus(_LOBBY_FORUM_DELETED); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' =>$this->gid, 'sync' => '1', 'do' => 'forummanagement'))); } else { LogUtil::registerError(_LOBBY_FORUM_DELETE_ERROR); } } else { // Update existing forum $obj['id'] = $this->fid; $forum = DBUtil::selectObjectByID('lobby_forums',$this->fid); $forum['title'] = $obj['title']; $forum['public_status'] = $obj['public_status']; $forum['description'] = $obj['description']; $result = DBUtil::updateObject($forum,'lobby_forums'); if ($result) { LogUtil::registerStatus(_LOBBY_FORUM_UPDATED); } else { LogUtil::registerError(_LOBBY_FORUM_UPDATE_ERROR); return false; } } } else { // Create new forum $obj['gid'] = $this->gid; $result = pnModAPIFunc('lobby','forums','add',$obj); if (!$result) { return false; } } return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'sync' => 1, 'do' => 'forummanagement'))); } return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { var $id; function initialize(&$render) { $id = (int)FormUtil::getPassedValue('id'); $this->id = $id; // Load article if id is set $index = DBUtil::selectObjectByID('lobby_pages',$this->id); $index['indexpage'] = $index['text']; $render->assign($index); return true; } function handleCommand(&$render, &$args) { if ($args['commandName']=='update') { // get the form data and do a validation check $obj = $render->pnFormGetValues(); $obj['text'] = $obj['indexpage']; $obj['id'] = $this->id; // preview mode? if ($obj['preview'] == 1) { LogUtil::registerStatus(_LOBBY_INDEXPAGE_ARTICLEPREVIEW); $render->assign($obj); } else { if (!$render->pnFormIsValid()) return false; // store or update group $count = DBUtil::selectObjectCountByID('lobby_pages',$this->id); if ($count == 1) { $result = DBUtil::updateObject($obj,'lobby_pages'); } else { $result = DBUtil::insertObject($obj,'lobby_pages','',false,true); } if ($result) { LogUtil::registerStatus(_LOBBY_INDEXPAGE_CREATED); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->id))); } else { LogUtil::registerError(_LOBBY_INDEXPAGE_CREATIONERROR); return false; } } } return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { var $album; var $gid; function initialize(&$render) { $gid = (int)FormUtil::getPassedValue('id'); $aid = (int)FormUtil::getPassedValue('aid'); $this->gid = $gid; // Sync blind by default Loader::includeOnce('modules/lobby/includes/common_groups.php'); lobby_groupsync($gid); if ($aid > 0) { // load forum $album = pnModAPIFunc('lobby','albums','get',array('id' => $aid, 'gid' => $gid)); $this->album = $album[0]; if ($this->album['gid'] == $this->gid) { $render->assign($this->album); } } $public_status_items = array ( array('text' => _LOBBY_ALL, 'value' => 0), array('text' => _LOBBY_SITEMEMBERS, 'value' => 1), array('text' => _LOBBY_GROUPMEMBERS, 'value' => 2) ); $render->assign('public_status_items', $public_status_items); $albums = pnModAPIFunc('lobby','albums','get',array('gid' => $this->gid)); $render->assign('albums', $albums); // Set page title PageUtil::setVar('title', _LOBBY_ALBUM_MANAGEMENT); return true; } function handleCommand(&$render, &$args) { if ($args['commandName']=='update') { // get the form data and do a validation check $obj = $render->pnFormGetValues(); // Create forum or update existing forum information if ($this->album['id'] > 0) { // Delete Forum? if ($obj['delete'] == 1) { // remove album $result = pnModAPIFunc('lobby','albums','del',$this->album); if ($result) { LogUtil::registerStatus(_LOBBY_ALBUM_DELETED); } else { LogUtil::registerError('_LOBBY_ALBUM_DELETE_ERROR'); } } else { // Update existing forum $obj['id'] = $this->album['id']; $album = DBUtil::selectObjectByID('lobby_albums',$obj['id']); $album['title'] = $obj['title']; $album['date'] = $obj['date']; $album['public_status'] = $obj['public_status']; $album['description'] = $obj['description']; $result = DBUtil::updateObject($album,'lobby_albums'); if ($result) { LogUtil::registerStatus(_LOBBY_ALBUM_UPDATED); } else { LogUtil::registerError(_LOBBY_ALBUM_UPDATE_ERROR); return false; } } } else { // Create new forum $obj['gid'] = $this->gid; $result = pnModAPIFunc('lobby','albums','add',$obj); if (!$result) { return false; } } return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'albummanagement'))); } return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get all groups * * @args['id'] int id of group (optional) * @args['offset'] int offset for dbutil (optional) * @args['numrows'] int numrows for dbutil (optional) * @args['orderby'] string sort criteria (optional) * @args['pending'] int ==1 only pending (optional) * @args['count'] int ==1 only count groups (optional) * @args['cat'] int category id (optional) * @return array the categories */ function lobby_groupsapi_get($args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_OVERVIEW)) { return false; } // Parameters $pending = (int)$args['pending']; $id = (int)$args['id']; $cat = (int)$args['cat']; $count = (int)$args['count']; if ($id > 0) { $group = DBUtil::selectObjectByID('lobby_groups',$id); if (($group['accepted'] == 1) || ($group['uid'] == pnUserGetVar('uid') || SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN))) { $result = $group; } else { $result = array(); } } else { $numrows = $args['numrows']; $offset = $args['offset']; $order = $args['orderby']; if (!isset($order) || ($order == '')) { $orderby = 'title ASC'; } else if ($order == 'latest') { $orderby = 'date DESC'; } else if ($order == 'members') { $orderby = 'members DESC'; } $table = pnDBGetTables(); $column = $table['lobby_groups_column']; $users_column = $tables['users_column']; $joinInfo[] = array ( 'join_table' => 'users', // table for the join 'join_field' => 'uname', // field in the join table that should be in the result with 'object_field_name' => 'uname', // ...this name for the new column 'compare_field_table' => 'uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table $joinInfo[] = array ( 'join_table' => 'lobby_categories', // table for the join 'join_field' => 'title', // field in the join table that should be in the result with 'object_field_name' => 'categoryname', // ...this name for the new column 'compare_field_table' => 'category', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table if ($pending == 1) { $where = $column['accepted']." = 0 "; } else { $where = "(".$column['accepted']." = 1 OR ".$column['uid']." = ".(int)pnUserGetVar('uid').")"; } if ($cat > 0) { $where.=" AND ".$column['category']." = ".$cat; } if ($count == 1) { $result = DBUtil::selectExpandedObjectCount('lobby_groups',$joinInfo,$where); } else { $result = DBUtil::selectExpandedObjectArray('lobby_groups',$joinInfo,$where,$orderby,$offset,$numrows); } return $result; } return $result; } /** * get status in a group * * @args['group'] object group * @args['uid'] int user id (optional) * @return int * 0 = no member * 1 = member * 2 = owner */ function lobby_groupsapi_getMemberStatus($args) { $group = $args['group']; if (!is_array($group)) return 0; $uid = (int)$args['uid']; if (!($uid > 1)) { if (pnUserLoggedIn()) { $uid = pnUserGetVar('uid'); } else { return 0; } } if ($uid == 1) { $status = 0; } else if ($group['uid'] == $uid) { $status = 2; } else { $status = (int)pnModAPIFunc('lobby','members','get',array('uid' => $uid, 'gid' => $group['id'], 'count' => 1)); } return $status; } /** * Check if a given user id is member of a given group id * * @args['uid'] int user id * @args['gid'] int group id * @return boolean */ function lobby_groupsapi_isMember($args) { $args['count'] = 1; $member_count = pnModAPIFunc('lobby','members','get',$args); return ($member_count > 0); } /** * Accept a group * * $args['id'] int group id * @return boolean */ function lobby_groupsapi_accept($args) { // Get Parameter $id = (int)FormUtil::getPassedValue('id'); if (!($id > 0)) { return false; } // Load group $group = DBUtil::selectObjectByID('lobby_groups',$id); // modify if not accepted and loaded and return success if (!($group['id'] == $id) || ($group['accepted'] == 1)) { return false; } else { $group['accepted'] = 1; return DBUtil::updateObject($group,'lobby_groups'); } } /** * Checks if a user is group owner * * $args['id'] int group id * $args['uid'] int user id * @return boolean */ function lobby_groupsapi_isOwner($args) { $id = (int)$args['id']; $uid = (int)$args['uid']; if (!($id > 0) || !($uid > 0)) { return false; } else { $group = DBUtil::selectObjectByID('lobby_groups',$id); return ($group['uid'] == $uid); } } /** * Invite a user into a group * $args['group'] object group * $args['id'] int group id * $args['uname'] string username * $args['text'] string optional invitation text * @return boolean + status message */ function lobby_groupsapi_invite($args) { $uname = $args['uname']; $uid = pnUserGetIDFromName($uname); $id = $args['id']; $text = $args['text']; $group = $args['group']; // check for valid username if (!($uid > 1)) { LogUtil::registerError(_LOBBY_UNAME_NOT_FOUND); return false; } else { $new_isMember = lobby_groupsapi_isMember(array('uid' => $uid, 'gid' => $id)); $isMember = lobby_groupsapi_isMember(array('uid' => pnUserGetVar('uid'), 'gid' => $id)); if ($new_isMember) { // user already member of group LogUtil::registerError(_LOBBY_USER_ALREADY_MEMBER); return false; } elseif (!$isMember) { // inviting user shoul be member of the group he invites another person to LogUtil::registerError(_LOBBY_INVITATIONS_ONLY_MEMBERS); return false; } else { // user already invited? $where = "gid = '".$id."' AND invited_uid = '".$uid."'"; $res = DBUtil::selectObjectCount('lobby_invitations',$where); if ($res > 0) { LogUtil::registerError(_LOBBY_USER_ALREADY_INVITED); return false; } // invite user $obj = array ( 'gid' => $id, 'uid' => pnUserGetVar('uid'), 'invited_uid' => $uid, 'text' => $text, 'date' => date("Y-m-d H:i:s",time()) ); $result = DBUtil::insertObject($obj,'lobby_invitations'); if ($result) { // send email Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_invitation($group,$uid,pnUserGetVar('uid'),$text); // register status message LogUtil::registerStatus(_LOBBY_USER_INVITED); } else { // register status message LogUtil::registerError(_LOBBY_USER_INVITATION_ERROR); } } } } /** * sync group * * @param $args['id'] int group id * @return boolean */ function lobby_groupsapi_sync($args) { $id = (int)$args['id']; Loader::includeOnce('modules/lobby/includes/common_groups.php'); return lobby_groupsync($id); } /** * get map code for category * * @param $args['cat'] * @param $args['width'] * @param $args['height'] * @return string html code */ function lobby_groupsapi_getMapCode($args) { $cat = $args['cat']; $width = $args['width']; $height = $args['height']; $groups = pnModAPIFunc('lobby','groups','get',array('cat' => $cat)); Loader::includeOnce('modules/lobby/includes/common_groups.php'); $code = lobby_buildcoordinates($groups,$width,$height); return $code; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ pnModLangLoad('lobby','email'); /** * notification to admin about a new group * */ function lobby_notify_newgroup($obj) { $adminmail = pnConfigGetVar('adminmail'); if (isset($adminmail)) { $render = pnRender::getInstance('lobby'); $render->assign($obj); $category = pnModAPIFunc('lobby','categories','get',array('id' => $obj['ud'])); if ($category['accepted'] != 1) { $render->assign('official', 1); } $message = $render->fetch('lobby_email_newgroup.htm'); $subject = _LOBBY_EMAIL_NEW_GROUP_FOR." ".pnConfigGetVar('sitename'); $result = pnMail($adminmail, $subject, $message, $headers, $html); return $result; } } /** * new group accepted by admin * */ function lobby_notify_groupaccepted($gid) { $group = pnModAPIFunc('lobby','groups','get',array('id' => $gid)); $render = pnRender::getInstance('lobby'); $render->assign($group); $message = $render->fetch('lobby_email_groupaccepted.htm'); $subject = '"'.$group['title'].'" '._LOBBY_EMAIL_ACCEPTED_AT." ".pnConfigGetVar('sitename'); $to = pnUserGetVar('email', (int)$group['uid']); $result = pnMail($to, $subject, $message, $headers, $html); return $result; } /** * new member waiting or added * */ function lobby_notify_newmember($gid, $uid) { $group = pnModAPIFunc('lobby','groups','get',array('id' => $gid)); $render = pnRender::getInstance('lobby'); $render->assign($group); $render->assign('uname',pnUserGetVar('uname',$uid)); $message = $render->fetch('lobby_email_newmember.htm'); if ($group['moderated'] == 1) { $subject = _LOBBY_EMAIL_NEW_REQUEST_FOR_GROUP; } else { $subject = _LOBBY_EMAIL_NEW_GROUP_MEMBER_FOR; } $subject.= ' "'.$group['title'].'" '._LOBBY_EMAIL_AT." ".pnConfigGetVar('sitename'); $to = pnUserGetVar('email', (int)$group['uid']); $result = pnMail($to, $subject, $message, $headers, $html); return $result; } /** * member deleted group membership, notification for group owner * */ function lobby_notify_quitmember($gid, $uid, $text) { $group = pnModAPIFunc('lobby','groups','get',array('id' => $gid)); $render = pnRender::getInstance('lobby'); $render->assign($group); if ($text != '') { $render->assign('text', $text); } $render->assign('uname',pnUserGetVar('uname',$uid)); $message = $render->fetch('lobby_email_quitmember.htm'); $subject = _LOBBY_EMAIL_MEMBERSHIP_ENDED; $subject.= ' "'.$group['title'].'" '._LOBBY_EMAIL_AT." ".pnConfigGetVar('sitename'); $to = pnUserGetVar('email', (int)$group['uid']); $result = pnMail($to, $subject, $message, $headers, $html); return $result; } /** * reject a membership request * */ function lobby_notify_rejectmembershiprequest($group, $uid) { $render = pnRender::getInstance('lobby'); $render->assign($group); $render->assign('youruname',pnUserGetVar('uname',$uid)); $message = $render->fetch('lobby_email_requestrejected.htm'); $subject = _LOBBY_MEMBERSHIP_REQUEST_FOR.' "'.$group['title'].'" '._LOBBY_WAS_REJECTED; $to = pnUserGetVar('email', (int)$uid); $result = pnMail($to, $subject, $message, $headers, $html); return $result; } /** * accept a membership request * */ function lobby_notify_newgroupmember($group,$uid) { $render = pnRender::getInstance('lobby'); $render->assign($group); $render->assign('youruname',pnUserGetVar('uname',$uid)); $message = $render->fetch('lobby_email_requestaccepted.htm'); $subject = _LOBBY_MEMBERSHIP_REQUEST_FOR.' "'.$group['title'].'" '._LOBBY_WAS_ACCEPTED; $to = pnUserGetVar('email', (int)$uid); $result = pnMail($to, $subject, $message, $headers, $html); return $result; } /** * send new topic information * */ function lobby_notify_newtopic($topic,$title,$text,$poster,$fid,$tid) { // get all subscribers for forum $forum_subscribers = pnModAPIFunc('lobby','subscriptions','get',array('fid' => $topic['fid'])); $emails = array(); foreach ($forum_subscribers as $x) { $uid = $x['uid']; $email = pnUserGetVar('email',$uid); if (isset($email) && ($email != '')) { $emails[$uid] = $email; } } // send mails to subscribers $group = pnModAPIFunc('lobby','groups','get',array('id' => $topic['gid'])); foreach ($emails as $uid=>$to) { if ($uid != pnUserGetVar('uid')) { $render = pnRender::getInstance('lobby'); $render->assign('uname', pnUserGetVar('uname',$uid)); $render->assign('posteruname', pnUserGetVar('uname',$poster)); $render->assign('title', $title); $render->assign('text', $text); $render->assign('tid', $tid); $render->assign('fid', $fid); $render->assign('id', $topic['gid']); $message = $render->fetch('lobby_email_topicnotify.htm'); $subject = _LOBBY_EMAIL_NEWTOPIC_GROUP.' "'.$group['title'].'" '._LOBBY_EMAIL_AT.' "'.pnConfigGetVar('sitename').'"'; $result = pnMail($to, $subject, $message, $headers, $html); } } } /** * send new reply information * */ function lobby_notify_newreply($topic,$posting) { // get all subscribers for forum $forum_subscribers = pnModAPIFunc('lobby','subscriptions','get',array('fid' => $topic['fid'])); $emails = array(); foreach ($forum_subscribers as $x) { $uid = $x['uid']; $email = pnUserGetVar('email',$uid); if (isset($email) && ($email != '')) { $emails[$uid] = $email; } } // get all subscribers to topic $topic_subscribers = pnModAPIFunc('lobby','subscriptions','get',array('tid' => $topic['id'])); foreach ($topic_subscribers as $x) { $uid = $x['uid']; $email = pnUserGetVar('email',$uid); if (isset($email) && ($email != '')) { $emails[$uid] = $email; } } // get lobbypager value $postsperpage = pnModGetVar('lobby','postsperpage'); $replies = $topic['replies']; $page = floor($replies/$postsperpage); if ($page == 0) { $lobbypager = 1; } else { $lobbypager = ($page*10)+1; } // send mails to subscribers $group = pnModAPIFunc('lobby','groups','get',array('id' => $topic['gid'])); foreach ($emails as $uid=>$to) { if ($uid != pnUserGetVar('uid')) { $render = pnRender::getInstance('lobby'); $render->assign('lobbypager', $lobbypager); $render->assign('uname', pnUserGetVar('uname',$uid)); $render->assign('posteruname', pnUserGetVar('uname',$posting['uid'])); $render->assign('topicuname', pnUserGetVar('uname',$topic['uid'])); $render->assign('topic', $topic); $render->assign('posting', $posting); $message = $render->fetch('lobby_email_replynotify.htm'); $subject = _LOBBY_EMAIL_NEWREPLY.' "'.$posting['title'].'" '._LOBBY_IN_GROUP.' "'.$group['title'].'" '._LOBBY_EMAIL_AT.' "'.pnConfigGetVar('sitename').'"'; $result = pnMail($to, $subject, $message, $headers, $html); } } } /** * send invitation to a user * */ function lobby_notify_invitation($group,$uid,$from_uid,$text) { $render = pnRender::getInstance('lobby'); $render->assign($group); $render->assign($uid); $uname = pnUserGetVar('uname',$from_uid); $render->assign('youruname',pnUserGetVar('uname',$uid)); $render->assign('uname',$uname); $render->assign('group',$group); $message = $render->fetch('lobby_email_invitation.htm'); $subject = _LOBBY_GROUP_INVITATION_FOR.' "'.$group['title'].'" '._LOBBY_FROM." ".$uname; $to = pnUserGetVar('email', (int)$uid); $result = pnMail($to, $subject, $message, $headers, $html); return $result; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get moderators * * @args['uid'] int user id (optional) * @args['gid'] int group id * @args['count'] int optional == 1 only counting * @return array */ function lobby_moderatorsapi_get($args) { $tables = pnDBGetTables(); $column = $tables['lobby_moderators_column']; $table = 'lobby_moderators'; $uid = (int)$args['uid']; $gid = (int)$args['gid']; $count = (int)$args['count']; if (!($gid > 0)) { LogUtil::registerError(_LOBBY_GROUP_GETMODERATORS_PARAMFAILURE); return false; } else { $where = $column['gid']." = ".$gid.""; if ($uid > 1) { $where.=" AND tbl.".$column['uid']." = ".$uid; } $joinInfo[] = array ( 'join_table' => 'users', // table for the join 'join_field' => 'uname', // field in the join table that should be in the result with 'object_field_name' => 'uname', // ...this name for the new column 'compare_field_table' => 'uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table if ($count == 1) { $result = (int)DBUtil::selectObjectCount($table,$where); } else { $result = DBUtil::selectExpandedObjectArray($table,$joinInfo,$where,$orderby,$offset,$numrows); if ($uid > 1) { $result = $result[0]; } } } return $result; } /** * add a moderator to a group * * @args['uid'] int user id * @args['gid'] int group id * @return boolean */ function lobby_moderatorsapi_add($args) { $uid = (int)$args['uid']; $gid = (int)$args['gid']; if (!($uid > 1) || !($gid > 0)) { LogUtil::registerError(_LOBBY_GROUP_ADDMODERATOR_FAILURE); return false; } else { // get Group $group = pnModAPIFunc('lobby','groups','get',array('id' => $gid)); if ($group['id'] != $gid) { // Something went wrong, groups not existent or something like that LogUtil::registerError('Group could not be found!'); return false; } else { $obj = array( 'gid' => $gid, 'uid' => $uid ); // Security Check if (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN) || ($group['uid'] == pnUserGetVar('uid'))) { if (lobby_moderatorsapi_isModerator($args)) { LogUtil::registerError(_LOBBY_GROUPS_ALREADY_MOD); return false; } // Insert moderator now into database $result = DBUtil::insertObject($obj,'lobby_moderators'); // Set message if ($result) { LogUtil::registerStatus(str_replace('%user%', pnUserGetVar('uname',$obj['uid']),_LOBBY_GROUPS_MODERATORADDED)); } else { LogUtil::registerError(_LOBBY_GROUPS_MODERATORADDERROR); } } else { LogUtil::registerError(_LOBBY_GROUP_MODERATORS_ACCESS_DENY); return false; } } } } /** * delete a moderator from a group * * @args['uid'] int user id * @args['gid'] int group id * @return boolean */ function lobby_moderatorsapi_del($args) { $uid = (int)$args['uid']; $gid = (int)$args['gid']; if (!($uid > 1) || !($gid > 0)) { LogUtil::registerError(_LOBBY_GROUP_DELMODERATOR_FAILURE); return false; } else { // get Group $group = pnModAPIFunc('lobby','groups','get',array('id' => $gid)); if ($group['id'] != $gid) { // Something went wrong, groups not existent or something like that LogUtil::registerError('Group could not be found!'); return false; } else { // Security Check if (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN) || ($group['uid'] == pnUserGetVar('uid'))) { if (!lobby_moderatorsapi_isModerator($args)) { LogUtil::registerError(_LOBBY_GROUP_WAS_NO_MODERATOR); return false; } // get moderator $moderator = lobby_moderatorsapi_get($args); $obj = DBUtil::selectObjectByID('lobby_moderators',$moderator['id']); $result = DBUtil::deleteObject($obj,'lobby_moderators'); if ($result) { LogUtil::registerStatus(_LOBBY_GROUPS_MODERATORREMOVED); } else { LogUtil::registerError(_LOBBY_GROUPS_MODERATORDELERROR); } } else { LogUtil::registerError(_LOBBY_GROUP_MODERATORS_ACCESS_DENY); return false; } } } return true; } /** * checks if a user is a moderator * * @args['uid'] int user id * @args['gid'] int group id * @return boolean */ function lobby_moderatorsapi_isModerator($args) { if (!pnUserLoggedIn()) { return false; }else { $args['count'] = 1; $result = (int)lobby_moderatorsapi_get($args); return ($result > 0); } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ // general define('_LOBBY_OCLOCK', 'o\'clock'); define('_LOBBY_GO', 'go'); define('_LOBBY_YES', 'yes'); define('_LOBBY_NO', 'no'); define('_LOBBY_ONLY_ADMIN_ACCESS', 'Only administrators and group creators have access to this function'); define('_LOBBY_FORUMS', 'Forums'); define('_LOBBY_FORUM', 'Forum'); define('_LOBBY_NEWS', 'News'); define('_LOBBY_BY', 'of'); define('_LOBBY_HOURS', 'hours'); define('_LOBBY_GROUP', 'Group'); define('_LOBBY_AUTHOR', 'Author'); define('_LOBBY_DATE', 'Date'); define('_LOBBY_OF', 'of'); define('_LOBBY_VISIT', 'visit'); define('_LOBBY_LAST', 'last'); define('_LOBBY_QUOTE', 'Cite text'); define('_LOBBY_GO_TO_TOP', 'Go to top'); define('_LOBBY_EDIT', 'modify'); // main define('_LOBBY_WELCOME', 'Welcome to your network'); define('_LOBBY_INTRO_WELCOME_TEXT', 'This is an overview of all groups. Feel free to create your own group!'); define('_LOBBY_CREATE_GROUP', 'Create your own group'); define('_LOBBY_RECENT_JOINS', 'New memberships'); define('_LOBBY_NEW_GROUPS', 'New groups'); define('_LOBBY_ALL_GROUPS_NEWS', 'News of all groups'); define('_LOBBY_MY_GROUPS_NEWS', 'News of my groups'); define('_LOBBY_ALL_GROUPS_POSTS', 'Topics of all groups'); define('_LOBBY_MY_GROUPS_POSTS', 'Topics of my groups'); define('_LOBBY_NO_NEW_GROUPS', 'No new groups created'); define('_LOBBY_GROUP_EDIT_INFORMATION', 'Main settings'); define('_LOBBY_GROUP_ADMIN_SYNC', 'Sync group'); define('_LOBBY_GROUP_ONLINE_MEMBERS', 'Members that are online'); define('_LOBBY_OUR_PLACE', 'This is the group\'s home'); define('_LOBBY_SHORT_LATEST_TOPICS', 'Sort by latest topics'); define('_LOBBY_SHORT_LATEST_POSTINGS', 'Sort by latest replied'); define('_LOBBY_FORUM_SHORTLINK_LATEST', 'Postings since last visit'); define('_LOBBY_FORUM_SHORTLINK_24', 'Postings of last 24h'); define('_LOBBY_FORUM_SHORTLINK_WEEK', 'Postings for last week'); define('_LOBBY_FORUM_SHORTLINK_LATEST_TOPICS', 'Topics since last visit'); define('_LOBBY_FORUM_SHORTLINK_24_TOPICS', 'Topics of last 24h'); define('_LOBBY_FORUM_SHORTLINK_WEEK_TOPICS', 'Topics for last week'); define('_LOBBY_SHOW_ALL_GROUPS', 'Display all groups'); define('_LOBBY_FORUM_SHORTLINK_ALL', 'Display all forums'); define('_LOBBY_NO_TOPICS_YET', 'No topics found yet'); define('_LOBBY_NO_NEW_ARTICLES', 'No article written yet'); define('_LOBBY_GROUP_FORUM_SHORTLINKS', 'Quick forum access'); define('_LOBBY_YOU_NEED_HELP', 'You need help'); define('_LOBBY_CLICK_HERE', 'click here'); define('_LOBBY_GROUP_HELP', 'You need help'); define('_LOBBY_NO_NEW_MEMBERS', 'No memberships found yet'); define('_LOBBY_ENTERED', 'has joined'); define('_LOBBY_GROUP_QUIT', 'Cancel membership'); define('_LOBBY_FORUMS_OVERVIEW_LINK', 'Current discussions of group'); define('_LOBBY_FORUMS_OWN_OVERVIEW_LINK', 'Current discussions of own groups'); // forums define('_LOBBY_DISPLAY_MODE', 'filter topics'); define('_LOBBY_SHOW_ALL', 'all groups'); define('_LOBBY_SHOW_ALL_OFFICIAL', 'official groups'); define('_LOBBY_SHOW_OWN', 'your own groups'); // list define('_LOBBY_GROUPS_LIST', 'Available groups'); define('_LOBBY_GROUPS_LIST_TEXT', 'All available groups are listed here.'); define('_LOBBY_QUICKDATA', 'Group facts'); define('_LOBBY_MEMBERS', 'Members'); define('_LOBBY_VISIT_GROUP', 'Visit group'); define('_LOBBY_CAT_FILTER_HINT', 'If you only want to display a special category click on the categories name'); define('_LOBBY_CAT_FILTER_DEACTIVATE', 'Deactivate filter'); define('_LOBBY_OPTIONS', 'Options'); // invite define('_LOBBY_UNAME_NOT_FOUND', 'User name could not be found'); define('_LOBBY_USER_INVITED', 'User was invited to group'); define('_LOBBY_USER_ALREADY_MEMBER', 'User is already a member of the group'); define('_LOBBY_USER_INVITATION_ERROR', 'Internal error - Invitation could not be sent'); define('_LOBBY_INVITATIONS_ONLY_MEMBERS', 'You have to be a member of a group to recommend the group to another user'); define('_LOBBY_USER_ALREADY_INVITED', 'An invitation for this group was already sent to this user earlier'); // edit define('_LOBBY_EDIT_INDEX_POSTINGS', 'Number of forum topics / postings that should be shown at the group index page'); define('_LOBBY_LAT', 'Latitude'); define('_LOBBY_LNG', 'Longitude'); define('_LOBBY_CLICK_CARD_FOR_COORDS', 'Just click on the card to grab coordinates of a visible point'); define('_LOBBY_MODIFY_GROUUP', 'Modify group or create new group'); define('_LOBBY_EDIT_GROUP_TITLE', 'Group title'); define('_LOBBY_EDIT_GROUP_NOCHANGELATER', 'You can not change this value after the group has been created'); define('_LOBBY_EDIT_GROUP_DESCRIPTION', 'Public description of the group'); define('_LOBBY_EDIT_GROUP_CATEGORY', 'Category to use for this group'); define('_LOBBY_EDIT_GROUP_MODERATED', 'Moderate new membership requests'); define('_LOBBY_EDIT_UPDATE_STORE', 'create / update group'); define('_LOBBY_EDIT_OFFICIALGROUPSECPL', 'If you choose an official group your request has to be accepted and activated by the site administrator before it can be used by other users'); define('_LOBBY_GROUPS_ADDERROR', 'Adding group failed'); define('_LOBBY_GROUPS_ADDED', 'The group "%group%" was added'); define('_LOBBY_GROUP_PENDING', 'You will be informed after the group was accepted by the admin.'); define('_LOBBY_FORUMTITLE_INTRODUCTION', 'Newbie forum'); define('_LOBBY_FORUMTITLE_INTRODUCTION_DESC', 'Say hello to the group as a new member here!'); define('_LOBBY_FORUMTITLE_Q_AND_A', 'Questions and answerd'); define('_LOBBY_FORUMTITLE_Q_AND_A_DESC', 'You need help? You want to know something? Ask here!'); define('_LOBBY_FORUMTITLE_PRIVATE', 'Private, internal forum'); define('_LOBBY_FORUMTITLE_PRIVATE_DESC', 'Discuss things in here that should be private'); define('_LOBBY_FORUMTITLE_TALK', 'Public group forum'); define('_LOBBY_FORUMTITLE_TALK_DESC', 'You can discuss public things here that could be read by other users that are not members, too'); define('_LOBBY_GROUP_EDIT_INITPROCESS', 'Group standard template was applied to group'); define('_LOBBY_GROUP_OWNER_NODELETE', 'You can not add the group creator as moderator'); define('_LOBBY_GROUP_ALREADY_EXISTS', 'The chosen title of the group already exists. Choose another one please'); define('_LOBBY_CREATE_FORUMS', 'Create some example forums'); define('_LOBBY_DELETE_GROUP', 'Delete group and every data that belongs to the group'); define('_LOBBY_DELETION_MEMBER_FAILS', 'Deleting the group failed'); define('_LOBBY_DELETION_NEWS_FAILS', 'Deleting news failed'); define('_LOBBY_DELETION_MODERATORS_FAILS', 'Deleting moderator failed'); define('_LOBBY_DELETION_MEMBER_PENDING_FAILS', 'Deleting membership request failed'); define('_LOBBY_DELETION_FORUMS_FAILS', 'Deleting forum failed'); define('_LOBBY_DELETION_GROUP_FAILS', 'Deleting group core data failed'); define('_LOBBY_GROUP_DELETED', 'Group was deleted'); define('_LOBBY_FORUMS_VISIBLE_TO_ALL', 'The forums in the forum overview should be visible to everybody. Topics and postings in the forums can only be read as you set the individual permissions.'); // groups api define('_LOBBY_GROUP_ADDMEMBER_FAILURE', 'Adding a new member failed'); define('_LOBBY_GROUPS_MEMBERADDED', 'The user "%member%" was added to the group'); define('_LOBBY_GROUP_GETMEMBERS_PARAMFAILURE', 'Parameter for reading group data incorrect'); define('_LOBBY_GROUP_SYNCED', 'Group was synced'); define('_LOBBY_GROUP_SYNC_ERROR', 'Sync failed'); define('_LOBBY_REALLY_DELETE', 'Do you really want to do this delete action'); // group define('_LOBBY_GROUPINDEX', 'Show index page for all groups'); define('_LOBBY_GROUP_NOT_YET_ACCEPTED', 'This group has not been activated by the site admin yet. Use the time for setting up your new group. After the group is accepted by the site administrator it will be online!'); define('_LOBBY_GROUP_INDEX_PAGE', 'To the group\'s index page'); define('_LOBBY_GROUP_NONEXISTENT', 'The chosen group does not exist or is not active yet.'); define('_LOBBY_GROUP_NEWS', 'Group news'); define('_LOBBY_GROUP_NONEWS', 'No news up to now'); define('_LOBBY_GROUP_FACTS', 'Facts'); define('_LOBBY_GROUP_LASTACTION', 'Last activity'); define('_LOBBY_GROUP_MEMBERS', 'Members'); define('_LOBBY_GROUP_ARTICLES', 'Articles (News)'); define('_LOBBY_GROUP_FORUMS', 'Group forums'); define('_LOBBY_GROUP_TOPICS', 'Forum topics'); define('_LOBBY_GROUP_POSTINGS', 'Forum postings'); define('_LOBBY_GROUP_NEW_TOPICS', 'New forum topics'); define('_LOBBY_GROUP_NEW_POSTINGS', 'New forum postings'); define('_LOBBY_GROUP_CATEGORY', 'Category'); define('_LOBBY_GROUP_CREATOR', 'Creator'); define('_LOBBY_GROUP_MODERATORS', 'Moderators'); define('_LOBBY_GROUP_YOURSTATUS', 'Your status'); define('_LOBBY_GROUP_MEMBER', 'Member'); define('_LOBBY_GROUP_NO_MEMBER', 'Guest'); define('_LOBBY_GROUP_JOIN', 'join'); define('_LOBBY_GROUP_PUBLICGROUP', 'Group is public - you can join the group right now'); define('_LOBBY_GROUP_MODERATEDGROUP', 'Group is moderated - you can create a membership request'); define('_LOBBY_GROUP_ADMIN_MENU', 'Manage'); define('_LOBBY_GROUP_ADMIN_PENDING', 'Pending requests'); define('_LOBBY_GROUP_ADMIN_MEMBER_MANAGEMENT', 'Manage members'); define('_LOBBY_GROUP_ADMIN_NEW_ARTICLE', 'Write article'); define('_LOBBY_GROUP_ADMIN_FORUM_MANAGEMENT', 'Manage forums'); define('_LOBBY_NEWS_INDEX', 'To the articles'); define('_LOBBY_GROUP_INVITE', 'Invite friends'); define('_LOBBY_GROUP_NOMEMBERS', 'No members yet'); define('_LOBBY_GROUP_NOMEMBERS_ONLINE', 'No members online'); define('_LOBBY_GROUP_RESPONSIBLE', 'Group creator'); define('_LOBBY_GROUP_FORUM_INDEX', 'Group forum overview'); define('_LOBBY_GROUP_FORUM_RECENT_TOPICS', 'latest topics'); define('_LOBBY_GROUP_FORUM_RECENT_POSTS', 'latest postings'); define('_LOBBY_GROUP_TROUBLE_CONTACT', 'Please contact the group creator in case of any problems'); define('_LOBBY_GROUP_MORE_TROUBLE_CONTACT', 'Pleas inform the site administrator if problems rise up the group creator can not solve'); define('_LOBBY_GROUP_MODIFY_INDEX', 'Create an individual home page for the group'); define('_LOBBY_GROUP_ADMIN_INDEXPAGE', 'Modify home page'); define('_LOBBY_GROUP_LATEST_MEMBERS', 'Latest members'); define('_LOBBY_GROUP_UPDATED', 'Group was updated'); define('_LOBBY_GROUP_UPDATE_ERROR', 'Updating group failed'); // group // invite define('_LOBBY_INVITE_ENTER_TEXT', 'Invitation text'); define('_LOBBY_INVITE_TO_SITE', 'Invite other users'); define('_LOBBY_INVITE_ENTER_UNAME', 'Enter username'); define('_LOBBY_INVITE_NO_MEMBER', 'Invite externals'); // group // quit define('_LOBBY_QUIT_MEMBERSHIP', 'Cancel membership'); define('_LOBBY_QUIT_MEMBERSHIP_TEXT', 'Cancelling the membership will send an email information to the creator of the group'); define('_LOBBY_QUIT_MEMBERSHIP_LINK', 'Cancel membership now'); define('_LOBBY_MEMBERSHIP_QUITTED', 'Membership was cancelled'); define('_LOBBY_MEMBERSHIP_QUIT_REASON', 'Please describe for the group creator the reason why you are cancelling your membership'); // group // forums define('_LOBBY_GROUP_NO_FORUM', 'No forum created yet'); define('_LOBBY_FORUM_TOPICS', 'Topics'); define('_LOBBY_FORUM_POSTS', 'Postings'); define('_LOBBY_FORUM_LATES_TOPIC', 'Latest topic'); define('_LOBBY_FORUM_LATES_POST', 'Latest posting'); define('_LOBBY_PUBLIC_STATUS_GROUP', 'Visible and usable only by members of this group'); define('_LOBBY_PUBLIC_STATUS_REGUSERS', 'Visible and usable by registered users of this website'); define('_LOBBY_PUBLIC_STATUS_ALL', 'Visible for all, usable for registered users of this website'); define('_LOBBY_SINCE_DATE', 'since the date'); define('_LOBBY_SINCE', 'since'); define('_LOBBY_TOPICS_SHOW', 'show'); //define('_LOBBY_FORUM_TOPICS_OF_LAST', 'Themen der letzten'); define('_LOBBY_LATEST_POSTS', 'Latest forum posts'); define('_LOBBY_LATEST_TOPICS', 'Latest forum topics'); // group // join define('_LOBBY_GROUP_JOINGROUP', 'Join this group'); define('_LOBBY_GROUP_JOIN_MODERATED', 'Group is moderated. This means, that nobody can join the group without the permission of the group creator. You can add text for the group creator that will be added to your membership request'); define('_LOBBY_GROUP_JOIN_TEXT', 'Additional information for the group creator'); define('_LOBBY_GROUP_JOIN_NOW', 'Join the group now'); define('_LOBBY_GROUP_JOIN_REQUEST', 'Send membership request'); define('_LOBBY_GROUP_JOIN_PUBLIC', 'You will become an active member immediately after submitting your request'); define('_LOBBY_GROUP_REQUESTSENT', 'Membership request was sent to the group owner.'); define('_LOBBY_GROUP_JOINERROR', 'Sending membership request failed'); define('_LOBBY_GROUP_ADD_ALREDY_MEMBER', 'You are already a member of this group'); define('_LOBBY_GROUP_ADD_ALREDY_PENDING', 'There is still an active membership request. Please wait until the group creator has decided'); define('_LOBBY_GROUPS_ADDERROR', 'Adding a user to the group failed!'); // groups // pending define('_LOBBY_GROUP_PENDING_MEMBERS', 'Pending membership requests'); define('_LOBBY_GROUP_PENDING_TEXT', 'Overview about all pending membership requests'); define('_LOBBY_GROUP_NO_PENDING', 'No pending requests found'); define('_LOBBY_GROUP_PENDING_ACCEPT', 'accept'); define('_LOBBY_GROUP_PENDING_DENY', 'reject'); define('_LOBBY_GROUP_PENDING_ACCEPT_ERROR', 'Adding member to group failed'); // group // article define('_LOBBY_NEWS_ADDARTICLE', 'Write or modify article'); define('_LOBBY_NEWS_EXPLANATION', 'You can write new articles here and set permissions individually for each article'); define('_LOBBY_NEWS_TITLE', 'Title of article'); define('_LOBBY_NEWS_TEXT', 'Article body'); define('_LOBBY_NEWS_STORE_UPDATE', 'Article was stored / updated'); define('_LOBBY_NEWS_PUBLIC_STATUS', 'Set visibility level for article'); define('_LOBBY_ALL', 'All user including guests should be able to read this article'); define('_LOBBY_GROUPMEMBERS', 'Only members of this group should be able to read this article'); define('_LOBBY_SITEMEMBERS', 'Members and registered users of this website should have access'); define('_LOBBY_NEWS_DELETE_ARTICLE', 'Delete the article'); define('_LOBBY_NEWS_DATE', 'Date and time of article'); define('_LOBBY_NEWS_DATE_EXPLANATION', 'if you specify a future date the article will automatically be displayed after the specified timestamp'); define('_LOBBY_NEWS_PREVIEW_ARTICLE', 'Preview mode - just preview, no storing'); define('_LOBBY_NEWS_ARTICLEPREVIEW', 'The article was not stored yet. To quit preview mode, remove the checkbox at "'._LOBBY_NEWS_PREVIEW_ARTICLE.'" please!'); define('_LOBBY_FORUM_PREVIEW', 'This is a preview. To quit preview mode remove the checkbox "'._LOBBY_NEWS_PREVIEW_ARTICLE.'" please.'); define('_LOBBY_NEWS_PREVIEW', 'Create article preview'); define('_LOBBY_NEWS_WRITTENBY', 'Author'); define('_LOBBY_NEWS_CREATED', 'Article created'); define('_LOBBY_NEWS_CREATIONERROR', 'Creating article failed'); define('_LOBBY_NEWS_EDIT', 'Edit article'); define('_LOBBY_ARTICLE_PREVIEW', 'Article preview'); define('_LOBBY_NEWS_UPDATED', 'Article was updated'); define('_LOBBY_NEWS_UPDATEERROR', 'Updating article failed!'); define('_LOBBY_NEWS_DELETED', 'Article deleted'); //group // news define('_LOBBY_NEWS_PUBLICSTATUS_TEXT', 'If you are not a member of this group not all news and topics might be displayed for you. Get a member of the group to access all information!'); define('_LOBBY_NEWS_INFUTURE', 'This article timestamp is in future. This Article can only be read by group admin'); define('_LOBBY_NEWS_NOAUTH_NOCONTENT', 'The chosen article does not exist or you are not allowed to view the article'); define('_LOBBY_NEWS_SEND_TO_GROUP', 'Send article via email to all group members'); define('_LOBBY_ARTICLE_SENT_TO_GROUP', 'Article was sent to all group members'); define('_LOBBY_ARTICLE_SENT_ERROR', 'Article could not be sent - sending was cancelled'); define('_LOBBY_GROUP_NEWS_FROM', 'News of group'); define('_LOBBY_NEWS_MAIL_FOOTER', 'This mail has been sent by the creator of the group. Please contact the group creator if there are any questions.'); define('_LOBBY_DEAR', 'Dear user'); define('_LOBBY_GROUP_NEWS_RELEASED', 'you are a member of a group whoose group creator has written a news article and sent this article to all members!'); define('_LOBBY_GROUP_LINK', 'Link to group'); define('_TRACKING_ARTICLE_SENT_ALREADY', 'An article can not be mailed twice!'); // group // membermanagement define('_LOBBY_MEMBER_MANAGEMENT', 'Member management'); define('_LOBBY_MEMBER_MANAGEMENT_EXPLANATION', 'You can manage members and their permisisons here.'); define('_LOBBY_MEMBER_MANAGEMENT_HOWTO', 'Please choose a member you want to modify fist. After doing this you will be able to modify the chosen member.'); define('_LOBBY_MEMBER_MANAGEMENT_SELECTUSER', 'Choose member of group'); define('_LOBBY_MEMBER_MANAGEMENT_LOAD', 'load user data'); define('_LOBBY_GROUP_REJECT_MEMBER_FAILURE', 'Parameters wrong for rejecting a group membership'); define('_LOBBY_GROUP_DELETE_MEMBER_FAILURE', 'Deleting membership failed'); define('_LOBBY_USER_NOT_A_MEMBER', 'The person is not a member of the group'); define('_LOBBY_USER_IS_OWNER', 'The person is creator of the group'); define('_LOBBY_USER_DELETED', 'User has been deleted from the group'); // group // membermanagement // modify define('_LOBBY_MEMBER_MANAGEMENT_GETERROR', 'User data could not be loaded'); define('_LOBBY_MEMBER_MANAGEMENT_SELECTEDUSER', 'Chosen user'); define('_LOBBY_MEMBER_MANAGEMENT_USER', 'User data'); define('_LOBBY_MEMBER_MANAGEMENT_DELETE', 'Remove the membership of the user'); define('_LOBBY_MEMBER_MANAGEMENT_APPLY', 'Apply changes'); define('_LOBBY_MEMBER_MANAGEMENT_MODERATOR', 'User is moderator'); define('_LOBBY_MEMBER_MANAGEMENT_NOCHANGE', 'No changes were made'); define('_LOBBY_MEMBER_MANAGEMENT_BACKLINK', 'Back to member management page'); define('_LOBBY_MEMBERSHIP_REQUEST_REJECTED', 'Request was rejected'); define('_LOBBY_MEMBERSHIP_REJECT_ERROR', 'Rejecting request failed'); // group // modifyindex define('_LOBBY_INDEXPAGE_CREATED', 'Home page was stored'); define('_LOBBY_INDEXPAGE_CREATIONERROR', 'Storing home page failed'); define('_LOBBY_INDEXPAGE_ARTICLEPREVIEW', 'The page was not stored yet because you are in preview mode. Please remove checkbox at "'._LOBBY_NEWS_PREVIEW_ARTICLE.'" to quit preview mode!'); define('_LOBBY_INDEXPAGE_PREVIEW', 'Preview'); define('_LOBBY_INDEXPAGE_EXPLANATION', 'You can store a little information page to display important information for your group and for new members.'); define('_LOBBY_INDEXPAGE_STORE_UPDATE', 'Store / update'); define('_LOBBY_INDEXPAGE_TEXT', 'Content that should be added above the group index page'); // group // forummanagement define('_LOBBY_FORUM_MANAGEMENT', 'Manage forums'); define('_LOBBY_FORUM_MANAGEMENT_EXPLANATION', 'You can manage the forums and forum permissions here. You can change the settings later, too'); define('_LOBBY_FORUM_ADD_NEW_FORUM', 'Add new forum'); define('_LOBBY_FORUM_EXISTING_FORUMS', 'Existing forums'); define('_LOBBY_FORUM_TITLE', 'Forum title'); define('_LOBBY_FORUM_DESCRIPTION', 'Description'); define('_LOBBY_FORUM_PUBLIC_STATUS', 'Content should be visible for'); define('_LOBBY_FORUM_STORE_UPDATE', 'udpate / store'); define('_LOBBY_FORUM_CREATED', 'Forum "%forum%" was added'); define('_LOBBY_FORUM_SYNC_HINT', 'Please use sync function if topics or postings are not displayed the way they should be displayed or if the facts section displays wrong information.'); define('_LOBBY_FORUM_CREATION_ERROR', 'Adding forum failed'); define('_LOBBY_FORUM_NOFORUMS', 'No forum added yet'); define('_LOBBY_FORUM_UPDATED', 'Settings updated'); define('_LOBBY_FORUM_UPDATE_ERROR', 'Updating forum settings failed'); define('_LOBBY_FORUM_DELETED', 'Forum was deleted'); define('_LOBBY_FORUM_DELETE_ERROR', 'Deleting forum failed'); define('_LOBBY_FORUM_DELETE', 'Delete forum, topics and postings'); define('_LOBBY_FORUM_WRITABLE_HINT', 'Remember that forums that are public can also be used by other users than the group members.'); define('_LOBBY_FORUM_CLICK_TO_EDIT', 'To modify a forum click the edit link in the forum line. '); define('_LOBBY_SYNC_FORUM', 'sync'); define('_LOBBY_TOPICS_SYNCED_IN', 'Topics synced in'); define('_LOBBY_FORUM_PERMISSIONS', 'Permissions'); define('_LOBBY_FORUM_POS', 'Position'); define('_LOBBY_MOVE_UP', 'Move up'); define('_LOBBY_MOVE_DOWN', 'Move down'); define('_LOBBY_FORUM_ACTION', 'Action'); define('_LOBBY_STATUS_PUBLIC', 'Guests: read, Users: write, Members: write'); define('_LOBBY_STATUS_MEMBERS', 'Guests: none, Users: write, Members: write'); define('_LOBBY_STATUS_PRIVATE', 'Guests: none, Users: none, Members: write'); // forumtopics api define('_LOBBY_TOPICSAPI_ADD_PARAMERROR', 'Wrong parameters for topic add api function'); define('_LOBBY_TOPIC_CREATION_ERROR', 'Topic creation error'); // moderators api define('_LOBBY_GROUP_GETMODERATORS_PARAMFAILURE','Wrong parameter for get moderators function'); define('_LOBBY_GROUP_ADDMODERATOR_FAILURE', 'Wrong parameter for adding a new moderator'); define('_LOBBY_GROUP_MODERATORS_ACCESS_DENY', 'You have no permission to add or remove a moderator'); define('_LOBBY_GROUPS_MODERATORADDERRO', 'Adding moderator failed'); define('_LOBBY_GROUPS_MODERATORADDED', 'User "%user%" is now marked as moderator. Permissions have been granted'); define('_LOBBY_GROUPS_ALREADY_MOD', 'User is already moderator'); define('_LOBBY_GROUP_DELMODERATOR_FAILURE', 'Wrong parameter for delete moderator from group api function'); define('_LOBBY_GROUP_WAS_NO_MODERATOR', 'The user is no moderator and can not be deleted as moderator'); define('_LOBBY_GROUPS_MODERATORREMOVED', 'Moderator permissions removed from user'); define('_LOBBY_GROUPS_MODERATORDELERROR', 'Removing permissions failed'); // group // forum define('_LOBBY_CFORUM_SUBSCRIBED', 'Subscription active'); define('_LOBBY_FORUM_INDEX', 'Forum overview'); define('_LOBBY_FORUM_PUBLICSTATUS_TEXT', 'Maybe not all information available here is displayed to you. If you are not a member of this group join the group to access all information'); define('_LOBBY_NEW_TOPIC', 'Create new topic'); define('_LOBBY_FORUM_NOPOSTS', 'No topic created yet or no permissions to access topics'); define('_LOBBY_FORUM_TOPIC_TITLE', 'Title'); define('_LOBBY_FORUM_TOPIC_LASTDATE', 'Date'); define('_LOBBY_FORUM_TOPIC_EXPLANATION', 'Start a new topic here. Please consider netiquette!'); define('_LOBBY_FORUM_TOPIC_REPLIES', 'Replies'); define('_LOBBY_NEW_REPLY', 'Write reply'); define('_LOBBY_FORUM_REPLY_EXPLANATION', 'You can add a reply here. Please use preview function before sending the reply and read the written reply before posting it!'); define('_LOBBY_FORUM_REPLY_PREFIX', 'Reply'); define('_LOBBY_REPLY_POSTED', 'Reply posted'); define('_LOBBY_FORUM_NO_POST_AUTH', 'Only group members can discuss here. Please join the group if you want to discuss here!'); define('_LOBBY_FORUM_STORE_REPLY', 'Store reply'); define('_LOBBY_NO_FORUM_SELECTED', 'No valid forum chosen'); define('_LOBBY_FORUM_NOT_SUBSCRIBED', 'no subscription'); define('_LOBBY_FORUM_SUBSCRIBED', 'subscription active'); define('_LOBBY_FORUM_SUBSCRIBE', 'subscribe'); define('_LOBBY_FORUM_SUBSCRIBED_NOW', 'Forum subscribed'); define('_LOBBY_FORUM_SUBSCRIBE_ERROR', 'Subscribing failed'); define('_LOBBY_FORUM_ALREADY_SUBSCRIBED', 'Subscription exists already'); define('_LOBBY_FORUM_UNSUBSCRIBE', 'Delete subscription'); define('_LOBBY_FORUM_UNSUBSCRIBED_NOW', 'Subscription deleted'); define('_LOBBY_FORUM_UNSUBSCRIBE_ERROR', 'Subscription deletion error for forum'); define('_LOBBY_TOPIC_SUBSCRIBED_NOW', 'Topic subscribed'); define('_LOBBY_TOPIC_SUBSCRIBE_ERROR', 'Topic subscription error'); define('_LOBBY_TOPIC_ALREADY_SUBSCRIBED', 'Topic subscribed already'); define('_LOBBY_TOPIC_UNSUBSCRIBED_NOW', 'Subscription deleted'); define('_LOBBY_TOPIC_UNSUBSCRIBE_ERROR', 'Deleting topic subscription failed'); define('_LOBBY_POSTING_TITLE', 'Topic title'); define('_LOBBY_FORUM_STORE', 'Store topic'); define('_LOBBY_FORUM_JUST_PREVIEW', 'Activate preview mode'); define('_LOBBY_POSTING_CONTENT', 'Content of posting'); define('_LOBBY_TOPIC_CREATED', 'Topic created'); define('_LOBBY_TOPIC_CREATION_ERROR', 'Topic creation error'); define('_LOBBY_FORUM_CONTAINS', 'Forum contains'); define('_LOBBY_TOPICS_AND', 'topics and'); define('_LOBBY_POSTS', 'postings'); define('_LOBBY_MODERATOR_ACTIONS', 'Moderator actions'); define('_LOBBY_TOPIC_DELETE', 'delete topic'); define('_LOBBY_TOPIC_CLOSE', 'close topic'); define('_LOBBY_TOPIC_REOPEN', 'reopen topic'); define('_LOBBY_TOPIC_MARK', 'mark topic'); define('_LOBBY_TOPIC_UNMARK', 'remove topic marker'); define('_LOBBY_TOPIC_MOVE', 'move topic'); define('_LOBBY_TOPIC_UPDATE_FAILED', 'updating topic failed'); define('_LOBBY_MODERATION_TOPIC_DELETED', 'Topic deleted'); define('_LOBBY_EDIT_NOTPOSSIBLE', 'You can not modify the posting now. Modifications are only possible until the first reply is posted. Only group moderators are able to apply changes later.'); define('_LOBBY_MODERATION_TOPIC_UNMARKED', 'Topic is not marked any more'); define('_LOBBY_MODERATION_TOPIC_MARKED', 'Topic marked'); define('_LOBBY_MODERATION_TOPIC_REOPENED', 'Topic reopened'); define('_LOBBY_MODERATION_TOPIC_CLOSED', 'Topic closed'); define('_LOBBY_FORUM_TOPIC_LOCKED', 'Topic was closed. No more replies are possible.'); define('_LOBBY_ILLEGAL_MODERATOR_ACTION', 'You are not a moderator... Go away!'); define('_LOBBY_MODERATOR_DELETE_POSTING', 'Delete this post'); define('_LOBBY_MODERATION_POSTING_DELETED', 'Post deleted'); define('_LOBBY_FORUM_INSTANT_ABO', 'Subscribe topic if there is no subscription yet'); define('_LOBBY_FORUM_POSTING_INFO', 'Information'); define('_LOBBY_FORUM_TOPICS_LAST_VISIT', 'Show topics since last visit'); define('_LOBBY_FORUM_POSTINGS_LAST_VISIT', 'Show postings since last visit'); define('_LOBBY_FORUM_LATEST_POSTING', 'Show latest posting'); define('_LOBBY_RESET_LAST_VISIT', 'reset'); define('_LOBBY_MODERATOR_EDIT_POSTING', 'Edit post'); define('_LOBBY_FORUM_EDIT_HINT', 'Postings can be added afterwards until the first reply has been stored. After this a post can only be modified by a group moderator'); define('_LOBBY_LAST_EDITED', 'Edited '); define('_LOBBY_POST_MODIFIED', 'Posting was modified'); define('_LOBBY_MOVE_TOPIC_TO', 'Move topic to'); define('_LOBBY_MODERATION_HOTTOPIC', 'Hot discussed topic'); define('_LOBBY_POST_MODIFY_ERROR', 'Changing posting failed'); define('_LOBBY_TOPIC_MOVED', 'Topic moved'); define('_LOBBY_NO_EDIT_PERMISSION', 'No permission'); define('_LOBBY_LAST_REPLY', 'last reply'); define('_LOBBY_MARK_QUOTE', 'Please mark the text you want to cite and click the cite link to add the cite. You can add multiple cites to a posting.'); define('_LOBBY_MARK_QUOTE_DONE', 'The following text was added as a cite.'); //groups //help define('_LOBBY_HELP_PAGE', 'Some explanations that might help you to use the groups'); define('_LOBBY_HELP_INTRODUCTION', 'You can find some help here for the daily group usage. If there are further questions, please contact the support of this website.'); define('_LOBBY_HELP_GENERAL', 'General information'); define('_LOBBY_HELP_GENERAL_TEXT', 'You can create own groups with this software. Groups will have their group title, a group description and you will be able to create an individual setup. You will be able to manage memberships, pending members and you can add some coordinates to your group to make it be displayed in an overview map.'); define('_LOBBY_HELP_MEMBERSHIP', 'Group memberships'); define('_LOBBY_HELP_MEMBERSHIP_TEXT', 'Everybody can join every group. But the group creator can decide if users should immediately become a member of if they have to pass a moderation process. In this case you are a new member of the group if the creator allows you to join the group.'); define('_LOBBY_HELP_GROUPRULES', 'Group rules'); define('_LOBBY_HELP_GROUPRULES_TEXT', 'Every group has to create their own rules. The responsible person for a group is the group creator.'); define('_LOBBY_HELP_FUNCTIONS', 'group functions'); define('_LOBBY_HELP_COORDS', 'Setup coordinate'); define('_LOBBY_HELP_COORDS_TEXT', 'If you want to be listed regionally add a coordinate to your group to integrate the group into a big map.'); define('_LOBBY_HELP_NEWS', 'Articles and news'); define('_LOBBY_HELP_NEWS_TEXT', 'Every group has its own news system. News can also be sent by email (newsletter) to all group members. The permissions for every article can be set individually.'); define('_LOBBY_HELP_FORUMS', 'Forums'); define('_LOBBY_HELP_FORUMS_TEXT', 'Setup your own forums with an individual permission management.'); define('_LOBBY_HELP_FORUMS_TEXT2', 'Topics and forums can be subscribed. Information emails will be sent to all subscribed users if there are new replies or topics.'); define('_LOBBY_HELP_FORUMS_TEXT3', 'To make it easy you can create defined forums in the group creation process.'); define('_LOBBY_HELP_MISC', 'Other'); define('_LOBBY_HELP_NAVIGATION_HINT', 'Please do not use the back and forward buttons of your webbrowser while you surf and use the groups. This might cause errors in some cases! Please navigate using the link structure.'); // forum legend define('_LOBBY_FORUM_LEGEND', 'Legend'); define('_LOBBY_FORUM_HOT_TOPIC', 'Hot discussed topic'); define('_LOBBY_FORUM_TOPIC_MARKED', 'marked topic'); define('_LOBBY_FORUM_LAST_TOPIC_LINK', 'Link to latest reply (red border = unread reply exists)'); // list define('_LOBBY_SORT_CRITERIA', 'resort'); define('_LOBBY_ALPHABETICAL', 'alphabetical (A-Z)'); define('_LOBBY_LATEST', 'Creation date (latest first)'); define('_LOBBY_COUNTEDMEMBERS', 'Memberships'); define('_LOBBY_MAP', 'show all groups in map'); define('_LOBBY_NO_CAT_FILTER', 'show all categories'); define('_LOBBY_RELOAD', 'reload'); define('', ''); define('', ''); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * initialise the module * */ function lobby_init() { // Create tables $tables = array ( 'lobby_pages', 'lobby_groups', 'lobby_categories', 'lobby_moderators', 'lobby_members', 'lobby_members_pending', 'lobby_invitations', 'lobby_news', 'lobby_users', 'lobby_forums', 'lobby_forum_subscriptions', 'lobby_forum_topics', 'lobby_forum_topic_subscriptions', 'lobby_forum_posts', 'lobby_forum_posts_text', 'lobby_albums', 'lobby_albums_pictures', ); foreach ($tables as $table) { if (!DBUtil::createTable($table)) { return false; } } // Set initial values for module variables pnModSetVar('lobby','postsperpage',10); pnModSetVar('lobby','topicsperpage',15); pnModSetVar('lobby','newsperpage',15); return true; } /** * upgrade routine */ function lobby_upgrade($oldversion) { switch($oldversion) { case '1.0': case '1.1': if (!DBUtil::changeTable('lobby_groups')) return false; case '1.2': if (!DBUtil::changeTable('lobby_groups')) return false; if (!DBUtil::createTable('lobby_albums')) return false; if (!DBUtil::createTable('lobby_albums_pictures')) return false; } return true; } /** * initialise the module * */ function lobby_delete() { // Drop tables $tables = array ( 'lobby_pages', 'lobby_groups', 'lobby_categories', 'lobby_moderators', 'lobby_members', 'lobby_members_pending', 'lobby_invitations', 'lobby_news', 'lobby_users', 'lobby_forums', 'lobby_forum_subscriptions', 'lobby_forum_topics', 'lobby_forum_topic_subscriptions', 'lobby_forum_posts', 'lobby_forum_posts_text', 'lobby_albums', 'lobby_albums_pictures', ); foreach ($tables as $table) { if (!DBUtil::dropTable($table)) { return false; } } // Delete module variables pnModDelVar('lobby'); return true; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ Loader::includeOnce('modules/lobby/includes/common_categories.php'); class lobby_user_editHandler { var $id; var $group; function initialize(&$render) { $uid = pnUserGetVar('uid'); $yesno_items = array ( array('text' => _LOBBY_YES, 'value' => 1), array('text' => _LOBBY_NO, 'value' => 0), ); $render->assign('yesno_items', $yesno_items); // Assign categories $categories = pnModAPIFunc('lobby','categories','get'); $category_items = lobby_categoriesToPullDown($categories); // is there a group that should be loaded? $id = (int)FormUtil::getPassedValue('id'); if ($id > 0) { $group = DBUtil::selectObjectByID('lobby_groups',$id); $coords = unserialize($group['coordinates']); $group['lng'] = $coords['lng']; $group['lat'] = $coords['lat']; $this->group = $group; if (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN) || ($group['uid'] == pnUserGetVar('uid'))) { $render->assign($group); $render->assign('edit', 1); // overwrite category items if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) { $category = pnModAPIFunc('lobby','categories','get',array('id' => $group['category'])); $category_items = lobby_categoryToPullDown($category); } else { $category = pnModAPIFunc('lobby','categories','get'); $category_items = lobby_categoriesToPullDown($category); } } else { LogUtil::registerPermissionError(); return $render->pnFormRedirect(pnModUrl('lobby')); } } $render->assign('category_items', $category_items); // Is MyMap module available? $mymapavailable = pnModAvailable('MyMap'); if ($mymapavailable) { $render->assign('mymapavailable', $mymapavailable); $render->assign('coords', $coords); } return true; } function handleCommand(&$render, &$args) { if ($args['commandName']=='update') { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_COMMENT)) return LogUtil::registerPermissionError(); // get the pnForm data and do a validation check $obj = $render->pnFormGetValues(); if (!$render->pnFormIsValid()) return false; // is there a special action to be done? $delete = (int)$obj['delete']; // Should the group be deleted? if ($delete == 1) { // delete forums $id = $this->group['id']; $forums = pnModAPIFunc('lobby','forums','get',array('gid' => $id)); prayer($forums); $fids = array(); foreach ($forums as $forum) { $result = pnModAPIFunc('lobby','forums','del',array('id' => $forum['id'])); if (!$result) { return LogUtil::registerError(_LOBBY_DELETION_FORUMS_FAILS); } } // delete news articles $where = 'gid = '.$id; $result = DBUtil::deleteWhere('lobby_news',$where); if (!$result) { return LogUtil::registerError(_LOBBY_DELETION_NEWS_FAILS); } // delete albums $albums = pnModAPIFunc('lobby','albums','get',array('gid' => $id)); foreach ($albums as $album) { $result = pnModAPIFunc('lobby','albums','del',array('id' => $album['id'])); if (!$result) { return false; } } // delete index page $result = DBUtil::deleteObjectByID('lobby_pages',$id); // delete members $where = 'gid = '.$id; $result = DBUtil::deleteWhere('lobby_members',$where); if (!$result) { return LogUtil::registerError(_LOBBY_DELETION_MEMBER_FAILS); } // delete pending members $result = DBUtil::deleteWhere('lobby_members_pending',$where); if (!$result) { return LogUtil::registerError(_LOBBY_DELETION_MEMBER_PENDING_FAILS); } // delete moderators $result = DBUtil::deleteWhere('lobby_moderators',$where); if (!$result) { return LogUtil::registerError(_LOBBY_DELETION_MODERATORS_FAILS); } // delete group information itself $result = DBUtil::deleteObject($this->group,'lobby_groups'); if (!$result) { return LogUtil::registerError(_LOBBY_DELETION_GROUP_FAILS); } else { LogUtil::registerStatus(_LOBBY_GROUP_DELETED); return $render->pnFormRedirect(pnModURL('lobby','user','main')); } } // is there a coordinate? if (($obj['lng'] != '') && ($obj['lat'] != '')) { $coords = array( 'lng' => str_replace(',','.',$obj['lng']), 'lat' => str_replace(',','.',$obj['lat']) ); unset($obj['lng']); unset($obj['lat']); $obj['coordinates'] = serialize($coords); } else { $obj['coords'] = ''; } // store or update group if ($this->group['id'] > 0) { // update an existing group $upd = $this->group; $upd['boxes_shownews'] = $obj['boxes_shownews']; $upd['boxes_showforumlinks'] = $obj['boxes_showforumlinks']; $upd['boxes_showalbums'] = $obj['boxes_showalbums']; $upd['coordinates'] = $obj['coordinates']; $upd['description'] = $obj['description']; $upd['moderated'] = $obj['moderated']; $upd['indextopics'] = $obj['indextopics']; $upd['forumsvisible'] = $obj['forumsvisible']; if (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)){ $upd['category'] = $obj['category']; } $result = DBUtil::updateObject($upd,'lobby_groups'); if ($result) { LogUtil::registerStatus(_LOBBY_GROUP_UPDATED); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $upd['id']))); } else { LogUtil::registerError(_LOBBY_GROUP_UPDATE_ERROR); } } else { // a new group has to be created // is there already a groupt named like the new group? $count = DBUtil::selectObjectCount('lobby_groups','title LIKE \''.DataUtil::formatForStore($obj['title'])."'"); if ($count > 0) { LogUtil::registerError(_LOBBY_GROUP_ALREADY_EXISTS); return false; } $obj['date'] = date("Y-m-d H:i:s",time()); $obj['last_action'] = $obj['date']; $obj['uid'] = pnUserGetVar('uid'); // get category $category = pnModAPIFunc('lobby','categories','get',array('id' => $obj['category'])); if ($category['official'] == 1) { LogUtil::registerStatus(_LOBBY_GROUP_PENDING); } else { $obj['accepted'] = 1; } $result = DBUtil::insertObject($obj,'lobby_groups'); if ($result) { LogUtil::registerStatus(str_replace('%group%',$obj['title'],_LOBBY_GROUPS_ADDED)); } else { LogUtil::registerError(_LOBBY_GROUPS_ADDERROR); return false; } // statusmessage about the things that will go on now LogUtil::registerStatus(_LOBBY_GROUP_EDIT_INITPROCESS); // add the owner to the new group pnModAPIFunc('lobby','members','add',array('uid' => pnUserGetVar('uid'), 'gid' => $obj['id'])); // add owner as moderator pnModAPIFunc('lobby','moderators','add',array('uid' => pnUserGetVar('uid'), 'gid' => $obj['id'])); // add new forums to the group if ($obj['skeleton'] == 1) { $forums = array (); $forums[] = array ( 'public_status' => 2, 'title' => _LOBBY_FORUMTITLE_INTRODUCTION, 'description' => _LOBBY_FORUMTITLE_INTRODUCTION_DESC ); $forums[] = array ( 'public_status' => 1, 'title' => _LOBBY_FORUMTITLE_Q_AND_A, 'description' => _LOBBY_FORUMTITLE_Q_AND_A_DESC ); $forums[] = array ( 'public_status' => 1, 'title' => _LOBBY_FORUMTITLE_TALK, 'description' => _LOBBY_FORUMTITLE_TALK_DESC ); $forums[] = array ( 'public_status' => 2, 'title' => _LOBBY_FORUMTITLE_PRIVATE, 'description' => _LOBBY_FORUMTITLE_PRIVATE_DESC ); foreach ($forums as $forum) { pnModAPIFunc('lobby','forums','add',array('gid' => $obj['id'], 'title' => $forum['title'], 'description' => $forum['description'], 'public_status' => $forum['public_status'])); } } // send Mail Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_newgroup($obj); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $obj['id']))); } } return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ Loader::includeOnce('modules/lobby/includes/common_members.php'); class lobby_user_pluginHandler { var $uid; var $gid; var $moderator; function initialize(&$render) { $gid = (int)FormUtil::getPassedValue('id'); $uid = (int)FormUtil::getPassedValue('uid'); $this->gid = $gid; $this->uid = $uid; $moderator = pnModAPIFunc('lobby','moderators','isModerator',array('uid' => $this->uid, 'gid' => $this->gid)); if ($moderator) { $render->assign('moderator', 1); } else { $render->assign('moderator', 0); } // Get user $user = pnModAPIFunc('lobby','members','get',array('gid' => $this->gid, 'uid' => $this->uid)); if (!isset($user) || !is_array($user)) { LogUtil::registerError(_LOBBY_MEMBER_MANAGEMENT_GETERROR); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'membermanagement'))); } $render->assign($user); return true; } function handleCommand(&$render, &$args) { if ($args['commandName']=='update') { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_COMMENT)) return LogUtil::registerPermissionError(); // get the pnForm data and do a validation check $obj = $render->pnFormGetValues(); if (!$render->pnFormIsValid()) return false; $moderator = pnModAPIFunc('lobby','moderators','isModerator',array('uid' => $this->uid, 'gid' => $this->gid)); $isGroupOwner = pnModAPIFunc('lobby','groups','isOwner',array('id' => $this->gid, 'uid' => $this->uid)); // delete user? if ($obj['delete'] == 1) { if ($isGroupOwner) { LogUtil::registerError(_LOBBY_GROUP_OWNER_NODELETE); } else { if ($moderator) { pnModAPIFunc('lobby','moderators','del',array('gid' => $this->gid, 'uid' => $this->uid)); } $result = pnModAPIFunc('lobby','members','del',array('uid' => $this->uid, 'gid' => $this->gid)); if ($result) { LogUtil::registerStatus(_LOBBY_USER_DELETED.': '.pnUserGetVar($this->uid,'uname')); } } } else if (($obj['moderator'] == 1) && (!$moderator)) { pnModAPIFunc('lobby','moderators','add',array('gid' => $this->gid, 'uid' => $this->uid)); } else if (($obj['moderator'] != 1) && ($moderator)) { if (!$isGroupOwner) { // If person was a moderator delete moderator status! pnModAPIFunc('lobby','moderators','del',array('gid' => $this->gid, 'uid' => $this->uid)); } else { LogUtil::registerError(_LOBBY_GROUP_OWNER_NODELETE); } } else { // Otherwise say that we did nothing... LogUtil::registerStatus(_LOBBY_MEMBER_MANAGEMENT_NOCHANGE); } return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'membermanagement'))); } return true; } }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * bbsmile plugin * shows all available smilies * *@params textfieldid */ function smarty_function_bbsmile($params, &$smarty) { $out = ""; if(pnModAvailable('bbsmile') && pnModIsHooked('bbsmile', 'lobby')) { $out = pnModFunc('bbsmile', 'user', 'bbsmiles', array('textfieldid' => $params['textfieldid'])); } return $out; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * Check if a post is still editable * */ function lobby_editablePost($post) { $topic = pnModAPIFunc('lobby','forumtopics','get',array('id' => $post['tid'])); if (($post['id'] == $post['tid']) && ($topic['replies'] > 0)) { return false; } else { $tables = pnDBGetTables(); $column = $tables['lobby_forum_posts_column']; $where = $column['id']." > ".$post['id']." AND ".$post['tid']." = ".$column['tid']; $result = DBUtil::selectObjectCount('lobby_forum_posts',$where); if ($result == 0) { return true; } else { return false; } } }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { function initialize(&$render) { return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * the main user function * * @return output The main module page */ function lobby_admin_main() { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = pnRender::getInstance('lobby'); // Get pending categories $pending = pnModAPIFunc('lobby','groups','get',array('pending' => 1)); $render->assign('pending', $pending); // Return the output return $render->fetch('lobby_admin_main.htm'); } /** * pending groups management * * @return output The main module page */ function lobby_admin_pending() { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = pnRender::getInstance('lobby'); // Get Action $action = FormUtil::getPassedValue('action'); $id = (int)FormUtil::getPassedValue('id'); if (isset($action) && ($action == 'accept') && ($id > 0)) { $result = pnModAPIFunc('lobby','groups','accept',array('id' => $id)); if ($result) { // send Mail Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_groupaccepted($id); LogUtil::registerStatus(_LOBBY_GROUP_ACCEPTED); } else { LogUtil::registerError(_LOBBY_GROUP_ACCEPTED_ERROR); } return pnRedirect(pnModURL('lobby','admin','pending')); } // Get pending categories $pending = pnModAPIFunc('lobby','groups','get',array('pending' => 1)); $render->assign('pending', $pending); $authid = SecurityUtil::generateAuthKey(); $render->assign('authid', $authid); // Return the output return $render->fetch('lobby_admin_pending.htm'); } /** * the category management function * * @return output The main module page */ function lobby_admin_categories() { // load handler class Loader::requireOnce('modules/lobby/includes/classes/admin/categories.php'); // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = FormUtil::newpnForm('lobby'); // Return the output return $render->pnFormExecute('lobby_admin_categories.htm', new lobby_admin_categoriesHandler()); } /** * the category management function * * @return output The main module page */ function lobby_admin_settings() { // load handler class Loader::requireOnce('modules/lobby/includes/classes/admin/settings.php'); // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = FormUtil::newpnForm('lobby'); // Return the output return $render->pnFormExecute('lobby_admin_settings.htm', new lobby_admin_settingsHandler()); } /** * import groups, forums, etc. * * @return output The main module page */ function lobby_admin_import() { // load handler class Loader::requireOnce('modules/lobby/includes/classes/admin/import.php'); // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = FormUtil::newpnForm('lobby'); // Return the output return $render->pnFormExecute('lobby_admin_import.htm', new lobby_admin_importHandler()); } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * switch categories into form pulldown format * */ function lobby_categoriesToPullDown($categories) { $result = array(); foreach ($categories as $category) { if ($category['official'] == 1) { $category['title'].="*"; } $result[] = array ('text' => (string)$category['title'], 'value' => (int)$category['id']); } return $result; } /** * switch category into form pulldown format * */ function lobby_categoryToPullDown($category) { $result = array(); $result[] = array ('text' => (string)$category['title'], 'value' => (int)$category['id']); return $result; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ // general define('_LOBBY_YES', 'Ja'); define('_LOBBY_NO', 'Nein'); define('_LOBBY_BACKEND', 'Administration des Moduls "lobby"'); // Header define('_LOBBY_MAIN', 'Startseite Administration'); define('_LOBBY_PENDING_GROUPS', 'Gruppen freischalten'); define('_LOBBY_CATEGORY_MANAGEMENT', 'Kategorien verwalten'); define('_LOBBY_SETTINGS', 'Einstellungen'); define('_LOBBY_IMPORT', 'Import'); // main define('_LOBBY_AMDIN_TEXT', 'Willkommen auf den Administrationsseiten des Moduls. Hier können Gruppen freigeschalten werden, welche zur Bewerbung ausstehen, und alle weiteren Einstellungen lassen sich hier regeln.'); define('_LOBBY_AMDIN_PENDING_GROUPS', 'Anzahl wartender Gruppenfreischaltungen'); // import define('_LOBBY_IMPORT_MANAGEMENT', 'Importieren verschiedener Inhalte in das Modul'); define('_LOBBY_IMPORT_USERS', 'Benutzergruppen importieren'); define('_LOBBY_IMPORT_USERS_TEXT', 'Hier können Benutzergruppen aus dem Modul Groups importiert werden. Bitte hierzu die entsprechende Groups-Gruppe wählen, dann angeben, in welche Gruppe des Gruppenmoduls die Benutzerliste integriert werden soll. Änderungen werden dann sofort ausgeführt.'); define('_LOBBY_IMPORT_FORUMS', 'Foreninhalte importieren'); define('_LOBBY_IMPORT_FORUMS_TEXT', 'Hier können aus Dizkus-Foren Inhalte eingelesen und kopiert werden. Wichtig ist, dass das neue Forum, in welches Inhalte eingelesen werden sollen, eistiert. Einfach Dizus-Forum und dann Zielforum wählen und die Beiträge werden sofort eingelesen.'); define('_LOBBY_COPY_FROM', 'Kopiere von'); define('_LOBBY_COPY_TO', 'nach'); define('_LOBBY_SELECT_FOR_ACTION', 'auswählen für Import'); define('_LOBBY_NO_IMPORT_SELECTED', 'Kein Import ausgewählt. Ziel und Ausgangsgruppe /-forum muss jeweils gewählt werden!'); define('_LOBBY_IMPORT_SKIP_USER', 'Überspringe Benutzer, da bereits Mitglied in Zielgruppe'); define('_LOBBY_ADDED_USER', 'Füge Benutzer ein'); define('_LOBBY_IMPORTED_USERS', 'Erfolgreich importierte Benutzer'); define('_LOBBY_FAILED_USER', 'Fehler beim importieren von Benutzer'); define('_LOBBY_TOPIC_IMPORT_ERROR', 'Fehler beim Importieren eines Topics'); define('_LOBBY_TOPIC_IMPORTED', 'Thema importiert'); define('_LOBBY_POSTING_IMPORT_ERROR', 'Beim Importieren der zum Thema gehörenden Postings ist ein Fehler aufgetreten'); // categories define('_LOBBY_CATEGORY_OFFICIAL', 'Offizielle Kategorie'); define('_LOBBY_CATEGORY_MANAGEMENT', 'Kategorien bearbeiten'); define('_LOBBY_CATEGORY_TITLE', 'Titel der Kategorie'); define('_LOBBY_CATEGORY_UPDATE_STORE', 'Speichern / aktualisieren'); define('_LOBBY_CATEGORY_INSERTED', 'Kategorie wurde hinzugefügt'); define('_LOBBY_CATEGORY_STOREFAILURE', 'Beim Speichern der Kategorie ist ein Fehler aufgetreten'); define('_LOBBY_CATEGORY_UPDATED', 'Kategorie wurde aktualisiert'); define('_LOBBY_CATEGORY_OFFICIAL_EXPL', 'Offizielle Gruppen durchlaufen einen Moderationsprozess und müssen einmalig freigeschalten werden. Nicht-Offizielle sind sofort nach Anmelden aktiv!'); define('_LOBBY_CATEGORY_NOCATECORIES', 'Es sind noch keine Kategorien angelegt'); define('_LOBBY_CATEGORY_OVERVIEW', 'Übersicht über existierende Kategorien, zum Editieren anklicken'); define('_LOBBY_CATEGORY_DELETE', 'Diese Kategorie löschen - nur möglich, wenn diese (noch) nicht verwendet wird'); define('_LOBBY_CATEGORY_DELETEERROR', 'Beim Löschen der Kategorie ist ein Fehler aufgetreten'); define('_LOBBY_CATEGORY_DELETED', 'Die Kategorie wurde gelöscht'); // pending define('_LOBBY_PENDING_NO_PENDING', 'Keine zur Freischaltung ausstehenden Gruppen'); define('_LOBBY_GROUP_NAME', 'Bezeichnung'); define('_LOBBY_GROUP_AUTHOR', 'Gründer'); define('_LOBBY_GROUP_ DATE', 'Gründungsdatum'); define('_LOBBY_GROUP_CATEGORY', 'Kategorie'); define('_LOBBY_ACTION', 'Aktion'); define('_LOBBY_ACCEPT', 'freischalten'); define('_LOBBY_DELETE', 'löschen'); define('_LOBBY_GROUP_ACCEPTED', 'Gruppe wurde freigeschalten'); define('_LOBBY_GROUP_ACCEPTED_ERROR', 'Es ist ein Fehler beim Freischalten der Gruppe aufgetreten'); // settings define('_LOBBY_CREATE_GROUP_URL', 'URL, auf welche beim "Gruppe erstellen"-Link weitergeleitet werden soll'); define('_LOBBY_CREATE_GROUP_URL_TEXT', 'Wird hier kein Wert eingetragen, gelangen die Benutzer beim Klick auf "neue Gruppe erstellen" sofort zum Formular dafür. Wenn eine Seite dazwischengeschalten werden soll, welche angezeigt wird, kann diese hier angegeben werden. Auf dieser Seite können dann Erklärungen etc. vorhanden sein. Es muss dazu ein Link zu folgender URL vorhanden sein, denn unter dieser URL können Benutzer Gruppen registrieren'); define('_LOBBY_SETTINGS_MANAGEMENT', 'Verwalten der Haupteinstellungen'); define('_LOBBY_TOPICS_PER_PAGE', 'Anzuzeigende Forenthemen pro Übersichtsseite'); define('_LOBBY_POSTS_PER_PAGE', 'Anzuzeigende Postings pro Übersichtsseite bei Ansicht eines Forenthemas'); define('_LOBBY_NEWS_PER_PAGE', 'News pro Seite bei Ansicht der Neuigkeiten-Übersicht'); define('_LOBBY_SETTINGS_UPDATE', 'Einstellungen speichern'); define('_LOBBBY_SETTINGS_STORED', 'Einstellungen wurden gespeichert');<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * on Load function * * @return void */ function lobby_myprofileapi_onLoad() { return true; } /** * This function returns 1 if Ajax should not be used loading the plugin * * @return string */ function lobby_myprofileapi_noAjax($args) { return true; } /** * This function returns the name of the tab * * @return string */ function lobby_myprofileapi_getTitle($args) { $uid = (int)FormUtil::getPassedValue('uid'); $memberships = pnModAPIFunc('lobby','members','getMemberships',array('uid' => $uid)); $counter = count($memberships); if ($counter > 0) { pnModLangLoad('lobby','myprofile'); return _LOBBY_TABTITLE; } else { return false; } } /** * This function returns additional options that should be added to the plugin url * * @return string */ function lobby_myprofileapi_getURLAddOn($args) { return ''; } /** * This function shows the content of the main MyProfile tab * * @return output */ function lobby_myprofileapi_tab($args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_OVERVIEW)) return LogUtil::registerPermissionError(); // Load lang defines pnModLangLoad('lobby','myprofile'); // Get parameter $uid = FormUtil::getPassedValue('uid'); if (!isset($uid) || (!($uid>0))) { logUtil::registerError(_LOBBY_NOUSERSPECIFIED); return pnRedirect(pnModURL('lobby','user','main')); } // Get groups $memberships = pnModAPIFunc('lobby','members','getMemberships',array('uid' => $uid)); $groups = array(); foreach ($memberships as $ms) { $group = pnModAPIFunc('lobby','groups','get',array('id' => $ms)); $status = pnModAPIFunc('lobby','groups','getMemberStatus',array('uid' => $uid, 'group' => $group)); if ($status == 2) { $group['owner'] = 1; } else { $isMod = pnModAPIFunc('lobby','moderator','isModerator',array('gid' => $group['id'], 'uid' => $uid)); if ($isMod) { $group['moderator'] = 1; } } $groups[] = $group; } // Get render instance $render = pnRender::getInstance('lobby'); // Assign variales $render->assign('uname', pnUserGetVar('uname',$uid)); $render->assign('groups', $groups); // Get output $output = $render->fetch('lobby_myprofile_tab.htm'); return $output; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get members of a group * * $args['uid'] int user id (optional) * $args['gid'] int group id * $args['count'] int optional == 1 only counting * $args['pending'] int optional == 1 show pending members * $args['online'] int optional == 1 only users that are online now * $args['offset'] int optional * $args['numrows'] int optional * $args['showall'] int optional ==1 if all groups should be used (index page e.g.) * $args['groupinformation'] int optional ==1 if group information should be added to result * $args['sort'] string sort criteria * @return array */ function lobby_membersapi_get($args) { // Get Tables $tables = pnDBGetTables(); $pending = (int)$args['pending']; if ($pending == 1) { $column = $tables['lobby_members_pending_column']; $table = 'lobby_members_pending'; } else { $column = $tables['lobby_members_column']; $table = 'lobby_members'; } // Get Parameters $uid = (int)$args['uid']; $gid = (int)$args['gid']; $count = (int)$args['count']; $showall = (int)$args['showall']; $online = (int)$args['online']; $groupinformation = (int)$args['groupinformation']; if (!($gid > 0) && ($showall != 1)) { // LogUtil::registerError(_LOBBY_GROUP_GETMEMBERS_PARAMFAILURE); return false; } else { // Cache function static $lobbyCacheMembers; $varName = "x"; if ($pending == 1) $varName.= "p"; if ($count == 1) $varName.= "c"; if ($uid > 1) $varName.="u".$uid."u"; if ($showall == 1) $varName.="s"; if ($online == 1) $varName.="o"; if ($groupinformation = 1) $varName.="g"; if (isset($lobbyCacheMembers)) { if (isset($lobbyCacheMembers[$varName])) { return $lobbyCacheMembers[$varName]; } } // Start to build sql statement if ($showall == 0) $where = $column['gid']." = ".$gid.""; if ($uid > 1) { $where.=" AND tbl.".$column['uid']." = ".$uid; } $users_column = $tables['users_column']; $joinInfo[] = array ( 'join_table' => 'users', // table for the join 'join_field' => 'uname', // field in the join table that should be in the result with 'object_field_name' => 'uname', // ...this name for the new column 'compare_field_table' => 'uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table if ($groupinformation == 1) { $joinInfo[] = array ( 'join_table' => 'lobby_groups', // table for the join 'join_field' => array('title','description','members','articles','forums','topics','postings','moderated','accepted','last_action','category','coordinates'), // field in the join table that should be in the result with 'object_field_name' => array('title','description','members','articles','forums','topics','postings','moderated','accepted','last_action','category','coordinates'), // ...this name for the new column 'compare_field_table' => 'gid', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table } // online (optional) if ($online == 1) { $idletime = (pnConfigGetVar('secinactivemins') * 60); // join information because we need the join to the sessions table $joinInfo[] = array ( 'join_table' => 'session_info', // table for the join 'join_field' => 'lastused', // field in the join table that should be in the result with 'object_field_name' => 'session_uid', // ...this name for the new column 'compare_field_table' => 'uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table $sess_column = &$tables['session_info_column']; $where.= " AND ".$sess_column['lastused']." > '".date("Y-m-d H:i:s",(time()-$idletime))."'"; } if (($count == 1) && ($online != 1)) { $result = DBUtil::selectObjectCount($table,$where); } elseif (($count == 1) && ($online != 1)) { $result = DBUtil::selectExpandedObjectCount($table,$joinInfo,$where); } else { $offset = $args['offset']; $numrows = $args['numrows']; $sort = $args['sort']; if ($sort == 'latest') { $orderby = "tbl.".$column['id']." DESC"; } else { $orderby = "a.".$users_column['uname']." ASC"; } $result = DBUtil::selectExpandedObjectArray($table,$joinInfo,$where,$orderby,$offset,$numrows); if ($uid > 1) { $result = $result[0]; } } } // Cache result $lobbyCacheMembers[$varName] = $result; // return result return $result; } /** * add a user to a group * * @args['uid'] int user id * @args['gid'] int group id * @args['text'] string request text * @return boolean */ function lobby_membersapi_add($args) { $uid = (int)$args['uid']; $gid = (int)$args['gid']; $text = $args['text']; if (!($uid > 1) || !($gid > 0)) { LogUtil::registerError(_LOBBY_GROUP_ADDMEMBER_FAILURE); return false; } else { // get Group $group = pnModAPIFunc('lobby','groups','get',array('id' => $gid)); $groupOwner = (($group['uid'] == pnUserGetVar('uid')) || (SecurityUtil::checkPermission('lobby::'.$id, '::', ACCESS_ADMIN))); if ($group['id'] != $gid) { // Something went wrong, groups not existent or something like that LogUtil::registerError(_LOBBY_GROUP_ADDMEMBER_FAILURE); return false; } else { $obj = array( 'gid' => $gid, 'uid' => $uid, 'text' => $text, 'date' => date("Y-m-d H:i:s",time()) ); if (($group['moderated'] == 1) && ($group['uid'] != $uid)) { // is the member already member or pending? $table = pnDBGetTables(); $column_pending = $table['lobby_members_pending_column']; $column_members = $table['lobby_members_column']; $where_pending = $column_pending['uid']." = ".$uid." AND ".$column_pending['gid']." = ".$gid; $where_members = $column_members['uid']." = ".$uid." AND ".$column_members['gid']." = ".$gid; $pending_count = (int)DBUtil::selectObjectCount('lobby_members_pending',$where_pending); $members_count = (int)DBUtil::selectObjectCount('lobby_members',$where_members); if ($pending_count > 0) { // if the call was done by the group owner we will move the contact from pending status if ($groupOwner) { // get object, add it into member table and delete delte it from pending table $pending = DBUtil::selectObject('lobby_members_pending',$where_pending); $result = DBUtil::deleteObject($pending,'lobby_members_pending'); if (!$result) { return LogUtil::registerError('_LOBBY_GROUP_PENDING_ACCEPT_ERROR'); } if ($members_count == 0) { if (!$result) { return LogUtil::registerError('_LOBBY_GROUP_PENDING_ACCEPT_ERROR'); } } else { return LogUtil::registerError(_LOBBY_GROUP_ADD_ALREDY_MEMBER); } } else { return LogUtil::registerError(_LOBBY_GROUP_ADD_ALREDY_PENDING); } } else if ($members_count > 0) { return LogUtil::registerError(_LOBBY_GROUP_ADD_ALREDY_MEMBER); } else { $result = DBUtil::insertObject($obj,'lobby_members_pending'); if ($result) { return LogUtil::registerStatus(_LOBBY_GROUP_REQUESTSENT); } else { return LogUtil::registerError(_LOBBY_GROUP_JOINERROR); } } } // Insert Member now into database $result = DBUtil::insertObject($obj,'lobby_members'); // Set message if ($result) { LogUtil::registerStatus(str_replace('%member%',pnUserGetVar('uname', $uid),_LOBBY_GROUPS_MEMBERADDED)); } else { LogUtil::registerError(_LOBBY_GROUPS_ADDERROR); } // Send an Email to the user that was added if ($group['uid'] == $uid) { // ToDo: Email schicken "wurde hinzugefügt" } } } } /** * reject a user's request to be added to a group * * @args['uid'] int user id * @args['group'] object group * @return boolean */ function lobby_membersapi_reject($args) { $uid = (int)$args['uid']; $group = $args['group']; $gid = (int)$group['id']; if (!($uid > 1) || !($gid > 0)) { LogUtil::registerError(_LOBBY_GROUP_REJECT_MEMBER_FAILURE); return false; } else { // get Group $table = pnDBGetTables(); $column = $table['lobby_members_pending_column']; $where = $column['uid']." = ".$uid." AND ".$column['gid']." = ".$gid; $result = DBUtil::selectObjectArray('lobby_members_pending',$where); $obj = $result[0]; $result = DBUtil::deleteObject($obj,'lobby_members_pending'); if ($result) { LogUtil::registerStatus(_LOBBY_MEMBERSHIP_REQUEST_REJECTED); // send Mail Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_rejectmembershiprequest($group,$uid); return true; } else { LogUtil::registerError(_LOBBY_MEMBERSHIP_REJECT_ERROR); return false; } } } /** * reject a user's request to be added to a group * * @args['uid'] int user id * @args['gid'] int group id * @return boolean */ function lobby_membersapi_del($args) { prayer($args); $uid = (int)$args['uid']; $gid = (int)$args['gid']; if (!(($uid > 1) && ($gid > 0))) { LogUtil::registerError(_LOBBY_GROUP_DELETE_MEMBER_FAILURE); return false; } else { // Is the user a member of this group? $isMember = pnModAPIFunc('lobby','groups','isMember',array('uid' => $uid, 'gid' => $gid)); $group = pnModAPIFunc('lobby','group','get',array('id' => $gid)); $isOwner = ($group['uid'] == $uid); if (!$isMember) { LogUtil::registerError(_LOBBY_USER_NOT_A_MEMBER); return false; } else if ($isOwner) { LogUtil::registerError(_LOBBY_USER_IS_OWNER); return false; } else { $table = pnDBGetTables(); $column = $table['lobby_members_column']; $where = $column['uid']." = ".$uid." AND ".$column['gid']." = ".$gid; return DBUtil::deleteWhere('lobby_members',$where); } } } /** * get the memberships of a user * * $args['uid'] int user id * @return array */ function lobby_membersapi_getMemberships($args) { $uid = (int)$args['uid']; if ($uid == 0) { return false; } else { $tables = pnDBGetTables(); $column = $tables['lobby_members_column']; $where = $column['uid']." = '".$uid."'"; $result = DBUtil::selectObjectArray('lobby_members',$where); $r = array(); foreach ($result as $item) { $r[]=$item['gid']; } return $r; } }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get index page of a group * * @args['gid'] int group id (optional) * @return array */ function lobby_pagesapi_get($args) { $id = (int)$args['gid']; $result = DBUtil::selectObjectByID('lobby_pages',$id); if (isset($result['text']) && ($result['text'] != '')) return $result['text']; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * function sets subscription status * * $args['fid'] int forum id * $args['tid'] int topic id * $args['uid'] int user id * @return boolean */ function lobby_subscriptionsapi_set($args) { $fid = (int)$args['fid']; $tid = (int)$args['tid']; $uid = (int)$args['uid']; $forum = pnModAPIFunc('lobby','forums','get',array('id' => $fid)); $group = pnModAPIFunc('lobby','groups','get',array('id' => $forum['gid'])); $memberstatus = pnModAPIFunc('lobby','groups','getMemberStatus',array('group' => $group, 'uid' => $uid)); // Check if user is in the group if a private forum is selected if ( ($forum['public_status'] == 2) && ($memberstatus < 1) ) { LogUtil::registerError(_LOBBY_FORUM_NO_PERMISSION); return false; } if ($fid > 0) { $is = lobby_subscriptionsapi_get($args); if (!$is) { $obj = array ( 'fid' => $fid, 'uid' => $uid ); $result = DBUtil::insertObject($obj,'lobby_forum_subscriptions'); if ($result) { LogUtil::registerStatus(_LOBBY_FORUM_SUBSCRIBED_NOW); } else { LogUtil::registerError(_LOBBY_FORUM_SUBSCRIBE_ERROR); } } else { LogUtil::registerStatus(_LOBBY_FORUM_ALREADY_SUBSCRIBED); } } else if ($tid > 0) { $is = lobby_subscriptionsapi_get($args); if (!$is) { $obj = array ( 'tid' => $tid, 'uid' => $uid ); $result = DBUtil::insertObject($obj,'lobby_forum_topic_subscriptions'); if ($result) { LogUtil::registerStatus(_LOBBY_TOPIC_SUBSCRIBED_NOW); } else { LogUtil::registerError(_LOBBY_TOPIC_SUBSCRIBE_ERROR); } } else { LogUtil::registerStatus(_LOBBY_TOPIC_ALREADY_SUBSCRIBED); } } else { // wrong parameters return false; } } /** * function gets subscription status * * $args['fid'] int forum id * $args['tid'] int topic id * $args['uid'] int user id * @return boolean */ function lobby_subscriptionsapi_get($args) { $fid = (int)$args['fid']; $tid = (int)$args['tid']; $uid = (int)$args['uid']; $tables = pnDBGetTables(); $column_forums = $tables['lobby_forum_subscriptions_column']; $column_topics = $tables['lobby_forum_topic_subscriptions_column']; $column_members = $tables['lobby_members_column']; $table_members = $tables['lobby_members']; // Information for security check: // public_status from forum: // 0 = all, 1 = registered users, 2 = members of group. if ($tid > 0) { $whereArray = array(); // get topic for security check // get topic $topic = pnModAPIFunc('lobby','forumtopics','get',array('id' => $tid)); // get forum and its pubic_status $forum = pnModAPIFunc('lobby','forums','get',array('id' => $topic['fid'])); // get information if user is member of group or not if ($forum['public_status'] > 1) { $whereArray[] = $column_topics['uid']." IN (SELECT ".$column_members['uid']." FROM ".$table_members." WHERE ".$column_members['gid']." = ".$forum['gid'].")"; } // subscribe topic if ($uid > 1) { $whereArray[] = $column_topics['uid']." = ".$uid; } $whereArray[] = $column_topics['tid']." = ".$tid; $where = implode(' AND ',$whereArray); if (($uid > 1) && ($tid > 0)) { $result = DBUtil::selectObjectCount('lobby_forum_topic_subscriptions',$where); if ($result != 0) { return true; } else { return false; } } else { $result = DBUtil::selectObjectArray('lobby_forum_topic_subscriptions',$where); return $result; } } else if ($fid > 0){ // forum $whereArray = array(); // get topic for security check // get forum and its pubic_status $forum = pnModAPIFunc('lobby','forums','get',array('id' => $fid,'showall' => 1)); // get information if user is member of group or not if ($forum['public_status'] > 1) { $whereArray[] = $column_topics['uid']." IN (SELECT ".$column_members['uid']." FROM ".$table_members." WHERE ".$column_members['gid']." = ".$forum['gid'].")"; } if ($uid > 1) { $whereArray[] = $column_forums['uid']." = ".$uid; } $whereArray[] = $column_forums['fid']." = ".$fid; $where = implode(' AND ',$whereArray); if (($uid > 1) && ($fid > 0)) { $result = DBUtil::selectObjectCount('lobby_forum_subscriptions',$where); if ($result != 0) { return true; } else { return false; } } else { $result = DBUtil::selectObjectArray('lobby_forum_subscriptions',$where); return $result; } } else { // parameters wrong? return false; } } /** * function deletes subscription * * $args['fid'] int forum id * $args['tid'] int topic id * $args['uid'] int user id * @return boolean */ function lobby_subscriptionsapi_del($args) { $fid = (int)$args['fid']; $tid = (int)$args['tid']; $uid = (int)$args['uid']; if ($uid == 0) { $uid = pnUserGetVar('uid'); } $tables = pnDBGetTables(); $column_forums = $tables['lobby_forum_subscriptions_column']; $column_topics = $tables['lobby_forum_topic_subscriptions_column']; if ($tid > 0) { // topic $where = $column_topics['uid']." = ".$uid." AND ".$column_topics['tid']." = ".$tid; $result = DBUtil::selectObjectArray('lobby_forum_topic_subscriptions',$where); if (!$result) { return false; } else { $obj=$result[0]; $result = DBUtil::deleteObject($obj,'lobby_forum_topic_subscriptions'); if ($result) { LogUtil::registerStatus(_LOBBY_TOPIC_UNSUBSCRIBED_NOW); } else { LogUtil::registerError(_LOBBY_TOPIC_UNSUBSCRIBE_ERROR); } } } else if ($fid > 0){ // forum $where = $column_forums['uid']." = ".$uid." AND ".$column_forums['fid']." = ".$fid; $result = DBUtil::selectObjectArray('lobby_forum_subscriptions',$where); if (!$result) { return false; } else { $obj=$result[0]; $result = DBUtil::deleteObject($obj,'lobby_forum_subscriptions'); if ($result) { LogUtil::registerStatus(_LOBBY_FORUM_UNSUBSCRIBED_NOW); } else { LogUtil::registerError(_LOBBY_FORUM_UNSUBSCRIBE_ERROR); } } } else { // parameters wrong? return false; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get albums * * @args['gid'] int group id * @args['id'] int album id * @args['showall'] int optional, ==1 show all not considering permissions * * @return int or boolean */ function lobby_albumsapi_get($args) { $id = (int)$args['id']; $gid = (int)$args['gid']; $showall = (int)$args['showall']; $tables = pnDBGetTables(); $column = $tables['lobby_albums_column']; $where = array(); if (!($gid > 0)) { // get album and group id to check ownership later... $result = DBUtil::selectObjectByID('lobby_albums',$id); $gid = $result['gid']; } if ($gid > 0) $where[] = "tbl.".$column['gid']." = ".$gid; if ($id > 0) $where[] = "tbl.".$column['id']." = ".$id; if (($showall == 1) || (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN))) { $mystatus = 2; } else { if (!pnUserLoggedIn()) { $mystatus = 0; } else { if ($gid > 0) { $groupstatus = pnModAPIFunc('lobby','groups','isMember',array('uid' => pnUserGetVar('uid'), 'gid' => $gid)); if ($groupstatus > 0) { $mystatus = 2; } else { $mystatus = 1; } } else { // Todo: Check here if user making this call is member of the group // ... // till then: easy way! $mystatus = 1; // no access for internal group albums } } } $where[] = "tbl.".$column['public_status']." <= ".$mystatus; $wherestring = implode(' AND ',$where); $orderby = $column['date']." DESC"; $result = DBUtil::selectObjectArray('lobby_albums',$wherestring,$orderby); if ($id > 0) { // add fotos to album $orderby = 'date DESC'; $where = 'aid = '.$id; $pictures = DBUtil::selectObjectArray('lobby_albums_pictures',$where,$orderby); foreach ($pictures as $item) { $picture = pnModAPIFunc('UserPictures','user','get',array('id' => $item['pid'])); if ($picture[0]['id'] > 0) { $content[] = $picture[0]; } } $result[0]['pictures'] = $content; $resultObject = $result; } else { // add index foto to each album $resultList = array(); foreach ($result as $item) { $where = 'aid = '.$item['id']; $albumpictures = DBUtil::selectObjectArray('lobby_albums_pictures',$where,$orderby,-1,1); $coverId = (int)$albumpictures[0]['pid']; if ($coverId > 0) { $picture = pnModAPIFunc('UserPictures','user','get',array('id' => $coverId)); if ($picture[0]['id'] > 0) { $item['cover'] = $picture[0]; } } $resultList[]=$item; } $resultObject = $resultList; } return $resultObject; } /** * add a new album * * This function adds a new forum into the database * * @args['gid'] int * @args['id'] int * @args['title'] string * @args['description'] string * @args['public_status'] string * * @return boolean */ function lobby_albumsapi_add($args) { $obj['gid'] = (int)$args['gid']; if (!($obj['gid']) > 0) { LogUtil::registerError(_LOBBY_ALBUMM_CREATION_ERROR); return false; } if (!isset($args['date']) || ($args['date'] == null) || ($args['date'] == '')) { $obj['date'] = date("Y-m-d H:i:s",time()); } else { $obj['date'] = $args['date']; } $obj['title'] = $args['title']; $obj['description'] = $args['description']; $obj['public_status'] = $args['public_status']; $result = DBUtil::insertObject($obj,'lobby_albums'); if ($result > 0) { LogUtil::registerStatus(_LOBBY_ALBUM_CREATED); return $result; } else { LogUtil::registerError(_LOBBY_ALBUM_CREATION_ERROR); return false; } } /** * delete a album * * $args['id'] int album id * @return booleam */ function lobby_albumsapi_del($args) { $id = (int)$args['id']; if (!($id > 0)) { return false; } else { // albums $where = 'aid = '.$id; $result = DBUtil::deleteWhere('lobby_albums_pictures',$where); if ($result) { $where = 'id = '.$id; $result = DBUtil::deleteWhere('lobby_albums',$where); } return $result; } } /** * add a picture to a album * * $args['aid'] int album id * $args['pid'] int userpicture picture id * @return boolean */ function lobby_albumsapi_addPicture($args) { $aid = (int)$args['aid']; $pid = (int)$args['pid']; $uid = pnUserGetVar('uid'); if (!($aid > 0) || !($pid > 0)) { return false; } // Load Group $album = lobby_albumsapi_get(array('id' => $aid)); $album = $album[0]; // if (pnusergetvar('uid') == 26351) prayer($album); if (!$album) { return false; } $group = pnModAPIFunc('lobby','groups','get',array('id' => $album['gid'])); // prayer($group); if (!$group) { return false; } // Check permission $memberStatus = pnModAPIFunc('lobby','groups','getMemberStatus',array('group' => $group, 'uid' => $uid)); if (!($memberStatus > 0)) { return false; } // Add Picture (if picture is not already added) $where = "aid = $aid and pid = $pid"; $result = (int)DBUtil::selectObjectCount('lobby_albums_pictures',$where); if ($result > 0) { LogUtil::registerError(_LOBBY_PICTURE_ALREADY_EXISTS); return false; } // get Picture and check ownership $picture = pnModAPIFunc('UserPictures','user','get',array('id' => $pid)); if ($picture[0]['uid'] != $uid) { return false; } // Add picture now $obj = array( 'date' => date("Y-m-d H:i:s",time()), 'aid' => $aid, 'pid' => $pid ); $result = DBUtil::insertObject($obj,'lobby_albums_pictures'); return $result; } /** * delete a picture to a album * * $args['aid'] int album id * $args['pid'] int userpicture picture id * @return boolean */ function lobby_albumsapi_delPicture($args) { $aid = (int)$args['aid']; $pid = (int)$args['pid']; $uid = pnUserGetVar('uid'); if (!($aid > 0) || !($pid > 0)) { return false; } // Load Group $album = lobby_albumsapi_get(array('id' => $aid)); if (!$album) { return false; } $album=$album[0]; $group = pnModAPIFunc('lobby','groups','get',array('id' => $album['gid'])); if (!$group) { return false; } // Check permission $memberStatus = pnModAPIFunc('lobby','groups','getMemberStatus',array('group' => $group, 'uid' => $uid)); if (!($memberStatus > 0)) { return false; } // Delete Picture if picture_uid = $uid or admin... $where = "aid = $aid and pid = $pid"; if ($memberStatus < 2) { // we need to check id picture id belongs to user $picture = pnModAPIFunc('UserPictures','user','get',array('id' => $pid)); if ((int)$picture[0]['uid'] != $uid) { LogUtil::registerError(_LOBBY_NO_PERM_TO_DEL_PICTURE); return false; } } $result = (int)DBUtil::deleteWhere('lobby_albums_pictures',$where); return $result; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ define('_LOBBY_GROUP_NEWS_ALL', 'News of all groups'); define('_LOBBY_GROUP_NEWS_AL_TEXT', 'Integration of the group\'s news. Parameters: category=CATEGORYID for a category filter.'); define('_LOBBY_NO_NEW_ARTICLES', 'No new news found'); define('_LOBBY_FROM_GROUP', 'in group'); define('_LOBBY_READ_ARTICLE', 'Read article'); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { var $id; var $gid; function initialize(&$render) { $gid = (int)FormUtil::getPassedValue('id'); $aid = (int)FormUtil::getPassedValue('aid'); $delete = (int)FormUtil::getPassedValue('delete'); $this->gid = $gid; pnModLangLoad('UserPictures'); // Load albums $albums = pnModAPIFunc('lobby','albums','get',array('gid' => $this->gid)); $render->assign('albums', $albums); // Check edit mode and get own pictures if needed $editmode = (int)FormUtil::getPassedValue('editmode'); // Add a picture if pid is given $pid = (int)FormUtil::getPassedValue('pid'); if ($pid > 0) { if ($delete == 1) { $result = pnModAPIFunc('lobby','albums','delPicture',array('aid' => $aid, 'pid' => $pid)); if ($result) { LogUtil::registerStatus(_LOBBY_PICTURE_DELETED); } else { LogUtil::registerStatus(_LOBBY_PICTURE_DEL_ERROR); } } else { $result = pnModAPIFunc('lobby','albums','addPicture',array('aid' => $aid, 'pid' => $pid)); if ($result) { LogUtil::registerStatus(_LOBBY_PICTURE_ADDED); } else { LogUtil::registerStatus(_LOBBY_PICTURE_ADD_ERROR); } } } // Handle editmode and get own pictures id needed $render->assign('editmode', $editmode); if ($editmode == 1) { $pictures = pnModAPIFunc('UserPictures','user','get',array('uid' => pnUserGetVar('uid'), 'template_id' => 0)); $render->assign('ownPictures', $pictures); } // Load album if id is set if ($aid > 0) { $album = pnModAPIFunc('lobby','albums','get',array('id' => $aid)); $this->album = $album[0]; $render->assign($this->album); } // Add style sheet PageUtil::addVar('stylesheet',ThemeUtil::getModuleStylesheet('UserPictures')); return true; } } <file_sep><?php /* * get plugins with type / title * * @param $args['id'] int optional, show specific one or all otherwise * @return array */ function lobby_mailzapi_getPlugins($args) { // Load language definitions pnModLangLoad('lobby','mailz'); $plugins = array(); // Add first plugin.. You can add more using more arrays $plugins[] = array( 'pluginid' => 1, // internal id for this module 'title' => _LOBBY_GROUP_NEWS_ALL, 'description' => _LOBBY_GROUP_NEWS_AL_TEXT, 'module' => 'lobby' ); return $plugins; } /* * get content for plugins * * @param $args['pluginid'] int id number of plugin (internal id for this module, see getPlugins method) * @param $args['params'] string optional, show specific one or all otherwise * @param $args['uid'] int optional, user id for user specific content * @param $args['contenttype'] string h or t for html or text * @param $args['last'] datetime timtestamp of last newsletter * @return array */ function lobby_mailzapi_getContent($args) { // Load language definitions pnModLangLoad('lobby','mailz'); switch ($args['pluginid']) { case 1: // All news from all groups () $since = '2009-08-26'; // Get params $cat = (int) $args['params']['category']; if ($cat > 0) { $catFilter = $cat; } $allNews = pnModAPIFunc('lobby','news','get',array('since' => $since, 'catfilter' => $catFilter)); if ($args['contenttype'] == 't') { // Text plugin $output.="\n"; foreach ($allNews as $news) { $output.=$news['title']." (".$news['group_title']."):\n"; $output.=pnGetBaseURL().pnModURL('lobby','user','group',array('id' => $news['gid'], 'do' => "news", 'story' => $news['id']))."\n\n"; } } else { // Html plugin $render = pnRender::getInstance('lobby'); $render->assign('allNews', $allNews); $output = $render->fetch('lobby_mailz_allnews.htm'); } return $output; break; default: return 'wrong plugin id given'; } // return emtpy string because we do not need anything to display in here... return ''; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { var $id; var $gid; function initialize(&$render) { $gid = (int)FormUtil::getPassedValue('id'); $this->gid = $gid; // Load article if id is set $story = (int)FormUtil::getPassedValue('story'); if ($story > 0) { $this->id = $story; $article = pnModAPIFunc('lobby','news','get',array('id' => $this->id, 'gid' => $gid, 'infuture' => 1)); $article['articletext'] = $article['text']; $render->assign($article); } $public_status_items = array ( array('text' => _LOBBY_ALL, 'value' => 0), array('text' => _LOBBY_SITEMEMBERS, 'value' => 1), array('text' => _LOBBY_GROUPMEMBERS, 'value' => 2) ); $render->assign('public_status_items', $public_status_items); if (!($this->id > 0)) { // Add initial date $initDate = date("Y-m-d H:i",time()); $render->assign('date',$initDate); } return true; } function handleCommand(&$render, &$args) { if ($args['commandName']=='update') { // get the form data and do a validation check $obj = $render->pnFormGetValues(); $obj['uid'] = pnUserGetVar('uid'); $obj['gid'] = $this->gid; $obj['text']= $obj['articletext']; $obj['date'] = DateUtil::transformInternalDate(DateUtil::parseUIDate($obj['date'])); // preview mode? if ($obj['preview'] == 1) { LogUtil::registerStatus(_LOBBY_NEWS_ARTICLEPREVIEW); $render->assign('preview', 1); $render->assign('title', $obj['title']); $render->assign('text', $obj['text']); $render->assign('date', $obj['date']); $render->assign('uid', $obj['uid']); } else { if (!$render->pnFormIsValid()) return false; // store or update group if ($this->id > 0) { $obj['id'] = $this->id; // Is there an action to be done? if ($obj['delete'] == 1) { $result = DBUtil::deleteObject($obj,'lobby_news'); if ($result) { LogUtil::registerStatus(_LOBBY_NEWS_DELETED); // Update group information Loader::includeOnce('modules/lobby/includes/common_groups.php'); lobby_groupsync($this->id); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'sync' => 1, 'do' => "news"))); } else { LogUtil::registerError(_LOBBY_NEWS_UPDATEERROR); } } else { // update an existing article $result = DBUtil::updateObject($obj,'lobby_news'); if ($result) { LogUtil::registerStatus(_LOBBY_NEWS_UPDATED); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'news', 'story' => $obj['id']))); } else { LogUtil::registerError(_LOBBY_NEWS_UPDATEERROR); return false; } } } else { // add new article $result = DBUtil::insertObject($obj,'lobby_news'); if ($result) { LogUtil::registerStatus(_LOBBY_NEWS_CREATED); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'sync' => 1, 'do' => 'news', 'story' => $obj['id']))); } else { LogUtil::registerError(_LOBBY_NEWS_CREATIONERROR); return false; } } } } return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * Smarty modifier to create a link to a topic * * Available parameters: * Example * * <!--[$uid|userlink uname=$uname]--> * * @param array $string the contents to transform * @return string the modified output */ function smarty_function_userlink($params, &$smarty) { $uid = $params['uid']; $uname = $params['uname']; $float = $params['float']; $backgroundcolor = $params['backgroundcolor']; // at least we need a user id if(!isset($uid)) { return ''; } if (!isset($float)) { $float = 'left'; } // get user's avatar $avatar = pnUserGetVar('_YOURAVATAR',$uid); if (($avatar != '') && ($avatar != 'blank.gif')) { $avatar = pnGetBaseURL().'images/avatar/'.$avatar; } else { $avatar = pnGetBaseURL().'images/icons/large/mac.gif'; } // username given as parameter? if (!isset($uname) || ($uname == '')) { $uname = pnUserGetVar('uname',$uid); } // get static variables to create unique number for THIS plugin call static $lobby_unique_counter; // count... if (!($lobby_unique_counter > 0)) { $lobby_unique_counter = 1; } else { $lobby_unique_counter++; } // return unique value for this modifier call... $number = $lobby_unique_counter; // create output $render = pnRender::getInstance('lobby'); // assign variables $render->assign('avatar', $avatar); $render->assign('uname', $uname); $render->assign('number', $number); $render->assign('uid', $uid); $render->assign('float', $float); if (isset($backgroundcolor) && (strlen($backgroundcolor) > 0)) { $backgroundcolor = "background-color: ".$backgroundcolor.";"; $render->assign('backgroundcolor', $backgroundcolor); } // return created output return $render->fetch('lobby_plugins_userlink.htm'); } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * bbcode plugin * shows all available bbcode tags * *@params $params $images boolean if true then show images instead of text links *@params $params $textfieldid string id of the textfield to update */ function smarty_function_plainbbcode($params, &$smarty) { extract($params); $out = ""; if(isset($params['textfieldid']) && !empty($params['textfieldid'])) { if(pnModAvailable('bbcode') && pnModIsHooked('bbcode', 'lobby')) { $out = pnModFunc('bbcode', 'user', 'bbcodes', $params); } } return $out; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * switch memnbers into form pulldown format * */ function lobby_groupsync($id) { // Check parameter $id = (int)$id; if (!($id > 0)) { return false; } // get group object without caching $group = DBUtil::selectObjectByID('lobby_groups',$id,'id',null,null,null,false,null); // sync members $group['members'] = (int)DBUtil::selectObjectCountByID('lobby_members',$id,'gid'); // sync albums $group['albums'] = (int)DBUtil::selectObjectCountByID('lobby_albums',$id,'gid'); // sync articles $group['articles'] = (int)DBUtil::selectObjectCountByID('lobby_news',$id,'gid'); // sync topics $group['topics'] = DBUtil::selectObjectCountByID('lobby_forum_topics',$id,'gid'); // sync postings // get forums first $forums = DBUtil::selectObjectArray('lobby_forums','gid = '.$id); $fres = array(); foreach ($forums as $item) { $fres[] = $item['id']; } if (count($fres) > 0) { $fstring = implode(', ',$fres); $group['postings'] = DBUtil::selectObjectCount('lobby_forum_posts','fid IN ('.$fstring.')'); } else { $group['postings'] = 0; } // sync forums $group['forums'] = DBUtil::selectObjectCountByID('lobby_forums',$id,'gid'); pnModAPIFunc('lobby','forums','sync',array('gid' => $id)); return DBUtil::updateObject($group,'lobby_groups'); } /** * handle last visit date * */ function lobby_lastvisit($group) { // Variables $expiretime = 1*60*60; // 1h $groupvar = '_lobby_'.$group['id']; $groupvar_ts = '_lobby_ts_'.$group['id']; $uid = pnUserGetVar('uid'); // There is a visit. Only go on if user is logged in if (!pnUserLoggedIn()) { return true; } else { // Get last action timestamp from session variables $lastaction = (int)SessionUtil::getVar($groupvar); $lastaction_ts = (int)SessionUtil::getVar($groupvar_ts); // Should the last login date be resetted? $reset = (int)FormUtil::getPassedValue('reset'); if (($reset == 1) && ($lastaction_ts > 0)) { $lastaction_ts = 1; // reset will be done now automatically } // Is there already a session for this user? if (!($lastaction_ts > 0)) { // Get database entry from lobby_users table $obj = DBUtil::selectObjectByID('lobby_users',$uid); $obj['array'] = unserialize($obj['array']); $obj['last_action'] = date("Y-m-d H:i:s",time()); $lastaction = (time()-(60*60*24*7*52)); // No last usage found? Set last usage to 52 Weeks... Should be enough ;) if (!((int)$obj['id'] > 0)) { // Create new entry in datbase $array = array(); $array[$group['id']] = $lastaction; $obj['array'] = serialize($array); $obj['id'] = $uid; DBUtil::insertObject($obj,'lobby_users','id',true,true); } else { // Set entry in database to time() $array = $obj['array']; if ($array[$group['id']] > 0) { // If there is an old entry use this as last action timestamp SessionUtil::setVar($groupvar,$array[$group['id']]); } else { // Otherwise last visit is some days ago (faked..) SessionUtil::setVar($groupvar,$lastaction); } // Store last update of last visit variable SessionUtil::setVar($groupvar_ts,time()); // Store actual real timestamp now $array[$group['id']] = time(); $obj['array'] = serialize($array); DBUtil::updateObject($obj,'lobby_users'); } } else { //Session exists already, Check for age if ($lastaction_ts < (time()-$expiretime)) { // Session has expired, set new variables $lastaction = time(); SessionUtil::setVar($groupvar,$lastaction); SessionUtil::setVar($groupvar_ts,$lastaction); // Store into Database // An database entry must exist now because we created it before in this routine here $obj = DBUtil::selectObjectByID('lobby_users',$uid); $obj['array'] = unserialize($obj['array']); $obj['array'][$group['id']] = $lastaction; $obj['array'] = serialize($obj['array']); $obj['last_action'] = date("Y-m-d H:i:s",time()); DBUtil::updateObject($obj,'lobby_users'); } } return $lastaction; } } /** * build coordinates for mymap * */ function lobby_buildcoordinates($groups,$width,$height) { $coords = array(); foreach ($groups as $group) { $c = $group['coordinates']; $c = unserialize($c); $lat = $c['lat']; $lng = $c['lng']; $coords[] = array( 'lat' => $lat, 'lng' => $lng, 'title' => $group['title'], 'text' => '<a href='.pnModURL('lobby','user','group',array('id' => $group['id'])).'>'._LOBBY_VISIT.'</a>' ); // only one marker displayed! } $mapcode = pnModAPIFunc('MyMap','user','generateMap',array( 'coords' => $coords, // must be an array 'maptype' => 'HYBRID', // HYBRID, SATELLITE or NORMAL 'width' => $width, // width in pixels 'height' => $height, // height in pixels 'zoomfactor' => 10 // zoomfactor - 1 is closest )); // zoomfactor only relevant if there is return $mapcode; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get postings for a given topic * * $args['tid'] int topic id * or * @args['offset'] int offset for pager * @args['numrows'] int numrows for pager * $args['id'] int posting id * @return array */ function lobby_forumpostsapi_get($args) { $tid = (int)$args['tid']; $pid = (int)$args['id']; $numrows = $args['numrows']; $offset = $args['offset']; $tables = pnDBGetTables(); $column = $tables['lobby_forum_posts_column']; $column_posts = $tables['lobby_forum_posts_column']; $joinInfo[] = array ( 'join_table' => 'lobby_forum_posts_text', // table for the join 'join_field' => 'text', // field in the join table that should be in the result with 'object_field_name' => 'text', // ...this name for the new column 'compare_field_table' => 'id', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table $joinInfo[] = array ( 'join_table' => 'users', // table for the join 'join_field' => 'uname', // field in the join table that should be in the result with 'object_field_name' => 'uname', // ...this name for the new column 'compare_field_table' => 'uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table if ($pid > 0) { $result = DBUtil::selectExpandedObjectByID('lobby_forum_posts',$joinInfo,$pid); return $result; } else if ($tid > 0){ // Load complete postings tree $orderby = $column_posts['date']." ASC"; $where = $column_posts['tid']." = ".$tid; $result = DBUtil::selectExpandedObjectArray('lobby_forum_posts',$joinInfo,$where,$orderby,$offset,$numrows); if ($pid > 0) { return $result[0]; } else { return $result; } } } /** * creates a new posting * * $args['fid'] int forum id * $args['tid'] int topic id * $args['uid'] int user id (optional) * $args['title'] string title * $args['text'] string content of posting * $args['date'] string date (optional) * $args['quiet'] boolean no output and notification email * @return int (new id) or false otherwise */ function lobby_forumpostsapi_add($args) { $fid = (int)$args['fid']; $uid = (int)$args['uid']; $tid = (int)$args['tid']; $quiet = $args['quiet']; if ( ( !($fid > 0 ) ) || ( ($uid < 2) && (!$quiet) ) ) { LogUtil::registerError(_LOBBY_TOPICSAPI_ADD_PARAMERROR); return false; } $title = $args['title']; $text = $args['text']; $subscribe = (int)$args['subscribe']; if (!$uid > 0) { $uid = pnUserGetVar('uid'); } if (isset($args['date']) && ($args['date'] != '')) { $date = $args['date']; } else { $date = date("Y-m-d H:i:s"); } // check text for NULL, important for import function for Dizkus if (!isset($text)) { $text = ''; } $posting = array ( 'uid' => $uid, 'date' => $date, 'tid' => $tid, 'fid' => $fid, 'date' => $date, 'title' => $title, 'text' => $text ); // get topic if ($tid > 0) { // We need this check to see if topic was closed till now.. // only neccesarry if topic id is given - new topic otherwise! $topic = DBUtil::selectObjectByID('lobby_forum_topics',$tid); if ($topic['locked'] == 1) { LogUtil::registerError(_LOBBY_FORUM_TOPIC_LOCKED); return false; } } $result = DBUtil::insertObject($posting,'lobby_forum_posts'); if (!$result) { return false; } // Add text $result = DBUtil::insertObject($posting,'lobby_forum_posts_text','',false,true); if (!$result) { // Failure? delete post and return false success DBUtil::deleteObject($posting,'lobby_forum_posts'); return false; } else { // Update topic information is not done automatically and has to be // called by the function that adds a new post if ($tid > 0) { if (!$args['quiet']) { LogUtil::registerStatus(_LOBBY_REPLY_POSTED); // send notification emails Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_newreply($topic,$posting); } // make abo for topic if ($subscribe == 1) { pnModAPIFunc('lobby','subscriptions','set',array('tid' => $tid, 'uid' => pnUserGetVar('uid'))); } } return $posting['id']; } } /** * delete a post * * $args['id'] int post id * @return booleam */ function lobby_forumpostsapi_del($args) { $id = (int)$args['id']; if (!($id > 0)) { return false; } else { $obj = DBUtil::selectObjectByID('lobby_forum_posts',$id); $obj_text = DBUtil::selectObjectByID('lobby_forum_posts_text',$id); if (($obj['id'] == ($obj_text['id'])) && ($id == $obj['id'])) { //delete objects DBUtil::deleteObject($obj,'lobby_forum_posts'); DBUtil::deleteObject($obj_text,'lobby_forum_posts'); return true; } else { return false; } } }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_admin_importHandler { var $id; function initialize(&$render) { // Get Groups groups $groups = pnModAPIFunc('Groups','user','getall'); $groups_items = array( array('text' => _LOBBY_SELECT_FOR_ACTION, 'value' => -1) ); foreach ($groups as $group) { $groups_items[] = array('text' => $group['name'], 'value' => $group['gid']); } // Get lobby groups $groups = pnModAPIFunc('lobby','groups','get'); $lobby_groups_items = array( array('text' => _LOBBY_SELECT_FOR_ACTION, 'value' => -1) ); foreach ($groups as $group) { $sort_groups[$group['id']] = $group; // we need this later for forum import $lobby_groups_items[] = array('text' => $group['title'], 'value' => $group['id']); } $dizkus = pnModAvailable('Dizkus'); if ($dizkus) { // Get lobby forums $lobby_forums = pnModAPIFunc('lobby','forums','get',array('showall' => 1)); $lobby_forums_items = array( array('text' => _LOBBY_SELECT_FOR_ACTION, 'value' => -1) ); foreach ($lobby_forums as $forum) { $gid = $forum['gid']; $grouptitle = $sort_groups[$gid]['title']; $lobby_forums_items[] = array('text' => $forum['id'].': '.$grouptitle.' - '.$forum['title'], 'value' => $forum['id']); } // Get Dizkus forums $forums_items = array( array('text' => _LOBBY_SELECT_FOR_ACTION, 'value' => -1) ); $forums = pnModAPIFunc('Dizkus','admin','readforums'); foreach ($forums as $forum) { $forums_items[] = array( 'text' => $forum['forum_id'].': '.$forum['forum_name'], 'value' => $forum['forum_id']); } } // Assign data $render->assign('dizkus', $dizkus); $render->assign('groups_items', $groups_items); $render->assign('lobby_groups_items', $lobby_groups_items); $render->assign('forums_items', $forums_items); $render->assign('lobby_forums_items', $lobby_forums_items); return true; } function handleCommand(&$render, &$args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) { return LogUtil::registerPermissionError(); } if ($args['commandName']=='update') { // get the pnForm data and do a validation check $obj = $render->pnFormGetValues(); if (!$render->pnFormIsValid()) return false; if (($obj['group'] > 0) && ($obj['lobby_group'])) { $counter=0; // Import group // Get members of Groups group $group = pnModAPIFunc('Groups','user','get',array('gid' => $obj['group'])); $users = $group['members']; $date = date("Y-m-h H:i:s",time()); foreach ($users as $user) { // Check if user is already a member $isMember = pnModAPIFunc('lobby','groups','isMember',array('uid' => $user['uid'], 'gid' => $obj['lobby_group'])); if ($isMember) { LogUtil::registerStatus(_LOBBY_IMPORT_SKIP_USER.': '.pnUserGetVar('uname',$user['uid'])); } else { $insert = array( 'uid' => $user['uid'], 'gid' => $obj['lobby_group'], 'date' => $date ); $result = DBUtil::insertObject($insert,'lobby_members'); if ($result) { LogUtil::registerStatus(_LOBBY_ADDED_USER.': '.pnUserGetVar('uname',$user['uid'])); $counter++; } else { LogUtil::registerError(_LOBBY_FAILED_USER.': '.pnUserGetVar('uname',$user['uid'])); } } } pnModAPIFunc('lobby','groups','sync',array('id' => $obj['lobby_group'])); LogUtil::registerStatus(_LOBBY_IMPORTED_USERS.': '.$counter); } else if (($obj['forum'] > 0) && ($obj['lobby_forum'])) { // Get target group pnModLangLoad('lobby','user'); $lobby_forum = pnModAPIFunc('lobby','forums','get',array('id' => $obj['lobby_forum'],'showall' => 1)); $lobby_group = pnModAPIFunc('lobby','groups','get',array('id' => $lobby_forum['gid'])); // Import forum $forum = pnModAPIFunc('Dizkus','user','readforum',array('forum_id' => $obj['forum'], 'topics_per_page' => -1)); $counter_topics = 0; $counter_posts = 0; $topics = $forum['topics']; foreach ($topics as $topic) { $topic = pnModAPIFunc('Dizkus','user','readtopic',array('topic_id' => $topic['topic_id'], 'complete' => true)); $title = $topic['topic_title']; $posts = $topic['posts']; $text = $posts[0]['post_text']; //$text = str_replace("<br />","\n",$text); $args = array ( 'gid' => $lobby_group['id'], 'fid' => $lobby_forum['id'], 'uid' => $posts[0]['poster_data']['uid'], 'title' => $title, 'text' => $text, 'date' => $posts[0]['post_time'], 'quiet' => true ); $result = pnModAPIFunc('lobby','forumtopics','add',$args); if ($result) { $tid = $result['id']; LogUtil::registerStatus(_LOBBY_TOPIC_IMPORTED.': '.$title.' ('.$tid.')'); $first = true; foreach ($posts as $post) { if (!$first) { $args = array ( 'tid' => $tid, 'gid' => $lobby_group['id'], 'fid' => $lobby_forum['id'], 'uid' => $post['poster_data']['uid'], 'title' => $title, 'text' => $post['post_text'], 'quiet' => true, 'date' => $post['post_time'] ); $result2 = pnModAPIFunc('lobby','forumposts','add',$args); if (!$result2) { LogUtil::registerError(_LOBBY_POSTING_IMPORT_ERROR); } } else { $first = false; } } // Sync topic pnModAPIFunc('lobby','forumtopics','sync',array('id' => $tid)); } else { LogUtil::registerError(_LOBBY_TOPIC_IMPORT_ERROR.': ID '.$tid); } pnModAPIFunc('lobby','groups','sync',array('id' => $lobby_forum['gid'])); } } else { LogUtil::registerError(_LOBBY_NO_IMPORT_SELECTED); } } // return with redirect return $render->pnFormRedirect(pnModURL('lobby','admin','import')); } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ define('_LOBBY_TABTITLE', 'Gruppen'); define('_LOBBY_NOUSERSPECIFIED', 'Kein Benutzer ausgewählt'); define('_LOBBY_GROUP_MEMBERSHIPS', 'Benutzer %username% ist Mitglied in folgenden Gruppen'); define('_LOBBY_IS_OWNER', '%username% ist Gründer dieser Gruppe'); define('_LOBBY_IS_MODERATOR', '%username% ist Moderator in dieser Gruppe'); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * the main user function * * @return output The main module page */ function lobby_user_main() { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_OVERVIEW)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = pnRender::getInstance('lobby'); // Assign variables // Get new founded groups $newGroups = pnModAPIFunc('lobby','groups','get',array('orderby' => 'latest', 'numrows' => 7, 'offset' => 0)); $render->assign('newGroups', $newGroups); // Get news memberships $newMembers = pnModAPIFunc('lobby','members','get',array('showall' => 1, 'numrows' => 7, 'offset' => 0, 'sort' => 'latest', 'groupinformation' => 1)); $render->assign('newMembers', $newMembers); // Get news $allNews = pnModAPIFunc('lobby','news','get',array('numrows' => 7, 'offset' => 0)); $render->assign('allNews', $allNews); $ownNews = pnModAPIFunc('lobby','news','get',array('onlyown' => 1, 'numrows' => 7, 'offset' => 0)); $render->assign('ownNews', $ownNews); // Get topics $allTopics = pnModAPIFunc('lobby','forumtopics','get',array('numrows' => 7, 'offset' => 0)); $render->assign('allTopics', $allTopics); $ownTopics = pnModAPIFunc('lobby','forumtopics','get',array('numrows' => 7, 'offset' => 0, 'owngroups' => 1)); $render->assign('ownTopics', $ownTopics); $modVars = pnModGetVar('lobby'); $render->assign('modVars', $modVars); $loggedIn = (int)pnUserLoggedIn(); $render->assign('loggedIn', $loggedIn); // Return the output return $render->fetch('lobby_user_main.htm'); } /** * show forum posts * * @return output The main module page */ function lobby_user_forums($args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_OVERVIEW)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = pnRender::getInstance('lobby'); $module = pnModGetName(); if (isset($args) && ($module != 'lobby')) { // This is important if function is embedded via content for example $numrows = (int)$args['numrows']; $offset = (int)$args['lobbypager']; // Module != lobby, so we have to load the css PageUtil::addVar('stylesheet','modules/lobby/pnstyle/style.css'); // Pager causes problems when integrated in other modules... $countTopics = false; } else { $numrows = (int)FormUtil::getPassedValue('numrows'); $offset = (int)FormUtil::getPassedValue('lobbypager'); $countTopics = true; } if ($numrows == 0 ) { $numrows = 15; } if ($offset > 0) { $offset--; } else { $offset = 0; } // Assign some variables and parameters $render->assign('numrows', $numrows); $render->assign('includeforum', 1); $render->assign('includegroup', 1); // Get mode and Topics $mode = (int)FormUtil::getPassedValue('mode'); if ($mode == 3) { $owngroups = 1; } else { if (pnUserLoggedIn()) { $owngroups = 2; } else { $owngroups = 0; } if ($mode == 2) { $official = 1; } } // Get topics $allTopics = pnModAPIFunc('lobby','forumtopics','get',array('numrows' => $numrows, 'offset' => $offset, 'owngroups' => $owngroups, 'official' => $official)); if ($countTopics) { $allTopicsCount = pnModAPIFunc('lobby','forumtopics','get',array('count' => 1, 'owngroups' => $owngroups, 'official' => $official)); } $render->assign('allTopics', $allTopics); $render->assign('allTopicsCount', $allTopicsCount); $ownTopics = pnModAPIFunc('lobby','forumtopics','get',array('numrows' => $numrows, 'offset' => $offset, 'owngroups' => 1)); $render->assign('ownTopics', $ownTopics); // Assign postsperpage value for index page $postsperpage = pnModGetVar('lobby','postsperpage'); $render->assign('postsperpage', $postsperpage); // Return the output return $render->fetch('lobby_user_forums.htm'); } /** * list available groups * * @return output */ function lobby_user_list($args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_OVERVIEW)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = pnRender::getInstance('lobby'); // Assign variables $itemsperpage = 15; $offset = (int)FormUtil::getPassedValue('lobbypager'); if ($offset > 0) { $offset--; } // Get Category filter if (isset($args) && (count($args) > 0)) { $cat = (int)$args['cat']; $map = (int)$args['map']; $width = (int)$args['width']; $height = (int)$args['height']; $notext = (int)$args['notext']; $order = (string)$args['order']; } else { $cat = (int)FormUtil::getPassedValue('cat'); $map = (int)FormUtil::getPassedValue('map'); $width = (int)FormUtil::getPassedValue('width'); $height = (int)FormUtil::getPassedValue('height'); $notext = (int)FormUtil::getPassedValue('notext'); $order = (string)FormUtil::getPassedValue('order'); } if ($width == 0) { $width = 900; } if ($height == 0) { $height = 400; } // Get groups $mymap = pnModAvailable('MyMap'); if (($mymap) && ($map == 1)) { $render->assign('map', 1); $code = pnModAPIFunc('lobby','groups','getMapCode',array('cat' => $cat, 'width' => $width, 'height' => $height)); $render->assign('code', $code); } else { $groups = pnModAPIFunc('lobby','groups','get',array('orderby' => $order, 'numrows' => $itemsperpage, 'offset' => $offset, 'cat' => $cat)); } $groupscount = pnModAPIFunc('lobby','groups','get',array('count' => 1, 'cat' => $cat)); $render->assign('mymap', $mymap); $render->assign('notext', $notext); $render->assign('groups', $groups); $render->assign('cat', $cat); $render->assign('groupscount', $groupscount); $render->assign('itemsperpage',$itemsperpage); // Get categories and assign them to template $categories = pnModAPIFunc('lobby','categories','get'); $render->assign('categories', $categories); // Return the output return $render->fetch('lobby_user_list.htm'); } /** * the main user function * * @return output */ function lobby_user_group() { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_OVERVIEW)) return LogUtil::registerPermissionError(); //*** START OF STANDARD DATA FOR LEFT COLUMN **// // Common groups functions inclusion Loader::includeOnce('modules/lobby/includes/common_groups.php'); // Get group id $id = (int)FormUtil::getPassedValue('id'); // should a synchronisation be done? $sync = (int)FormUtil::getPassedValue('sync'); if ($sync == 1) { $result = lobby_groupsync($id); } // Add JS PageUtil::addVar('javascript','modules/lobby/includes/javascript/lobby.js'); // get group $group = pnModAPIFunc('lobby','groups','get',array('id' => $id)); if (!($id > 0) || ($group['id'] != $id)) { LogUtil::registerError(_LOBBY_GROUP_NONEXISTENT); return pnRedirect(pnModURL('lobby')); } // Last visit handling - important for forums $lastvisit = lobby_lastvisit($group); // Create output and call handler class $render = FormUtil::newpnForm('lobby'); // Assign variables $render->assign('group',$group); // check if permissions are group owner: $groupOwner = (($group['uid'] == pnUserGetVar('uid')) || (SecurityUtil::checkPermission('lobby::'.$id, '::', ACCESS_ADMIN))); $render->assign('groupOwner', $groupOwner); $loggedIn = pnUserLoggedIn(); $render->assign('loggedIn',$loggedIn); if ($loggedIn) { $memberStatus = pnModAPIFunc('lobby','groups','getMemberStatus',array('group' => $group, 'uid' => pnUserGetVar('uid'))); $render->assign('memberStatus', $memberStatus); } // get category $category = pnModAPIFunc('lobby','categories','get',array('id' => $group['category'])); $render->assign('category',$category); // get members $facts['members'] = pnModAPIFunc('lobby','members','get',array('gid' => $group['id'], 'count' => 1)); if ($groupOwner) { $facts['pending'] = (int)pnModAPIFunc('lobby','members','get',array('gid' => $group['id'],'pending' => 1, 'count' => 1)); } // get moderators $moderators = pnModAPIFunc('lobby','moderators','get',array('gid' => $group['id'])); $render->assign('moderators', $moderators); $isModerator = pnModAPIFunc('lobby','moderators','isModerator',array('gid' => $group['id'], 'uid' => pnUserGetVar('uid'))); if ($isModerator || $groupOwner) { $render->assign('moderator', 1); $render->assign('authid', SecurityUtil::generateAuthKey()); } // Get Newsarticles $newsperpage = pnModGetVar('lobby',$newsperpage); $articles_short = pnModAPIFunc('lobby','news','get',array('gid' => $id, 'numrows' => 5)); $render->assign('articles_short', $articles_short); // If latest article > last visit the news - box should be opened by default. $first_article = $articles_short[0]; $openNews = 0; if ($first_article['id'] > 0) { if ((int)strtotime($first_article['date']) > $lastvisit) { $openNews = 1; } } if ($group['boxes_shownews'] == 1) { $openNews = 1; } $render->assign('openNews', $openNews); // Load Userpictures lang if module is available if (pnModAvailable('UserPictures')) { pnModLangLoad('UserPictures','user'); } // get albums if ($group['albums'] > 0) { // get all and take care of viewers permissions $albums = pnModAPIFunc('lobby','albums','get',array('gid' => $group['id'])); $latestpicture = $albums[0]; $render->assign('latestpicture',$latestpicture); } // Assign facts $facts['creator'] = pnUserGetVar('uname',$group['uid']); $facts['status'] = (int)pnModAPIFunc('lobby','groups','getMemberStatus',array('group' => $group)); $facts['newsperpage'] = 25; // loggedin-Status, Userinfo and facts $render->assign('loggedin', (int)pnUserLoggedIn()); $render->assign('viewer_uid', pnUserGetVar('uid')); $render->assign('facts',$facts); // Get Pager information $offset = (int)FormUtil::getPassedValue('lobbypager'); if ($offset > 0) { $offset--; } // Get action if set $action = FormUtil::getPassedValue('action'); // Set Standard page title PageUtil::setVar('title', _LOBBY_GROUP.' '.$group['title']); // Assign some values for forum shortlinks if (pnUserLoggedIn() && ($lastvisit > 0)) { $lastvisit_date = date("Y-m-d H:i:s",$lastvisit); $render->assign('lastvisit', $lastvisit_date); $render->assign('lastvisit_encoded', base64_encode($lastvisit_date)); } //*** END OF STANDARD DATA FOR LEFT COLUMN **// $do = FormUtil::getPassedValue('do'); if (!isset($do) || ($do == '')) { $incFile = "lobby_includes_index.htm"; } else { $incFile = "lobby_includes_".$do.".htm"; } if ($render->template_exists($incFile)) { $render->assign('incFile', $incFile); } switch ($do) { case 'albummanagement': // Only the group owner or sysadmin should be allowed to view this site if (!$groupOwner) { LogUtil::registerError(_LOBBY_ONLY_ADMIN_ACCESS); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } $template = 'albummanagement'; Loader::includeOnce('modules/lobby/includes/classes/user/albummanagement.php'); break; case 'forummanagement': // Only the group owner or sysadmin should be allowed to view this site if (!$groupOwner) { LogUtil::registerError(_LOBBY_ONLY_ADMIN_ACCESS); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } $template = 'forummanagement'; Loader::includeOnce('modules/lobby/includes/classes/user/forummanagement.php'); break; case 'modifyindex': // Only the group owner or sysadmin should be allowed to view this site if (!$groupOwner) { LogUtil::registerError(_LOBBY_ONLY_ADMIN_ACCESS); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } $template = 'modifyindex'; Loader::includeOnce('modules/lobby/includes/classes/user/modifyindex.php'); break; case 'membermanagement': // Only the group owner or sysadmin should be allowed to view this site if (!$groupOwner) { LogUtil::registerError(_LOBBY_ONLY_ADMIN_ACCESS); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } // Check for action if (isset($action) && ($action == 'modify')) { $template = 'membermanagement_modify'; Loader::includeOnce('modules/lobby/includes/classes/user/membermanagement_modify.php'); } else { $template = 'membermanagement'; Loader::includeOnce('modules/lobby/includes/classes/user/membermanagement.php'); } break; case 'sync': // Only the group owner or sysadmin should be allowed to view this site if (!$groupOwner) { LogUtil::registerError(_LOBBY_ONLY_ADMIN_ACCESS); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } // Check for action $template = 'index'; Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); Loader::includeOnce('modules/lobby/includes/common_groups.php'); $result = lobby_groupsync($id); if ($result) { LogUtil::registerStatus(_LOBBY_GROUP_SYNCED); } else { LogUtil::registerError(_LOBBY_GROUP_SYNC_ERROR); } return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); break; case 'pending': // Only the group owner or sysadmin should be allowed to view this site if (!$groupOwner) { LogUtil::registerError(_LOBBY_ONLY_ADMIN_ACCESS); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } // is there a action to do? if (($action == 'deny') || ($action == 'accept')) { $add = (int)FormUtil::getPassedValue('add'); if ($action == 'accept') { pnModAPIFunc('lobby','members','add',array('gid' => $id, 'uid' => $add)); // send Mail Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_newgroupmember($group,$add); } else { pnModAPIFunc('lobby','members','reject',array('group' => $group, 'uid' => $add)); // Mail was sent through function! } // Clear the browsers URL return pnRedirect(pnModURL('lobby','user','group',array('id' => $id, 'do' => 'pending'))); } $pending = pnModAPIFunc('lobby','members','get',array('pending' => 1, 'gid' => $id)); $render->assign('pending',$pending); $authid = SecurityUtil::generateAuthKey(); $render->assign('authid', $authid); $template = 'pending'; Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); break; case 'invite': Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); $args = array ( 'uname' => FormUtil::getPassedValue('uname'), 'text' => FormUtil::getPassedValue('invitetext'), 'id' => $id, 'group' => $group ); pnModAPIFunc('lobby','groups','invite',$args); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); break; case 'help': Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); $template = 'help'; break; case 'news': $story = (int)FormUtil::getPassedValue('story'); if ($story > 0) { $article = pnModAPIFunc('lobby','news','get',array('gid' => $id, 'id' => $story, 'infuture' => $groupOwner)); $render->assign($article); if (strtotime($article['date']) > time()) { $render->assign('infuture', 1); } // is the article to be sent to all? if ($groupOwner) { $send = (int) FormUtil::getPassedValue('send'); if ($send == 1) { if ($article['sent'] == 1) { LogUtil::registerError(_TRACKING_ARTICLE_SENT_ALREADY); } else { $result = pnModAPIFunc('lobby','news','sendStory',$article); if ($result) { LogUtil::registerStatus(_LOBBY_ARTICLE_SENT_TO_GROUP); } else { LogUtil::registerError(_LOBBY_ARTICLE_SENT_ERROR); } } } } // Set page title PageUtil::setVar('title', $article['title'].' :: '._LOBBY_GROUP_NEWS.' '.$group['title']); $template = 'news_story'; } else { $articles = pnModAPIFunc('lobby','news','get',array('gid' => $id, 'infuture' => $groupOwner, 'numrows' => $facts['newsperpage'], 'offset' => $offset)); $render->assign('articles',$articles); $template = 'news'; // Set page title PageUtil::setVar('title', _LOBBY_GROUP_NEWS.' '.$group['title']); } Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); break; case 'albums': $template = 'albums'; Loader::includeOnce('modules/lobby/includes/classes/user/albums.php'); break; case 'article': // Only the group owner or sysadmin should be allowed to view this site if (!$groupOwner) { LogUtil::registerError(_LOBBY_ONLY_ADMIN_ACCESS); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } $template = 'article'; Loader::includeOnce('modules/lobby/includes/classes/user/article.php'); break; case 'join': $template = 'join'; if ($memberStatus > 0) { LogUtil::registerError(_LOBBY_USER_ALREADY_MEMBER); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } Loader::includeOnce('modules/lobby/includes/classes/user/join.php'); break; case 'forums': // Assign postsperpage value for index page $postsperpage = pnModGetVar('lobby','postsperpage'); $posts = pnModAPIFunc('lobby','forumtopics','get',array('gid' => $id, 'numrows' => 5)); $render->assign('topics', $posts); $render->assign('postsperpage', $postsperpage); $render->assign('includeforum',1); // Check for action if (isset($action) && (($action == 'latesttopics') || ($action == 'latestposts'))) { $render->assign('mode', $action); $topicsperpage = pnModGetVar('lobby','topicsperpage'); $render->assign('topicsperpage', $topicsperpage); $hours = (int)FormUtil::getPassedValue('hours'); $date = FormUtil::getPassedValue('date'); if ($date != '') { $date=base64_decode($date); $date = date("Y-m-d H:i:s",strtotime($date)); } else if (!($hours > 0)) { $hours = 24; $date = date("Y-m-d H:i:s",time()-60*60*$hours); $render->assign('hours',$hours); } else if ($hours > 0) { $render->assign('hours',$hours); $date = date("Y-m-d H:i:s",time()-60*60*$hours); } // Assign date $render->assign('date',$date); if (($action == 'latesttopics')) { $sort = 'creationdate'; } $topics = pnModAPIFunc('lobby','forumtopics','get',array('gid' => $id, 'numrows' => $topicsperpage, 'offset' => $offset, 'sort' => $sort, 'date' => $date)); $topics_count = pnModAPIFunc('lobby','forumtopics','get',array('gid' => $id, 'date' => $date, 'sort' => $sort, 'count' => 1)); $render->assign('topics',$topics); $render->assign('topics_count',$topics_count); $template = 'forums_latesttopics'; } else { $template = 'forums'; $forums = pnModAPIFunc('lobby','forums','get',array('gid' =>$id, 'showall' => $group['forumsvisible'])); $render->assign('forums', $forums); } Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); break; case 'forum': $template = 'forum'; Loader::includeOnce('modules/lobby/includes/classes/user/forum.php'); break; case 'members': $template = 'members'; // Load member information $membersperpage = 56; $members = pnModAPIFunc('lobby','members','get',array('gid' => $group['id'], 'numrows' => $membersperpage, 'offset' => $offset, 'sort' => 'uname')); $render->assign('members',$members); $render->assign('membersperpage', $membersperpage); Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); break; case 'quit': if (!pnUserLoggedIn()) { LogUtil::registerPermissionError(); return pnRedirect(pnModURL('lobby','user','group',array('id' => $id))); } $confirm = (int)FormUtil::getPassedValue('confirm'); if ($confirm == 1) { if (SecurityUtil::confirmAuthKey()) { // delete user from group $result = pnModAPIFunc('lobby','members','del',array('gid' => $id, 'uid' => pnUserGetVar('uid'))); if (!$result) { LogUtil::registerError(_LOBBY_GROUP_DELETE_MEMBER_FAILURE); } else { // send email to group owner Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_quitmember($id,pnUserGetVar('uid'),FormUtil::getPassedValue('text')); // display message and return to group's index page LogUtil::registerStatus(_LOBBY_MEMBERSHIP_QUITTED); return pnRedirect(pnModUrl('lobby','user','group',array('id' => $id))); } } else { // authkey wrong LogUtil::registerAuthIDError(); } } $authid = SecurityUtil::generateAuthKey(); $render->assign('authid', $authid); $template = 'quit'; // Load member information Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); break; default: // Load individual home page $index = pnModAPIFunc('lobby','pages','get',array('gid' => $id)); if (strlen($index) > 6) { $render->assign('index', $index); } // Load member information $membersperpage = 14; $members = pnModAPIFunc('lobby','members','get',array('gid' => $group['id'], 'numrows' => $membersperpage, 'offset' => $offset, 'sort' => 'latest')); $render->assign('members',$members); $render->assign('membersperpage', $membersperpage); // Add online members $onlinemembers = pnModAPIFunc('lobby','members','get',array('online' => 1, 'gid' => $group['id'])); $onlinememberscount = pnModAPIFunc('lobby','members','get',array('count' => 1, 'online' => 1, 'gid' => $group['id'])); $render->assign('onlinemembers',$onlinemembers); $render->assign('onlinememberscount',$onlinememberscount); // Load forum information $topics = pnModAPIFunc('lobby','forumtopics','get',array('gid' => $id, 'numrows' => $group['indextopics'], 'sort' => 'creationdate')); $render->assign('topics', $topics); $posts = pnModAPIFunc('lobby','forumtopics','get',array('gid' => $id, 'numrows' => $group['indextopics'])); $render->assign('posts', $posts); $render->assign('indexpage', 1); $template = "index"; // Get module availability for mymap module $mymapavailable = pnModAvailable('MyMap'); $render->assign('mymapavailable', $mymapavailable); $coords = unserialize($group['coordinates']); $render->assign('coords', $coords); // Assign postsperpage value for index page $postsperpage = pnModGetVar('lobby','postsperpage'); $render->assign('postsperpage', $postsperpage); $render->assign('includeforum',1); // Load dummy class Loader::includeOnce('modules/lobby/includes/classes/user/dummy.php'); break; } // Assign template for plugin and return output $render->assign('template','lobby_user_groups_include_'.$template.'.htm'); return $render->pnFormExecute('lobby_user_group.htm',new lobby_user_pluginHandler()); } /** * edit group information * * @return output */ function lobby_user_edit() { // load handler class Loader::requireOnce('modules/lobby/includes/classes/user/edit.php'); // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_COMMENT)) return LogUtil::registerPermissionError(); // Create output and call handler class $render = FormUtil::newpnForm('lobby'); // Return the output return $render->pnFormExecute('lobby_user_edit.htm', new lobby_user_editHandler()); } /** * fake links for netbiker... */ function lobby_user_memberslist() { $gid = Formutil::getpassedvalue('gid'); $args = array ( 'gid' => $gid ); return pnRedirect(pnModURL('Groups','user','memberslist',$args)); } function lobby_user_membership() { $action = Formutil::getpassedvalue('action'); $gid = Formutil::getpassedvalue('gid'); $args = array ( 'action' => $action, 'gid' => $gid ); return pnRedirect(pnModURL('Groups','user','membership',$args)); }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ // general define('_LOBBY_OCLOCK', 'Uhr'); define('_LOBBY_GO', 'los'); define('_LOBBY_YES', 'Ja'); define('_LOBBY_NO', 'Nein'); define('_LOBBY_ONLY_ADMIN_ACCESS', 'Zugriff auf die zuletzt ausgewählte Funktion ist nur Administratoren oder Gruppeninhabern erlaubt'); define('_LOBBY_FORUMS', 'Foren'); define('_LOBBY_FORUM', 'Forum'); define('_LOBBY_NEWS', 'Neuigkeiten'); define('_LOBBY_BY', 'von'); define('_LOBBY_HOURS', 'Stunden'); define('_LOBBY_GROUP', 'Gruppe'); define('_LOBBY_AUTHOR', 'Verfasser'); define('_LOBBY_DATE', 'Datum'); define('_LOBBY_OF', 'von'); define('_LOBBY_VISIT', 'besuchen'); define('_LOBBY_LAST', 'letzter'); define('_LOBBY_QUOTE', 'Text zitieren'); define('_LOBBY_GO_TO_TOP', 'Nach oben springen'); define('_LOBBY_EDIT', 'bearbeiten'); // main define('_LOBBY_WELCOME', 'Willkommen in deinem Netzwerk'); define('_LOBBY_INTRO_WELCOME_TEXT', 'Auf dieser Seite siehst Du, was sich hier neues tut und getan hat. Alle Gruppen sind hier vertreten. Wen Du übrigens denkst, in deinem Bereich oder Interessensgebiet fehlt noch eine Gruppe, dann kannst Du aktiv werden und selbst eine Gruppe gründen'); define('_LOBBY_CREATE_GROUP', 'Eine eigene Gruppe erstellen'); define('_LOBBY_RECENT_JOINS', 'Neue Mitglieder in allen Gruppen'); define('_LOBBY_NEW_GROUPS', 'Neue gegründete Gruppen'); define('_LOBBY_ALL_GROUPS_NEWS', 'Neuigkeiten aus allen Gruppen'); define('_LOBBY_MY_GROUPS_NEWS', 'Neuigkeiten aus meinen Gruppen'); define('_LOBBY_ALL_GROUPS_POSTS', 'Themen aus allen Gruppen'); define('_LOBBY_MY_GROUPS_POSTS', 'Themen aus meinen Gruppen'); define('_LOBBY_NO_NEW_GROUPS', 'Keine neuen Gruppen gegründet'); define('_LOBBY_GROUP_EDIT_INFORMATION', 'Grundeinstellungen'); define('_LOBBY_GROUP_ADMIN_SYNC', 'Gruppe synchronisieren'); define('_LOBBY_GROUP_ONLINE_MEMBERS', 'Gruppenmitglieder, welche im Moment online sind'); define('_LOBBY_OUR_PLACE', 'Hier ist die Gruppe zu Hause'); define('_LOBBY_SHORT_LATEST_TOPICS', 'Nach neu gestarteten Themen sortieren'); define('_LOBBY_SHORT_LATEST_POSTINGS', 'Nach aktuellsten Antworten sortieren'); define('_LOBBY_FORUM_SHORTLINK_LATEST', 'Postings seit letzten Besuch'); define('_LOBBY_FORUM_SHORTLINK_24', 'Postings der letzten 24h'); define('_LOBBY_FORUM_SHORTLINK_WEEK', 'Postings der letzten Woche'); define('_LOBBY_FORUM_SHORTLINK_LATEST_TOPICS', 'Themen seit letzten Besuch'); define('_LOBBY_FORUM_SHORTLINK_24_TOPICS', 'Themen der letzten 24h'); define('_LOBBY_FORUM_SHORTLINK_WEEK_TOPICS', 'Themen der letzten Woche'); define('_LOBBY_SHOW_ALL_GROUPS', 'Alle Gruppen anzeigen'); define('_LOBBY_FORUM_SHORTLINK_ALL', 'Alle Foren zeigen'); define('_LOBBY_NO_TOPICS_YET', 'Noch keine Themen vorhanden'); define('_LOBBY_NO_NEW_ARTICLES', 'Noch kein Artikel vorhanden'); define('_LOBBY_GROUP_FORUM_SHORTLINKS', 'Foren-Schnellzugriff'); define('_LOBBY_YOU_NEED_HELP', 'Wenn Du Hilfe benötigst, dann'); define('_LOBBY_CLICK_HERE', 'hier klicken'); define('_LOBBY_GROUP_HELP', 'Wird Hilfe benötigt'); define('_LOBBY_NO_NEW_MEMBERS', 'Noch keine Mitgliedschaften vorhanden'); define('_LOBBY_ENTERED', 'ist beigetreten zu'); define('_LOBBY_GROUP_QUIT', 'Mitgliedschaft beenden'); define('_LOBBY_FORUMS_OVERVIEW_LINK', 'Aktuelle Diskussionen aller Gruppen'); define('_LOBBY_FORUMS_OWN_OVERVIEW_LINK', 'Aktuelle Diskussionen eigener Gruppen'); // forums define('_LOBBY_DISPLAY_MODE', 'Beiträge filtern / anzeigen'); define('_LOBBY_SHOW_ALL', 'aus allen Gruppen'); define('_LOBBY_SHOW_ALL_OFFICIAL', 'aus allen offiziellen Gruppen'); define('_LOBBY_SHOW_OWN', 'nur eigene Gruppen'); // list define('_LOBBY_GROUPS_LIST', 'Verfügbare Gruppen'); define('_LOBBY_GROUPS_LIST_TEXT', 'Hier sind nun die verfügbaren Gruppen angezeigt. In Klammer dahinter ist jeweils die Kategorie, welcher die Gruppe zugeordnet ist. Soll nach einer Kategorie gefiltert werden und andere Kategorien ausgeblendet werden - klicke einfach den Namen der Kategorie an.'); define('_LOBBY_QUICKDATA', 'Daten zur Gruppe'); define('_LOBBY_MEMBERS', 'Mitglieder'); define('_LOBBY_VISIT_GROUP', 'Gruppe besuchen'); define('_LOBBY_CAT_FILTER_HINT', 'Durch das Anklicken einer bestimmten Kategorie werden nur noch Gruppen eben dieser Kategorie angezeigt. Um wieder alle Gruppen ansehen zu können, müssen Sie den Filter deaktivieren'); define('_LOBBY_CAT_FILTER_DEACTIVATE', 'Filter deaktivieren'); define('_LOBBY_OPTIONS', 'Optionen'); // invite define('_LOBBY_UNAME_NOT_FOUND', 'Benutzername konnte nicht gefunden werden - bitte Schreibweise prüfen, eventuell hast Du dich vertippt?'); define('_LOBBY_USER_INVITED', 'Benutzer wirde zur Gruppe eingeladen'); define('_LOBBY_USER_ALREADY_MEMBER', 'Benutzer ist bereits Mitglied der Gruppe'); define('_LOBBY_USER_INVITATION_ERROR', 'Der Benutzer konnte wegen eines internen Fehlers nicht eingeladen werden'); define('_LOBBY_INVITATIONS_ONLY_MEMBERS', 'Um ein andres Mitglied in eine Gruppe einladen zu können musst Du selbst Mitglied der Gruppe sein!'); define('_LOBBY_USER_ALREADY_INVITED', 'Für den Benutzer liegt bereits eine ausgesprochene Einladung für diese Gruppe vor und Mehrfacheinladungen sind nicht möglich!'); // edit define('_LOBBY_EDIT_INDEX_POSTINGS', 'Anzahl der Themen der Foren, welche auf der Gruppenstartseite angezeigt werden sollen'); define('_LOBBY_LAT', 'Breitengrad'); define('_LOBBY_LNG', 'Längengrad'); define('_LOBBY_CLICK_CARD_FOR_COORDS', 'Zur automatischen Übernahme von Koordinaten einfach an gewünschter Stelle auf die Karte klicken!'); define('_LOBBY_MODIFY_GROUUP', 'Gruppe modifizieren oder neu anlegen'); define('_LOBBY_EDIT_GROUP_TITLE', 'Name / Bezeichnung der Gruppe'); define('_LOBBY_EDIT_GROUP_NOCHANGELATER', 'Diese Eingabe kann nach dem Anlegen der Gruppe nicht mehr geändert werden'); define('_LOBBY_EDIT_GROUP_DESCRIPTION', 'Beschreibung welche zur Gruppe angezeigt werden soll und für Mitglieder und Nichtmitglieder sichtbar ist'); define('_LOBBY_EDIT_GROUP_CATEGORY', 'Kategorie, in welche die Gruppe eingeordnet werden soll'); define('_LOBBY_EDIT_GROUP_MODERATED', 'Neuzugänge bedürfen einer Freischaltung'); define('_LOBBY_EDIT_UPDATE_STORE', 'Gruppe erstellen / Änderungen speichern'); define('_LOBBY_EDIT_OFFICIALGROUPSECPL', 'Gruppen, welche in eine Rubrik eingeordnet werden, die mit einem Stern gekennzeichnet sind, müssen vor der endgültigen Nutzung erst durch den Seitenbetreiber freigegeben werden.'); define('_LOBBY_GROUPS_ADDERROR', 'Fehler beim hinzufügen der Gruppe'); define('_LOBBY_GROUPS_ADDED', 'Gruppe "%group%" wurde hinzugefügt'); define('_LOBBY_GROUP_PENDING', 'Hinweis: Die Gruppe muss nach dem sie angelegt wurde erst von Seitenbetreiber freigeschalten werden, bevor sie von allen Mitgliedern genutzt und eingesehen werden kann! Du erhältst dann eine Nachricht, wenn das geschehen ist!'); define('_LOBBY_FORUMTITLE_INTRODUCTION', 'Vorstellungsrunde'); define('_LOBBY_FORUMTITLE_INTRODUCTION_DESC', 'Hier können neue Mitglieder Hallo sagen und sich der Gruppe vorstellen - so weiß man gleich, mit wem man es zu tun hat!'); define('_LOBBY_FORUMTITLE_Q_AND_A', 'Fragen und Antworten'); define('_LOBBY_FORUMTITLE_Q_AND_A_DESC', 'Etwas unklar? Oder hast Du eine Frage? Hier kannst Du Antworten auf deine Fragen für die Gruppe finden oder Fragen stellen und Antworten bekommen'); define('_LOBBY_FORUMTITLE_PRIVATE', 'Internes, privates Gruppen-Forum'); define('_LOBBY_FORUMTITLE_PRIVATE_DESC', 'In diesem Forum können interne Sachen diskutiert werden welche nur für Gruppenmitglieder einsehbar sind'); define('_LOBBY_FORUMTITLE_TALK', 'öffentliches Gruppenforum'); define('_LOBBY_FORUMTITLE_TALK_DESC', 'Hier diskutierte Themen können auch von Nicht-Mitgliedern beantwortet werden. Gut für potentielle Mitglieder, hier einmal reinzuschnuppern!'); define('_LOBBY_GROUP_EDIT_INITPROCESS', 'Die Standardeinstellungen für neue Gruppen werden nun übernommen und abgearbeitet'); define('_LOBBY_GROUP_OWNER_NODELETE', 'Der Gründer einer Gruppe kann nicht als Moderator oder Mitglied gelöscht werden!'); define('_LOBBY_GROUP_ALREADY_EXISTS', 'Eine Gruppe mit diesem Namen existiert bereits'); define('_LOBBY_CREATE_FORUMS', 'Standard-Foren-Landschaft gleich mit erstellen'); define('_LOBBY_DELETE_GROUP', 'Gruppe mit allen Inhalten, Gruppenzugehörigkeiten und Newsartikeln sowie Foren unwiderruflich und ohne weitere Sicherheitsabfrage komplett löschen'); define('_LOBBY_DELETION_MEMBER_FAILS', 'Beim Löschen der Mitglieder ist ein Fehler aufgetreten'); define('_LOBBY_DELETION_NEWS_FAILS', 'Beim Löschen der News zur Gruppe ist ein Fehler aufgetreten!'); define('_LOBBY_DELETION_MODERATORS_FAILS', 'Beim Löschen der Moderatoren ist ein Fehler aufgetreten'); define('_LOBBY_DELETION_MEMBER_PENDING_FAILS', 'Beim Löschen öffener Mitgliedsanträge ist ein Fehler aufgetreten'); define('_LOBBY_DELETION_FORUMS_FAILS', 'Beim Löschen der Gruppenforen ist ein Fehler aufgetreten'); define('_LOBBY_DELETION_GROUP_FAILS', 'Beim Löschen der Gruppenkerndaten ist ein Fehler aufgetreten'); define('_LOBBY_GROUP_DELETED', 'Die Gruppe wurde vollständig entfernt'); define('_LOBBY_FORUMS_VISIBLE_TO_ALL', 'Die vorhandenen Foren sollen in der Übersicht für alle sichtbar sein. Themen können trotzdem nur von denen gelesen werden, die die entsprechende Berechtigung haben. So kann man zum Beispiel von außen die Aktivität einer Gruppe einsehen, was bei lauter versteckten Foren oft nicht möglich ist. Eine Gruppe kann so attraktiver wirken und mehr Neuanmeldungen erzielen.'); // groups api define('_LOBBY_GROUP_ADDMEMBER_FAILURE', 'Fehler beim Hinzufügen eines Mitglieds zu einer Gruppe'); define('_LOBBY_GROUPS_MEMBERADDED', 'Mitglied "%member%" wurde hinzugefügt'); define('_LOBBY_GROUP_GETMEMBERS_PARAMFAILURE', 'Parameter für das Auslesen der Gruppenmitglieder fehlerhaft'); define('_LOBBY_GROUP_SYNCED', 'Gruppen wurde synchronisiert'); define('_LOBBY_GROUP_SYNC_ERROR', 'Fehler beim Synchronisieren aufgetreten'); define('_LOBBY_REALLY_DELETE', 'Soll die Löschaktion wirklich ausgeführt werden? Bitte zum Löschen OK klicken. Das Löschen kann nicht rückgängig gemacht werden!'); // group define('_LOBBY_GROUPINDEX', 'Startseite / Übersicht über neueste Aktivitäten aller Gruppen anzeigen'); define('_LOBBY_GROUP_NOT_YET_ACCEPTED', 'Diese Gruppe ist noch nicht vom Seitenbetreiber akzeptiert worden. Das bedeutet, dass die Gruppe noch nicht öffentlich einsehbar ist. Lediglich Administratoren und Du als Gruppengründer kannst die Gruppe sehen. Das soll aber nicht daran hindern, die Gruppe mit Startseite, Foren, News etc. schon einmal herzurichten, denn wenn der Seitenbetreiber die Gruppe dann frei gibt, sieht sie gleich richtig gut aus!'); define('_LOBBY_GROUP_INDEX_PAGE', 'Gruppen-Startseite'); define('_LOBBY_GROUP_NONEXISTENT', 'Die ausgewählte Gruppe existiert nicht oder ist noch nicht freigeschalten. Bitte später erneut versuchen.'); define('_LOBBY_GROUP_NEWS', 'Neuigkeiten'); define('_LOBBY_GROUP_NONEWS', 'Keine Neuigkeiten bis jetzt'); define('_LOBBY_GROUP_FACTS', 'Daten & Fakten'); define('_LOBBY_GROUP_LASTACTION', 'Letzte Aktivität'); define('_LOBBY_GROUP_MEMBERS', 'Mitglieder'); define('_LOBBY_GROUP_ARTICLES', 'Artikel (Neuigkeiten)'); define('_LOBBY_GROUP_FORUMS', 'Foren in der Gruppe'); define('_LOBBY_GROUP_TOPICS', 'Themen in den Foren'); define('_LOBBY_GROUP_POSTINGS', 'Postings in den Foren'); define('_LOBBY_GROUP_NEW_TOPICS', 'Neue Themen in den Foren'); define('_LOBBY_GROUP_NEW_POSTINGS', 'Neue Postings in den Foren'); define('_LOBBY_GROUP_CATEGORY', 'Kategoriezuordnung'); define('_LOBBY_GROUP_CREATOR', 'Gruppengründer'); define('_LOBBY_GROUP_MODERATORS', 'Moderatoren'); define('_LOBBY_GROUP_YOURSTATUS', 'Dein Status'); define('_LOBBY_GROUP_MEMBER', 'Mitglied'); define('_LOBBY_GROUP_NO_MEMBER', 'kein Mitglied'); define('_LOBBY_GROUP_JOIN', 'beitreten'); define('_LOBBY_GROUP_PUBLICGROUP', 'Beitreten: keine Freischaltung notwendig'); define('_LOBBY_GROUP_MODERATEDGROUP', 'Beitreten: Freischalten notwendig'); define('_LOBBY_GROUP_ADMIN_MENU', 'Verwaltung'); define('_LOBBY_GROUP_ADMIN_PENDING', 'Offene Mitgliedsanträge'); define('_LOBBY_GROUP_ADMIN_MEMBER_MANAGEMENT', 'Mitglieder verwalten'); define('_LOBBY_GROUP_ADMIN_NEW_ARTICLE', 'Newsartikel schreiben'); define('_LOBBY_GROUP_ADMIN_FORUM_MANAGEMENT', 'Foren verwalten'); define('_LOBBY_NEWS_INDEX', 'Zu allen Artikeln'); define('_LOBBY_GROUP_INVITE', 'Freunde einladen'); define('_LOBBY_GROUP_NOMEMBERS', 'Noch keine Mitglieder'); define('_LOBBY_GROUP_NOMEMBERS_ONLINE', 'Keine Mitglieder im Moment online'); define('_LOBBY_GROUP_RESPONSIBLE', 'Gruppengründer'); define('_LOBBY_GROUP_FORUM_INDEX', 'Forenübersicht der Gruppe'); define('_LOBBY_GROUP_FORUM_RECENT_TOPICS', 'die neuesten Themen'); define('_LOBBY_GROUP_FORUM_RECENT_POSTS', 'die neuesten Beiträge'); define('_LOBBY_GROUP_TROUBLE_CONTACT', 'Im Falle von Problemen in der Gruppe bitte an den verantw. Gruppengründer wenden.'); define('_LOBBY_GROUP_MORE_TROUBLE_CONTACT', 'Bei schwerwiegenden Verstößen bitte die Gruppe dem Betreiber dieser Seiten melden!'); define('_LOBBY_GROUP_MODIFY_INDEX', 'Eine eigene Startseite mit Eingangsinformationen für die Besucher dieser Gruppe erstellen'); define('_LOBBY_GROUP_ADMIN_INDEXPAGE', 'Startseite modifizieren'); define('_LOBBY_GROUP_LATEST_MEMBERS', 'Die neuesten Mitglieder'); define('_LOBBY_GROUP_UPDATED', 'Die Gruppe wurde aktualisiert'); define('_LOBBY_GROUP_UPDATE_ERROR', 'Beim Aktualisieren der Gruppendaten ist ein Fehler aufgetreten'); // group // invite define('_LOBBY_INVITE_ENTER_TEXT', 'Einladungstext'); define('_LOBBY_INVITE_TO_SITE', 'Personen ins Netzwerk einladen'); define('_LOBBY_INVITE_ENTER_UNAME', 'Benutzername eingeben'); define('_LOBBY_INVITE_NO_MEMBER', 'Hier externe einladen'); // group // quit define('_LOBBY_QUIT_MEMBERSHIP', 'Beenden der Mitgliedschaft in'); define('_LOBBY_QUIT_MEMBERSHIP_TEXT', 'Durch das Beenden deiner Mitgliedschaft in der Gruppe wirst Du von der Mitgliederliste genommen. Um neu in die Gruppe zu gelangen musst Du dich wieder neu bewerben und ggf. vom Gruppengründer für die Gruppe neu freigeschalten werden. Die Abmeldung aus der Gruppe wird unverzüglich ausgeführt und der Gruppenbesitzer wird darüber per Email informiert.'); define('_LOBBY_QUIT_MEMBERSHIP_LINK', 'Hier klicken um sofort die Mitgliedschaft zu beenden'); define('_LOBBY_MEMBERSHIP_QUITTED', 'Mitgliedschaft der wurde gekündigt und aufgehoben'); define('_LOBBY_MEMBERSHIP_QUIT_REASON', 'Wenn Du dem Gruppengründer den Grund der Kündigung der Mitgliedschaft mitteilen willst, kannst Du folgendes Textfeld nutzen'); // group // forums define('_LOBBY_GROUP_NO_FORUM', 'In dieser Gruppe gibt es aktuell kein Forum'); define('_LOBBY_FORUM_TOPICS', 'Themen'); define('_LOBBY_FORUM_POSTS', 'Beiträge'); define('_LOBBY_FORUM_LATES_TOPIC', 'Neuestes Thema'); define('_LOBBY_FORUM_LATES_POST', 'Letzter Beitrag'); define('_LOBBY_PUBLIC_STATUS_GROUP', 'Einsehbar und nutzbar nur für Gruppenmitglieder'); define('_LOBBY_PUBLIC_STATUS_REGUSERS', 'Einsehbar und nutzbar durch registrierte Benutzer'); define('_LOBBY_PUBLIC_STATUS_ALL', 'Einsehbar durch alle, nutzbar durch registrierte Benutzer'); define('_LOBBY_SINCE_DATE', 'seit dem Datum'); define('_LOBBY_SINCE', 'seit'); define('_LOBBY_TOPICS_SHOW', 'anzeigen'); //define('_LOBBY_FORUM_TOPICS_OF_LAST', 'Themen der letzten'); define('_LOBBY_LATEST_POSTS', 'Die neuesten Forenbeiträge'); define('_LOBBY_LATEST_TOPICS', 'Die neuesten Forenthemen'); // group // join define('_LOBBY_GROUP_JOINGROUP', 'Dieser Gruppe beitreten'); define('_LOBBY_GROUP_JOIN_MODERATED', 'Diese Gruppe ist moderiert, was heisst, dass der Gruppe nicht direkt beigetreten werden kann und für den Beitritt die Erlaubnis des Gruppeninhabers erforderlich ist. Deiner Anmeldung für die Gruppe kannst Du einen Text hinzufügen, welcher dem Verantwortlichen dann angezeigt wird.'); define('_LOBBY_GROUP_JOIN_TEXT', 'Information für den Gruppenadministrator für deine Aufnahme in die Gruppe'); define('_LOBBY_GROUP_JOIN_NOW', 'Der Gruppe sofort beitreten'); define('_LOBBY_GROUP_JOIN_REQUEST', 'Antrag auf Gruppenmitgliedschaft senden'); define('_LOBBY_GROUP_JOIN_PUBLIC', 'Mit dem Klick auf "Gruppe beitreten" ist die Mitgliedschaft sofort aktiv.'); define('_LOBBY_GROUP_REQUESTSENT', 'Anfrage auf Mitgliedschaft wurde abgeschickt und ist in Bearbeitung'); define('_LOBBY_GROUP_JOINERROR', 'Ein Fehler ist aufgetreten beim stellen der Beitrittsanfrage'); define('_LOBBY_GROUP_ADD_ALREDY_MEMBER', 'Du bist bereits Mitglied dieser Gruppe'); define('_LOBBY_GROUP_ADD_ALREDY_PENDING', 'Ein Aufnahmeantrag für die Gruppe ist bereits gestellt - bitte warte das Ergebnis ab!'); define('_LOBBY_GROUPS_ADDERROR', 'Das endgültige Hinzufugen zu einer Gruppe wurde mit einem Fehler abgebrochen!'); // groups // pending define('_LOBBY_GROUP_PENDING_MEMBERS', 'Auf Freischaltung wartende Personen'); define('_LOBBY_GROUP_PENDING_TEXT', 'Die hier nun aufgeführten Personen haben sich für diese Gruppe als Mitglied beworben. Bei der Anmeldung zur Gruppe kann ein Text zur Verbindungsaufnahme ausgefüllt werden, welcher dann hier mit angezeigt wird. Solange durch den Gruppenadministrator keine Aktion erfolgt, ändert sich der Status nicht. Bitte entscheide baldmöglichst, was mit den Personen geschehen soll, damit diese nicht zu lange im Ungewissen gehalten werden. Die Ausgabe der Personen ist nach Datum sortiert - ältere Anfragen erscheinen ganz oben.'); define('_LOBBY_GROUP_NO_PENDING', 'Es warten aktuell keine Mitglieder auf Freischaltung'); define('_LOBBY_GROUP_PENDING_ACCEPT', 'akzeptieren'); define('_LOBBY_GROUP_PENDING_DENY', 'ablehnen'); define('_LOBBY_GROUP_PENDING_ACCEPT_ERROR', 'Beim hinzufügen des Mitglieds ist ein Fehler aufgetreten'); // group // article define('_LOBBY_NEWS_ADDARTICLE', 'Artikel schreiben oder bearbeiten'); define('_LOBBY_NEWS_EXPLANATION', 'Hier können News-Artikel geschrieben werden. Je nachdem, wie die Sichtbarkeit dann von Dir ausgewählt wird, ist der Artikel so nur in der Gruppe, nur für alle Mitglieder dieser Seite oder auch für alle Gäste sichtbar. Dies kann je nach Artikel individuell geregelt werden.'); define('_LOBBY_NEWS_TITLE', 'Titelzeile des Artikels'); define('_LOBBY_NEWS_TEXT', 'Inhalt des Artikels'); define('_LOBBY_NEWS_STORE_UPDATE', 'Artikel speichern bzw. aktualisieren'); define('_LOBBY_NEWS_PUBLIC_STATUS', 'Dieser Artikel soll für folgende Gruppe lesbar sein'); define('_LOBBY_ALL', 'Alle Benutzer dieser Seite inklusive Gäste'); define('_LOBBY_GROUPMEMBERS', 'Nur für Mitglieder dieser Gruppe'); define('_LOBBY_SITEMEMBERS', 'Für registrierte Mitglieder dieser Seite und Mitglieder dieser Gruppe'); define('_LOBBY_NEWS_DELETE_ARTICLE', 'Diesen Artikel unwiderruflich löschen'); define('_LOBBY_NEWS_DATE', 'Datum und Zeit des Artikels'); define('_LOBBY_NEWS_DATE_EXPLANATION', 'Artikel mit Datum in der Zukunft werden erst nach Erreichen des Datums angezeigt und Artikel, welche in die Vergangenheit zurückdatiert werden, werden auch entsprechend eingeordnet'); define('_LOBBY_NEWS_PREVIEW_ARTICLE', 'Vorschau-Modus: Nur Vorschau, kein Speichern'); define('_LOBBY_NEWS_ARTICLEPREVIEW', 'Der Artikel wurde noch nicht gespeichert und nur zum Ansehen der Vorschau erzeugt. Zum Verlassen des Vorschau-Modus bitte das Häkchen bei "'._LOBBY_NEWS_PREVIEW_ARTICLE.'" wieder entfernen!'); define('_LOBBY_FORUM_PREVIEW', 'Dies ist eine Vorschau für das Forenthema. Bitte, wenn das Bearbeiten abgeschlossen ist, das Häkchen bei "'._LOBBY_NEWS_PREVIEW_ARTICLE.'" entfernen und abschicken.'); define('_LOBBY_NEWS_PREVIEW', 'Erzeugte Vorschau für den Artikel'); define('_LOBBY_NEWS_WRITTENBY', 'Autor'); define('_LOBBY_NEWS_CREATED', 'Artikel wurde erstellt'); define('_LOBBY_NEWS_CREATIONERROR', 'Beim Erstellen des Artikels ist ein Fehler aufgetreten'); define('_LOBBY_NEWS_EDIT', 'Artikel editieren'); define('_LOBBY_ARTICLE_PREVIEW', 'Beitragsvorschau'); define('_LOBBY_NEWS_UPDATED', 'Der Artikel wurde aktualisiert'); define('_LOBBY_NEWS_UPDATEERROR', 'Beim Aktualisieren des Artikels ist ein Fehler aufgetreten!'); define('_LOBBY_NEWS_DELETED', 'Artikel wurde gelöscht'); //group // news define('_LOBBY_NEWS_PUBLICSTATUS_TEXT', 'Als Nichtmitglied einer Gruppe oder als nicht registrierter Benutzer sehen sie nur die Artikel der Gruppe ein, welche hierfür freigegeben sind. Wenn Du bei der Gruppe Mitglied wirst bzw. Dich bei dieser Seite anmeldest, hast Du Zugriff auf deutlich mehr Informationen als jetzt.'); define('_LOBBY_NEWS_INFUTURE', 'Das Datum dieses Artikels liegt in der Zukunft - dieser Artikel ist damit nur für den Autor einsehbar'); define('_LOBBY_NEWS_NOAUTH_NOCONTENT', 'Der Artikel existiert nicht oder Du hast nicht die notwendigen Rechte, diesen Artikel einzusehen. Melde Dich bei diesen Seiten an, um den Zugriff auf die Inhalte auszuweiten'); define('_LOBBY_NEWS_SEND_TO_GROUP', 'Artikel per Mail an Gruppe schicken'); define('_LOBBY_ARTICLE_SENT_TO_GROUP', 'Der Artikel wurde an alle Mitglieder der Gruppe geschickt'); define('_LOBBY_ARTICLE_SENT_ERROR', 'Der Artikel konnte nicht verschickt werden - Der Versand wurde abgebrochen'); define('_LOBBY_GROUP_NEWS_FROM', 'Gruppen-News der Gruppe'); define('_LOBBY_NEWS_MAIL_FOOTER', 'Dieses Email wurde aufgrund der Gruppenmitgliedschaft zu obiger Gruppe bei '.pnGetBaseURL().' verschickt. Bei Fragen wende Dich bitte an den Gruppenverantwortlichen / Gruppengründer, welcher diesen Versand veranlasst hat.'); define('_LOBBY_DEAR', 'Lieber Benutzer'); define('_LOBBY_GROUP_NEWS_RELEASED', 'in einer Gruppe, in welcher Du Mitglied bist, wurden News veröffentlicht. Diese hat der Gruppenverantwortliche gleich allen Mitgliedern per Email zustellen lassen, so dass Du schnell auf dem Laufenden gehalten wirst!'); define('_LOBBY_GROUP_LINK', 'Link zur Gruppe'); define('_TRACKING_ARTICLE_SENT_ALREADY', 'Ein Artikel kann nur einmal per Email an alle geschickt werden - Mehrfachsendung nicht möglich!'); // group // membermanagement define('_LOBBY_MEMBER_MANAGEMENT', 'Mitglieder-Management'); define('_LOBBY_MEMBER_MANAGEMENT_EXPLANATION', 'Hier können die Mitglieder der Gruppe bearbeitet werden. So können Mitglieder entfernt werden oder mit dem Status Moderator versehen werden. Grundsätzlich gibt es ein sehr einfaches Rechtesystem für die Verwaltung. Der Gruppeninhaber darf alles, ein Moderator darf alles in den Foren der Gruppen. Artikel schreiben, Foren- und Gruppeneinstellungen ändern ist einem Moderator jedoch nicht erlaubt. Allerdings kann er Forenbeiträge bearbeiten, löschen, sperren etc. und so eine große Hilfe sein. Moderatoren sollten mit Bedacht ausgewählt werden, denn der Gruppeninhaber trägt immer noch die alleinige Verantwortung für seine Gruppe dem Betreiber dieses Netzwerks gegenüber.'); define('_LOBBY_MEMBER_MANAGEMENT_HOWTO', 'Um ein Mitglied hier zu bearbeiten oder seinen Status zu verändern muss es zuerst aus der DropDown-List ausgewählt werden. Dann wird das Bearbeitungsmenü angezeigt und Änderungen, Statuswechsel oder Löschungen können vorgenommen werden.'); define('_LOBBY_MEMBER_MANAGEMENT_SELECTUSER', 'Benutzer der Gruppe auswählen'); define('_LOBBY_MEMBER_MANAGEMENT_LOAD', 'Benutzer laden'); define('_LOBBY_GROUP_REJECT_MEMBER_FAILURE', 'Fehlerhafte Parameter beim Zurückweisen eines Antrags einer Person auf Zugang zu einer Gruppe'); define('_LOBBY_GROUP_DELETE_MEMBER_FAILURE', 'Fehler beim Löschen einer Mitgliedschaft'); define('_LOBBY_USER_NOT_A_MEMBER', 'Person ist kein Mitglied der Gruppe'); define('_LOBBY_USER_IS_OWNER', 'Person ist Gründer der Gruppe'); define('_LOBBY_USER_DELETED', 'Der Benutzer wurde aus der Gruppe gelöscht'); // group // membermanagement // modify define('_LOBBY_MEMBER_MANAGEMENT_GETERROR', 'Der Benutzer konnte nicht geladen werden'); define('_LOBBY_MEMBER_MANAGEMENT_SELECTEDUSER', 'Ausgewählter Benutzer'); define('_LOBBY_MEMBER_MANAGEMENT_USER', 'Daten zum Mitglied'); define('_LOBBY_MEMBER_MANAGEMENT_DELETE', 'Den Benutzer aus dieser Gruppe entfernen'); define('_LOBBY_MEMBER_MANAGEMENT_APPLY', 'Änderungen anwenden'); define('_LOBBY_MEMBER_MANAGEMENT_MODERATOR', 'Benutzer ist Moderator'); define('_LOBBY_MEMBER_MANAGEMENT_NOCHANGE', 'Es wurden keine Änderungen am ausgewählten Benutzer vorgenommen'); define('_LOBBY_MEMBER_MANAGEMENT_BACKLINK', 'Zurück zur Mitgliederverwaltung'); define('_LOBBY_MEMBERSHIP_REQUEST_REJECTED', 'Der Antrag auf Mitgliedschaft wurde nun zurückgewiesen'); define('_LOBBY_MEMBERSHIP_REJECT_ERROR', 'Beim Zurückweisen des Mitgliedschaftsantrags ist ein Fehler aufgetreten'); // group // modifyindex define('_LOBBY_INDEXPAGE_CREATED', 'Startseite wurde gespeichert'); define('_LOBBY_INDEXPAGE_CREATIONERROR', 'Fehler beim Anlegen der Startseite'); define('_LOBBY_INDEXPAGE_ARTICLEPREVIEW', 'Die Seite wurde noch nicht gespeichert und nur zum Ansehen der Vorschau erzeugt. Zum Verlassen des Vorschau-Modus bitte das Häkchen bei "'._LOBBY_NEWS_PREVIEW_ARTICLE.'" wieder entfernen!'); define('_LOBBY_INDEXPAGE_PREVIEW', 'Vorschau des aktuellen Bearbeitungsstands'); define('_LOBBY_INDEXPAGE_EXPLANATION', 'Du kannst eine kleine Startseite erstellen, welche über den neuesten Forenthemen und Antworten und Mitgliedern angezeigt wird. Sie sollte nicht mit Informationen überladen sein und andere interessiert an dieser Gruppe machen.'); define('_LOBBY_INDEXPAGE_STORE_UPDATE', 'Seite speichern / aktualisieren'); define('_LOBBY_INDEXPAGE_TEXT', 'Inhalt, welcher auf der Startseite eingebunden werden soll'); // group // forummanagement define('_LOBBY_FORUM_MANAGEMENT', 'Verwaltung der Gruppenforen'); define('_LOBBY_FORUM_MANAGEMENT_EXPLANATION', 'Hier können vorhandene Foren verwaltet und editiert werden und neue Foren angelegt werden. Wichtig ist vor allem die Sichtbarkeit der Foren. Manches sollen nur Mitglieder lesen können, manches können alle lesen können. Die Einstellungen können jederzeit beliebig editiert und abgeändert werden. Man sollte jedoch vorsichtig sein, wenn man ein Forum in der Sichtbarkeits-Stufe ändert und Inhalte plötzlich allen zugänglich sind und Mitglieder dort Sachen gepostet haben, die sie nicht allen zugänglich haben wollen.'); define('_LOBBY_FORUM_ADD_NEW_FORUM', 'Neues Forum hinzufügen'); define('_LOBBY_FORUM_EXISTING_FORUMS', 'Vorhandene Gruppen-Foren'); define('_LOBBY_FORUM_TITLE', 'Foren-Titel'); define('_LOBBY_FORUM_DESCRIPTION', 'Beschreibungstext für das Forum'); define('_LOBBY_FORUM_PUBLIC_STATUS', 'Inhalt des Forums soll einsehbar bzw. nutzbar sein für'); define('_LOBBY_FORUM_STORE_UPDATE', 'Forum anlegen / aktualisieren'); define('_LOBBY_FORUM_CREATED', 'Das Forum "%forum%" wurde erfolgreich angelegt'); define('_LOBBY_FORUM_SYNC_HINT', 'Bitte verwende die Funktion "synchronisieren", wenn Beitragszähler oder Benutzernamen bei Postings nicht stimmen sollten oder Darstellungsfehler auftreten. Diese Funktion kann manche Probleme beheben.'); define('_LOBBY_FORUM_CREATION_ERROR', 'Beim Erstellen eines Forums ist ein Fehler aufgetreten'); define('_LOBBY_FORUM_NOFORUMS', 'Noch keine Foren angelegt'); define('_LOBBY_FORUM_UPDATED', 'Einstellungen des Forums wurden aktualisiert'); define('_LOBBY_FORUM_UPDATE_ERROR', 'Beim Speichern der Einstellungen zum Forum ist ein Fehler aufgetreten'); define('_LOBBY_FORUM_DELETED', 'Das Forum wurde gelöscht'); define('_LOBBY_FORUM_DELETE_ERROR', 'Beim Löschen des Forums ist ein Fehler aufgetreten'); define('_LOBBY_FORUM_DELETE', 'Forum mit allen Inhalten unwiderruflich, sofort und ohne Nachfrage komplett löschen'); define('_LOBBY_FORUM_WRITABLE_HINT', 'Wenn ein Forum für Gäste oder registrierte Mitglieder freigegeben ist, können diese auch Beiträge in den Foren verfassen. Nur wenn das Forum ausschließlich für die Gruppe eingerichtet wird ist es nur für Gruppenmitglieder einsehbar und beschreibbar.'); define('_LOBBY_FORUM_CLICK_TO_EDIT', 'Um ein Forum zu bearbeiten, bitte in der Tabellenzeile des Forums den Link "bearbeiten" anklicken. '); define('_LOBBY_SYNC_FORUM', 'synchronisieren'); define('_LOBBY_TOPICS_SYNCED_IN', 'Themen wurden synchronisiert in'); define('_LOBBY_FORUM_PERMISSIONS', 'Zugriffsschutz'); define('_LOBBY_FORUM_POS', 'Position'); define('_LOBBY_MOVE_UP', 'Forum nach oben schieben'); define('_LOBBY_MOVE_DOWN', 'Forum nach unten schieben'); define('_LOBBY_FORUM_ACTION', 'Aktion'); define('_LOBBY_STATUS_PUBLIC', 'Gäste: lesen, Nutzer: schreiben, Mitglieder: schreiben'); define('_LOBBY_STATUS_MEMBERS', 'Gäste: kein, Nutzer: schreiben, Mitglieder: schreiben'); define('_LOBBY_STATUS_PRIVATE', 'Gäste: kein, Nutzer: kein, Mitglieder: schreiben'); // forumtopics api define('_LOBBY_TOPICSAPI_ADD_PARAMERROR', 'Parameter falsch übergeben für Funktion Thema erstellen'); define('_LOBBY_TOPIC_CREATION_ERROR', 'Das Thema konnte nicht erstellt werden'); // moderators api define('_LOBBY_GROUP_GETMODERATORS_PARAMFAILURE','Falsche oder fehlende Parameter beim Auslesen der Moderatoren'); define('_LOBBY_GROUP_ADDMODERATOR_FAILURE', 'Fehlerhafte Parameter beim Hinzufügen eines neuen Moderators zu einer Gruppe'); define('_LOBBY_GROUP_MODERATORS_ACCESS_DENY', 'Keine Rechte um einen Moderator zu dieser Gruppe hinzuzufügen oder zu entfernen'); define('_LOBBY_GROUPS_MODERATORADDERRO', 'Fehler beim Hinzufügen eines neuen Moderators zur Gruppe'); define('_LOBBY_GROUPS_MODERATORADDED', 'Benutzer "%user%" wurde als Moderator hinzugefügt'); define('_LOBBY_GROUPS_ALREADY_MOD', 'Der Benutzer ist bereits Moderator'); define('_LOBBY_GROUP_DELMODERATOR_FAILURE', 'Fehlerhafte oder falsche Parameter beim Löschen eines Moderators aus einer Gruppe'); define('_LOBBY_GROUP_WAS_NO_MODERATOR', 'Der Benutzer war kein Moderator und kann daher nicht als Moderator gelöscht werden'); define('_LOBBY_GROUPS_MODERATORREMOVED', 'Moderatorenrechte wurden entzogen'); define('_LOBBY_GROUPS_MODERATORDELERROR', 'Beim Entziehen der Moderatorenrechte ist ein Fehler aufgetreten'); // group // forum define('_LOBBY_CFORUM_SUBSCRIBED', 'Forenabo existent'); define('_LOBBY_FORUM_INDEX', 'Forenübersicht'); define('_LOBBY_FORUM_PUBLICSTATUS_TEXT', 'Wenn Du kein Mitglied dieser Gruppe bist hast Du nur sehr eingeschränkten Zugriff auf die Inhalte dieser Gruppe. Meist sind Foren für nicht registrierte Benutzer generell nicht sichtbar geschalten und auch für Mitglieder des Netzwerks ist viel nicht zugänglich. Wenn Du an der Gruppe Interesse hast, werde Mitglied und gelange so an alle wichtigen Informationen.'); define('_LOBBY_NEW_TOPIC', 'Neues Thema erstellen'); define('_LOBBY_FORUM_NOPOSTS', 'Noch keine Themen vorhanden oder Zugriff auf Themen nicht erlaubt'); define('_LOBBY_FORUM_TOPIC_TITLE', 'Titel des Themas'); define('_LOBBY_FORUM_TOPIC_LASTDATE', 'Datum'); define('_LOBBY_FORUM_TOPIC_EXPLANATION', 'Hier kannst Du ein neues Foren-Thema beginnen. Das Thema wird nach Abschicken dann ganz oben auf der Liste angezeigt und andere Mitglieder können darauf antworten. Bitte gib Dir Mühe beim Schreiben, denn Du willst ja auch, dass andere Leute deinen Text einfach und schnell lesen können. Gerne kannst Du dafür die Vorschaufunktion nutzen. Behalte bitte in Diskussionen auch den guten Umgangston bei, den wir von Dir gewohnt sind! Viel Spaß...'); define('_LOBBY_FORUM_TOPIC_REPLIES', 'Antworten'); define('_LOBBY_NEW_REPLY', 'Antwort zu diesem Thema verfassen'); define('_LOBBY_FORUM_REPLY_EXPLANATION', 'Hier kannst Du nun eine Antwort zum diskutierten Thema machen. Auch wenn manche Diskussion hitzig werden kann: bedenke, dass am anderen Ende der Internets auch ein Mensch sitzt. Aber da guter Umgangston für Dich selbstverständlich ist, brauchen wir hier auch nichts weiter schreiben. Die Antwort wird dann am Ende des Antwort-Baums hinzugefügt und vorherige Autoren werden meist zudem per Email über Deine Nachricht informiert. Um einen schönen Beitrag zu verfassen, kannst Du natürlich die Vorschaufunktion nutzen, bevor die Antwort endgültig gespeichert wird.'); define('_LOBBY_FORUM_REPLY_PREFIX', 'Antwort'); define('_LOBBY_REPLY_POSTED', 'Die Antwort wurde gespeichert'); define('_LOBBY_FORUM_NO_POST_AUTH', 'Ein neues Thema oder eine Antwort zu den Themen können nur Gruppenmitglieder erstellen. Vielleicht ein Grund, der Gruppe beizutreten?'); define('_LOBBY_FORUM_STORE_REPLY', 'Antwort speichern'); define('_LOBBY_NO_FORUM_SELECTED', 'Es wurde kein gültiges Forum ausgewählt'); define('_LOBBY_FORUM_NOT_SUBSCRIBED', 'kein Abo'); define('_LOBBY_FORUM_SUBSCRIBED', 'im Abo'); define('_LOBBY_FORUM_SUBSCRIBE', 'abonnieren'); define('_LOBBY_FORUM_SUBSCRIBED_NOW', 'Forum nun im Abo'); define('_LOBBY_FORUM_SUBSCRIBE_ERROR', 'Bei Versuch das Forum zu abonnieren ist ein Fehler aufgetreten'); define('_LOBBY_FORUM_ALREADY_SUBSCRIBED', 'Das Forum ist bereits im Abonnement'); define('_LOBBY_FORUM_UNSUBSCRIBE', 'Abo löschen'); define('_LOBBY_FORUM_UNSUBSCRIBED_NOW', 'Das Foren-Abonnement wurde gelöscht'); define('_LOBBY_FORUM_UNSUBSCRIBE_ERROR', 'Das Abonnement des Forums konnte nicht gelöscht werden - es ist ein Fehler aufgetreten'); define('_LOBBY_TOPIC_SUBSCRIBED_NOW', 'Das Thema ist nun abonniert'); define('_LOBBY_TOPIC_SUBSCRIBE_ERROR', 'Beim Abonnieren des Themas ist ein Fehler aufgetreten'); define('_LOBBY_TOPIC_ALREADY_SUBSCRIBED', 'Das Thema ist bereits abonniert'); define('_LOBBY_TOPIC_UNSUBSCRIBED_NOW', 'Das Themen-Abonnement wurde gelöscht'); define('_LOBBY_TOPIC_UNSUBSCRIBE_ERROR', 'Beim Löschen des Themen-Abonnements ist ein Fehler aufgetreten'); define('_LOBBY_POSTING_TITLE', 'Titel des Themas'); define('_LOBBY_FORUM_STORE', 'Thema speichern'); define('_LOBBY_FORUM_JUST_PREVIEW', 'Vorschaumodus aktivieren'); define('_LOBBY_POSTING_CONTENT', 'Inhalt des Themas'); define('_LOBBY_TOPIC_CREATED', 'Forenthema wurde erstellt'); define('_LOBBY_TOPIC_CREATION_ERROR', 'Beim Versuch das Thema anzulegen ist ein Fehler aufgetreten'); define('_LOBBY_FORUM_CONTAINS', 'Das Forum enthält'); define('_LOBBY_TOPICS_AND', 'Themen und insgesamt'); define('_LOBBY_POSTS', 'Beiträge'); define('_LOBBY_MODERATOR_ACTIONS', 'Moderationsmöglichkeiten'); define('_LOBBY_TOPIC_DELETE', 'Thema löschen'); define('_LOBBY_TOPIC_CLOSE', 'Thema schließen'); define('_LOBBY_TOPIC_REOPEN', 'Thema wieder eröffnen'); define('_LOBBY_TOPIC_MARK', 'Thema markieren'); define('_LOBBY_TOPIC_UNMARK', 'Themenmarkierung entfernen'); define('_LOBBY_TOPIC_MOVE', 'Thema verschieben'); define('_LOBBY_TOPIC_UPDATE_FAILED', 'Das aktualisieren des Themas ist fehlgeschlagen'); define('_LOBBY_MODERATION_TOPIC_DELETED', 'Das Thema wurde gelöscht'); define('_LOBBY_EDIT_NOTPOSSIBLE', 'Das Editieren des Themas ist nicht mehr möglich. Themen können nur so lange bearbeitet werden, bis eine Antwort auf dieses verfasst wurde und Antworten können nur so lange editiert werden, bis weitere Antworten geschrieben wurden. Dies dient alleine dazu, Diskussionen im Nachhinein nicht verfälschbar zu machen. Wenn dringend etwas verändert werden muss, wende Dich bitte an einen Moderator der Gruppe.'); define('_LOBBY_MODERATION_TOPIC_UNMARKED', 'Die Markierung des Themas wurde zurückgenommen'); define('_LOBBY_MODERATION_TOPIC_MARKED', 'Das Thema wurde markiert'); define('_LOBBY_MODERATION_TOPIC_REOPENED', 'Das Thema wurde wieder eröffnet'); define('_LOBBY_MODERATION_TOPIC_CLOSED', 'Das Thema wurde abgeschlossen'); define('_LOBBY_FORUM_TOPIC_LOCKED', 'Dieses Thema wurde von einem Moderator geschlossen - das Erstellen von weiteren Antworten ist daher nicht mehr möglich'); define('_LOBBY_ILLEGAL_MODERATOR_ACTION', 'Du hast keine Moderatorenrechte. Finger weg von Moderatorenfunktionen!'); define('_LOBBY_MODERATOR_DELETE_POSTING', 'Diesen Beitrag löschen'); define('_LOBBY_MODERATION_POSTING_DELETED', 'Der Beitrag wurde gelöscht'); define('_LOBBY_FORUM_INSTANT_ABO', 'Das Thema gleich abonnieren, falls noch nicht geschehen'); define('_LOBBY_FORUM_POSTING_INFO', 'Informationen'); define('_LOBBY_FORUM_TOPICS_LAST_VISIT', 'Themen seit der letzten Nutzung anzeigen'); define('_LOBBY_FORUM_POSTINGS_LAST_VISIT', 'Beiträge seit der letzten Nutzung anzeigen'); define('_LOBBY_FORUM_LATEST_POSTING', 'Neuesten Beitrag anzeigen'); define('_LOBBY_RESET_LAST_VISIT', 'zurücksetzen'); define('_LOBBY_MODERATOR_EDIT_POSTING', 'Beitrag bearbeiten'); define('_LOBBY_FORUM_EDIT_HINT', 'Beiträge können bearbeitet werden - aber dies nicht unbegrenzt lange. Im Nachhinein veränderte Beiträge können eine Diskussion abfälschen und in falschem Licht erscheinen lassen. Sobald jemand auf deinen Beitrag geantwortet hat oder schon jemand nach Dir eine andere Antwort zum Thema abgegeben hat, ist ein Bearbeiten ausgeschlossen und nur noch durch Moderatoren möglich.'); define('_LOBBY_LAST_EDITED', 'Beitrag wurde editiert; zuletzt am'); define('_LOBBY_POST_MODIFIED', 'Beitrag wurde abgeändert'); define('_LOBBY_MOVE_TOPIC_TO', 'Thema verschieben in Forum'); define('_LOBBY_MODERATION_HOTTOPIC', 'Dieses Thema ist ein viel disktuertes Thema'); define('_LOBBY_POST_MODIFY_ERROR', 'Fehler beim Anändern des Beitrags aufgetreten'); define('_LOBBY_TOPIC_MOVED', 'Thema wurde verschoben'); define('_LOBBY_NO_EDIT_PERMISSION', 'Keine Berechtigung, diesen Beitrag zu editieren'); define('_LOBBY_LAST_REPLY', 'letzte Antwort von'); define('_LOBBY_MARK_QUOTE', 'Bitte in dem Beitrag die Stellen mit der Maus markieren, welche zitiert werden sollen. Mehrfachzitierungen sind möglich und werden automatisch nacheinander eingefügt.'); define('_LOBBY_MARK_QUOTE_DONE', 'Folgender Text wurde im Antwort-Feld als Zitat hinzugefügt. Weitere Zitate sind möglich!'); //groups //help define('_LOBBY_HELP_PAGE', 'Erklärungen und Hilfestellungen zu den Gruppen'); define('_LOBBY_HELP_INTRODUCTION', 'Hier findest Du einige Hilefstellungen rund um die Gruppenfunktionen dieser Seite. Wenn Fragen auftreten, die Du selbst nicht mit Hilfe dieses Textes beantworten kannst, frage bitte beiden Moderatoren der Gruppe oder beim Ersteller der Gruppe nach. Diese werden Dir helfen können, da sie mit diesen Funktionen hier vertraut sind. Sofern das nicht Hilft, kannst Du dich an den Support dieser Seite wenden. Beachte aber, dass eine Antwort unter Umständen nicht sofort bearbeitet werden kann und die Bearbeitung einige Werktage benötigt.'); define('_LOBBY_HELP_GENERAL', 'Generelles zu den Gruppen'); define('_LOBBY_HELP_GENERAL_TEXT', 'Mit dem Gruppenmodul ist es möglich, eigene Gruppen einzurichten. Gruppen haben einen Titel, eine Beschreibung, verschiedene Einstellungen zum Mitgliedermanagement und die Möglichkeit, Koordinaten anzugeben. Sofern Koordinaten angegeben werden kann die Gruppe geografisch zugeordnet werden und in eine Landkarte mit eingefügt werden. Gruppen sollen Interessensgemeinschaften möglich machen, welche im Idealfall sich geografisch einordnen lassen. Zudem ist es optional möglich, Gruppen in Kategorien einzuordnen. So ist eine Klassifizierung der Gruppen gewährleistet.'); define('_LOBBY_HELP_MEMBERSHIP', 'Mitgliedschaft in Gruppen'); define('_LOBBY_HELP_MEMBERSHIP_TEXT', 'Gruppen kann grundsätzlich jeder beitreten. Möglicherweise bedarf der Beitritt - das ist von den Einstellungen abhängig, welche der Gruppengründer getroffen hat - der Zustimmung des Gruppengründers. Über die Zustimmung wirst Du jedoch dann per Email informiert. Ebenso wird der Gruppengründer informiert. Du brauchst also keine Angst haben, dass dein Mitgliedschaftsantrag gehörlos untergeht. Sofern keine gesonderte Zustimmung notwendig ist, wird man unmittelbar Mitglied der Gruppe, für welche man sich beworben hat.'); define('_LOBBY_HELP_GROUPRULES', 'Regeln und Ziele einer Gruppe'); define('_LOBBY_HELP_GROUPRULES_TEXT', 'Die Regeln in einer Gruppe hängen von Ziel und Gründer der Gruppe ab. Wie man sich in der Gruppe zu verhalten hat, sollte der Gruppengründer am besten als Beitrag dort schreiben. Natürlich kann sich der Gruppengründer nicht über die allgemeinen Geschäftsbedingungen oder die Hausordnung dieser Seite hinwegsetzen. Die Regeln müssen also im Rahmen bleiben. Die Moderationsgewalt und die alleinige Verantwortung für eine Gruppe liegt beim Gruppengründer, weshalb bei Fragen und Problemen dieser auch der erste Ansprechpartner für Dich sein sollte. Hilft dies nichts und besteht ein gravierendes Problem, kannst Du dich vertrauensvoll an den / die Seitenbetreiber bzw. den Support dieser Plattform wenden - um Dein Anliegen wird sich dann gekümmert.'); define('_LOBBY_HELP_FUNCTIONS', 'Funktionen und Möglichkeiten einer Gruppe'); define('_LOBBY_HELP_COORDS', 'Standort festlegen'); define('_LOBBY_HELP_COORDS_TEXT', 'Die Gruppe kann mit einer Koordinate verknüpft werden und bekommt dann auf der Startseite eine Karte mit eingeblendet, wo die Gruppe zu Hause ist. So erkennt man sofort, wo eine Gruppe regional hingehört. Zudem können alle Gruppen einer Kategorie so grafisch auf eine Landkarte projeziert werden, was bei der regionalen Suche nach Gruppen helfen kann.'); define('_LOBBY_HELP_NEWS', 'Neuigkeiten und Artikel'); define('_LOBBY_HELP_NEWS_TEXT', 'Jede Gruppe hat ein eigenes Newssystem und kann so Artikel veröffentlichen. Beim Veröffentlichen lässt sich leicht festlegen, welcher Personenkreis (Gäste, Benutzer der Seite, Mitglieder der Gruppe) die Nachricht lesen darf. Die Nachrichten werden dann bei der Gruppe stets in der Menüspalte eingeblendet und sind auch per RSS-Feed abrufbar.'); define('_LOBBY_HELP_FORUMS', 'Diskussionsforen'); define('_LOBBY_HELP_FORUMS_TEXT', 'Jede Gruppe kann eine beliebig große Forenlandschaft einrichten. Hier kann auch festgelegt werden, welcher Personenkreis (Gäste, Benutzer der Seite, Mitglieder der Gruppe) das Forum einsehen darf bzw. benutzen darf. Hier ist zu beachten, welche Wirkung die Foren erzielen sollen. Manchmal bietet es sich an, wenn man Interessenten einen Einblick in die Gruppe geben will, bestimmte Foren auch für Seitenmitglieder bzw. Gäste einsehbar bzw. nutzbar zu machen.'); define('_LOBBY_HELP_FORUMS_TEXT2', 'Foren und Beiträge können ins Abonnement genommen werden. Das bedeutet dann, dass Du bei neuen Beiträge oder Antworten automatisch dieses per Email zugeschickt bekommst.'); define('_LOBBY_HELP_FORUMS_TEXT3', 'Beim Einrichten einer Gruppe wird die Möglichkeit angeboten, eine Standard-Forenlandschaft mit zu erstellen. Diese kann als Anhalt direkt mit generiert werden und erleichtert neuen Gruppengründern die Arbeit. Selbstverständlich lassen sich Foren im Nachhinein verändern oder wieder löschen.'); define('_LOBBY_HELP_MISC', 'Verschiedenes'); define('_LOBBY_HELP_NAVIGATION_HINT', 'Bei der Nutzung der Gruppen solltest Du unbedingt die Nutzung deiner Browser-Tasten für "vor" und "zurück" verzichten. Nutzt Du diese Tasten, kann dies zu Fehler führen. Deswegen bitte wenn möglich zur Navigation nur die Links auf den Seiten verwenden.'); // forum legend define('_LOBBY_FORUM_LEGEND', 'Symbol-Erklärungen'); define('_LOBBY_FORUM_HOT_TOPIC', 'Vieldiskutiertes Thema'); define('_LOBBY_FORUM_TOPIC_MARKED', 'Markiertes Thema'); define('_LOBBY_FORUM_LAST_TOPIC_LINK', 'Link zu aktuellster Antwort (roter Rand = ungelesene Antwort)'); // list define('_LOBBY_SORT_CRITERIA', 'Anzeige ändern / neu sortieren'); define('_LOBBY_ALPHABETICAL', 'alphabetisch (A-Z)'); define('_LOBBY_LATEST', 'Gründungsdatum (neueste zuerst)'); define('_LOBBY_COUNTEDMEMBERS', 'Mitgliederanzahl'); define('_LOBBY_MAP', 'alle als Karte anzeigen'); define('_LOBBY_NO_CAT_FILTER', 'alle Kategorien anzeigen'); define('_LOBBY_RELOAD', 'neu laden'); // albummanagement define('_LOBBY_ALBUM_UPDATED', 'Album aktualisiert'); define('_LOBBY_ALBUM_MANAGEMENT', 'Gruppen-Alben verwalten'); define('_LOBBY_ALBUM_MANAGEMENT_EXPLANATION', 'Hier kannst Du für deine Gruppe Alben anlegen. Diese Alben können dann durch die Gruppe gefüllt werden. Jeder kann dann ganz einfach aus seinen Benutzerbildern Bilder in das Album kopieren. Die Alben selbst werden dann nach Datum sortiert, d.h. das neueste Album ist ganz oben.'); define('_LOBBY_FORUM_EXISTING_ALBUMS', 'Angelegte Alben'); define('_LOBBY_ALBUM_DATE', 'Verknüpftes Datum'); define('_LOBBY_ALBUM_TITLE', 'Alben-Titel'); define('_LOBBY_ALBUM_DESCRIPTION', 'Alben-Beschreibung'); define('_LOBBY_ACTION', 'Aktion'); define('_LOBBY_ADD_NEW_ALBUM', 'Neues Album erstellen'); define('_LOBBY_ALBUM_PUBLIC_STATUS', 'Regelung der Zugriffsrechte auf das Album'); define('_LOBBY_ALBUM_STORE_UPDATE', 'Album anlegen oder Daten aktualisieren'); define('_LOBBY_ALBUM_CREATED', 'Das Album ist nun erstelle und Gruppenmitglieder können Bilder hinzufügen'); define('_LOBBY_ALBUM_DELETE', 'Album löschen'); define('_LOBBY_GROUP_ALBUMS', 'Foto-Alben'); define('_LOBBY_ALBUMS_UPLOAD_PICTURES_FIRST', 'Du kannst nur Bilder hinzufügen, welche in deinem Benutzeralbum sind'); define('_LOBBY_EDITMODE_ALBUM_HINT', 'Alle Fotos, welche sich in Ihrem Benutzeralbum befinden, sind hier dargestellt. Mit einem Klick auf das Foto wird es dem Album hinzugefügt.'); define('_LOBBY_ALBUM_ADDMODE_OFF', 'Modus zum Hinzufügen von Bildern deaktivieren'); define('_LOBBY_ALBUM_ADDMODE_ON', 'Modus zum Hinzufügen von Bildern aktivieren'); define('_LOBBY_ALBUM_OVERVIEW', 'Zurück zur Alben-Übersicht der Gruppe'); define('_LOBBY_PICTURE_ADDED', 'Das Bild wurde dem Album hinzugefügt. Wichtig: Das Bild wurde im Gruppenalbum nur referenziert, d.h. wenn das Bild später aus der eigenen Galerie gelöscht wird, wird es automatisch auch vom Gruppenalbum entfernt.'); define('_LOBBY_PICTURE_ADD_ERROR', 'Das Bild konnte dem Album nicht hinzugefügt werden.'); define('_LOBBY_PICTURE_ALREADY_EXISTS', 'Das Bild existiert schon in diesem Album und kann nicht zweimal hinzugefügt werden'); define('_LOBBY_NO_PICTURE_AVAILABLE_OR_VISIBLE','Es wurde entweder noch kein Bild im Album hinzugefügt oder es fehlen Dir Zugriffsrechte auf das Album'); define('_LOBBY_UPLOADED_PICTURES', 'Hochgeladene Bilder'); define('_LOBBY_CLICK_AND_USE_CURSOR_FOR_SLIDESHOW', 'Nach Klick auf ein Bild kann mit den Cursortasten bequem weitergeschalten werden!'); define('_LOBBY_DELETE_PICTURE_ABOVE', 'Obiges Bild aus dem Album entfernen'); define('_LOBBY_SHOW_DELETE_LINKS', 'Links zum Entfernen der Bilder anzeigen.'); define('_LOBBY_PICTURE_DELETED', 'Bild wurde entfernt'); define('_LOBBY_PICTURE_ADD_ERROR', 'Bild konnte nicht entfernt werden'); define('_LOBBY_PICTURE_DEL_ERROR', 'Das Bild konnte nicht gelöscht werden. Möglicherweise sind die hierfür notwendigen Zugriffsrechte nicht vorhanden.'); define('_LOBBY_NO_ALBUMS', 'Keine Alben bisher angelegt'); define('_LOBBY_GROUP_ADMIN_ALBUM_MANAGEMENT', 'Gruppen-Bildergalerien'); define('_LOBBY_ALBUM_DELETED', 'Album gelöscht'); define('_LOBBY_ALBUM_DELETE_ERROR', 'Fehler: Album konnte nicht gelöscht werden'); define('_LOBBY_LATEST_PICTURE', 'Neuester Bilderupload'); define('_LOBBY_SHOW_ALL_ALBUMS', 'Alle Gruppen-Alben anzeigen'); define('_LOBBY_FORUMS_SHOW_NEWS_IN_BOXES', 'Die neuesten Nachrichten der Gruppe seitlich automatisch aufklappen und anzeigen'); define('_LOBBY_FORUMS_SHOW_FORUM_LINKS_IN_BOXES', 'Die Foren-Schnell-Links seitlich automatisch aufklappen und anzeigen'); define('_LOBBY_FORUMS_SHOW_LATEST_ALBUM_PICTURE_IN_BOXES', 'Letzten Bilder-Upload der Gruppenalben seitlich automatisch aufklappen und anzeigen'); define('_LOBBY_VISIT_ALBUM', 'Album aufrufen'); define('_LOBBY_NO_PERM_TO_DEL_PICTURE', 'Dieses Bild kann nur durch den Gruppenbetreiber oder den Inhaber des Bildes gelöscht werden!'); define('_LOBBY_ALBUM_DELETED', 'Das Album wurde gelöscht'); define('', ''); define('', ''); define('', ''); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_admin_settingsHandler { var $id; function initialize(&$render) { $modvars = pnModGetVar('lobby'); $render->assign($modvars); return true; } function handleCommand(&$render, &$args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) { return LogUtil::registerPermissionError(); } if ($args['commandName']=='update') { // get the pnForm data and do a validation check $obj = $render->pnFormGetValues(); if (!$render->pnFormIsValid()) return false; pnModSetVar('lobby','postsperpage', $obj['postsperpage']); pnModSetVar('lobby','topicsperpage', $obj['topicsperpage']); pnModSetVar('lobby','newsperpage', $obj['newsperpage']); pnModSetVar('lobby','creategroupurl', $obj['creategroupurl']); LogUtil::registerStatus(_LOBBBY_SETTINGS_STORED); return $render->pnFormRedirect(pnModURL('lobby','admin','settings')); } return $render->pnFormRedirect(pnModURL('lobby','admin','categories')); } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * Populate tables array for the module * * @return array The table information. */ function lobby_pntables() { // Initialise table array $table = array(); $lobby = DBUtil::getLimitedTablename('lobby'); $table['lobby'] = $lobby; // Set the table name $table['lobby_groups'] = $lobby."_groups"; $table['lobby_categories'] = $lobby."_categories"; $table['lobby_moderators'] = $lobby."_moderators"; $table['lobby_members'] = $lobby."_members"; $table['lobby_pages'] = $lobby."_pages"; $table['lobby_users'] = $lobby."_users"; $table['lobby_members_pending'] = $lobby."_members_pending"; $table['lobby_invitations'] = $lobby."_invitations"; $table['lobby_news'] = $lobby."_news"; $table['lobby_forums'] = $lobby."_forums"; $table['lobby_forum_subscriptions'] = $lobby."_forum_subscriptions"; $table['lobby_forum_topics'] = $lobby."_forum_topics"; $table['lobby_forum_topic_subscriptions'] = $lobby."_forum_topic_subscriptions"; $table['lobby_forum_posts'] = $lobby."_forum_posts"; $table['lobby_forum_posts_text'] = $lobby."_forum_posts_text"; $table['lobby_albums'] = $lobby."_albums"; $table['lobby_albums_pictures'] = $lobby."_albums_pictures"; // Columns for tables $table['lobby_groups_column'] = array ( 'id' => 'id', 'uid' => 'uid', 'title' => 'title', 'date' => 'date', 'members' => 'members', 'articles' => 'articles', 'indextopics' => 'indextopics', 'topics' => 'topics', 'forums' => 'forums', 'postings' => 'postings', 'picture' => 'picture', 'forumsvisible' => 'forumsvisible', 'description' => 'description', 'last_action' => 'last_action', 'accepted' => 'accepted', 'moderated' => 'moderated', 'category' => 'category', 'albums' => 'albums', 'albums_pictures' => 'albums_pictures', 'coordinates' => 'coordinates', 'boxes_shownews' => 'boxes_shownews', 'boxes_showforumlinks' => 'boxes_showforumlinks', 'boxes_showalbums' => 'boxes_showalbums' ); $table['lobby_groups_column_def'] = array ( 'id' => "I AUTOINCREMENT PRIMARY", 'uid' => "I NOTNULL DEFAULT 0", 'title' => "C(60) NOTNULL DEFAULT ''", 'date' => "T NOTNULL", 'members' => "I NOTNULL DEFAULT 0", 'articles' => "I NOTNULL DEFAULT 0", 'indextopics' => "I NOTNULL DEFAULT 5", 'topics' => "I NOTNULL DEFAULT 0", 'forums' => "I NOTNULL DEFAULT 0", 'postings' => "I NOTNULL DEFAULT 0", 'picture' => "C(120) NOTNULL DEFAULT ''", 'forumsvisible' => "I(1) NOTNULL DEFAULT 1", 'description' => "C(255) NOTNULL DEFAULT ''", 'last_action' => "T NOTNULL", 'accepted' => "L NOTNULL DEFAULT 0", 'moderated' => "L NOTNULL DEFAULT 0", 'category' => "I NOTNULL DEFAULT 0", 'albums' => "I NOTNULL DEFAULT 0", 'albums_pictures' => "I NOTNULL DEFAULT 0", 'coordinates' => "C(99) NOTNULL DEFAULT ''", 'boxes_shownews' => "I(1) NOTNULL DEFAULT 1", 'boxes_showforumlinks' => "I(1) NOTNULL DEFAULT 1", 'boxes_showalbums' => "I(1) NOTNULL DEFAULT 1" ); $table['lobby_categories_column'] = array ( 'id' => 'id', 'title' => 'title', 'official' => 'official' ); $table['lobby_categories_column_def'] = array ( 'id' => "I AUTOINCREMENT PRIMARY", 'title' => "C(60) NOTNULL DEFAULT ''", 'official' => "L NOTNULL" ); $table['lobby_pages_column'] = array ( 'id' => 'id', 'text' => 'text' ); $table['lobby_pages_column_def'] = array ( 'id' => "I NOTNULL PRIMARY", 'text' => "XL NOTNULL" ); $table['lobby_users_column'] = array ( 'id' => 'id', 'array' => 'array', 'last_action' => 'last_action' ); $table['lobby_users_column_def'] = array ( 'id' => "I NOTNULL PRIMARY", 'array' => "XL NOTNULL", 'last_action' => "T NOTNULL" ); $table['lobby_moderators_column'] = array ( 'id' => 'id', 'gid' => 'gid', 'uid' => 'uid' ); $table['lobby_moderators_column_def'] = array ( 'id' => "I AUTOINCREMENT PRIMARY", 'gid' => "I NOTNULL DEFAULT 0", 'uid' => "I NOTNULL DEFAULT 0" ); $table['lobby_members_column'] = array ( 'id' => 'id', 'gid' => 'gid', 'uid' => 'uid', 'date' => 'date' ); $table['lobby_members_column_def'] = array ( 'id' => "I AUTOINCREMENT PRIMARY", 'gid' => "I NOTNULL DEFAULT 0", 'uid' => "I NOTNULL DEFAULT 0", 'date' => "T NOTNULL" ); $table['lobby_members_pending_column'] = array ( 'id' => 'id', 'gid' => 'gid', 'uid' => 'uid', 'date' => 'date', 'text' => 'text' ); $table['lobby_users_column'] = array ( 'id' => 'id', 'array' => 'array', 'last_action' => 'last_action' ); $table['lobby_users_column_def'] = array ( 'id' => "I PRIMARY", 'array' => "XL NOTNULL", 'last_action' => "T NOTNULL" ); $table['lobby_members_pending_column_def'] = array ( 'id' => "I AUTOINCREMENT PRIMARY", 'gid' => "I NOTNULL DEFAULT 0", 'uid' => "I NOTNULL DEFAULT 0", 'date' => "T NOTNULL", 'text' => "C(255) NOTNULL DEFAULT ''" ); $table['lobby_invitations_column'] = array ( 'id' => 'id', 'gid' => 'gid', 'uid' => 'uid', 'invited_uid' => 'invited_uid', 'text' => 'text', 'date' => 'date' ); $table['lobby_invitations_column_def'] = array ( 'id' => "I AUTOINCREMENT PRIMARY", 'gid' => "I NOTNULL DEFAULT 0", 'uid' => "I NOTNULL DEFAULT 0", 'invited_uid' => "I NOTNULL DEFAULT 0", 'text' => "C(255) NOTNULL DEFAULT ''", 'date' => "T NOTNULL" ); $table['lobby_news_column'] = array ( 'id' => 'id', 'gid' => 'gid', 'public_status' => 'public_status', 'uid' => 'uid', 'title' => 'title', 'text' => 'text', 'date' => 'date', 'sent' => 'sent' ); $table['lobby_news_column_def'] = array ( 'id' => "I AUTOINCREMENT PRIMARY", 'gid' => "I NOTNULL DEFAULT 0", 'public_status' => "L NOTNULL DEFAULT 0", 'uid' => "I NOTNULL DEFAULT 0", 'title' => "C(60) NOTNULL DEFAULT ''", 'text' => "XL NOTNULL", 'date' => "T NOTNULL", 'sent' => "I(1) NOTNULL DEFAULT 0" ); $table['lobby_forums_column'] = array( 'id' => 'id', 'gid' => 'gid', 'title' => 'title', 'description' => 'description', 'sort_nr' => 'sort_nr', 'topics' => 'topics', 'posts' => 'posts', 'public_status' => 'public_status', 'last_poster' => 'last_poster', 'last_poster_date' => 'last_poster_date', 'last_poster_tid' => 'last_poster_tid', 'last_topic_poster' => 'last_topic_poster', 'last_topic_date' => 'last_topic_date', 'last_tid' => 'last_tid' ); $table['lobby_forums_column_def'] = array( 'id' => "I AUTOINCREMENT PRIMARY", 'gid' => "I NOTNULL DEFAULT 0", 'title' => "C(60)", 'description' => "C(255)", 'sort_nr' => "I NOTNULL DEFAULT -1", 'topics' => "I NOTNULL DEFAULT 0", 'posts' => "I NOTNULL DEFAULT 0", 'public_status' => "L NOTNULL DEFAULT 0", 'last_poster' => "I NOTNULL DEFAULT 0", 'last_poster_date' => "T NOTNULL", 'last_poster_tid' => "I NOTNULL DEFAULT 0", 'last_topic_poster' => "I NOTNULL DEFAULT 0", 'last_topic_date' => "T NOTNULL", 'last_tid' => "I NOTNULL DEFAULT 0" ); $table['lobby_forum_subscriptions_column'] = array( 'id' => 'id', 'fid' => 'fid', 'uid' => 'uid' ); $table['lobby_forum_subscriptions_column_def'] = array( 'id' => "I AUTOINCREMENT PRIMARY", 'fid' => "I NOTNULL DEFAULT 0", 'uid' => "I NOTNULL DEFAULT 1" ); $table['lobby_forum_topics_column'] = array( 'id' => 'id', 'fid' => 'fid', 'pid' => 'pid', 'gid' => 'gid', 'replies' => 'replies', 'locked' => 'locked', 'marked' => 'marked', 'date' => 'date', 'last_date' => 'last_date', 'last_pid' => 'last_pid', 'last_uid' => 'last_uid', 'uid' => 'uid' ); $table['lobby_forum_topics_column_def'] = array( 'id' => "I NOTNULL PRIMARY", 'fid' => "I NOTNULL DEFAULT 0", 'pid' => "I NOTNULL DEFAULT 0", 'gid' => "I NOTNULL DEFAULT 0", 'replies' => "I NOTNULL DEFAULT 0", 'locked' => "L NOTNULL DEFAULT 0", 'marked' => "L NOTNULL DEFAULT 0", 'date' => "T NOTNULL", 'last_date' => "T NOTNULL", 'last_pid' => "I NOTNULL DEFAULT 0", 'last_uid' => "I NOTNULL DEFAULT 1", 'uid' => "I NOTNULL DEFAULT 1" ); $table['lobby_forum_topic_subscriptions_column'] = array( 'id' => 'id', 'tid' => 'tid', 'uid' => 'uid' ); $table['lobby_forum_topic_subscriptions_column_def'] = array( 'id' => "I AUTOINCREMENT PRIMARY", 'tid' => "I NOTNULL DEFAULT 0", 'uid' => "I NOTNULL DEFAULT 1" ); $table['lobby_forum_posts_column'] = array( 'id' => 'id', 'uid' => 'uid', 'fid' => 'fid', 'tid' => 'tid', 'title' => 'title', 'date' => 'date' ); $table['lobby_forum_posts_column_def'] = array( 'id' => "I AUTOINCREMENT PRIMARY", 'uid' => "I NOTNULL DEFAULT 1", 'fid' => "I NOTNULL DEFAULT 0", 'tid' => "I NOTNULL DEFAULT 0", 'title' => "C(100) NOTNULL DEFAULT ''", 'date' => "T NOTNULL" ); $table['lobby_forum_posts_text_column'] = array( 'id' => 'id', 'text' => 'text' ); $table['lobby_forum_posts_text_column_def'] = array( 'id' => "I NOTNULL PRIMARY ", 'text' => "XL NOTNULL" ); $table['lobby_albums_column'] = array( 'id' => 'id', 'gid' => 'gid', 'title' => 'title', 'description' => 'description', 'date' => 'date', 'public_status' => 'public_status' ); $table['lobby_albums_column_def'] = array( 'id' => "I AUTOINCREMENT PRIMARY ", 'gid' => "I NOTNULL DEFAULT 0", 'title' => "C(125) NOTNULL DEFAULT ''", 'description' => "XL NOTNULL", 'date' => "T NOTNULL", 'public_status' => "L NOTNULL DEFAULT 0" ); $table['lobby_albums_pictures_column'] = array( 'id' => 'id', 'aid' => 'aid', 'pid' => 'pid', 'date' => 'date' ); $table['lobby_albums_pictures_column_def'] = array( 'id' => "I AUTOINCREMENT PRIMARY ", 'aid' => "I NOTNULL DEFAULT 0", 'pid' => "I NOTNULL DEFAULT 0", 'date' => "T NOTNULL" ); // Return table information return $table; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ // general define('_LOBBY_YES', 'yes'); define('_LOBBY_NO', 'no'); define('_LOBBY_BACKEND', 'Administration of "lobby" module'); // Header define('_LOBBY_MAIN', 'Administration backend'); define('_LOBBY_PENDING_GROUPS', 'Activate pending groups'); define('_LOBBY_CATEGORY_MANAGEMENT', 'Manage categories'); define('_LOBBY_SETTINGS', 'Settings'); define('_LOBBY_IMPORT', 'Import'); // main define('_LOBBY_AMDIN_TEXT', 'Welcome to the admin backend. You can activate pending groups and configure main settings here'); define('_LOBBY_AMDIN_PENDING_GROUPS', 'Amount of pending groups'); // import define('_LOBBY_IMPORT_MANAGEMENT', 'Import different content into groups'); define('_LOBBY_IMPORT_USERS', 'Import user groups'); define('_LOBBY_IMPORT_USERS_TEXT', 'Just choose the user group you want to import. Action will be done immediately after clicking the button'); define('_LOBBY_IMPORT_FORUMS', 'Import forums'); define('_LOBBY_IMPORT_FORUMS_TEXT', 'Choose the source and target. Import will be done immediately after a click on the button'); define('_LOBBY_COPY_FROM', 'Copy from'); define('_LOBBY_COPY_TO', 'to'); define('_LOBBY_SELECT_FOR_ACTION', 'Choose for import'); define('_LOBBY_NO_IMPORT_SELECTED', 'Please choose an import type!'); define('_LOBBY_IMPORT_SKIP_USER', 'User not imported because the user is already member of the target group'); define('_LOBBY_ADDED_USER', 'Adding user'); define('_LOBBY_IMPORTED_USERS', 'user imported sucessfully'); define('_LOBBY_FAILED_USER', 'Importing users failed'); define('_LOBBY_TOPIC_IMPORT_ERROR', 'Importing topic failed'); define('_LOBBY_TOPIC_IMPORTED', 'Topic imported'); define('_LOBBY_POSTING_IMPORT_ERROR', 'Postings belonging to a topic could not be imported'); // categories define('_LOBBY_CATEGORY_OFFICIAL', 'official category'); define('_LOBBY_CATEGORY_MANAGEMENT', 'Manage categories'); define('_LOBBY_CATEGORY_TITLE', 'category title'); define('_LOBBY_CATEGORY_UPDATE_STORE', 'store / update'); define('_LOBBY_CATEGORY_INSERTED', 'Category was added'); define('_LOBBY_CATEGORY_STOREFAILURE', 'Storing or updating category failed'); define('_LOBBY_CATEGORY_UPDATED', 'Category updated'); define('_LOBBY_CATEGORY_OFFICIAL_EXPL', 'Official groups are moderated and have to be activated by the site administrator. Groups that are not marked as official (non official) will be active after the user creates them.'); define('_LOBBY_CATEGORY_NOCATECORIES', 'There are no categories created yet'); define('_LOBBY_CATEGORY_OVERVIEW', 'Category overview. Click on the title to modify a category'); define('_LOBBY_CATEGORY_DELETE', 'Delete this category (only possible if category is not used yet)'); define('_LOBBY_CATEGORY_DELETEERROR', 'Deleting category failed'); define('_LOBBY_CATEGORY_DELETED', 'Category deleted'); // pending define('_LOBBY_PENDING_NO_PENDING', 'No groups are pending'); define('_LOBBY_GROUP_NAME', 'Description'); define('_LOBBY_GROUP_AUTHOR', 'Creator'); define('_LOBBY_GROUP_ DATE', 'Creation date'); define('_LOBBY_GROUP_CATEGORY', 'Category'); define('_LOBBY_ACTION', 'Action'); define('_LOBBY_ACCEPT', 'activate'); define('_LOBBY_DELETE', 'delete'); define('_LOBBY_GROUP_ACCEPTED', 'Group was activated'); define('_LOBBY_GROUP_ACCEPTED_ERROR', 'Activating group failed'); // settings define('_LOBBY_CREATE_GROUP_URL', 'You can optionally specify a url here that should be linked with the "create new group" link instead of standard page (for example, to create an explanation page)'); define('_LOBBY_CREATE_GROUP_URL_TEXT', 'If there is no URL specified the users will automatically be forwarded to the group creation form. You may want to create your own page to explain this step and link the form manually'); define('_LOBBY_SETTINGS_MANAGEMENT', 'Manage settings'); define('_LOBBY_TOPICS_PER_PAGE', 'Amount of topics to show on a page'); define('_LOBBY_POSTS_PER_PAGE', 'Amount of postings to show in a topic page'); define('_LOBBY_NEWS_PER_PAGE', 'News items per page in the news section'); define('_LOBBY_SETTINGS_UPDATE', 'Store settings'); define('_LOBBBY_SETTINGS_STORED', 'Settings stored');<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ // general define('_LOBBY_DEAR', 'Dear'); define('_LOBBY_GROUP_INVITATION_FOR', 'Invitation to group'); define('_LOBBY_FROM', 'from'); // new group define('_LOBBY_EMAIL_NEW_GROUP', 'A new group has been registered'); define('_LOBBY_EMAIL_PENDING_NOW', 'Please activate the group if it is in an official category'); define('_LOBBY_EMAIL_NEW_GROUP_FOR', 'New group registration for'); define('_LOBBY_EMAIL_VIEW_GROUP', 'Show group'); define('_LOBBY_EMAIL_VIEW_PENDING', 'Manage pending groups'); // new join define('_LOBBY_EMAIL_NEW_REQUEST_FOR_GROUP','Subscription request for group'); define('_LOBBY_EMAIL_NEW_GROUP_MEMBER_FOR', 'New member in group'); define('_LOBBY_EMAIL_AT', 'at'); define('_LOBBY_EMAIL_NEW_MEMBER', 'Username of new request / member'); define('_LOBBY_EMAIL_PENDING_USER', 'User is awaiting activation'); define('_LOBBY_EMAIL_PENDING_USERS', 'Manage pending users for group'); define('_LOBBY_EMAIL_USER_ADDED', 'User was added to group'); // membership ended define('_LOBBY_EMAIL_MEMBERSHIP_ENDED', 'A member has cancelled membership in group '); define('_LOBBY_EMAIL_MEMBERSHIP_QUIT', 'User who has left the group'); define('_LOBBY_EMAIL_QUIT_TEXT', 'This text was entered as reason'); // group accepted define('_LOBBY_EMAIL_ACCEPTED_AT', 'was activated at'); define('_LOBBY_EMAIL_GROUP_ACCEPTED', 'Group was activated by site administrator'); // membership request rejected define('_LOBBY_MEMBERSHIP_REQUEST_FOR', 'Membership request for'); define('_LOBBY_WAS_REJECTED', 'was rejected'); define('_LOBBY_CONTACT_OWNER_FOR_DETAILS', 'We are sorry that we have to inform you that your membership request was rejected. Please contact the group owner for details.'); // membership request accepted define('_LOBBY_WAS_ACCEPTED', 'was accepted'); // new topic notification define('_LOBBY_EMAIL_NEWTOPIC_GROUP', 'New topic in group'); define('_LOBBY_NEW_TOPIC_POSTED', 'Topic that was created'); define('_LOBBY_POSTER', 'Author'); // new reply to a topic notification define('_LOBBY_EMAIL_NEWREPLY', 'New reply'); define('_LOBBY_IN_GROUP', 'in group'); define('_LOBBY_TO_TOPIC_OF', 'For the topic of'); define('_LOBBY_WAS_REPLY_POSTED', 'there was a new answer written'); // invitation define('_LOBBY_GROUP_INVITATION_FOR', 'You were invited to the group'); define('_LOBBY_GROUP_INVITATION_OF', 'Inviting user\'s username'); define('_LOBBY_GROUP_INVITATION_TEXT', 'The following text was added to the invitation by the inviting user'); define('_LOBBY_GROUP_HOMEPAGE', 'Link to the webpage of this group'); define('_LOBBY_GROUP_JOINPAGE', 'Get a member of the group'); <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get topics for a forum * * @param $args['fid'] int forum id * @param $args['id'] int topic id (optional) * @param $args['offset'] int optional offset * @param $args['numrows'] int optional numrows * @param $args['date'] int optional date filter * @param $args['count'] int optional to count only * @param $args['sort'] string optional, == creationdate if topics, not postings should be handled * @param $args[]'official'] int optional, ==1 if only topics from official groups should be loaded * @param $args['owngroups'] int optional, ==1 if only own groups should be handled * @param $args['sticky'] int optional, ==1 if marked topics should be on top * @return int or boolean */ function lobby_forumtopicsapi_get($args) { $fid = (int)$args['fid']; $gid = (int)$args['gid']; $id = (int)$args['id']; $count = (int)$args['count']; $official = (int)$args['official']; $sticky = (int)$args['sticky']; $owngroups = (int)$args['owngroups']; $sort = $args['sort']; $date = $args['date']; $offset = $args['offset']; $numrows = $args['numrows']; $tables = pnDBGetTables(); $column = $tables['lobby_forum_posts_column']; $column_topics = $tables['lobby_forum_topics_column']; $column_forums = $tables['lobby_forums_column']; $column_groups = $tables['lobby_groups_column']; $column_categories = $tables['lobby_categories_column']; $whereArray = array(); // Should only own groups or all groups be handled? if ($owngroups == 1) { // show only own groups, also for admin if (!pnUserLoggedIn()) { return array(); } else { // Get groups $groups = pnModAPIFunc('lobby','members','getMemberships',array('uid' => pnUserGetVar('uid'))); foreach ($groups as $group) { $whereOrArray[] = "tbl.".$column_topics['gid']." = ".$group; } if (count($whereOrArray) > 0) { $whereArray[] = "(".implode(' OR ',$whereOrArray).")"; } else { return array(); } } } else { // handle all groups if ($fid > 0) { $whereArray[] = "tbl.".$column['fid']." = ".$fid; } if ($gid > 0) { $whereArray[] = "tbl.".$column_topics['gid']." = ".$gid; } if (!pnUserLoggedIn()) { $mystatus = 0; } else { if (!($gid > 0)) { $isMember = false; } else { $isMember = pnModAPIFunc('lobby','groups','isMember',array('uid' => pnUserGetVar('uid'), 'gid' => $gid)); } if ($isMember) { $mystatus = 2; } else { $mystatus = 1; } } // Admin Check if (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)) { $mystatus = 2; } if ($mystatus < 2) { $whereArray[] = "b.".$column_forums['public_status']." <= ".$mystatus; } } if ($date != '') { if ($sort == 'creationdate') { $whereArray[] = "tbl.".$column_topics['date']." > '".$date."'"; } else { $whereArray[] = "tbl.".$column_topics['last_date']." > '".$date."'"; } } // a $joinInfo[] = array ( 'join_table' => 'lobby_forum_posts', // table for the join 'join_field' => 'title', // field in the join table that should be in the result with 'object_field_name' => 'title', // ...this name for the new column 'compare_field_table' => 'id', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table // b $joinInfo[] = array ( 'join_table' => 'lobby_forums', // table for the join 'join_field' => 'title', // field in the join table that should be in the result with 'object_field_name' => 'forum_title', // ...this name for the new column 'compare_field_table' => 'fid', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table // c $joinInfo[] = array ( 'join_table' => 'lobby_forum_posts_text', // table for the join 'join_field' => 'text', // field in the join table that should be in the result with 'object_field_name' => 'text', // ...this name for the new column 'compare_field_table' => 'id', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table // d $joinInfo[] = array ( 'join_table' => 'users', // table for the join 'join_field' => 'uname', // field in the join table that should be in the result with 'object_field_name' => 'uname', // ...this name for the new column 'compare_field_table' => 'uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table // e $joinInfo[] = array ( 'join_table' => 'users', // table for the join 'join_field' => 'uname', // field in the join table that should be in the result with 'object_field_name' => 'last_uname', // ...this name for the new column 'compare_field_table' => 'last_uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table // f $joinInfo[] = array ( 'join_table' => 'lobby_groups', // table for the join 'join_field' => 'title', // field in the join table that should be in the result with 'object_field_name' => 'group_title', // ...this name for the new column 'compare_field_table' => 'gid', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table // If only official postings should be included we will add an where clase and a join information if ($official == 1) { $category_table = DBUtil::getLimitedTablename('lobby_categories'); $whereArray[] = "f.".$column_groups['category']." IN ( SELECT ".$column_categories['id']." from ".$category_table." WHERE official = 1 )"; } // if only one should be selected... // if ($id > 0) { // $whereArray[] = "tbl.".$column_topics['id']." = ".(int)$id; // } // Build where string $where = implode(' AND ',$whereArray); if ($sticky == 1) { $orderby = $column_topics['marked']." = 1 DESC, "; } if ($sort == 'creationdate') { $orderby.= "tbl.".$column_topics['date']." DESC"; } else{ $orderby.= "tbl.".$column_topics['last_date']." DESC"; } if ($id > 0) { $result = DBUtil::selectExpandedObjectByID('lobby_forum_topics',$joinInfo,$id); if ((int)$result['fid'] != (int)FormUtil::getpassedvalue('fid')) { //prayer($whereArray); //prayer($result); //print "fid: $fid"; //prayer($args); //print "<hr>"; // die("...."); LogUtil::registerError('wrong parameters for API function - access to topic denied!'); return false; } //$result = DBUtil::selectExpandedObjectArray('lobby_forum_topics',$joinInfo,$where); } else { if ($count == 1) { $result = DBUtil::selectExpandedObjectCount('lobby_forum_topics',$joinInfo,$where); } else { $result = DBUtil::selectExpandedObjectArray('lobby_forum_topics',$joinInfo,$where,$orderby,$offset,$numrows); } } // prayer($result); return $result; } /** * creates a new topic * * $args['gid'] int group id * $args['fid'] int forum id * $args['uid'] int user id (optional) * $args['title'] string title * $args['date'] string date (optional) * $args['text'] string content * $args['quiet'] boolean no output and notification email * @return int (new id) or false otherwise */ function lobby_forumtopicsapi_add($args) { $gid = (int)$args['gid']; $fid = (int)$args['fid']; $uid = (int)$args['uid']; $quiet = $args['quiet']; if ( ( !($fid > 0 ) ) || ( ($uid < 2) && (!$quiet) ) ) { LogUtil::registerError(_LOBBY_TOPICSAPI_ADD_PARAMERROR); return false; } $title = $args['title']; $text = $args['text']; $subscribe = (int)$args['subscribe']; if (!($uid > 0)) { $uid = pnUserGetVar('uid'); } if (isset($args['date']) && ($args['date'] != '')) { $date = $args['date']; } else { $date = date("Y-m-d H:i:s"); } $posting = array( 'uid' => $uid, 'date' => $date, 'fid' => $fid, 'gid' => $gid, 'date' => $date, 'text' => $text, 'title' => $title, 'quiet' => $quiet, 'tid' => 0 // topic id == 0 means that posting is topic ); // Create posting $post_id = pnModAPIFunc('lobby','forumposts','add',$posting); if (!$post_id) { return false; } else { // Create topic with post id $topic = array ( 'id' => $post_id, 'date' => $date, 'last_date' => $date, 'gid' => $gid, 'uid' => $uid, 'fid' => $fid ); $result = DBUtil::insertObject($topic,'lobby_forum_topics','id',true); if ($result > 0) { $obj_post = DBUtil::selectObjectByID('lobby_forum_posts',$post_id); $obj_post_text = DBUtil::selectObjectByID('lobby_forum_posts_text',$post_id); // update id $obj_post['tid'] = $result['id']; $obj_post_text['tid'] = $result['id']; DBUtil::updateObject($obj_post,'lobby_forum_posts'); DBUtil::updateObject($obj_post_text,'lobby_forum_posts_text'); // update forum information! $forum = DBUtil::selectObjectByID('lobby_forums',$fid); $forum['topics']++; $forum['posts']++; $forum['last_poster'] = $uid; $forum['last_topic_poster'] = $uid; $forum['last_poster_date'] = $date; $forum['last_topic_date'] = $date; DBUtil::updateObject($forum,'lobby_forums'); // send notification emails only if date was not set. // if date was set the function was called by the import tool if (!$args['quiet']) { // make abo for topic if ($subscribe == 1) { pnModAPIFunc('lobby','subscriptions','set',array('tid' => $obj_post['tid'], 'uid' => pnUserGetVar('uid'))); } Loader::includeOnce('modules/lobby/includes/common_email.php'); lobby_notify_newtopic($topic,$obj_post['title'],$obj_post_text['text'],$topic['uid'],$topic['fid'],$topic['id']); // Status message LogUtil::registerStatus(_LOBBY_TOPIC_CREATED); } return $result; } else { LogUtil::registerError(_LOBBY_TOPIC_CREATION_ERROR); return false; } } } /** * delete a topic with all postings * * $args['id'] int topic id * @return booleam */ function lobby_forumtopicsapi_del($args) { $id = (int)$args['id']; if (!($id > 0)) { return false; } else { // delete Subscriptions if (!DBUtil::deleteWhere('lobby_forum_topic_subscriptions','tid ='.$id)) { return false; } // get topic $obj = DBUtil::selectObjectByID('lobby_forum_topics',$id); // get all posts $posts = pnModAPIFunc('lobby','forumposts','get',array('tid' => $id)); foreach ($posts as $post) { $result = pnModAPIFunc('lobby','forumposts','del',array('id' => $post[id])); if (!$result) { return false; } } // delete topic $result = DBUtil::deleteObject($obj,'lobby_forum_topics'); return $result; } } /** * move a topic to another forum * * @param $args['id'] int topic id * @param $args['to'] int target forum id * @return boolean */ function lobby_forumtopicsapi_move($args) { $id = (int)$args['id']; $to = (int)$args['to']; // get topic $topic = lobby_forumtopicsapi_get(array('id' => $id)); // get target forum $forum = pnModAPIFunc('lobby','forums','get',array('id' => $to, 'gid' => $topic['gid'])); // Target forum must be in same group as destination if ($forum['gid'] != 0 ) { if ($topic['gid'] == $forum['gid']) { // update topic $obj = DBUtil::selectObjectByID('lobby_forum_topics',$id); $obj['fid'] = $to; $result = DBUtil::updateObject($obj,'lobby_forum_topics'); if ($result) { $tables = pNDBGetTables(); $column = $tables['lobby_forum_posts_column']; $where = $column['tid']." = ".$id; $objects = DBUtil::selectObjectArray('lobby_forum_posts',$where); foreach ($objects as $o) { $o['fid'] = $to; DBUtil::updateObject($o,'lobby_forum_posts'); } return true; } else { LogUtil::registerError('could not update org topic'); return false; } } else { LogUtil::registerError('cannot move topic to another group!'); return false; } } else { LogUtil::registerError('wrong / no group selected'); return false; } } /** * sync a topic * * @param $args['id'] int topic id * @return boolean */ function lobby_forumtopicsapi_sync($args) { // Parameters $id = (int)$args['id']; // Tables $tables = pnDBGetTables(); $pcolumn = $tables['lobby_forum_posts_column']; $tcolumn = $tables['lobby_forum_topics_column']; DBUtil::SQLCache(true); // Get object $topic = DBUtil::selectObjectByID('lobby_forum_topics',$id); if ($topic['id'] != $id) { return false; } // Get replies $replies = DBUtil::selectObjectCountByID('lobby_forum_posts',$id,$pcolumn['tid']); $replies--; // The original topic post is not a reply $topic['replies'] = $replies; // Last reply and last_date if ($replies == 0) { $topic['last_date'] = $topic['date']; $topic['last_pid'] = $topic['id']; $topic['last_uid'] = $topic['uid']; } else { $where = $pcolumn['tid']." = ".$id; $orderby = $pcolumn['date'].' DESC'; $result = DBUtil::selectObjectArray('lobby_forum_posts',$where,$orderby,-1,1); $lastpost = $result[0]; $topic['last_date'] = $lastpost['date']; $topic['last_pid'] = $lastpost['id']; $topic['last_uid'] = $lastpost['uid']; } // Update object $result = DBUtil::updateObject($topic,'lobby_forum_topics'); return $result; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { var $fid; var $gid; var $tid; var $pid; function initialize(&$render) { $gid = (int)FormUtil::getPassedValue('id'); $fid = (int)FormUtil::getPassedValue('fid'); $tid = (int)FormUtil::getPassedValue('topic'); $this->tid = $tid; $this->gid = $gid; $this->fid = $fid; // is there an action to be done? $action = FormUtil::getPassedValue('action'); if ($action == 'subscribe') { if (!SecurityUtil::confirmAuthKey()) { LogUtil::registerAuthIDError(); } else if ($tid > 0) { pnModAPIFunc('lobby','subscriptions','set',array('tid' => $tid, 'uid' => pnUserGetVar('uid'))); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('do' => 'forum', 'id' => $gid, 'fid' => $fid, 'topic' => $tid))); } else if ($fid > 0) { pnModAPIFunc('lobby','subscriptions','set',array('fid' => $fid, 'uid' => pnUserGetVar('uid'))); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('do' => 'forum', 'id' => $gid, 'fid' => $fid))); } } else if ($action == 'unsubscribe') { if (!SecurityUtil::confirmAuthKey()) { LogUtil::registerAuthIDError(); } else if ($tid > 0) { pnModAPIFunc('lobby','subscriptions','del',array('tid' => $tid, 'uid' => pnUserGetVar('uid'))); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('do' => 'forum', 'id' => $gid, 'fid' => $fid, 'topic' => $tid))); } else if ($fid > 0) { pnModAPIFunc('lobby','subscriptions','del',array('fid' => $fid, 'uid' => pnUserGetVar('uid'))); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('do' => 'forum', 'id' => $gid, 'fid' => $fid))); } } else if (($action == 'edit') && (!isset($this->pid))) { // We will handle it later to store the edited post // Assign editmode $pid = (int)FormUtil::getPassedValue('pid'); $post = pnModAPIFunc('lobby','forumposts','get',array('id' => $pid)); // Security Check $isModerator = pnModAPIFunc('lobby','moderators','isModerator',array('gid' => $this->gid, 'uid' => pnUserGetVar('uid'))); // Load lib and check if Posting is really editable Loader::includeOnce('modules/lobby/includes/common_forum.php'); if (!lobby_editablePost($post)) { if (!($isModerator || (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)))) { LogUtil::registerError(_LOBBY_EDIT_NOTPOSSIBLE); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'forum', 'fid' => $this->fid, 'topic' => $tid))); } } if ($post['uid'] == pnUserGetVar('uid') || $isModerator || (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN))) { // Assign content to Template $render->assign('editmode', 1); $render->assign($post); $this->pid = $post['id']; // check if really editable! // Todo } else { LogUtil::registerError(_LOBBY_NO_EDIT_PERMISSION); } } else if ($action == 'moderate') { $moderation = FormUtil::getPassedValue('moderation'); // get group $group = pnModAPIFUnc('lobby','groups','get',array('id' => $this->gid)); $groupOwner = (($group['uid'] == pnUserGetVar('uid')) || (SecurityUtil::checkPermission('lobby::'.$id, '::', ACCESS_ADMIN))); $isModerator = ($groupOwner || pnModAPIFunc('lobby','moderators','isModerator',array('gid' => $this->gid, 'uid' => pnUserGetVar('uid')))); if (!pnUserLoggedIn()) { $isModerator = false; } if (!$isModerator) { LogUtil::registerError(_LOBBY_ILLEGAL_MODERATOR_ACTION); } else if (SecurityUtil::confirmAuthKey()){ $topic = DBUtil::selectObjectByID('lobby_forum_topics',$this->tid); if ($moderation == 'close') { LogUtil::registerStatus(_LOBBY_MODERATION_TOPIC_CLOSED); $topic['locked'] = 1; } else if ($moderation == 'reopen') { LogUtil::registerStatus(_LOBBY_MODERATION_TOPIC_REOPENED); $topic['locked'] = 0; } else if ($moderation == 'mark') { LogUtil::registerStatus(_LOBBY_MODERATION_TOPIC_MARKED); $topic['marked'] = 1; } else if ($moderation == 'unmark') { LogUtil::registerStatus(_LOBBY_MODERATION_TOPIC_UNMARKED); $topic['marked'] = 0; } else if ($moderation == 'delete') { LogUtil::registerStatus(_LOBBY_MODERATION_TOPIC_DELETED); pnModAPIFunc('lobby','forumtopics','del',array('id' => $topic['id'])); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $gid, 'sync' => 1, 'do' => 'forum', 'fid' => $fid))); } else if ($moderation == 'deleteposting') { $pid = (int)FormUtil::getPassedValue('pid'); $posting = pnModAPIFunc('lobby','forumposts','get',array('id' => $pid)); if ($posting['fid'] == $fid) { pnModAPIFunc('lobby','forumposts','del',array('id' => $pid)); pnModAPIFunc('lobby','forumtopics','sync',array('id' => $posting['tid'])); // Sync forum the topic was inside pnModAPIFunc('lobby','forums','sync',array('id' => $posting['fid'])); LogUtil::registerStatus(_LOBBY_MODERATION_POSTING_DELETED); // Redirect now - sync already done... Otherwise the next updateobject will cancel our sync return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $gid, 'sync' => 1, 'do' => 'forum', 'fid' => $fid, 'topic' => $this->tid))); } } else if ($moderation == 'move') { // Get Parameter and move actual topic $to_forum = (int)FormUtil::getPassedValue('to_forum','POST'); $result = pnModAPIFunc('lobby','forumtopics','move',array('id' => $this->tid, 'to' => $to_forum)); if ($result) { LogUtil::registerStatus(_LOBBY_TOPIC_MOVED); // Sync forums of the group pnModAPIFunc('lobby','forums','sync',array('gid' => $gid)); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $gid, 'sync' => 1, 'do' => 'forum', 'fid' => $to_forum, 'topic' => $this->tid))); } } // Update topic $result = DBUtil::updateObject($topic,'lobby_forum_topics'); if (!$result) { LogUtil::registerError(_LOBBY_TOPIC_UPDATE_FAILED); } else { return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $gid, 'sync' => 1, 'do' => 'forum', 'fid' => $fid, 'topic' => $tid))); } } else { LogUtil::registerAuthIDError(); } } // load forum for group $forum = pnModAPIFunc('lobby','forums','get',array('id' => $this->fid, 'gid' => $this->gid)); // no forum? if (!($forum['id'] > 0) || ($forum['gid'] != $this->gid)) { LogUtil::registerError(_LOBBY_NO_FORUM_SELECTED); return pnRedirect(pnModURL('lobby','user','group',array('do'=>'forums', 'id' => $gid))); } $render->assign('forum', $forum); // offset and numrows.. // Now we need to check if a topic should be loaded or the complete topic index of a forum is needed $offset = (int)FormUtil::getPassedValue('lobbypager'); if ($offset > 0) { $offset--; } if ($tid > 0) { $mode="posts"; // number of posts per page; $numrows = pnModGetVar('lobby','postsperpage'); // assign topic - needed in topic and postings view $topic = pnModAPIFunc('lobby','forumtopics','get',array('id' => $this->tid, 'gid' => $this->gid, 'fid' => $this->fid)); // load a special topic $posts = pnModAPIFunc('lobby','forumposts','get',array('tid' => $this->tid, 'numrows' => $numrows, 'offset' => $offset)); $render->assign('posts',$posts); $render->assign('topic', $topic); // assign title for new reply if ($action != 'edit') { $render->assign('title', _LOBBY_FORUM_REPLY_PREFIX.': '.$topic['title']); } $render->assign('postcount', ($topic['replies']+1)); // Set page title PageUtil::setVar('title', $topic['title']." :: ".$forum['title']); } else { $mode="topics"; // number of posts per page; $numrows = pnModGetVar('lobby','topicsperpage'); $postsperpage = pnModGetVar('lobby','postsperpage'); // load postings $topics = pnModAPIFunc('lobby','forumtopics','get',array('fid' => $this->fid, 'numrows' => $numrows, 'offset' => $offset, 'gid' => $this->gid, 'sticky' => 1)); $render->assign('topics', $topics); $render->assign('postsperpage', $postsperpage); // Set page title PageUtil::setVar('title', $forum['title']); } $render->assign('mode',$mode); $render->assign('numrows', $numrows); return true; } function handleCommand(&$render, &$args) { if ($args['commandName'] == 'update') { // get the form data and do a validation check $obj = $render->pnFormGetValues(); // are we in edit mode? if ($this->pid > 0) { // Load lib and check if Posting is really editable $pid = (int)FormUtil::getPassedValue('pid'); $post = pnModAPIFunc('lobby','forumposts','get',array('id' => $pid)); $isModerator = pnModAPIFunc('lobby','moderators','isModerator',array('gid' => $this->gid, 'uid' => pnUserGetVar('uid'))); Loader::includeOnce('modules/lobby/includes/common_forum.php'); if (!lobby_editablePost($post)) { if (!($isModerator || (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN)))) { LogUtil::registerError(_LOBBY_EDIT_NOTPOSSIBLE); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'forum', 'fid' => $this->fid, 'topic' => $tid))); } } // We have to update / store a posting $obj1 = DBUtil::selectObjectByID('lobby_forum_posts',$this->pid); $obj2 = DBUtil::selectObjectByID('lobby_forum_posts_text',$this->pid); $obj1['title'] = $obj['title']; $bbcode = pnModIsHooked('bbcode','lobby'); if ($bbcode) { $bbcode_start = "[size=small][i]"; $bbcode_end = "[/i][/size]"; } $obj2['text'] = $obj['text'].$bbcode_start."\n "._LOBBY_LAST_EDITED.': '.date("Y-m-d H:i:s",time()).' '._LOBBY_BY.' '.pnUserGetVar('uname').$bbcode_end."\n"; $tables = pnDBGetTables(); $posts_column = $tables['lobby_forum_posts_column']; $poststext_column = $tables['lobby_forum_posts_text_column']; $obj['title'] = DataUtil::formatForStore($obj1['title']); $obj['text'] = DataUtil::formatForStore($obj2['text']); $sql1 = "UPDATE ".$tables['lobby_forum_posts']." SET ".$posts_column['title']." = '".$obj['title']."' WHERE ".$posts_column['id']." = ".$this->pid; $sql2 = "UPDATE ".$tables['lobby_forum_posts_text']." SET ".$poststext_column['text']." = '".$obj['text']."' WHERE ".$poststext_column['id']." = ".$this->pid; $result = DBUtil::executeSQL($sql1); //DBUtil-Bug? $result = DBUtil::updateObject($obj1,'lobby_forums_posts',$posts_column['id']); if ($result) { $result2 = DBUtil::executeSQL($sql2); //DBUtil-Bug? $result2 = DBUtil::updateObject($obj2,'lobby_forums_posts_text',$posts_column['id'],true,false); } // print message if ($result2) { LogUtil::registerStatus(_LOBBY_POST_MODIFIED); // return to topic and sync before returning pnModAPIFunc('lobby','forums','sync',array('id' => $this->fid)); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'do' => 'forum', 'fid' => $this->fid, 'topic' => $this->tid))); } else { LogUtil::registerError(_LOBBY_POST_MODIFY_ERROR); return false; } } // get Variables $obj['uid'] = pnUserGetVar('uid'); $obj['gid'] = $this->gid; $obj['fid'] = $this->fid; // preview mode? if ($obj['preview'] == 1) { LogUtil::registerStatus(_LOBBY_FORUM_PREVIEW); $render->assign('preview', 1); $render->assign('title', $obj['title']); $render->assign('text', $obj['text']); } else { if (!$render->pnFormIsValid()) return false; // store or update group if ($this->id > 0) { $obj['id'] = $this->id; // Is there an action to be done? } else { if ($this->tid > 0) { // add new post $obj['tid'] = $this->tid; $pid = pnModAPIFunc('lobby','forumposts','add',$obj); // Sync topic pnModAPIFunc('lobby','forumtopics','sync',array('id' => $this->tid)); // get lobbypager value $postsperpage = pnModGetVar('lobby','postsperpage'); $topic = pnModAPIFunc('lobby','forumtopics','get',array('id' => $this->tid, 'fid' => $this->fid)); $replies = $topic['replies']; $page = floor($replies/$postsperpage); if ($page == 0) { $lobbypager = 1; } else { $lobbypager = ($page*10)+1; } return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'sync' => 1, 'do' => 'forum', 'fid' => $this->fid, 'topic' => $this->tid, 'lobbypager' => $lobbypager))."#".$pid); } else { // add new topic $newtopic = pnModAPIFunc('lobby','forumtopics','add',$obj); $tid = $newtopic['id']; if ($tid > 0) { // return to new topic but sync before doing this pnModAPIFunc('lobby','forums','sync',array('id' => $this->fid)); return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'sync' => 1, 'do' => 'forum', 'fid' => $this->fid, 'topic' => $tid))); } else { LogUtil::registerError(_LOBBY_TOPIC_CREATION_ERROR); return false; } } } } } return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ function smarty_function_subscription($params, &$smarty) { $fid = (int)$params['fid']; $tid = (int)$params['tid']; $status = (int)$params['status']; $gid = (int)$params['gid']; $authid = SecurityUtil::generateAuthKey('lobby'); $c=''; //prayer($params); // if ($status < 1) { // return ''; // } if ($tid > 0) { // Check if forum itself is subscribed $f_subscribed = pnModAPIFunc('lobby','subscriptions','get',array('fid' => $fid, 'uid' => pnUserGetVar('uid'))); if ($f_subscribed) { $c.='<a href="'.pnModURL('lobby','user','group',array('id' => $gid, 'do' => 'forum', 'fid' => $fid)).'">'._LOBBY_CFORUM_SUBSCRIBED.'</a>'; } else { $subscribed = pnModAPIFunc('lobby','subscriptions','get',array('tid' => $tid, 'uid' => pnUserGetVar('uid'))); if ($subscribed) { $c.=_LOBBY_FORUM_SUBSCRIBED.', <a href="'.pnModURL('lobby','user','group',array('id' => $gid, 'do' => 'forum', 'fid' => $fid, 'topic' => $tid, 'action' => 'unsubscribe', 'authid' => $authid)).'">'._LOBBY_FORUM_UNSUBSCRIBE."</a>"; } else { $c.=_LOBBY_FORUM_NOT_SUBSCRIBED.', <a href="'.pnModURL('lobby','user','group',array('id' => $gid, 'do' => 'forum', 'fid' => $fid, 'topic' => $tid, 'action' => 'subscribe', 'authid' => $authid)).'">'._LOBBY_FORUM_SUBSCRIBE."</a>"; } } } else if ($fid > 0) { $subscribed = pnModAPIFunc('lobby','subscriptions','get',array('fid' => $fid, 'uid' => pnUserGetVar('uid'))); if ($subscribed) { $c.=_LOBBY_FORUM_SUBSCRIBED.', <a href="'.pnModURL('lobby','user','group',array('id' => $gid, 'do' => 'forum', 'fid' => $fid, 'action' => 'unsubscribe', 'authid' => $authid)).'">'._LOBBY_FORUM_UNSUBSCRIBE."</a>"; } else { $c.=_LOBBY_FORUM_NOT_SUBSCRIBED.', <a href="'.pnModURL('lobby','user','group',array('id' => $gid, 'do' => 'forum', 'fid' => $fid, 'action' => 'subscribe', 'authid' => $authid)).'">'._LOBBY_FORUM_SUBSCRIBE."</a>"; } } else { return ''; } // return text return $c; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get all news * * @args['gid'] int id of group (optional) * @args['id'] int id of special article (optional) * @args['infuture']int ==1 also show future art(optional) * @args['offset'] int offset for dbutil (optional) * @args['numrows'] int numrows for dbutil (optional) * @args['since'] int date-timestamp, news since.. (optional) * @args['count'] int ==1 count, returns int (optional) * @args['onlyown'] int ==1 only show own groups (optional) * $args['catfilter'] int category filter, id of category (optional) * @return array the categories */ function lobby_newsapi_get($args) { // Security check: by public status and group membership is integrated $id = (int)$args['id']; $gid = (int)$args['gid']; $count = (int)$args['count']; $onlyown = (int)$args['onlyown']; $since = $args['since']; $category = (int)$args['catfilter']; $infuture = (int)$args['infuture']; if (($onlyown == 1) && (!(pnUserGetVar('uid') > 1))) { return array(); } if ($gid > 0) { $groupstatus = pnModAPIFunc('lobby','groups','isMember',array('uid' => pnUserGetVar('uid'), 'gid' => $gid)); } else { $groupstatus = 0; } $tables = pnDBGetTables(); $news_column = $tables['lobby_news_column']; $groups_column = $tables['lobby_groups_column']; $where = array(); if ($gid > 0) { $where[] = "tbl.".$news_column['gid']." = ".$gid; } if ($category > 0) { $where[] = "b.".$groups_column['category']." = ".$category; } if ($id > 0) { $where[] = "tbl.".$news_column['id']." = ".$id; } if ($infuture != 1) { $where[] = "tbl.".$news_column['date']." <= '".date("Y-m-d H:i:s",time())."'"; } if (isset($since) && ($since != '')) { $where[] = "tbl.".$news_column['date']." >= '".$since."'"; } if (!pnUserLoggedIn()) { $mystatus = 0; } else { if ($groupstatus > 0) { $mystatus = 2; } else { $mystatus = 1; } } // add in part for sql query if no gid is given if (!($gid > 0)) { if (pnUserLoggedIn()) { // get user's groups an add them $groups = pnModAPIFunc('lobby','members','getMemberships',array('uid' => pnUserGetVar('uid'))); if (count($groups) > 0) { $in = "(".implode(',',$groups).")"; } } } // If only own groups should be displayed but there are no groups => return if (($onlyown == 1) && (!(count($groups) > 0))) { return array(); } if (isset($in) && (strlen($in) > 0) && ($onlyown == 1)) { $where[] = "tbl.".$news_column['gid']." IN "."(".implode(',',$groups).")"; } else if (isset($in) && (strlen($in) > 0)) { $where[] = "( tbl.".$news_column['public_status']." <= ".$mystatus." OR tbl.".$news_column['gid']." IN "."(".implode(',',$groups).") )"; } else { $where[] = "tbl.".$news_column['public_status']." <= ".$mystatus; } $orderby = "tbl.".$news_column['date']." DESC"; $numrows = $args['numrows']; $offset = $args['offset']; // build where part for sql query $wherestring = implode(' AND ',$where); // get result if ($count == 1) { $result = DBUtil::selectObjectCount('lobby_news',$wherestring); } else { // joinArray $joinInfo[] = array ( 'join_table' => 'users', // table for the join 'join_field' => 'uname', // field in the join table that should be in the result with 'object_field_name' => 'uname', // ...this name for the new column 'compare_field_table' => 'uid', // regular table column that should be equal to 'compare_field_join' => 'uid'); // ...the table in join_table $joinInfo[] = array ( 'join_table' => 'lobby_groups', // table for the join 'join_field' => array('category','title'), // field in the join table that should be in the result with 'object_field_name' => array('category','group_title'), // ...this name for the new column 'compare_field_table' => 'gid', // regular table column that should be equal to 'compare_field_join' => 'id'); // ...the table in join_table $result = DBUtil::selectExpandedObjectArray('lobby_news',$joinInfo,$wherestring,$orderby,$offset,$numrows); } if (!$result) { return array(); } if ($id > 0) { return $result[0]; } else { return $result; } } /** * Send an article to all group members * * @param $article (object) Article * @return boolean */ function lobby_newsapi_sendStory($story) { if (!$story || !($story['id'] > 0)) { return false; } // Assign Data $render = pnRender::getInstance('lobby'); $render->assign($story); $output = $render->fetch('lobby_email_story.htm'); // Get Members and Group $members = pnModAPIFunc('lobby','members','get',array('gid' => $story['gid'])); $group = pnModAPIFunc('lobby','groups','get',array('id' => $story['gid'])); // Prepare and send mail $subject = _LOBBY_GROUP_NEWS_FROM.' '.$group['title'].': '.$story['title']; $body = $output; foreach ($members as $m) { $to = pnUserGetVar('email',$m['uid']); if ($to != '') { $result = pnMail($to, $subject, $body, array('header' => '\nMIME-Version: 1.0\nContent-type: text/html'), true); if (!$result) { return false; } } } // Mark article as sent $obj = DBUtil::selectObjectByID('lobby_news',$story['id']); $obj['sent'] = 1; DBUtil::updateObject($obj,'lobby_news'); // return success return true; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * add a new forum * * This function adds a new forum into the database * * @args['gid'] int * @args['id'] int * @args['title'] string * @args['description'] string * @args['public_status'] string * * @return boolean */ function lobby_forumsapi_add($args) { $obj['gid'] = (int)$args['gid']; if (!($obj['gid']) > 0) { LogUtil::registerError(_LOBBY_FORUM_CREATION_ERROR); return false; } $obj['title'] = $args['title']; $obj['description'] = $args['description']; $obj['public_status'] = $args['public_status']; $result = DBUtil::insertObject($obj,'lobby_forums'); if ($result > 0) { LogUtil::registerStatus(str_replace('%forum%', $obj['title'], _LOBBY_FORUM_CREATED)); return $result; } else { LogUtil::registerError(_LOBBY_FORUM_CREATION_ERROR); return false; } } /** * get forums * * @args['gid'] int group id * @args['id'] int forum id * @args['showall'] int optional, ==1 show all not considering permissions * * @return int or boolean */ function lobby_forumsapi_get($args) { $id = (int)$args['id']; $gid = (int)$args['gid']; $showall = (int)$args['showall']; // if ($gid == 0) { // LogUtil::registerError('no group id specified - might cause problems!'); // } $tables = pnDBGetTables(); $column = $tables['lobby_forums_column']; $where = array(); if ($gid > 0) $where[] = "tbl.".$column['gid']." = ".$gid; if ($id > 0) $where[] = "tbl.".$column['id']." = ".$id; if (($showall == 1) || (SecurityUtil::checkPermission('lobby::', '::', ACCESS_ADMIN))) { $mystatus = 2; } else { if (!pnUserLoggedIn()) { $mystatus = 0; } else { if ($gid > 0) { $groupstatus = pnModAPIFunc('lobby','groups','isMember',array('uid' => pnUserGetVar('uid'), 'gid' => $gid)); if ($groupstatus > 0) { $mystatus = 2; } else { $mystatus = 1; } } else { // Todo: Check here if user making this call is member of the group // ... // till then: easy way! $mystatus = 1; // no access for internal group forums } } } $where[] = "tbl.".$column['public_status']." <= ".$mystatus; $wherestring = implode(' AND ',$where); $orderby = $column['sort_nr']." ASC"; $result = DBUtil::selectObjectArray('lobby_forums',$wherestring,$orderby); if ($id > 0) { return $result[0]; } else { return $result; } } /** * delete a forum * * $args['id'] int forum id * @return booleam */ function lobby_forumsapi_del($args) { $id = (int)$args['id']; if (!($id > 0)) { return false; } else { // forums $forum = DBUtil::selectObjectByID('lobby_forums',$id); // delete Subscriptions if (!DBUtil::deleteWhere('lobby_forum_subscriptions','fid ='.$id)) { return false; } $obj = DBUtil::selectObjectByID('lobby_forum_topics',$id); // get all topics $topics = pnModAPIFunc('lobby','forumtopics','get',array('fid' => $id)); foreach ($topics as $topic) { $result = pnModAPIFunc('lobby','forumtopics','del',array('id' => $topic[id])); if (!$result) { return false; } } // delete forum $result = DBUtil::deleteObject($forum,'lobby_forums'); return $result; } } /** * Sync forum * * @param $args['gid'] int group id * @param $args['id'] int forum id * @return boolean */ function lobby_forumsapi_sync($args) { $gid = (int)$args['gid']; $id = (int)$args['id']; if (($gid == 0) && ($id == 0)) { return false; } // sync each forum if ($gid > 0) { $where = 'gid = '.$gid; } else { $where = 'id ='.$id; } $forums = DBUtil::selectObjectArray('lobby_forums',$where); $group['postings'] = 0; foreach ($forums as $forum) { // sync postings and topics for each forum $forum['posts']=(int)DBUtil::selectObjectCountByID('lobby_forum_posts',$forum['id'],'fid'); $forum['topics']=(int)DBUtil::selectObjectCountByID('lobby_forum_topics',$forum['id'],'fid'); // ToDo: get last poster uid, date $result = DBUtil::selectObjectArray('lobby_forum_topics','fid = '.$forum['id'],'id DESC'); if ($result) { $last = $result[0]; $forum['last_topic_date'] = $last['last_date']; $forum['last_topic_poster'] = $last['uid']; $forum['last_tid'] = $last['id']; } $result = DBUtil::selectObjectArray('lobby_forum_posts','fid = '.$forum['id'],'id DESC'); if ($result) { $last = $result[0]; $forum['last_poster'] = $last['uid']; $forum['last_poster_date'] = $last['date']; $forum['last_poster_tid'] = $last['tid']; } // sync posts for group $group['postings']+=$forum['posts']; // update forum DBUtil::updateObject($forum,'lobby_forums'); } return true; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * return news as rss * * @return output The main module page */ function lobby_rss_news() { // Create output and call handler class $render = pnRender::getInstance('lobby'); // Get parameters $id = (int)FormUtil::getPassedValue('id'); $group = pnModAPIFunc('lobby','groups','get',array('id' => $id)); if ($group['id'] != $id) { print "group not found"; return true; } // Assign variables $articles = pnModAPIFunc('lobby','news','get',array('gid' => $id, 'numrows' => 50)); $group['date'] = date('r', strtotime($group['date'])); $render->assign('group', $group); $render->assign('author', pnUserGetVar('uname',$group['uid'])); foreach ($articles as $a) { $a['date'] = date('r',strtotime($a['date'])); $r[] = $a; } $render->assign('articles', $r); // Return the output $output = $render->display('lobby_rss_news.htm'); header ("content-type: text/xml"); print $output; return true; } /** * return new members as rss * * @return output The main module page */ function lobby_rss_members() { // Create output and call handler class $render = pnRender::getInstance('lobby'); // Get parameters $id = (int)FormUtil::getPassedValue('id'); $group = pnModAPIFunc('lobby','groups','get',array('id' => $id)); if ($group['id'] != $id) { print "group not found"; return true; } // Assign variables $members = pnModAPIFunc('lobby','members','get',array('gid' => $group['id'], 'numrows' => 100, 'offset' => null, 'sort' => 'latest')); $render->assign('members', $members); $render->assign('group', $group); // Return the output $output = $render->display('lobby_rss_members.htm'); header ("content-type: text/xml"); print $output; return true; } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ class lobby_user_pluginHandler { var $id; var $gid; function initialize(&$render) { $gid = (int)FormUtil::getPassedValue('id'); $this->gid = $gid; // Get user list $users = pnModAPIFunc('lobby','memberspending','get',array('gid' => $this->gid)); $render->assign('pending', $users); return true; } function handleCommand(&$render, &$args) { if ($args['commandName']=='update') { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_COMMENT)) return LogUtil::registerPermissionError(); // get the pnForm data and do a validation check $obj = $render->pnFormGetValues(); if (!$render->pnFormIsValid()) return false; // user is loaded now. return $render->pnFormRedirect(pnModURL('lobby','user','group',array('id' => $this->gid, 'sync' => 1, 'do' => 'membermanagement', 'action' => 'modify', 'uid' => $obj['user']))); } return true; } } <file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ /** * get all categories * * @args['id'] int id of category (optional) * @return array the categories */ function lobby_categoriesapi_get($args) { // Security check if (!SecurityUtil::checkPermission('lobby::', '::', ACCESS_OVERVIEW)) { return false; } $id = (int)$args['id']; if ($id > 0) { $result = DBUtil::selectObjectByID('lobby_categories',$id); } else { $result = DBUtil::selectObjectArray('lobby_categories'); } return $result; }<file_sep><?php /** * @package lobby * @version $Id $ * @author <NAME> * @link http://www.ifs-net.de * @copyright Copyright (C) 2009 * @license no public license - read license.txt in doc directory for details */ $modversion['name'] = 'lobby'; // the version string must not exceed 10 characters! $modversion['version'] = '1.2'; $modversion['description'] = 'social network interaction platform'; $modversion['displayname'] = 'lobby'; // The following in formation is used by the credits module // to display the correct credits $modversion['changelog'] = 'docs/changelog.txt'; $modversion['credits'] = 'docs/credits.txt'; $modversion['help'] = 'docs/help.txt'; $modversion['license'] = 'docs/license.txt'; $modversion['official'] = 0; $modversion['author'] = '<NAME>'; $modversion['contact'] = 'http://www.ifs-net.de/'; // The following information tells the PostNuke core that this // module has an admin option. $modversion['admin'] = 1; // module dependencies $modversion['dependencies'] = array( array( 'modname' => 'EZComments', 'minversion' => '1.6', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED), array( 'modname' => 'ContactList', 'minversion' => '1.1', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED), array( 'modname' => 'MyProfile', 'minversion' => '1.2', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED), array( 'modname' => 'UserPictures', 'minversion' => '1.1', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED), array( 'modname' => 'InterCom', 'minversion' => '2.1', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED), array( 'modname' => 'scribite', 'minversion' => '2.0', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED), array( 'modname' => 'Invitation', 'minversion' => '1.0', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED), array( 'modname' => 'MyMap', 'minversion' => '1.3', 'maxversion' => '', 'status' => PNMODULE_DEPENDENCY_RECOMMENDED) ); // This one adds the info to the DB, so that users can click on the // headings in the permission module $modversion['securityschema'] = array();
7f4d59e2cbd3b835b768cc090cf46e3f1102c457
[ "PHP" ]
51
PHP
ifs-net/Lobby
0496d5ac47974b636910a1f4f5078db7a9e9c3e7
f6d517ca8346be09b9918202041d5f9514da34fb
refs/heads/master
<repo_name>duchy01/Konk<file_sep>/dist/assets/scripts/common.js $(function () { 'use strict'; $('.work-carousel').owlCarousel({ loop:true, responsiveClass:true, responsive:{ 0:{ items:2, nav:true, margin:16 }, 1280:{ items:3, nav:true, margin:20 } } }); $('.more-carousel').owlCarousel({ loop:true, responsiveClass:true, responsive:{ 0:{ items:2, nav:true, margin:16 }, 1280:{ items:3, nav:true, margin:20 } } }); $('.button_calc').click(function(){ $('.cost_base').hide(); $('.cost_calc').show(); }); $('.razlik_bordered input[type="radio"]:checked').each(function(){ $(this).closest('label').addClass('active'); }); $('.razlik_bordered input[type="radio"]').change(function(){ if($(this).prop('checked')){ $(this).closest('label').addClass('active').siblings().removeClass('active'); } }); $('.tabed').change(function(){ if($(this).val()==1){ $('.calc_house').show(); $('.calc_flat').hide(); } else{ $('.calc_house').hide(); $('.calc_flat').show(); } }); $('.tabs li').click(function(){ $(this).addClass('act').siblings().removeClass('act'); }); $('.menu_button').click(function(){ if(!$(this).hasClass('open')) { $('#popup_bg').trigger('click'); $('body').append('<div id="popup_bg"></div>'); $('#menu').removeClass('hide'); $(this).addClass('open'); } else{ $('#popup_bg').remove(); $('.menu_button').removeClass('open'); $('.zajavka').removeClass('open'); $('.popup').addClass('hide'); } }); $('.zajavka').click(function () { if(!$(this).hasClass('open')) { $('#popup_bg').trigger('click'); $('body').append('<div id="popup_bg"></div>'); $('#popup_zajavka').removeClass('hide'); $(this).addClass('open'); } else { $('#popup_bg').remove(); $('.menu_button').removeClass('open'); $('.zajavka').removeClass('open'); $('.popup').addClass('hide'); } }); $('body').on('click','#popup_bg', function () { $(this).remove(); $('.popup').addClass('hide'); $('.menu_button').removeClass('open'); $('.zajavka').removeClass('open'); }); $('.top_blokc2 .col-xs-12 h3').click(function () { if (!$(this).hasClass('open')) { $(this).closest('.col-xs-12').find('.top_inner').slideDown(); $(this).addClass('open'); } else { $(this).closest('.col-xs-12').find('.top_inner').slideUp(); $(this).removeClass('open'); } }); if($('#map').length){ load_googlemaps_script(); } }); function load_googlemaps_script() { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' + '&signed_in=false&callback=initialize'; document.body.appendChild(script); } var styles = [{"featureType":"all","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape","elementType":"all","stylers":[{"visibility":"on"},{"color":"#f3f4f4"}]},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"weight":0.9},{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#83cead"}]},{"featureType":"road","elementType":"all","stylers":[{"visibility":"on"},{"color":"#ffffff"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"on"},{"color":"#fee379"}]},{"featureType":"road.arterial","elementType":"all","stylers":[{"visibility":"on"},{"color":"#fee379"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#7fc8ed"}]}]; var cell = [ [[55.7622, 37.6835], [59.970748, 30.364044], [42.806729, 132.882161]], [[55.764, 37.683], [59.9765048, 30.362344], [42.8165029, 132.88]] ]; function initialize() { var map; var marker ; var options = { mapTypeControlOptions: { mapTypeIds: [ 'Styled'] }, center: new google.maps.LatLng(cell[1][0][0],cell[1][0][1]), zoom: 15, mapTypeId: 'Styled' }; map = new google.maps.Map(document.getElementById('map'), options); var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' }); map.mapTypes.set('Styled', styledMapType); marker = new google.maps.Marker({ position: new google.maps.LatLng(cell[0][0][0],cell[0][0][1]), map: map, animation: google.maps.Animation.DROP, icon: 'assets/images/pointer.png' }); }<file_sep>/dist/injiner.html <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimal-ui"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="imagetoolbar" content="no"> <meta name="msthemecompatible" content="no"> <meta name="cleartype" content="on"> <meta name="HandheldFriendly" content="True"> <meta name="format-detection" content="telephone=no"> <meta name="format-detection" content="address=no"> <title>injiner</title> <link href="assets/styles/common.css?1437200455061" rel="stylesheet"> </head> <body> <div class="main"> <div class="main_wrap"> <header> <button class="zajavka btn">Оставить заявку</button><span class="tel_header">+7 (499) 994 94 47</span> <a href="#menu" class="menu_button"></a> <a href="/"><img src="assets/images/logo.png" alt="logo" class="logo"></a> </header> <div id="popup_zajavka" class="hide next_form popup"> <input type="text" placeholder="Ваше имя" class="ghtrt"> <input type="email" placeholder="Номер телефона" class="ghtrt"> <input type="text" placeholder="Дата звонка" class="ghtrt"> <input type="text" placeholder="Время звонка" class="ghtrt"> <input type="submit" value="Отправить" class="btn know_more center-block"> </div> <div id="menu" class="popup next_form hide"> <div class="menu_wrap"> <div><a href="/">Главная</a></div> <div><a href="javascript:void(0);">Услуги</a></div> <div><a href="javascript:void(0);">О компании</a></div> <div><a href="javascript:void(0);">Отзывы</a></div> <div><a href="javascript:void(0);">Цены</a></div> <div><a href="javascript:void(0);">Работы</a></div> <div><a href="javascript:void(0);">Акции</a></div> <div><a href="javascript:void(0);">Согласование</a></div> <div><a href="javascript:void(0);">Контакты</a></div> </div> <div class="menu_wrap">г. Москва, Ул. Марии Ульяновой, д.33/23 <br>+7 (499) 994-94-47 <br><a href="mailto:<EMAIL>"><EMAIL></a></div> </div> <div class="container-fluid top_blokc3"> <div class="row"> <div class="col-xs-12 col-sm-4 menu_3_item_1"></div> <div class="col-xs-12 col-sm-4 menu_3_item_2"></div> <div class="col-xs-12 col-sm-4 menu_3_item_3"></div> </div> </div> <div class="container-fluid about"> <div class="width_adaptiv"> <h2>Инженерно-геологические изыскания: <br>описание, назначение</h2></div> <div class="width_adaptiv about_text">Инженерно-геологические изыскания позволяют определить геоморфологические и геогидрологические процессы, происходящие на исследуемой территории, определить состав и свойства грунта; уровень, состав и агрессивность к различным строительным материалам грунтовых вод; прогнозировать изменение текущих инженерно-геологических процессов при взаимодействии построенного объекта со средой.</div> <div class="width_adaptiv"><b>Эти работы проводятся на самой ранней стадии строительства и являются необходимой частью предпроектной подготовки.</b></div> </div> <div class="container-fluid bgcolor_f7f7f7"> <div class="row"> <div class="col-xs-6 pos_relative"> <div class="row"><img src="assets/images/content/injiner_pic.jpg" alt="" class="img-100"> <div class="text_inner"> <div class="h4_wrap"> <h4>В состав инженерно-геологических изысканий входят следущие работы</h4></div> </div> </div> </div> <div class="col-xs-6"> <div class="row"> <ul class="slyled"> <li>Бурение скважин</li> <li>Полевые исследования грунтов (статическое, динамическое зондирование, испытание грунтов штампом и т.д.)</li> <li>Геофизические исследования</li> <li>Гидрогеологические исследования (опытные откачки, гидрогеологическое моделирование и др.)</li> <li>Стационарные наблюдения (мониторинг)</li> <li>Лабораторные исследования грунтов и подземных вод</li> <li>Обследование грунтов оснований существующих зданий и сооружений</li> <li>Составление прогноза изменений инженерно-геологических условий</li> <li>Оценка опасности и риска геологических процессов</li> </ul> </div> </div> </div> </div> <div class="bgcolor_48ceb9 center-text"> <div class="width_adaptiv">При производстве инженерно-геологических изысканий под малоэтажную застройку (коттеджи, загородные дома, небольшие складские и хозяйственные объекты) уже существуют расчетные нормы объемов бурения и отбора образцов грунта для исследований.</div> </div> <div class="width_adaptiv"> <h3 class="museo500 center-text">изыскания под многоэтажное строительство</h3> <div class="answer"> <div class="answer1">Если необходимо проведение изысканий под многоэтажное строительство либо крупные производственные объекты, от заказчика потребуется техническое задание на производство геологических работ, согласованное с организацией, осуществляющей проектирование данного объекта.</div> <div class="answer2"><img src="assets/images/smile.png" alt="" class="nomer"><span class="answer2_span">В данном случае, разрабатывается индивидуальная программа инженерно-геологических изысканий под конкретный объект строительства с учетом его технических характеристик, площади застройки, геологического строения и предполагаемых инженерно-геологических процессов в данной местности.</span></div> </div> </div> <div class="container-fluid bgcolor_f7f7f7"> <div class="row"> <div class="col-xs-6 pos_relative"> <div class="row"><img src="assets/images/content/injiner_pic2.jpg" alt="" class="img-100"> <div class="text_inner"> <div class="h4_wrap"> <h4>Расчетный объем инженерно-геологических изысканий должен быть достаточен для обоснования комплекса проектных решений</h4></div> </div> </div> </div> <div class="col-xs-6"> <div class="row"> <ul class="slyled"> <li>Обоснование технической возможности и экономической целесообразности строительства объекта в данном районе</li> <li>Сравнение возможных вариантов расположения проектируемого объекта и выбор из них оптимального</li> <li>Обоснование компоновки зданий и сооружений проектируемого объекта по выбранному варианту</li> <li>Аргументация расчетных схем оснований и среды зданий и сооружений</li> <li>Осуществление авторского надзора за производством строительных работ</li> </ul> </div> </div> </div> </div> <div class="bgcolor_e4e7e9"> <div class="width_adaptiv"> <p>Бурение геологических скважин и отбор грунта для лабораторных испытаний выполняется по специально разработанной схеме. По результатам лабораторных исследований физических и химических свойств образцов грунта и грунтовых вод подготавливается технических отчет, даются рекомендации по выбору параметров фундамента, средств защиты.</p> <p>Дополнительные методы исследований (зондирование, прессиометрия, штамповые испытания) необходимы при многоэтажном жилом строительстве и возведении крупных технически сложных производственных и складских объектов.</p> </div> </div> <div class="call_us width_adaptiv"> <h2>Получите консультацию</h2> <div class="about_text">Просто оставьте нам свой номер телефона или почту <br> и мы ответим на все интересующие вас вопросы!</div> <form action="#" method="post" class="call_form"> <input type="text" placeholder="Ваше имя" required> <input type="text" placeholder="Почта или телефон" required> <input type="submit" value="Отправить" class="btn"> </form> </div> </div> </div> <footer> <div class="width_adaptiv soc"> <a href="javascript:void(0);" class="fb"></a> <a href="javascript:void(0);" class="tvit"></a> <a href="javascript:void(0);" class="vk"></a> <a href="javascript:void(0);" class="odn"></a> </div> </footer> <script src="/assets/scripts/debug.js?1437200455061"></script> <script src="/assets/scripts/plugins.js?1437200455061"></script> </body> </html>
efe671092a3fbcfb998bf5b8e22cc2e141c0eadd
[ "JavaScript", "HTML" ]
2
JavaScript
duchy01/Konk
08814542d6104a957c861754e90e356bed181e86
b4673528c311d0c3524df7615b51b2d5f456c94d
refs/heads/main
<repo_name>zel0rd/QuizWord<file_sep>/quiz-word/src/service/user.js import firebase from "../config/firebase-config"; const getUsers = async () => { let result = ""; await firebase .auth() .User() .then((res) => { result = res; return res; }) .catch((err) => { return err; }); return result; }; const delUser = async () => { const user = await firebase.auth().currentUser; console.log(user) user.delete() .then(function() { console.log("success") }) .catch (function() { console.log("fail") }) } export { delUser, getUsers};<file_sep>/quiz-word/src/config/firebase-config.js import firebase from 'firebase' const firebaseConfig = { apiKey: "<KEY>", authDomain: "quizword-a2d37.firebaseapp.com", projectId: "quizword-a2d37", storageBucket: "quizword-a2d37.appspot.com", messagingSenderId: "335235445215", appId: "1:335235445215:web:596082091f2068f2fb546a", measurementId: "G-02W2LXZQDE" }; firebase.initializeApp(firebaseConfig); firebase.analytics(); export default firebase;
dc2e6ed974b857f1e8ddd361cfddee700ac73197
[ "JavaScript" ]
2
JavaScript
zel0rd/QuizWord
71406124a22092d3f314aea8a2daca9ed37b08d8
23645798840ccf58c54500021fa340ad0d1523d7
refs/heads/master
<repo_name>fostimus/ninja-board<file_sep>/quarkus/test-helper/src/main/java/com/data/services/ninja/test/AbstractResourceTest.java package com.data.services.ninja.test; import com.redhat.services.ninja.entity.Database; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; import io.restassured.parsing.Parser; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; @QuarkusTest public abstract class AbstractResourceTest { @ConfigProperty(name = "database.file", defaultValue = "database.json") String databaseLocation; protected Database ninjaDatabase; @BeforeAll static void init() { RestAssured.defaultParser = Parser.JSON; } @BeforeEach void initEach() throws IOException { Jsonb jsonb = JsonbBuilder.create(); ninjaDatabase = jsonb.fromJson(getDatabaseStream(), Database.class); Path path = Paths.get(databaseLocation); Files.write(path, getDatabaseStream().readAllBytes()); Logger.getAnonymousLogger().log(Level.INFO, path.toAbsolutePath().toString()); } protected InputStream getDatabaseStream(){ return AbstractResourceTest.class.getClassLoader().getResourceAsStream("/com/redhat/services/ninja/test/database.json"); } } <file_sep>/quarkus/data-client/src/main/java/com/redhat/services/ninja/client/UserClient.java package com.redhat.services.ninja.client; import com.redhat.services.ninja.entity.User; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("data/user") @RegisterRestClient @ApplicationScoped public interface UserClient { @GET @Path("{identifier}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) User get(@PathParam("identifier") String username); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) User create(User user); } <file_sep>/quarkus/data-service/src/main/java/com/redhat/services/ninja/data/controller/UserResource.java package com.redhat.services.ninja.data.controller; import com.redhat.services.ninja.entity.User; import com.redhat.services.ninja.data.service.DatabaseEngine; import com.redhat.services.ninja.data.operation.IdentifiableDatabaseOperations; import javax.inject.Inject; import javax.ws.rs.Path; @Path("/data/user") public class UserResource extends AbstractIdentifiableResource<String, User, IdentifiableDatabaseOperations<String,User>> { @Inject DatabaseEngine engine; @Override public DatabaseEngine getEngine() { return engine; } @Override public IdentifiableDatabaseOperations<String,User> getOperations() { return engine.getUserOperations(); } }<file_sep>/README.md # community-ninja-board Front end user interface for the Giveback Ninja Program(v1) and a parallel system to replace the former called v2. ## Deployment locally (laptop) / or for DEV purposes ### Local v1 Deployment #### Setting up the environment variables ``` export TRELLO_API_TOKEN=<your token> export TRELLO_API_KEY=<your token> export GITHUB_API_TOKEN=<your token> export GITLAB_API_TOKEN=<your token> export GD_CREDENTIALS=<contents of you google drive credentials.json file (escaped & in quotes)> export GRAPHS_PROXY=<optional: url to an external proxy storage app> export USERS_LDAP_PROVIDER=<optional: ldap url for user lookup> ``` note: see *Getting your google drive credentials.json file* below for the GD_CREDENTIALS value #### Starting up the application Included in the pom is a jetty plugin, so as long as you have maven installed you just run: ``` mvn clean package -DskipTests jetty:run -Djetty.port=8082 ``` ### Local v2 Deployment #### Deploy Back-End Services 1. Follow steps in https://github.com/redhat-cop/ninja-board/blob/v2/quarkus/README.MD #### Deploy Front-End 1. Follow steps in https://github.com/redhat-cop/ninja-board/blob/v2/react/ninja-react/README.md ## Deployment on Openshift ### Deployment Using the OpenShift Applier The project can be deployed using the [openshift-applier](https://github.com/redhat-cop/openshift-applier). #### Prerequisites The following prerequisites must be satisfied: 1. [Ansible](https://www.ansible.com/) 2. OpenShift Command Line Interface (CLI) 3. OpenShift environment ### v1 OpenShift Deployment #### Setting up the deployment config files **Optional:** If you want to deploy a different github repository (ie, a forked copy of redhat-cop/ninja-board), then update the ansible variable `source_repo` in *.applier/inventory/group_vars/all.yml* or specify it as an extra variable. Configure the mandatory deployment parameters in *.openshift/applier/params/ninja-board-deployment* ``` github_api_token=<<PASSWORD> token> trello_api_token=<<PASSWORD> token> ... ``` Alternatively, you can target each of the environments for deployment by prepending `dev_` or `prod_` before each variable.s #### Getting your google drive credentials.json file ``` mkdir gdrive_temp cd gdrive_temp wget https://github.com/odeke-em/drive/releases/download/v0.3.9/drive_linux chmod +x drive_linux ./drive_linux init ``` This will output a url you need to visit and sign in, which will return an auth code to enter in the console. After you've entered the auto code, the credentials are stored in *gdrive_temp/.gd/credentials.json*. #### Login to OpenShift Login to OpenShift ``` oc login <openshift url> ``` #### Deployment Utilize the following steps to deploy the project 1. Clone the repository ``` git clone https://github.com/redhat-cop/ninja-board ``` 2. Change into the project directory and utilize Ansible Galaxy to retrieve required dependencies ``` ansible-galaxy install -r requirements.yml --roles-path=galaxy ``` 3. Ensure the variables have been updated in the _ninja-board-deployment_ params file 4. Execute the _openshift-applier_ ``` ansible-playbook -i .applier/inventory galaxy/openshift-applier/playbooks/openshift-cluster-seed.yml -e="@.openshift/params/ninja-board-deployment" -e exclude_tags=ldap-rbac,ldap,v2 ``` Once complete, all of the v1 resources should be available in OpenShift ### v2 OpenShift Deployment #### Login to OpenShift Login to OpenShift ``` oc login <openshift url> ``` #### Deployment Utilize the following steps to deploy the project 1. Clone the repository and checkout v2 branch ``` git clone https://github.com/redhat-cop/ninja-board git checkout v2 ``` 2. Change into the project directory and utilize Ansible Galaxy to retrieve required dependencies ``` ansible-galaxy install -r requirements.yml --roles-path=galaxy ``` 3. Ensure the variables have been updated in the _.applier/inventory/group_vars/all.yml_ ansible params file to the desired values 4. Execute the _openshift-applier_ ``` ansible-playbook -i .applier/inventory galaxy/openshift-applier/playbooks/openshift-cluster-seed.yml -e="@.openshift/params/ninja-board-deployment" -e include_tags=v2 ``` ***NOTES*** * If you have not yet created the openshift dev project, you will need to change the `include_tags` argument to `include_tags=project-req-dev,v2` * If you have not yet created a Jenkins instance in the openshift dev project, you will need to change the `include_tags` argument to `include_tags=cicd,v2` * If you are not behind RedHat Network and would like access to services that use ldap, you will need to change the `include_tags` argument to `include_tags=ldap-rbac,ldap,v2`. This will ***FAIL*** if you do not have sufficient priveleges. If you don't have access to perform this, ask a cluster administrator. Once complete, all of the v2 resources should be available in OpenShift <file_sep>/quarkus/all-service/src/main/resources/application.properties com.redhat.services.ninja.client.UserClient/mp-rest/url=http://localhost:8080/ com.redhat.services.ninja.client.UserClient/mp-rest/scope=javax.inject.Singleton com.redhat.services.ninja.client.ScorecardClient/mp-rest/url=http://localhost:8080/ com.redhat.services.ninja.client.ScorecardClient/mp-rest/scope=javax.inject.Singleton com.redhat.services.ninja.client.LevelClient/mp-rest/url=http://localhost:8080/ com.redhat.services.ninja.client.LevelClient/mp-rest/scope=javax.inject.Singleton com.redhat.services.ninja.client.PeriodClient/mp-rest/url=http://localhost:8080/ com.redhat.services.ninja.client.PeriodClient/mp-rest/scope=javax.inject.Singleton com.redhat.services.ninja.client.EventClient/mp-rest/url=http://localhost:8080/ com.redhat.services.ninja.client.EventClient/mp-rest/scope=javax.inject.Singleton quarkus.http.cors=true quarkus.native.additional-build-args=-H:ReflectionConfigurationFiles=reflection-config.json mp.openapi.scan.disable=true<file_sep>/quarkus/scorecard-service/src/test/java/com/redhat/services/ninja/controller/ScorecardResourceTest.java package com.redhat.services.ninja.controller; import com.data.services.ninja.test.AbstractResourceTest; import com.redhat.services.ninja.client.EventClient; import com.redhat.services.ninja.client.ScorecardClient; import com.redhat.services.ninja.entity.Event; import com.redhat.services.ninja.entity.Point; import com.redhat.services.ninja.entity.Scorecard; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.mockito.InjectMock; import io.restassured.common.mapper.TypeRef; import io.restassured.http.ContentType; import org.eclipse.microprofile.rest.client.inject.RestClient; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @QuarkusTest class ScorecardResourceTest extends AbstractResourceTest { @InjectMock @RestClient ScorecardClient client; @InjectMock @RestClient EventClient eventClient; static private final Map<String, Scorecard> scorecards = new HashMap<>(); @BeforeAll static void initScorecards() { Scorecard newScorecard = new Scorecard(); newScorecard.setUsername("new_ninja"); scorecards.put("new_ninja", newScorecard); } @BeforeEach void initTest() { when(client.create(any(Scorecard.class))) .thenAnswer(a -> a.getArgument(0)); when(eventClient.create(any(Event.class))) .thenAnswer(a -> a.getArgument(0)); when(client.update(any(Scorecard.class))) .thenAnswer(a -> a.getArgument(0)); when(client.get(any())).thenAnswer(a -> scorecards.get(a.getArgument(0))); when(client.getAll()).thenReturn(new ArrayList<>(scorecards.values())); } @Test void increment() { Point point = new Point(); point.setValue(2); point.setPool("Trello"); point.setReference("trello/1"); Scorecard scorecard = given() .contentType(ContentType.JSON) .body(point) .when() .post("scorecard/new_ninja") .as(Scorecard.class); assertAll( () -> assertEquals("new_ninja", scorecard.getUsername()), () -> assertEquals(2, scorecard.getTotal()), () -> assertEquals(2, scorecard.getDetails().get("Trello")) ); } @Test void incrementNonExistingScorecard() { Point point = new Point(); point.setValue(3); point.setPool("Trello"); point.setReference("trello/3"); given() .when() .contentType(ContentType.JSON) .body(point) .post("scorecard/non_existing_ninja/Trello") .then() .statusCode(404); } @Test void getExistingScorecard() { Scorecard scorecard = given() .when() .get("scorecard/new_ninja") .as(Scorecard.class); assertEquals("new_ninja", scorecard.getUsername()); } @Test void getNonExistingScorecard() { given() .when() .get("scorecard/non_existing_ninja") .then() .statusCode(404); } @Test void getAllScorecards() { List<Scorecard> scorecards = given() .when() .get("scorecard") .as(new TypeRef<>() { }); for (int i = 0; i < scorecards.size() - 1; i++) { assertTrue(scorecards.get(i).getTotal() >= scorecards.get(i + 1).getTotal()); } } }<file_sep>/quarkus/data-service/src/test/java/com/redhat/services/ninja/data/controller/EventResourceTest.java package com.redhat.services.ninja.data.controller; import com.data.services.ninja.test.AbstractResourceTest; import com.redhat.services.ninja.entity.Event; import io.quarkus.test.junit.QuarkusTest; import io.restassured.common.mapper.TypeRef; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import java.util.List; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.*; @QuarkusTest class EventResourceTest extends AbstractResourceTest { @Test void create() { Event event = Event.Type.SUCCESSFUL_REGISTRATION.createEvent("new_user"); event.setUser("new_user"); Event createdEvent = given() .contentType(ContentType.JSON) .body(event) .when() .post("/data/event") .as(Event.class); assertAll( () -> assertEquals(event.getUser(), createdEvent.getUser()), () -> assertEquals(event.getType(), createdEvent.getType()), () -> assertNotNull(event.getTimestamp()) ); } @Test void getAll() { List<Event> allEvents = given() .when() .get("/data/event") .as(new TypeRef<>() { }); assertAll( () -> assertTrue(allEvents.stream().anyMatch(e -> e.getUser().equals("super_ninja"))), () -> assertTrue(allEvents.stream().anyMatch(e -> e.getUser().equals("modest_ninja"))) ); } }<file_sep>/quarkus/event-service/src/test/java/com/redhat/services/ninja/controller/EventResourceTest.java package com.redhat.services.ninja.controller; import com.data.services.ninja.test.AbstractResourceTest; import com.redhat.services.ninja.client.EventClient; import com.redhat.services.ninja.entity.Event; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.mockito.InjectMock; import io.restassured.common.mapper.TypeRef; import org.eclipse.microprofile.rest.client.inject.RestClient; import org.junit.jupiter.api.Test; import java.util.List; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; @QuarkusTest class EventResourceTest extends AbstractResourceTest { @InjectMock @RestClient EventClient client; @Test void getAllEvents() { when(client.getAll()) .thenAnswer(a -> ninjaDatabase.getEvents()); List<Event> events = given() .when() .get("event") .as(new TypeRef<>() { }); assertTrue(events.size() > 0); } }<file_sep>/quarkus/user-service/src/test/java/com/redhat/services/ninja/controller/UserResourceTest.java package com.redhat.services.ninja.controller; import com.data.services.ninja.test.AbstractResourceTest; import com.redhat.services.ninja.client.EventClient; import com.redhat.services.ninja.client.ScorecardClient; import com.redhat.services.ninja.client.UserClient; import com.redhat.services.ninja.entity.Event; import com.redhat.services.ninja.entity.Scorecard; import com.redhat.services.ninja.entity.User; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.mockito.InjectMock; import io.restassured.http.ContentType; import org.eclipse.microprofile.rest.client.inject.RestClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.ws.rs.core.Response; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @QuarkusTest class UserResourceTest extends AbstractResourceTest { @InjectMock @RestClient UserClient userClient; @InjectMock @RestClient ScorecardClient scorecardClient; @InjectMock @RestClient EventClient eventClient; @BeforeEach void initTest() { when(userClient.create(any(User.class))) .thenAnswer(a -> a.getArgument(0)); when(scorecardClient.create(any(Scorecard.class))) .thenAnswer(a -> a.getArgument(0)); when(eventClient.create(any(Event.class))) .thenAnswer(a -> a.getArgument(0)); } @Test void existingUserRegistration() { User newUser = new User(); newUser.setUsername("new_ninja"); newUser.setDisplayName("New Ninja"); newUser.setGithubUsername("new_ninja"); given() .contentType(ContentType.JSON) .body(newUser) .when() .post("user") .then() .statusCode(201) .contentType(ContentType.JSON) .body( "username", equalTo("new_ninja"), "displayName", equalTo("<NAME>"), "githubUsername", equalTo("new_ninja"), "region", equalTo("EMEA") ); } @Test void nonExistingUserRegistration() { User newUser = new User(); newUser.setUsername("no_ninja"); newUser.setDisplayName("No Ninja"); newUser.setGithubUsername("no_ninja"); given() .contentType(ContentType.JSON) .body(newUser) .when() .post("user") .then() .statusCode(404); } @Test void noUserContentRegistration() { given() .contentType(ContentType.JSON) .when() .post("user") .then() .statusCode(Response.Status.BAD_REQUEST.getStatusCode()); } }<file_sep>/react/src/config/ServerUrls.js import axios from "axios"; const local = axios.create({ baseURL: window.USER_MANAGEMENT_API_URL }); export const userFromToken = jwt => { return axios.get( 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + jwt ); }; const API = local; export default API; <file_sep>/quarkus/data-client/src/main/java/com/redhat/services/ninja/client/EventClient.java package com.redhat.services.ninja.client; import com.redhat.services.ninja.entity.Event; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; @Path("data/event") @RegisterRestClient @ApplicationScoped public interface EventClient { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) Event create(Event entity); @GET @Produces(MediaType.APPLICATION_JSON) List<Event> getAll(); } <file_sep>/ldap/Dockerfile FROM osixia/openldap:1.3.0 ADD bootstrap /container/service/slapd/assets/config/bootstrap <file_sep>/quarkus/entities/pom.xml <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.redhat.service.ninja</groupId> <artifactId>community-ninja-board</artifactId> <version>2.0.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>entities</artifactId> <version>2.0.0-SNAPSHOT</version> <name>Entities</name> <dependencies> <dependency> <groupId>jakarta.json.bind</groupId> <artifactId>jakarta.json.bind-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-core</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.jboss.jandex</groupId> <artifactId>jandex-maven-plugin</artifactId> <version>1.0.7</version> <executions> <execution> <id>make-index</id> <goals> <goal>jandex</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/ldap/README.md # OpenLDAP An OpenLDAP image based on [osixia/openldap](https://hub.docker.com/r/osixia/openldap/). Documentation of the base image can be found at https://github.com/osixia/docker-openldap. ### Deploying on OpenShift Inside the *ldap* subdirectory: The OpenLDAP image needs to run as root to deploy successfully. You can grant a `serviceaccount` access to `scc/anyuid` by processing the *rbac.yaml* template. ``` oc process -f .openshift/templates/rbac.yaml -o yaml | oc create -f - ``` The above will **FAIL** if you do not have sufficient privileges. If you don't have access to perform this, ask a cluster administrator. Once the service account has been granted access to `scc/anyuid`, you can process the *ldap.yaml* template. ``` oc process -f .openshift/templates/ldap.yaml -o yaml | oc create -f - ``` Once complete, all ldap resources should be available in OpenShift. ### Extending the schema/adding entries To add new attributes, you can edit the `bootstrap/schema/rhperson.schema`. You will need to rebuild/redeploy for changes to take place. To add new entries, you can edit the `ConfigMap` named `ldif-config`. You will need to redeploy the ldap image for changes to take place. <file_sep>/quarkus/data-service/src/main/java/com/redhat/services/ninja/data/operation/IdentifiableDatabaseOperations.java package com.redhat.services.ninja.data.operation; import com.redhat.services.ninja.entity.Identifiable; import java.util.Optional; public interface IdentifiableDatabaseOperations<I, T extends Identifiable<I>> extends BasicDatabaseOperations<T> { Optional<T> get(I identifier); default T update(T entity) { return create(entity); } T delete(I identifier); } <file_sep>/quarkus/entities/src/main/java/com/redhat/services/ninja/entity/Database.java package com.redhat.services.ninja.entity; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.LocalDateTime; import java.util.*; @RegisterForReflection public class Database { private LocalDateTime createdOn = LocalDateTime.now(); private Set<User> users = Set.of(); private Set<Scorecard> scorecards = Set.of(); private SortedSet<Level> levels; private List<Event> events = List.of(); private SortedSet<Period> history = new TreeSet<>(); public Database() { levels = new TreeSet<>(); Arrays.stream(Level.KNOWN_LEVEL.values()).map(Level.KNOWN_LEVEL::getLevel).forEach(levels::add); } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } public Set<Scorecard> getScorecards() { return scorecards; } public void setScorecards(Set<Scorecard> scorecards) { this.scorecards = scorecards; } public SortedSet<Level> getLevels() { return levels; } public void setLevels(SortedSet<Level> levels) { this.levels = levels; } public List<Event> getEvents() { return events; } public void setEvents(List<Event> events) { this.events = events; } public LocalDateTime getCreatedOn() { return createdOn; } public SortedSet<Period> getHistory() { return history; } public void setHistory(SortedSet<Period> history) { this.history = history; } public void setCreatedOn(LocalDateTime createdOn) { this.createdOn = createdOn; } } <file_sep>/react/src/AppLayout.jsx import React, { useState, useEffect } from "react"; import { PageHeader, Page } from "@patternfly/react-core"; import { userFromToken } from "./config/ServerUrls"; import NavBar from "./components/NavBar"; import RedHatLogo from "./assets/media/logo.svg"; import AppRoutes from "./AppRoutes"; /** * @author fostimus */ const AppLayout = props => { // on app load, check if token exists to see if user is authenticated useEffect(() => { userFromToken(localStorage.getItem("jwt-token")) .then(res => { console.log(res); if (res.status === 200) { setLoggedIn(true); } }) .catch(err => { setLoggedIn(false); }); }, []); // setting to true by default, as there is an issue on reload when default is false. when false, routes // will always refresh to the login page; this is because the state changes in the useEffect of this // AppLayout component, and re renders. However, the route already rendered to redirect to /login and no // longer knows to re-render whatever page it was previously on const [loggedIn, setLoggedIn] = useState(true); const logo = ( <img style={{ width: "150px", marginLeft: "20px" }} src={RedHatLogo} alt="Red Hat" /> ); // this Header construct is a PatternFly design // logoProps = specifies properties on the component specified in logoComponent. // here, we are specifying the Link component to go to our index route const Header = loggedIn ? ( <PageHeader logo={logo} logoProps={{ href: "/" }} topNav={<NavBar />} /> ) : null; return ( <Page mainContainerId="primary-app-container" header={Header}> <AppRoutes loggedIn={loggedIn} setLoggedIn={setLoggedIn} /> </Page> ); }; export default AppLayout; <file_sep>/react/src/components/ConfirmationModal.jsx import React from "react"; import { Modal, Button } from "@patternfly/react-core"; import "../assets/css/modal.css"; /** * @author fostimus */ const ConfirmationModal = props => { return ( <React.Fragment> <Modal className="modal" variant="small" title={props.modalTitle} isOpen={props.showModal} onClose={props.handleModalToggle} actions={[ <Button key="confirm" variant="primary" onClick={props.handleModalToggle} > OK </Button> ]} > {props.modalText} </Modal> </React.Fragment> ); }; export default ConfirmationModal; <file_sep>/quarkus/data-service/src/test/java/com/redhat/services/ninja/data/controller/LevelResourceTest.java package com.redhat.services.ninja.data.controller; import com.data.services.ninja.test.AbstractResourceTest; import com.redhat.services.ninja.entity.Level; import io.quarkus.test.junit.QuarkusTest; import io.restassured.common.mapper.TypeRef; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.*; @QuarkusTest class LevelResourceTest extends AbstractResourceTest { @Test void create() { Level newLevel = new Level(); newLevel.setMinimumPoint(150); newLevel.setName("GOLD"); Level createdLevel = given() .contentType(ContentType.JSON) .body(newLevel) .when() .put("/data/level") .as(Level.class); assertEquals(newLevel, createdLevel); } @Test void get() { Map<String, Level> levels = getLevels(); Level blackLevel = given() .when() .get("/data/level/BLACK") .as(Level.class); assertEquals(levels.get("BLACK"), blackLevel); } @Test void getAll() { Map<String, Level> levels = getLevels(); List<Level> allLevels = given() .when() .get("/data/level") .as(new TypeRef<>() { }); assertAll( () -> assertTrue(allLevels.contains(levels.get("ZERO"))), () -> assertTrue(allLevels.contains(levels.get("RED"))), () -> assertTrue(allLevels.contains(levels.get("GREY"))), () -> assertTrue(allLevels.contains(levels.get("BLACK"))) ); } @Test void update() { Map<String, Level> levels = getLevels(); Level level = levels.get("BLACK"); level.setMinimumPoint(90); given() .contentType(ContentType.JSON) .body(level) .when() .put("/data/level") .then() .body("minimumPoint", is(90)); } @Test void delete() { Map<String, Level> levels = getLevels(); Level blue = levels.get("BLUE"); Level level = given() .when() .delete("/data/level/BLUE") .as(Level.class); given().when() .get("/data/level/BLUE") .then() .statusCode(404); assertEquals(blue, level); } public Map<String, Level> getLevels() { return ninjaDatabase.getLevels().stream().collect(Collectors.toMap(Level::getIdentifier, Function.identity())); } }<file_sep>/quarkus/entities/src/main/java/com/redhat/services/ninja/entity/Event.java package com.redhat.services.ninja.entity; import javax.json.bind.annotation.JsonbPropertyOrder; import javax.json.bind.annotation.JsonbTransient; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Function; @JsonbPropertyOrder({"timestamp", "user", "type", "description"}) public class Event { private LocalDateTime timestamp = LocalDateTime.now(); private String user; private String type; private String description; public LocalDateTime getTimestamp() { return timestamp; } public void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getType() { return type; } public void setType(String type) { this.type = type; } @JsonbTransient public Optional<Type> getKnownType() { return Type.fromString(type); } @JsonbTransient public void setKnownType(Type type) { this.type = type.toString(); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public enum Type { SUCCESSFUL_REGISTRATION("User %s was registered successfully."), FAILED_LDAP_REGISTRATION("Failed to register User %s."), POINT_INCREMENT("User %s score changed by %d from %d to %d in category %s for %s."); private static final Function<String, String> NAME_NORMALIZER = name -> name.toLowerCase().replace('_', ' '); private static final Map<String, Type> TYPE_MAP = new HashMap<>(); static { for (Type type : Type.values()) { TYPE_MAP.put(type.toString(), type); } } private final String format; Type(String format) { this.format = format; } public static Optional<Type> fromString(String type) { var normalizedName = NAME_NORMALIZER.apply(type); return Optional.ofNullable(TYPE_MAP.get(normalizedName)); } public Event createEvent(Object... parameters) { Event event = new Event(); event.setKnownType(this); event.description = String.format(format, parameters); return event; } @Override public String toString() { return NAME_NORMALIZER.apply(this.name()); } } }<file_sep>/quarkus/entities/src/main/java/com/redhat/services/ninja/entity/Level.java package com.redhat.services.ninja.entity; import javax.json.bind.annotation.JsonbTransient; import java.util.Objects; public class Level implements Identifiable<String>, Comparable<Level> { private String name; private int minimumPoint; @Override @JsonbTransient public String getIdentifier() { return getName(); } public String getName() { return name; } public void setName(String name) { this.name = name.trim().toUpperCase(); } public int getMinimumPoint() { return minimumPoint; } public void setMinimumPoint(int minimumPoint) { this.minimumPoint = minimumPoint; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Level level = (Level) o; return name.equals(level.name); } @Override public int hashCode() { return Objects.hash(name); } @Override public int compareTo(Level level) { return Integer.compare(this.minimumPoint, level.minimumPoint); } public enum KNOWN_LEVEL { BLACK(75), RED(40), GREY(20), BLUE(5), ZERO(0); private final Level level; KNOWN_LEVEL(int minimumPoint) { this.level = new Level(); this.level.name = this.name(); this.level.minimumPoint = minimumPoint; } public Level getLevel() { return level; } } }<file_sep>/react/src/AppRoutes.jsx import React, { Fragment } from "react"; import { Route, Switch, Redirect } from "react-router-dom"; import { PageSection } from "@patternfly/react-core"; import FormSection from "./components/UserRegistrationForm"; import AdminSection from "./components/AdminConfigurable"; import ScorecardSection from "./components/Scorecard"; import LoginSection from "./components/NinjaLogin"; import AccountSection from "./components/AccountPage"; /** * @author fostimus */ // edit/add routes here export const ninjaRoutes = [ { id: 1, routeName: "Scorecards", routePath: "/scorecards", component: ScorecardSection }, { id: 2, routeName: "Leaderboard", routePath: "/leaderboard" }, { id: 3, routeName: "Events", routePath: "/events" }, { id: 4, routeName: "Responses Spreadsheet", routePath: "/responses-spreadsheets" }, { id: 5, routeName: "Support - Trello Query", routePath: "/support/trello-query" }, { id: 6, routeName: "Support - Trello Reconciliation", routePath: "/support/trello-reconciliation" } ]; //TODO: leverage component field in <Switch> component export const adminRoutes = [ { id: 1, routeName: "Config", routePath: "/config", component: AdminSection, adminPage: "Config" }, { id: 2, routeName: "Database", routePath: "/database", component: AdminSection, adminPage: "Database" } ]; export const accountRoutes = [ { id: 1, routeName: "Registration Form", routePath: "/registration-form", component: FormSection }, { id: 2, routeName: "Edit Account", routePath: "/edit-account", component: AccountSection }, ] const AppRoutes = props => { // TODO: add in a third case. // 1. not logged in --> routed to login page // 2. logged in, but not registered --> edit account/registration // 3. logged in and registered --> scorecards const firstComponent = properties => !props.loggedIn ? ( <LoginSection {...properties} loggedIn={props.loggedIn} setLoggedIn={props.setLoggedIn} /> ) : ( // will be profile page when it's made <Redirect to="/scorecards" /> ); return ( <Fragment> <Switch> {/*TODO: home page shouldn't be login; landing page should, but home should be ______*/} <Route key="home" exact path="/" render={properties => firstComponent(properties)} /> <Route key="login" path="/login" render={properties => firstComponent(properties)} /> {ninjaRoutes.map(route => ( <Route key={route.routeName} path={route.routePath}> {props.loggedIn ? route.component : <Redirect to="/login" />} </Route> ))} {adminRoutes.map(route => ( <Route key={route.routeName} path={route.routePath}> {props.loggedIn ? ( //TODO: use route.component and pass in route.adminPage as prop <AdminSection adminPage={route.adminPage} /> ) : ( <Redirect to="/login" /> )} </Route> ))} {accountRoutes.map(route => ( <Route key={route.routeName} path={route.routePath}> {props.loggedIn ? route.component : <Redirect to="/login" />} </Route> ))} <Route key="not-found" path="*" render={() => ( <PageSection> <div>Not Found</div> </PageSection> )} /> </Switch> </Fragment> ); }; export default AppRoutes; <file_sep>/quarkus/all-service/pom.xml <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.redhat.service.ninja</groupId> <artifactId>quarkus</artifactId> <version>2.0.0-SNAPSHOT</version> <relativePath>../quarkus-pom/pom.xml</relativePath> </parent> <artifactId>all-service</artifactId> <name>Bundled Services</name> <version>2.0.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-smallrye-openapi</artifactId> </dependency> </dependencies> <build> <sourceDirectory>..</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <release>11</release> <includes> <include>data-service/src/main/java/**</include> <include>user-service/src/main/java/**</include> <include>scorecard-service/src/main/java/**</include> <include>event-service/src/main/java/**</include> </includes> </configuration> </plugin> </plugins> </build> </project><file_sep>/quarkus/event-service/src/main/java/com/redhat/services/ninja/controller/EventResource.java package com.redhat.services.ninja.controller; import com.redhat.services.ninja.client.EventClient; import com.redhat.services.ninja.entity.Event; import org.eclipse.microprofile.rest.client.inject.RestClient; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; @Path("/event") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class EventResource { @Inject @RestClient EventClient eventClient; @GET public List<Event> getAll() { return eventClient.getAll(); } }<file_sep>/react/src/components/Scorecard.jsx import React, { useState, useEffect, useCallback } from "react"; import { Table, TableHeader, TableBody, sortable, SortByDirection } from "@patternfly/react-table"; import { PageSection } from "@patternfly/react-core"; import PaginationControls from "./PaginationControls"; import API from "../config/ServerUrls"; import "../assets/css/horizontal-scroll.css"; /** * @author fostimus */ const ScorecardSection = () => { return ( <PageSection> <div className="horizontal-scroll"> <SortableTable /> </div> </PageSection> ); }; export default ScorecardSection; export const SortableTable = props => { /** * State Initialization */ const [columns, setColumns] = useState([]); const [rows, setRows] = useState([]); const [displayedRows, setDisplayedRows] = useState([]); const [page, setPage] = useState(1); const [perPage, setPerPage] = useState(10); const [sortBy, setSortBy] = useState({}); /** * method to set/change which rows are displayed */ const changeDisplayedRows = useCallback( (amountOfRows, index, serverData = rows) => { //set the appropriate value to end looping at let targetEnd = index + amountOfRows; let loopEnd = serverData.length > targetEnd ? targetEnd : serverData.length; //create displayedRows from array of all rows let toBeDisplayed = []; for (let i = index; i < loopEnd; i++) { toBeDisplayed.push(serverData[i]); } setDisplayedRows(toBeDisplayed); }, [rows] ); /** * Retrieve and process data from server */ useEffect(() => { let mounted = true; API.get(`/scorecard`).then(response => { let tableHeaders = []; const scorecardMaps = processServerData(response.data, tableHeaders); const scorecardRows = scorecardMaps.map(scorecardMap => { return createScorecardRow(scorecardMap, tableHeaders); }); // create collection of columns with sortable functionality const sortableColumns = tableHeaders.map(header => { const sortableColumn = { title: header, transforms: [sortable] }; return sortableColumn; }); if (mounted) { setColumns(sortableColumns); setRows(scorecardRows); let loopEnd = scorecardRows.length > perPage ? perPage : scorecardRows.length; //create displayedRows from array of all rows let toBeDisplayed = []; for (let i = 0; i < loopEnd; i++) { toBeDisplayed.push(scorecardRows[i]); } setDisplayedRows(toBeDisplayed); } }); return () => (mounted = false); }, [perPage]); /** * Manipulation of data */ // uses displayedRows as opposed to rows, since we only want to sort the rows currently displayed const onSort = (_event, index, direction) => { const sortedRows = displayedRows.sort((a, b) => a[index] < b[index] ? -1 : a[index] > b[index] ? 1 : 0 ); setSortBy({ index, direction }); setDisplayedRows( direction === SortByDirection.asc ? sortedRows : sortedRows.reverse() ); }; const onPerPageSelect = newPerPage => { let currentIndex = page * perPage; changeDisplayedRows(newPerPage, currentIndex); setPerPage(newPerPage); }; return ( <React.Fragment> <Table aria-label="Sortable Table" sortBy={sortBy} onSort={onSort} cells={columns} rows={displayedRows} > <TableHeader /> <TableBody /> </Table> <PaginationControls rows={rows.length} page={page} setPage={setPage} perPage={perPage} onPerPageSelect={onPerPageSelect} changeDisplayedRows={changeDisplayedRows} /> </React.Fragment> ); }; /** * Helper methods - don't directly use state */ const isObject = value => { return value && typeof value === "object" && value.constructor === Object; }; //return value: Array of Maps, each map represents a scorecard const processServerData = (object, columnHeaders) => { return object.map(scorecard => { let scorecardMap = new Map(); getColumnHeadersAndScorecardMaps(scorecard, columnHeaders, scorecardMap); return scorecardMap; }); }; //recursive method to get all column headers into one array const getColumnHeadersAndScorecardMaps = ( scorecard, columnHeaders, scorecardMap ) => { Object.keys(scorecard).forEach(key => { if (!isObject(scorecard[key])) { // set up column headers if (!columnHeaders.includes(key)) { columnHeaders.push(key); } // populate scorecardMap scorecardMap.set(key, scorecard[key]); } else { // if value is an object, recursively call this function to flatten headers and scorecardMap getColumnHeadersAndScorecardMaps( scorecard[key], columnHeaders, scorecardMap ); } }); }; const createScorecardRow = (scorecardMap, initialColumns) => { // initialize the row with 0 as each element let row = []; for (var i = 0; i < initialColumns.length; i++) { row.push("0"); } // place the value of the scorecard map in the correct position, based on column headers for (const [key, value] of scorecardMap) { const position = initialColumns.indexOf(key); row.splice(position, 1, value.toString()); } return row; }; <file_sep>/quarkus/data-service/src/test/resources/application.properties %test.users.ldap.provider=ldap://i.wont.tell.you.the.real.value:389 %test.users.ldap.baseDN=ou=users,dc=wont,dc=tell<file_sep>/react/src/components/NavBar.jsx import React, { useState } from "react"; import { NavLink } from "react-router-dom"; import { Nav, NavExpandable, NavItem, NavList, NavVariants, Button } from "@patternfly/react-core"; import "../assets/css/nav.css"; /** * @author fostimus */ const NavBar = props => { const expandbleRef = React.createRef(); // this controls CSS highlighting when selecting a link const [activeGroup, setActiveGroup] = useState(""); const [activeItem, setActiveItem] = useState(""); // Since we are using 3rd party components from PatterFly, // we need to use refs to manually change the expandedState // when an item is clicked const closeExpandables = () => { expandbleRef.current.state.expandedState = false; }; const onSelect = result => { setActiveGroup(result.groupId); setActiveItem(result.itemId); }; const logout = () => { localStorage.removeItem("jwt-token"); localStorage.removeItem("display-name"); window.location.reload(); }; //TODO: Nav bar comes out of the page header when the window shrinks horizontally, and there is an obvious style change // TODO: styling for "Logged in as" and Logout button return ( <Nav className="account-menu" onSelect={onSelect}> <NavList className="right-align" variant={NavVariants.horizontal}> <NavExpandable key="ninja" title={"Account: " + localStorage.getItem("display-name")} srText="Account" groupId="account" isActive={activeGroup === "account"} ref={expandbleRef} > <NavItem key="account-edit" groupId="account" itemId="account-edit" isActive={activeItem === "account-edit"} onClick={closeExpandables} > <NavLink exact to="/edit-account"> Edit Account </NavLink> </NavItem> <NavItem key="authentication-logout" groupId="account" itemId="authentication-logout" isActive={activeItem === "authentication-logout"} onClick={logout} > Logout </NavItem> </NavExpandable> </NavList> </Nav> ); }; export default NavBar; <file_sep>/quarkus/README.MD # Quarkus Migration ## Goals * Enhance by adopting a MicroService Architecture * Allow single bundled deployment * Enhance performance by using Red Hat Technology (Quarkus) * Prioritising simplicity and maintainability ## Requirements * OpenJDK 11 - [Download from Red Hat](https://developers.redhat.com/products/openjdk/download) ## Structure This project has multiple components. So far they are: 3 Microservices, 3 supporting shared libraries. * Microservices that can be bundled user the `all-service` module * `user-service` - contains features related to the user such as Registration. * `scorecard-service` - groups features related to scorecard such as "Point Addition". * `data-service` - manages data and offer CRUD operations on entities. * Shared Libraries * `entities` - shared data model * `data-client` - interface for accessing the CRUD services of `data-service` * `test-helper` - helper classes for testing `all-service` is a special project that bundles all the available microservices. In addition, it includes an Open API specification available at `/openapi`. Running it in dev mode (`mvn quarkus:dev -f all-service`) will enable Swagger UI at `/swagger-ui`. The Shared Libraries are regular java projects indexed with jandex so that they can be Quarkus enhanced later. The services are Quarkus Project and inherit from `quarkus-pom`. ## Create Environment variables before running ### Linux ```shell script export USERS_LDAP_PROVIDER=i-wont-tell-you-the-real-value export USERS_LDAP_BASEDN=i-really-wont-tell-you-the-real-value export DATABASE_FILE=your-database-file-location # not required mvn install java -jar all-service/build/all-service-2.0.0-SNAPSHOT-runner.jar ``` ### Windows (PowerShell) ```shell script [System.Environment]::SetEnvironmentVariable('USERS_LDAP_PROVIDER','i-wont-tell-you-the-real-value', [System.EnvironmentVariableTarget]::User) # Need to set only once in user scope [System.Environment]::SetEnvironmentVariable('USERS_LDAP_BASEDN','i-really-wont-tell-you-the-real-value', [System.EnvironmentVariableTarget]::User) # Need to set only once in user scope [System.Environment]::SetEnvironmentVariable('DATABASE_FILE','use-your-ninja-database.json', [System.EnvironmentVariableTarget]::User) # Need to set only once in user scope ``` Note that the default location for the database file is: database.json. A good database example can be found [here](test-helper/src/main/resources/com/redhat/services/ninja/test/database.json). ## Building and running ```shell script mvn install java -jar all-service/target/all-service-2.0.0-SNAPSHOT-runner.jar ``` For native application: ```shell script mvn install mvn package -Pnative -f all-service ./all-service/target/all-service-2.0.0-SNAPSHOT-runner ``` ## Testing ### Important Note * Endpoint start with /data are for internal use only. * A scorecard cannot be created directly, creating a user creates its scorecard * The only way to modify a scorecard is by incrementing ### Operations Refer to [OpenAPI Spec](all-service/src/main/resources/META-INF/openapi.yaml). ### Linux ```shell script curl localhost:8080/user/some-user-id-that-do-exist curl localhost:8080/user/some-user-id-that-dont-exist curl -H "Content-Type: application/json" --data '{"username":"some-user-id-that-do-exist"}' localhost:8080/user curl localhost:8080/user/mail/some-mail-that-exist curl localhost:8080/data/user curl localhost:8080/data/scorecard curl localhost:8080/data/event ``` ### Windows (PowerShell) ```shell script Invoke-RestMethod -Uri http://localhost:8080/user/some-user-id-that-do-exist Invoke-RestMethod -Uri http://localhost:8080/user/some-user-id-that-dont-exist Invoke-RestMethod -ContentType 'application/json' -Body $(@{username='some-user-id-that-do-exist'} | ConvertTo-Json) -Uri http://localhost:8080/user -Method POST Invoke-RestMethod -Uri http://localhost:8080/user/mail/some-mail-that-exist Invoke-RestMethod localhost:8080/data/user Invoke-RestMethod localhost:8080/data/scorecard Invoke-RestMethod localhost:8080/data/event ``` Or (PowerShell) ```shell script curl http://localhost:8080/user/some-user-id-that-do-exist curl http://localhost:8080/user/some-user-id-that-dont-exist curl http://localhost:8080/user/mail/some-mail-that-exist curl http://localhost:8080/user -ContentType 'application/json' -Body $(@{username='some-user-id-that-do-exist'} | ConvertTo-Json) -Method POST curl http://localhost:8080/data/user curl http://localhost:8080/data/scorecard curl http://localhost:8080/data/event ```<file_sep>/quarkus/entities/src/main/java/com/redhat/services/ninja/entity/User.java package com.redhat.services.ninja.entity; import javax.json.bind.annotation.JsonbTransient; import java.util.Objects; public class User implements Identifiable<String>{ private String username; private String displayName; private String email; private String githubUsername; private String trelloUsername; private String region; @Override @JsonbTransient public String getIdentifier() { return getUsername(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGithubUsername() { return githubUsername; } public void setGithubUsername(String githubUsername) { this.githubUsername = githubUsername; } public String getTrelloUsername() { return trelloUsername; } public void setTrelloUsername(String trelloUsername) { this.trelloUsername = trelloUsername; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return username.equals(user.username); } @Override public int hashCode() { return Objects.hash(username); } } <file_sep>/Getting-Started.md #Getting Started ##Requirements * OpenShift Client (`oc`) * The deployment location must be within Red Hat Network. ## Create or set your current project. ```shell script oc new-project ninja-board-golum-experiment # or oc project ninja-board-golum-experiment ``` ##Deploying on OpenShift ```shell script oc process -f .openshift/templates/ninja-board-back-end.yaml -o yaml | oc apply -f - oc process -f .openshift/templates/ninja-board-front-end.yaml -p API_URL=http://$(oc get route ninja-board-back-end -o jsonpath='{.spec.host}') -o yaml | oc apply -f - ``` ## Open Front End URL within your browser of choice. To obtain this url: ```shell script oc get route ninja-board-front-end -o jsonpath='{.spec.host}' ```<file_sep>/react/src/components/AdminConfigurable.jsx import React, { Fragment } from "react"; import { PageSection } from "@patternfly/react-core"; import "../assets/css/admin.css"; /** * @author fostimus */ const AdminSection = props => { return ( <PageSection> <AdminConfigurable adminPage={props.adminPage} /> </PageSection> ); }; export default AdminSection; // component that just returns a textarea and a button to save info. // pass in the appropriate API to set the correct data // TODO: implement the above via API call to new quarkus app export const AdminConfigurable = props => { // if (props.adminPage !== 'Config' && props.adminPage !== 'Database') { // throw new Error("Invalid value; must be 'Config' or 'Database'"); // } return ( <Fragment> <h1>{props.adminPage}</h1> <textarea className="admin-input"></textarea> <div className="admin-submit"> <button type="submit" name="save"> Save </button> </div> </Fragment> ); }; <file_sep>/quarkus/data-service/src/test/java/com/redhat/services/ninja/data/controller/ScorecardResourceTest.java package com.redhat.services.ninja.data.controller; import com.data.services.ninja.test.AbstractResourceTest; import com.redhat.services.ninja.entity.Scorecard; import io.quarkus.test.junit.QuarkusTest; import io.restassured.common.mapper.TypeRef; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.*; @QuarkusTest class ScorecardResourceTest extends AbstractResourceTest { @Test void create() { Scorecard newScorecard = new Scorecard(); newScorecard.setUsername("new_ninja"); newScorecard.increment("Github", 2); Scorecard createdScorecard = given() .contentType(ContentType.JSON) .body(newScorecard) .when() .post("/data/scorecard") .as(Scorecard.class); assertAll( () -> assertEquals(newScorecard, createdScorecard), () -> assertEquals(newScorecard.getTotal(), createdScorecard.getTotal()) ); } @Test void getAll() { Map<String, Scorecard> scorecards = getScorecards(); List<Scorecard> allScorecards = given() .when() .get("/data/scorecard") .as(new TypeRef<>() { }); assertAll( () -> assertTrue(allScorecards.contains(scorecards.get("modest_ninja"))), () -> assertTrue(allScorecards.contains(scorecards.get("super_ninja"))) ); } @Test void update() { Map<String, Scorecard> scorecards = getScorecards(); Scorecard modestNinja = scorecards.get("modest_ninja"); modestNinja.increment("Trello", 5); given() .contentType(ContentType.JSON) .body(modestNinja) .when() .put("/data/scorecard") .then() .body("total", equalTo(modestNinja.getTotal())); } @Test void delete() { Map<String, Scorecard> scorecards = getScorecards(); Scorecard retiredNinja = scorecards.get("retired_ninja"); Scorecard scorecard = given() .when() .delete("/data/scorecard/retired_ninja") .as(Scorecard.class); assertEquals(retiredNinja, scorecard); } private Map<String, Scorecard> getScorecards(){ return ninjaDatabase.getScorecards().stream().collect(Collectors.toMap(Scorecard::getIdentifier, Function.identity())); } }<file_sep>/quarkus/user-service/src/test/resources/application.properties users.ldap.provider=ldap://i.wont.tell.you.the.real.value:389 users.ldap.baseDN=ou=users,dc=wont,dc=tell<file_sep>/quarkus/data-service/src/main/java/com/redhat/services/ninja/data/controller/EventResource.java package com.redhat.services.ninja.data.controller; import com.redhat.services.ninja.entity.Event; import com.redhat.services.ninja.data.operation.BasicDatabaseOperations; import com.redhat.services.ninja.data.service.DatabaseEngine; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/data/event") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class EventResource extends AbstractResource<Event, BasicDatabaseOperations<Event>>{ @Inject DatabaseEngine engine; @Override public DatabaseEngine getEngine() { return engine; } @Override public BasicDatabaseOperations<Event> getOperations() { return engine.getEventOperations(); } } <file_sep>/quarkus/scorecard-service/src/main/java/com/redhat/services/ninja/controller/LevelResource.java package com.redhat.services.ninja.controller; import com.redhat.services.ninja.client.LevelClient; import com.redhat.services.ninja.entity.Level; import org.eclipse.microprofile.rest.client.inject.RestClient; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; @Path("/level") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class LevelResource { @Inject @RestClient LevelClient levelClient; @GET public List<Level> getAll() { return levelClient.getAll(); } } <file_sep>/react/README.md This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). # Running 1. `npm install` 2. `npm start` # Current Status The user management features are the big ones to tackle now. Google OIDC is implemented, but the "implicit" flow is implemented and you should implement the "server" flow. The /registration-page is for submitting a request from the user to the backend hosted on Quarkus, which creates a user in the Giveback Ninja system. It was going to be repurposed into the "Edit Profile" page, with the first time logging in through Google sending the necessary info to "register" (create) a user. From the "Edit Profile" page, a user could then update more information as needed. # Background This project is set up with React.js, leveraging components from [PatternFly](https://www.patternfly.org). PatternFly is a library of reusable, familiar components on any webpage, e.g. Navigation Bar, Table, Buttons, Forms, etc. It includes CSS, so you don't have to worry about styling if you don't want to. It is recommended to use their CSS, as it is inline with the branding of PatternFly and Red Hat. Any files you need to use not related to JavaScript should be stored in [assets](src/assets). This includes CSS files, images, and other media. A majority of development work will happen in [components](src/components). These are the building blocks of your application, and good component design is crucial to a maintainable codebase. Since PatternFly is being used, custom components need to roll up into PatternFly wrappers, like `PageSection`, `PageHeader`, and `Page`. See PatternFly documentation for more info. Any configuration data should be stored in [config](src/config) and imported in the appropriate JS file. The top level of this project, with files such as `App.js`, `AppLayout.jsx`, and `AppRoutes.jsx` should stay as lean as possible, and be only for files that affect the entire project. If you cannot prefix your file name with `App` and it not make sense, then it most likely does not belong here. ## PatternFly Tips - Any component you want to use as a page in the application needs to be wrapped in `<PageSection></PageSection>` - If you need to access the state of a PatternFly component, use a [React ref](https://reactjs.org/docs/refs-and-the-dom.html). - Use the documentation to see what properties a component takes. # Known issues and potential improvements 1. When page shrinks, NavBar pops out of Header and has different styling. 2. Start up performance sucks # create-react-app Generated README Below is information automatically set up by [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br /> Open <http://localhost:3000> to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.<br /> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.<br /> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br /> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: <https://facebook.github.io/create-react-app/docs/code-splitting> ### Analyzing the Bundle Size This section has moved here: <https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size> ### Making a Progressive Web App This section has moved here: <https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app> ### Advanced Configuration This section has moved here: <https://facebook.github.io/create-react-app/docs/advanced-configuration> ### Deployment This section has moved here: <https://facebook.github.io/create-react-app/docs/deployment> ### `yarn build` fails to minify This section has moved here: <https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify> <file_sep>/quarkus/entities/src/main/java/com/redhat/services/ninja/entity/Period.java package com.redhat.services.ninja.entity; import javax.json.bind.annotation.JsonbTransient; import java.time.LocalDateTime; import java.util.*; public class Period implements Comparable<Period>, Identifiable<String> { private String name; private LocalDateTime cumulatedOn = LocalDateTime.now(); private Map<String, Record> records = new HashMap<>(); public Period() { } public Period(String name, Map<String, Record> records) { this.name = name; setRecords(records); } private static Map<String, Record> sort(Map<String, Record> records) { Map<String, Record> newRecords = new HashMap<>(); records.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .forEachOrdered(entry -> newRecords.put(entry.getKey(), entry.getValue())); return newRecords; } @Override @JsonbTransient public String getIdentifier() { return name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDateTime getCumulatedOn() { return cumulatedOn; } public void setCumulatedOn(LocalDateTime cumulatedOn) { this.cumulatedOn = cumulatedOn; } public Map<String, Record> getRecords() { return Collections.unmodifiableMap(records); } public void setRecords(Map<String, Record> records) { this.records = sort(records); } public void record(Scorecard... scorecards) { Arrays.stream(scorecards).forEach(scorecard -> { Record record = new Record(); record.setLevel(scorecard.getLevel()); record.setScore(scorecard.getTotal()); records.put(scorecard.getUsername(), record); }); records = sort(records); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Period period = (Period) o; return name.equals(period.name); } @Override public int hashCode() { return Objects.hash(name); } @Override public int compareTo(Period period) { Objects.requireNonNull(period, "Cannot compare with null value"); return -this.name.compareTo(period.name); } } <file_sep>/react/public/config/config.js // configuration is replaced by configmap in openshift window.USER_MANAGEMENT_API_URL="http://localhost:8080" <file_sep>/react/src/components/AccountPage.jsx import React from "react"; // import API from "../config/ServerUrls"; import { PageSection } from "@patternfly/react-core"; const AccountSection = props => { return ( <PageSection> <AccountPage {...props} /> </PageSection> ); }; export default AccountSection; // maybe use redux here for stage management? // create page/form to update account details export const AccountPage = props => { } <file_sep>/react/src/components/PaginationControls.jsx import React from "react"; import { Pagination, PaginationVariant } from "@patternfly/react-core"; /** * @author fostimus */ const PaginationControls = props => { const onSetPage = (_event, pageNumber) => { props.setPage(pageNumber); }; const onPerPageSelect = (_event, perPage) => { props.onPerPageSelect(perPage); }; const onNextClick = _event => { let index = props.page * props.perPage; props.changeDisplayedRows(props.perPage, index); props.setPage(props.page + 1); }; const onPreviousClick = _event => { let index = (props.page - 2) * props.perPage; props.changeDisplayedRows(props.perPage, index); props.setPage(props.page - 1); }; const onFirstClick = _event => { props.changeDisplayedRows(props.perPage, 0); props.setPage(1); }; const onLastClick = _event => { let amountOfRows = props.rows % props.perPage; let index = props.rows - amountOfRows; props.changeDisplayedRows(amountOfRows, index); }; return ( <Pagination itemCount={props.rows} widgetId="pagination-options-menu-bottom" perPage={props.perPage} page={props.page} variant={PaginationVariant.bottom} onSetPage={onSetPage} onPerPageSelect={onPerPageSelect} onNextClick={onNextClick} onPreviousClick={onPreviousClick} onFirstClick={onFirstClick} onLastClick={onLastClick} /> ); }; export default PaginationControls; <file_sep>/quarkus/user-service/src/test/java/com/redhat/services/ninja/mock/MockLdapService.java package com.redhat.services.ninja.mock; import com.redhat.services.ninja.service.LdapService; import com.redhat.services.ninja.user.RedHatUser; import io.quarkus.test.Mock; import javax.enterprise.context.ApplicationScoped; import java.util.List; import java.util.Map; @Mock @ApplicationScoped public class MockLdapService extends LdapService { @Override protected void init() { } @Override public List<RedHatUser> search(String key, String value) { if (key.equals("uid") && value.equals("new_ninja")) { RedHatUser user = RedHatUser.newMapper().apply(Map.of( "uid", "new_ninja", "employeeNumber", "new_ninja", "mail", "<EMAIL>", "mobile", "8888888888", "rhatLocation", "New York", "rhatJobTitle", "Consultant", "title", "Consultant", "rhatGeo", "EMEA", "rhatHireDate", "1/1/2020", "rhatJobCode", "14" ) ); return List.of(user); } else return List.of(); } }
d2dc403f6a27b03390643197355967cf0f9647a0
[ "Markdown", "JavaScript", "Maven POM", "INI", "Java", "Dockerfile" ]
41
Java
fostimus/ninja-board
bd312a4f8f81450f0c66ae2e41512f3a9d7a91c2
f424aa3431105b5c4d539d899935818f95e5bd72
refs/heads/master
<file_sep>from collections import defaultdict from collections import OrderedDict from collections import Counter import math import time import numpy as np import re from nltk.tokenize import TreebankWordTokenizer def split_by_person(msg_dict): msg_dict_by_person = defaultdict() for time in msg_dict: message = msg_dict[time] name = message[0] msg_type = message[1][0] if msg_type != "content": continue text = message[1][1] text = re.findall("[a-z]+", text.lower()) if name in msg_dict_by_person: msg_dict_by_person[name].append(text) else: msg_dict_by_person[name] = text return msg_dict_by_person def build_inverted_index(msg_dict_by_person): inverted_index = defaultdict() name_counter = 0 for name in msg_dict_by_person: names_messages = msg_dict_by_person[name] for message in names_messages: freqs = Counter(message) for word in freqs: if word not in inverted_index: inverted_index[word] = [0, 0] inverted_index[word][name_counter] += freqs[word] name_counter += 1 return inverted_index def create_word_ids(inv_idx): word_ids = defaultdict() words = sorted(inv_idx) counter = 0 for word in words: word_ids[word] = counter counter += 1 return word_ids def word_frequencies(word_ids, inv_idx): array = np.zeros(shape=(2, len(inv_idx))) for word in inv_idx: for person in range(2): array[person][word_ids[word]] = inv_idx[word][person] return array def create_weighted_word_freq_array(word_freqs): array_t = np.transpose(word_freqs) for i in range(len(array_t)): sum_col = np.sum(array_t[i]) + 1 for j in range(len(array_t[i])): word_freqs[j][i] = word_freqs[j][i]/sum_col return word_freqs def weighted_ranked_words(word_ids, weighted_words, name1, name2, num): names = [name1, name2] tops = {} for id in range(2): tops[names[id]] = [] top_fifty = sorted(weighted_words[id], reverse=True)[:num] top_fifty_indexes = [] count = 0 for freq in top_fifty: for elem in np.where(weighted_words[id]==freq)[0]: if elem not in top_fifty_indexes and count < num: top_fifty_indexes.append(elem) count += 1 tops[names[id]].append((freq, sorted(word_ids.keys())[elem])) return tops<file_sep>import json from collections import OrderedDict import matplotlib.pyplot as plt import datetime import time import numpy as np from dateutil.relativedelta import * import similarity name1 = "<NAME>" name2 = "<NAME>" with open('message.json', 'r') as fr: messages_dict = OrderedDict(json.load(fr)) messages = messages_dict["messages"] def build_msg_dict(messages): msg_dict ={} times_dict = {name1: [], name2: []} name1_count, name2_count = 0, 0 for message in messages: name = message["sender_name"] time = message["timestamp"] times_dict[name].append(time) if "photos" in message: msg_dict[time] = (name, ("photos", message["photos"])) elif "gifs" in message: msg_dict[time] = (name, ("gifs", message["gifs"])) elif "sticker" in message: msg_dict[time] = (name, ("sticker", message["sticker"])) elif "files" in message: msg_dict[time] = (name, ("files", message["files"])) elif "content" in message: msg_dict[time] = (name, ("content", message["content"])) elif "share" in message: msg_dict[time] = (name, ("share", message["share"])) elif "videos" in message: msg_dict[time] = (name, ("videos", message["videos"])) else: continue if name == name1: name1_count += 1 else: name2_count += 1 return name1_count, name2_count, times_dict, msg_dict def print_timestamp(timestamp): print(timestamp.strftime('%Y-%m-%d %H:%M:%S')) def add_day_to_name(name, times_dict, dates): for date_time in times_dict[name]: date = datetime.datetime.fromtimestamp(date_time).strftime('%Y-%m-%d') if date not in dates: dates[date] = 0 dates[date] += 1 def add_month_to_name(name, times_dict, months): for date_time in times_dict[name]: month = datetime.datetime.fromtimestamp(date_time).strftime('%Y-%m-01') if month not in months: months[month] = 0 months[month] += 1 def add_week_to_name(name, first_day, times_dict, weeks): for date_time in times_dict[name]: day = datetime.datetime.fromtimestamp(date_time) day_delta = (day - first_day).days week_num = (day_delta)/7 week = (first_day + relativedelta(weeks=+week_num)).strftime('%Y-%m-%d') if week not in weeks: weeks[week] = 0 weeks[week] += 1 def by_day(times_dict, name1, name2): dates1 = OrderedDict() dates2 = OrderedDict() add_day_to_name(name1, times_dict, dates1) add_day_to_name(name2, times_dict, dates2) return dates1, dates2 def by_month(times_dict, name1, name2): dates1 = OrderedDict() dates2 = OrderedDict() add_month_to_name(name1, times_dict, dates1) add_month_to_name(name2, times_dict, dates2) return dates1, dates2 def by_week (times_dict, first_day, name1, name2): dates1 = OrderedDict() dates2 = OrderedDict() add_week_to_name(name1, first_day, times_dict, dates1) add_week_to_name(name2, first_day, times_dict, dates2) return dates1, dates2 def plot_by_day (times_dict): dates1, dates2 = by_day(times_dict, name1, name2) maxx = datetime.datetime(*(time.strptime(max(max(dates1), max(dates2)), '%Y-%m-%d')[:3])) minn = datetime.datetime(*(time.strptime(min(min(dates1), min(dates2)), '%Y-%m-%d')[:3])) time_elapsed = (maxx-minn).days dates_list =[] for i in range(time_elapsed + 1): dates_list.append((minn + datetime.timedelta(days=i)).strftime('%Y-%m-%d')) person1_data = [] person2_data = [] for i in dates_list: if i in dates1: person1_data.append(dates1[i]) else: person1_data.append(0) for i in dates_list: if i in dates2: person2_data.append(dates2[i]) else: person2_data.append(0) plot_by_time(person1_data, person2_data, dates_list, "Day", 2) def plot_by_month (times_dict): dates1, dates2 = by_month(times_dict, name1, name2) maxx = datetime.datetime(*(time.strptime(max(max(dates1), max(dates2)), '%Y-%m-01')[:3])) minn = datetime.datetime(*(time.strptime(min(min(dates1), min(dates2)), '%Y-%m-01')[:3])) time_elapsed = (maxx.year - minn.year) * 12 + (maxx.month - minn.month) + 1 dates_list =[] for i in range(time_elapsed): dates_list.append((minn + relativedelta(months=+i)).strftime('%Y-%m')) person1_data = [] person2_data = [] for i in dates_list: temp_date = (i+"-01") if temp_date in dates1: person1_data.append(dates1[temp_date]) else: person1_data.append(0) for i in dates_list: temp_date = (i+"-01") if temp_date in dates2: person2_data.append(dates2[temp_date]) else: person2_data.append(0) plot_by_time(person1_data, person2_data, dates_list, "Month", 4) def plot_by_week (times_dict): first_week = datetime.datetime.fromtimestamp(min(min(times_dict[name1]), min(times_dict[name2]))) dates1, dates2 = by_week(times_dict, first_week, name1, name2) last_week = max(max(dates1), max(dates2)) last_week = datetime.datetime.strptime(last_week, '%Y-%m-%d') time_elapsed = (((last_week - first_week).days)/7) + 1 dates_list = [] for i in range(time_elapsed+1): dates_list.append((first_week + relativedelta(weeks=+i)).strftime('%Y-%m-%d')) person1_data = [] person2_data = [] for i in dates_list: if i in dates1: person1_data.append(dates1[i]) else: person1_data.append(0) for i in dates_list: if i in dates2: person2_data.append(dates2[i]) else: person2_data.append(0) plot_by_time(person1_data, person2_data, dates_list, "Week", 3) def plot_piechart(name1_count, name2_count, total_count): piechart = plt.subplot(2, 2, 1) labels = name1 + ": " + str(name1_count), name2 + ": " + str(name2_count) sizes = [float(name1_count)/total_count, float(name2_count)/total_count] piechart.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90) piechart.axis('equal') plt.title('Message Distribution') def plot_by_time (person1_data, person2_data, dates_list, period, num): ind = np.arange(len(dates_list)) width = 0.35 p1 = plt.subplot(2, 2, num) p2 = plt.subplot(2, 2, num) p1 = plt.bar(ind, person1_data, color='royalblue') p2 = plt.bar(ind, person2_data, bottom=person1_data, color='seagreen') plt.xticks(ind) plt.xticks(ind, dates_list, rotation=90) plt.legend((p1[0], p2[0]), (name1, name2)) plt.title('Message Distribution by ' + period) def plot(name1_count, name2_count, total_count, time_dict): plot_piechart(name1_count, name2_count, total_count) plot_by_day(time_dict) plot_by_week(time_dict) plot_by_month(time_dict) plt.show() def plot_avg_msg_length(name1_count, name2_count, msg_dict): name1_dict = { "content": 0, "photos": 0, "gifs": 0, "sticker": 0, "files": 0, "share": 0, "videos": 0, } name2_dict = { "content": 0, "photos": 0, "gifs": 0, "sticker": 0, "files": 0, "share": 0, "videos": 0, } for time in msg_dict: message = msg_dict[time] name = message[0] if name == name1: curr_dict = name1_dict else: curr_dict = name2_dict msg_type = message[1][0] if msg_type == "content": msg_length = len(message[1][1]) else: msg_length = 1 curr_dict[msg_type] += msg_length name1_dict["content"] /= name1_count name2_dict["content"] /= name2_count name1_list = sorted(name1_dict.values()) name2_list = sorted(name2_dict.values()) total_count = name1_count + name2_count messages = plt.subplot(2, 2, 1) plt.title("Average Message Length") messages = plt.bar([0,1], [name1_dict["content"], name2_dict["content"]], tick_label=[name1,name2], color='blue') photos = plt.subplot(2, 2, 2) amt1, amt2 = name1_dict["photos"], name2_dict["photos"] labels = str(amt1), str(amt2) photos.pie([amt1/float(amt1+amt2), amt2/float(amt1+amt2)], labels=labels) photos.axis('equal') photos.set_title("Photo Count") gifs = plt.subplot(2, 2, 3) amt1, amt2 = name1_dict["gifs"], name2_dict["gifs"] labels = str(amt1), str(amt2) gifs.pie([amt1/float(amt1+amt2), amt2/float(amt1+amt2)], labels=labels) gifs.axis('equal') gifs.set_title("Gif Count") sticker = plt.subplot(2, 2, 4) amt1, amt2 = name1_dict["sticker"], name2_dict["sticker"] labels = str(amt1), str(amt2) sticker.pie([amt1/float(amt1+amt2), amt2/float(amt1+amt2)], labels=labels) sticker.axis('equal') sticker.set_title("Sticker Count") plt.legend([name1, name2]) print(name1_dict) print(name2_dict) plt.show() def top_words_dict(msg_dict, num): msg_dict_by_person = similarity.split_by_person(msg_dict) inv_idx = similarity.build_inverted_index(msg_dict_by_person) word_ids = similarity.create_word_ids(inv_idx) word_freqs = similarity.word_frequencies(word_ids, inv_idx) weighted_words = similarity.create_weighted_word_freq_array(word_freqs) weighted_top = similarity.weighted_ranked_words(word_ids, weighted_words, name1, name2, num) return weighted_top def plot_top_words(top_words, name1, name2): scores = {} words = {} for name in top_words: scores[name] = [] words[name] = [] for result in top_words[name]: scores[name].append(result[0]) words[name].append(result[1]) ind = np.arange(len(top_words[name1])) ind2 = np.arange(len(top_words[name2])) p1 = plt.subplot(2, 1, 1) plt.title('Most Frequent Words - ' + name1) p1 = plt.bar(ind2, scores[name1], tick_label=words[name1], color='blue') plt.xticks(rotation=75) p2 = plt.subplot(2, 1, 2) plt.title('Most Frequent Words - ' + name2) p2 = plt.bar(ind, scores[name2], tick_label=words[name2], color='orange') plt.xticks(rotation=75) plt.show() def main(): name1_count, name2_count, times_dict, msg_dict = build_msg_dict(messages) total_count = name1_count+name2_count #plot(name1_count, name2_count, total_count, times_dict) #plot_avg_msg_length(name1_count, name2_count, msg_dict) top_words = top_words_dict(msg_dict, 25) plot_top_words(top_words, name1, name2) main()
5b7316613b4e4046d7a077ed47249de7f4d53c8b
[ "Python" ]
2
Python
jorstern/FbData
8df29f81d4481b6d473d0fe347f33ae0d656e33b
628de184cb93cbccc504b2f229161371bb3d279c
refs/heads/master
<file_sep>package com.trafiklab.bus.lines.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"StatusCode", "Message", "ExecutionTime", "ResponseData"}) public class BaseModel<T> { @JsonProperty("StatusCode") private int statusCode; @JsonProperty("Message") private Object message; @JsonProperty("ExecutionTime") private int executionTime; @JsonProperty("ResponseData") private ResponseData<T> responseData; @JsonProperty("StatusCode") public int getStatusCode() { return statusCode; } @JsonProperty("StatusCode") public void setStatusCode(int statusCode) { this.statusCode = statusCode; } @JsonProperty("Message") public Object getMessage() { return message; } @JsonProperty("Message") public void setMessage(Object message) { this.message = message; } @JsonProperty("ExecutionTime") public int getExecutionTime() { return executionTime; } @JsonProperty("ExecutionTime") public void setExecutionTime(int executionTime) { this.executionTime = executionTime; } @JsonProperty("ResponseData") public ResponseData<T> getResponseData() { return responseData; } @JsonProperty("ResponseData") public void setResponseData(ResponseData<T> responseData) { this.responseData = responseData; } }<file_sep>package com.trafiklab.bus.lines.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "LineNumber", "LineDesignation", "DefaultTransportMode", "DefaultTransportModeCode", "LastModifiedUtcDateTime", "ExistsFromDate" }) public class Line { @JsonProperty("LineNumber") private int lineNumber; @JsonProperty("LineDesignation") private String lineDesignation; @JsonProperty("DefaultTransportMode") private String defaultTransportMode; @JsonProperty("DefaultTransportModeCode") private String defaultTransportModeCode; @JsonProperty("LastModifiedUtcDateTime") private String lastModifiedUtcDateTime; @JsonProperty("ExistsFromDate") private String existsFromDate; @JsonProperty("LineNumber") public int getLineNumber() { return lineNumber; } @JsonProperty("LineNumber") public Line setLineNumber(int lineNumber) { this.lineNumber = lineNumber; return this; } @JsonProperty("LineDesignation") public String getLineDesignation() { return lineDesignation; } @JsonProperty("LineDesignation") public Line setLineDesignation(String lineDesignation) { this.lineDesignation = lineDesignation; return this; } @JsonProperty("DefaultTransportMode") public String getDefaultTransportMode() { return defaultTransportMode; } @JsonProperty("DefaultTransportMode") public void setDefaultTransportMode(String defaultTransportMode) { this.defaultTransportMode = defaultTransportMode; } @JsonProperty("DefaultTransportModeCode") public String getDefaultTransportModeCode() { return defaultTransportModeCode; } @JsonProperty("DefaultTransportModeCode") public void setDefaultTransportModeCode(String defaultTransportModeCode) { this.defaultTransportModeCode = defaultTransportModeCode; } @JsonProperty("LastModifiedUtcDateTime") public String getLastModifiedUtcDateTime() { return lastModifiedUtcDateTime; } @JsonProperty("LastModifiedUtcDateTime") public void setLastModifiedUtcDateTime(String lastModifiedUtcDateTime) { this.lastModifiedUtcDateTime = lastModifiedUtcDateTime; } @JsonProperty("ExistsFromDate") public String getExistsFromDate() { return existsFromDate; } @JsonProperty("ExistsFromDate") public void setExistsFromDate(String existsFromDate) { this.existsFromDate = existsFromDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Line line = (Line) o; return new EqualsBuilder() .append(lineNumber, line.lineNumber) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(lineNumber) .toHashCode(); } } <file_sep>connection.timeout.millis=5000 server.port=8090 api.key=cf3a198204d0459ba9ae3389fa628696 api.url=https://api.sl.se/api2/linedata.json?key=${api.key} journey.patterns.url=${api.url}&model=jour&DefaultTransportModeCode=BUS line.url=${api.url}&model=line&DefaultTransportModeCode=BUS stop.points.url=${api.url}&model=stop<file_sep>package com.trafiklab.bus.lines.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.List; import static java.util.Collections.EMPTY_LIST; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"Version", "Type", "Result"}) public class ResponseData<T> { @JsonProperty("Version") private String version; @JsonProperty("Type") private String type; @JsonProperty("Result") private List<T> result = EMPTY_LIST; @JsonProperty("Version") public String getVersion() { return version; } @JsonProperty("Version") public void setVersion(String version) { this.version = version; } @JsonProperty("Type") public String getType() { return type; } @JsonProperty("Type") public void setType(String type) { this.type = type; } @JsonProperty("Result") public List<T> getResult() { return result; } @JsonProperty("Result") public void setResult(List<T> result) { this.result = result; } }<file_sep>package com.trafiklab.bus.lines.controller; import com.trafiklab.bus.lines.service.BusLinesService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.util.NestedServletException; import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(MockitoExtension.class) class BusLinesControllerTest { @Mock private BusLinesService busLinesService; @InjectMocks private BusLinesController busLinesController; private MockMvc mockMvc; @BeforeEach void setUp() { mockMvc = MockMvcBuilders .standaloneSetup(busLinesController) .build(); } @Test void findLinesWithMostStops() throws Exception { when(busLinesService.findLinesWithMostStops(anyInt())).thenReturn(Collections.emptyList()); mockMvc.perform(get("/bus-lines/top-10-lines")) .andExpect(status().isOk()); verify(busLinesService).findLinesWithMostStops(10); } @Test void findStopsOnLine() throws Exception { when(busLinesService.findStopsOnLine(anyInt())).thenReturn(Collections.emptyList()); mockMvc.perform(get("/bus-lines/stops-on-line/1")) .andExpect(status().isOk()); verify(busLinesService).findStopsOnLine(1); } @Test void findStopsOnLine_invalidLineNumber() { Exception exception = assertThrows(NestedServletException.class, () -> mockMvc.perform(get("/bus-lines/stops-on-line/-235"))); assertThat("exception message: ", exception.getMessage(), containsString("line number should be a positive integer")); verify(busLinesService, never()).findStopsOnLine(-235); } }<file_sep># bus-lines-api An API hosting a couple of endpoints using data from Trafiklab’s open API (https://www.trafiklab.se). The API offers the following features: - Return the details of top 10 bus lines in Stockholm area with most bus stops on their route. - Return a list of every bus stop of the bus line provided. ## Key Technologies Used - Java 11 - Spring Boot - embedded tomcat - cache - scheduler - rest template - webflux (for integration tests) - Junit 5 - Mockito - slf4j - Maven - commons-lang3 ## Instructions to run the application - Download the source code from [[https://github.com/Chaithu-Narayana/bus-lines-api](https://github.com/Chaithu-Narayana/bus-lines-api)]. - Open the project using a Java IDE of your choice (IntelliJ or Eclipse). - Locate a file called '***BusLinesApplication***', right-click and run as a java application. - Since it is a spring boot application, no additional build steps are needed. The application listens on port '***8090***' once it is started successfully. ## API Responses The API responds with two formats based on the status returned. - Success response with a 200 http response code to the client - format as shown below > { > "status":"Success", // A string representing the status of the operation > "timestamp":"2020-01-18T18:45:00", //A date-time without a time-zone in the ISO-8601 calendar system > "data":[ > { > /* resultant data from endpoints */ > } > ] > } - Failure response with corresponding http status code to the client - format as shown below > { > "status":"Failure", // A string representing the status of the operation > "timestamp":"2020-01-18T18:45:00", //A date-time without a time-zone in the ISO-8601 calendar system > "errorMessage": "No bus line exists for number: 456" // A short description of the error encountered > } ## API Endpoints The API exposes two endpoints for use. They shall be invoked as follows. - ***Top 10 bus lines*** Use the below URL on a web browser or rest client - [http://localhost:8090/bus-lines/top-10-lines](http://localhost:8090/bus-lines/top-10-lines) If successful, the endpoint responds back with a sample response as below. { "status":"Success", "timestamp":"2020-01-18T18:45:00", "data":[ { "LineNumber":636, "LineDesignation":"636", "DefaultTransportMode":"", "DefaultTransportModeCode":"BUS", "LastModifiedUtcDateTime":"2007-08-24 00:00:00.000", "ExistsFromDate":"2007-08-24 00:00:00.000" }, { "LineNumber":626, "LineDesignation":"626", "DefaultTransportMode":"", "DefaultTransportModeCode":"BUS", "LastModifiedUtcDateTime":"2007-08-24 00:00:00.000", "ExistsFromDate":"2007-08-24 00:00:00.000" }, /** more bus lines data **/ ] } - ***Stops on a given bus line*** Use the below URL on a web browser or rest client - [http://localhost:8090/bus-lines/stops-on-line/{line-number}](http://localhost:8090/bus-lines/stops-on-line/{line-number}); where *line-number* is a ***positive integer*** representing the bus line (eg. 173) If successful, the endpoint responds back with a sample response as below. { "status":"Success", "timestamp":"2020-01-18T20:13:07", "data":[ { "StopPointNumber":13037, "StopPointName":"Bandhagen", "StopAreaNumber":13037, "LocationNorthingCoordinate":"59.2708250331152", "LocationEastingCoordinate":"18.0476716961957", "ZoneShortName":"A", "StopAreaTypeCode":"BUSTERM", "LastModifiedUtcDateTime":"2014-06-03 00:00:00.000", "ExistsFromDate":"2014-06-03 00:00:00.000" }, { "StopPointNumber":13055, "StopPointName":"Kämpetorpsskolan", "StopAreaNumber":13055, "LocationNorthingCoordinate":"59.2842499709449", "LocationEastingCoordinate":"17.9937633253391", "ZoneShortName":"A", "StopAreaTypeCode":"BUSTERM", "LastModifiedUtcDateTime":"2014-06-03 00:00:00.000", "ExistsFromDate":"2014-06-03 00:00:00.000" }, /** more bus stop points data **/ ] } ## Assumptions/Considerations - Trafiklab refreshes it's data between 00:00 and 2:00 hours, otherwise the data remains static for the rest of the day. So, this API caches that data and refreshes it everyday at 3 am. - UTF-8 encoding has been used and is recommended for use of this API - 'Direction Code' has not been considered in any of these endpoints as they anyways don't effect the outcome in both these cases. - API management aspects (securing access - authentication/authorization/api-key-protection) are not included in this assignment. <file_sep>package com.trafiklab.bus.lines; import com.fasterxml.jackson.databind.ObjectMapper; import com.trafiklab.bus.lines.service.CacheRefresher; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.client.ExpectedCount; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class BusLinesApplicationIntegrationTest { @Autowired private RestTemplate restTemplate; @Autowired private WebTestClient webClient; @Autowired private CacheRefresher cacheRefresher; @org.springframework.beans.factory.annotation.Value("${journey.patterns.url:URL_NOT_SET}") private String journeyPatternsEndPointUrl; @org.springframework.beans.factory.annotation.Value("${line.url:URL_NOT_SET}") private String lineEndPointUrl; @org.springframework.beans.factory.annotation.Value("${stop.points.url:URL_NOT_SET}") private String stopPointsEndPointUrl; private MockRestServiceServer mockServer; private ObjectMapper mapper = new ObjectMapper(); @BeforeEach void setUp() { mockServer = MockRestServiceServer.createServer(restTemplate); } @AfterEach void tearDown() { cacheRefresher.refreshAllCaches(); } @Test void findLinesWithMostStops() throws URISyntaxException, IOException { mockServer.expect(ExpectedCount.once(), requestTo(new URI(journeyPatternsEndPointUrl))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(Files.readString(Paths.get("src/test/resources/bus-jour-sample.json"), StandardCharsets.UTF_8)) ); mockServer.expect(ExpectedCount.once(), requestTo(new URI(lineEndPointUrl))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(Files.readString(Paths.get("src/test/resources/bus-line-sample.json"), StandardCharsets.UTF_8)) ); this.webClient.get().uri("/bus-lines/top-10-lines") .exchange() .expectStatus().isOk() .expectHeader().valueEquals("Content-Type", "application/json") .expectBody() .jsonPath("$.status").isEqualTo("Success") .jsonPath("$.resultData").isNotEmpty(); mockServer.verify(); } @Test void findStopsOnLine() throws URISyntaxException, IOException { mockServer.expect(ExpectedCount.once(), requestTo(new URI(journeyPatternsEndPointUrl))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(Files.readString(Paths.get("src/test/resources/bus-jour-sample.json"), StandardCharsets.UTF_8)) ); mockServer.expect(ExpectedCount.once(), requestTo(new URI(stopPointsEndPointUrl))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(Files.readString(Paths.get("src/test/resources/bus-stop-sample.json"), StandardCharsets.UTF_8)) ); this.webClient.get().uri("/bus-lines/stops-on-line/1") .exchange() .expectStatus().isOk() .expectHeader().valueEquals("Content-Type", "application/json") .expectBody() .jsonPath("$.status").isEqualTo("Success") .jsonPath("$.resultData").isNotEmpty(); mockServer.verify(); } @Test void findLinesWithMostStops_serverUnavailable() throws URISyntaxException { mockServer.expect(ExpectedCount.once(), requestTo(new URI(journeyPatternsEndPointUrl))) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.SERVICE_UNAVAILABLE)); this.webClient.get().uri("/bus-lines/top-10-lines") .exchange() .expectStatus().is5xxServerError() .expectHeader().valueEquals("Content-Type", "application/json") .expectBody().jsonPath("$.status").isEqualTo("Failure") .jsonPath("$.errorMessage").isNotEmpty(); mockServer.verify(); } } <file_sep>package com.trafiklab.bus.lines.service; import com.trafiklab.bus.lines.exception.BusLineNotFoundException; import com.trafiklab.bus.lines.model.JourneyPatternPointOnLine; import com.trafiklab.bus.lines.model.Line; import com.trafiklab.bus.lines.model.StopPoint; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.AbstractMap; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class BusLinesServiceImplTest { @Mock TrafiklabHelper trafiklabHelper; @InjectMocks BusLinesServiceImpl busLinesService; @BeforeEach void setUp() { when(trafiklabHelper.findJourneyPatternsByLine()).thenReturn(journeyPatternsByLine()); } @Test @DisplayName("linesWithMostStops") void findLinesWithMostStops() { when(trafiklabHelper.findAllBusLines()).thenReturn(allBusLines()); List<Line> lineWithMostStops = busLinesService.findLinesWithMostStops(1); assertThat("lines with max stops: ", lineWithMostStops, hasSize(1)); assertThat("line number with max stops: ", lineWithMostStops.get(0), hasProperty("lineNumber", is(2))); } @Test @DisplayName("stopsOnGivenLine") void findStopsOnLine() { when(trafiklabHelper.findAllBusStopPoints()).thenReturn(allBusStopPoints()); List<StopPoint> stopsOnLine = busLinesService.findStopsOnLine(1); assertThat("stops on given line: ", stopsOnLine, hasSize(3)); assertThat("stop name on given line: ", stopsOnLine.get(0), hasProperty("stopPointName", is("Arbetargatan"))); } @Test @DisplayName("stopsOnGivenLine - line doesn't exist") void findStopsOnLine_nonExistentLineNumber() { String expectedMessage = "No bus line exists for number: 3"; BusLineNotFoundException exception = assertThrows(BusLineNotFoundException.class, () -> busLinesService.findStopsOnLine(3)); assertThat("error message: ", exception.getMessage(), is(expectedMessage)); } private Map<Integer, List<JourneyPatternPointOnLine>> journeyPatternsByLine() { List<JourneyPatternPointOnLine> journeyPatternPointsForLineOne = List.of( createJourneyPatternPoint(1, 10006), createJourneyPatternPoint(1, 10012), createJourneyPatternPoint(1, 10018)); List<JourneyPatternPointOnLine> journeyPatternPointsForLineTwo = List.of( createJourneyPatternPoint(2, 10005), createJourneyPatternPoint(2, 10010), createJourneyPatternPoint(2, 10015), createJourneyPatternPoint(2, 10020)); return Map.ofEntries( new AbstractMap.SimpleEntry<>(1, journeyPatternPointsForLineOne), new AbstractMap.SimpleEntry<>(2, journeyPatternPointsForLineTwo) ); } private JourneyPatternPointOnLine createJourneyPatternPoint(int lineNumber, int stopPointNumber) { return new JourneyPatternPointOnLine() .setLineNumber(lineNumber) .setDirectionCode("1") .setJourneyPatternPointNumber(stopPointNumber); } private List<Line> allBusLines() { return List.of(createLine(1), createLine(2)); } private Line createLine(int lineNumber) { return new Line() .setLineNumber(lineNumber) .setLineDesignation(String.valueOf(lineNumber)); } private List<StopPoint> allBusStopPoints() { return List.of( createStopPoint(10006, "Arbetargatan"), createStopPoint(10012, "Frihamnsporten"), createStopPoint(10018, "Stadshagsplan")); } private StopPoint createStopPoint(int number, String name) { return new StopPoint() .setStopPointNumber(number) .setStopPointName(name); } }<file_sep>package com.trafiklab.bus.lines.service; import com.trafiklab.bus.lines.model.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.util.List; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class TrafiklabHelperTest { @Mock private RestTemplate restTemplate; @InjectMocks private TrafiklabHelper trafiklabHelper; @Test void findJourneyPatternsByLine() { String journeyPatternsUrl = "https://www.dummy.com/journey-patterns&mode=bus"; trafiklabHelper.setJourneyPatternsEndPointUrl(journeyPatternsUrl); JourneyPatternPointOnLine journeyPatternPointOne = createJourneyPatternPoint(1, 10006); JourneyPatternPointOnLine journeyPatternPointTwo = createJourneyPatternPoint(2, 10012); BaseModel<JourneyPatternPointOnLine> journeyPatternPointOnLineBaseModel = createBaseModelContaining(journeyPatternPointOne, journeyPatternPointTwo); when(restTemplate.exchange(eq(journeyPatternsUrl), eq(HttpMethod.GET), any(HttpEntity.class), eq(new ParameterizedTypeReference<BaseModel<JourneyPatternPointOnLine>>() { }))).thenReturn(new ResponseEntity<>(journeyPatternPointOnLineBaseModel, HttpStatus.OK)); Map<Integer, List<JourneyPatternPointOnLine>> journeyPatternsByLine = trafiklabHelper.findJourneyPatternsByLine(); assertThat("journeyPatternsByLine: ", journeyPatternsByLine, hasEntry(1, List.of(journeyPatternPointOne))); assertThat("journeyPatternsByLine: ", journeyPatternsByLine, hasEntry(2, List.of(journeyPatternPointTwo))); verify(restTemplate).exchange(eq(journeyPatternsUrl), eq(HttpMethod.GET), any(HttpEntity.class), eq(new ParameterizedTypeReference<BaseModel<JourneyPatternPointOnLine>>() { })); } @Test void findAllBusLines() { String linesUrl = "https://www.dummy.com/lines&mode=bus"; trafiklabHelper.setLineEndPointUrl(linesUrl); Line lineOne = createLine(1); Line lineTwo = createLine(2); BaseModel<Line> linesBaseModel = createBaseModelContaining(lineOne, lineTwo); when(restTemplate.exchange(eq(linesUrl), eq(HttpMethod.GET), any(HttpEntity.class), eq(new ParameterizedTypeReference<BaseModel<Line>>() { }))).thenReturn(new ResponseEntity<>(linesBaseModel, HttpStatus.OK)); List<Line> allBusLines = trafiklabHelper.findAllBusLines(); assertThat("allBusLines: ", allBusLines, hasSize(2)); assertThat("allBusLines: ", allBusLines, hasItems(lineOne, lineTwo)); verify(restTemplate).exchange(eq(linesUrl), eq(HttpMethod.GET), any(HttpEntity.class), eq(new ParameterizedTypeReference<BaseModel<Line>>() { })); } @Test void findAllBusStopPoints() { String stopPointsUrl = "https://www.dummy.com/stop-points"; trafiklabHelper.setStopPointsEndPointUrl(stopPointsUrl); StopPoint stopPointOne = createStopPoint(10006, "Arbetargatan", "BUSTERM"); StopPoint stopPointTwo = createStopPoint(10012, "Frihamnsporten", "METROSTN"); StopPoint stopPointThree = createStopPoint(10024, "Stadshagsplan", "BUSTERM"); BaseModel<StopPoint> stopPointsBaseModel = createBaseModelContaining(stopPointOne, stopPointTwo, stopPointThree); when(restTemplate.exchange(eq(stopPointsUrl), eq(HttpMethod.GET), any(HttpEntity.class), eq(new ParameterizedTypeReference<BaseModel<StopPoint>>() { }))).thenReturn(new ResponseEntity<>(stopPointsBaseModel, HttpStatus.OK)); List<StopPoint> allBusStopPoints = trafiklabHelper.findAllBusStopPoints(); assertThat("allBusStopPoints: ", allBusStopPoints, hasSize(2)); assertThat("allBusStopPoints: ", allBusStopPoints, hasItems(stopPointOne, stopPointThree)); verify(restTemplate).exchange(eq(stopPointsUrl), eq(HttpMethod.GET), any(HttpEntity.class), eq(new ParameterizedTypeReference<BaseModel<StopPoint>>() { })); } @SafeVarargs private <T> BaseModel<T> createBaseModelContaining(T... results) { BaseModel<T> lineBaseModel = new BaseModel<>(); ResponseData<T> responseData = new ResponseData<>(); responseData.setResult(List.of(results)); lineBaseModel.setResponseData(responseData); return lineBaseModel; } private JourneyPatternPointOnLine createJourneyPatternPoint(int lineNumber, int stopPointNumber) { return new JourneyPatternPointOnLine() .setLineNumber(lineNumber) .setDirectionCode("1") .setJourneyPatternPointNumber(stopPointNumber); } private Line createLine(int lineNumber) { return new Line() .setLineNumber(lineNumber) .setLineDesignation(String.valueOf(lineNumber)); } private StopPoint createStopPoint(int number, String name, String usage) { return new StopPoint() .setStopPointNumber(number) .setStopPointName(name) .setStopAreaTypeCode(usage); } } <file_sep>package com.trafiklab.bus.lines.controller.advice; import com.trafiklab.bus.lines.exception.BusLineNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.time.LocalDateTime; @RestControllerAdvice public class BusLinesExceptionHandler extends ResponseEntityExceptionHandler { private final Logger logger = LoggerFactory.getLogger(getClass()); @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public final BusLinesErrorResponse handleBadRequests(IllegalArgumentException ex) { return errorResponse("Invalid client request: ", ex); } @ExceptionHandler(BusLineNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public final BusLinesErrorResponse handleBusLineNotFoundException(BusLineNotFoundException ex) { return errorResponse("Bus line doesn't exist: ", ex); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public final BusLinesErrorResponse handleAllExceptions(Exception ex) { return errorResponse("An unexpected error occurred: ", ex); } private BusLinesErrorResponse errorResponse(String errorMessage, Exception ex) { logger.error(errorMessage, ex); return new BusLinesErrorResponse(ex.getMessage()); } static class BusLinesErrorResponse { private String status = "Failure"; private LocalDateTime timestamp = LocalDateTime.now().withNano(0); private String errorMessage; public BusLinesErrorResponse(String errorMessage) { this.errorMessage = errorMessage; } public String getStatus() { return status; } public LocalDateTime getTimestamp() { return timestamp; } public String getErrorMessage() { return errorMessage; } } } <file_sep>package com.trafiklab.bus.lines.config; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.client.RestTemplate; @Configuration @EnableCaching @EnableScheduling public class BusLinesApplicationConfig { @Value("${connection.timeout.millis:5000}") private int timeoutInMillis; @Bean public RestTemplate restTemplate() { return new RestTemplate(clientHttpRequestFactory()); } @Bean public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() { HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeoutInMillis) .setConnectionRequestTimeout(timeoutInMillis) .setSocketTimeout(timeoutInMillis) .build(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(config) .build(); clientHttpRequestFactory.setHttpClient(httpClient); return clientHttpRequestFactory; } } <file_sep>package com.trafiklab.bus.lines.service; import com.trafiklab.bus.lines.exception.BusLineNotFoundException; import com.trafiklab.bus.lines.model.JourneyPatternPointOnLine; import com.trafiklab.bus.lines.model.Line; import com.trafiklab.bus.lines.model.StopPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * Service component that services requests from the controller. */ @Service public class BusLinesServiceImpl implements BusLinesService { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Comparator<Map.Entry<Integer, List<JourneyPatternPointOnLine>>> byNumberOfStoppingPoints = Map.Entry.comparingByValue(Comparator.comparingInt(List::size)); private final TrafiklabHelper trafiklabHelper; @Autowired public BusLinesServiceImpl(TrafiklabHelper trafiklabHelper) { this.trafiklabHelper = trafiklabHelper; } /** * The results from this method may be cached as it always returns static data. * * {@inheritDoc} * {@link BusLinesService#findLinesWithMostStops(int)} */ @Override public List<Line> findLinesWithMostStops(int numberOfBusLines) { logger.info("Finding out the top " + numberOfBusLines + " lines with most number of stops."); return trafiklabHelper.findJourneyPatternsByLine() .entrySet() .stream() .sorted(byNumberOfStoppingPoints.reversed()) .limit(numberOfBusLines) .map(Map.Entry::getKey) .map(this::getLineDetailsFor) .collect(Collectors.toList()); } /** * {@inheritDoc} * {@link BusLinesService#findStopsOnLine(int)} */ @Override public List<StopPoint> findStopsOnLine(int lineNumber) { logger.info("Finding out stops on line: " + lineNumber); Map<Integer, List<JourneyPatternPointOnLine>> journeyPatternsByLine = trafiklabHelper.findJourneyPatternsByLine(); List<JourneyPatternPointOnLine> journeyPatternsOnRequestedLine = Optional.ofNullable(journeyPatternsByLine.get(lineNumber)) .orElseThrow(() -> new BusLineNotFoundException("No bus line exists for number: " + lineNumber)); return journeyPatternsOnRequestedLine.stream() .map(JourneyPatternPointOnLine::getJourneyPatternPointNumber) .map(this::getStopPointDetailsFor) .collect(Collectors.toList()); } private Line getLineDetailsFor(int lineNumber) { return trafiklabHelper.findAllBusLines() .stream() .filter(line -> line.getLineNumber() == lineNumber) .findFirst() .orElse(null); } private StopPoint getStopPointDetailsFor(int pointNumber) { return trafiklabHelper.findAllBusStopPoints() .stream() .filter(stopPoint -> stopPoint.getStopPointNumber() == pointNumber) .findFirst() .orElseThrow(() -> new IllegalStateException("No stop point details could be found for point number: " + pointNumber)); } } <file_sep>package com.trafiklab.bus.lines.service; import com.trafiklab.bus.lines.model.BaseModel; import com.trafiklab.bus.lines.model.JourneyPatternPointOnLine; import com.trafiklab.bus.lines.model.Line; import com.trafiklab.bus.lines.model.StopPoint; 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.cache.annotation.Cacheable; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Component that interacts with Trafiklab Api and packages the response for use in the application */ @Component public class TrafiklabHelper { private final Logger logger = LoggerFactory.getLogger(getClass()); private final RestTemplate restTemplate; @Value("${journey.patterns.url:URL_NOT_SET}") private String journeyPatternsEndPointUrl; @Value("${line.url:URL_NOT_SET}") private String lineEndPointUrl; @Value("${stop.points.url:URL_NOT_SET}") private String stopPointsEndPointUrl; @Autowired public TrafiklabHelper(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @PostConstruct @Cacheable("allJourneyPatternsForBuses") public Map<Integer, List<JourneyPatternPointOnLine>> findJourneyPatternsByLine() { List<JourneyPatternPointOnLine> allJourneyPatternsForBuses = findAllJourneyPatternsForBuses(); return allJourneyPatternsForBuses.parallelStream() .collect(Collectors.groupingBy(JourneyPatternPointOnLine::getLineNumber)); } @PostConstruct @Cacheable("allBusLines") public List<Line> findAllBusLines() { BaseModel<Line> apiResponse = invokeTrafiklabApiForBusLines(); return apiResponse.getResponseData().getResult(); } @PostConstruct @Cacheable("allBusStopPoints") public List<StopPoint> findAllBusStopPoints() { BaseModel<StopPoint> apiResponse = invokeTrafiklabApiForBusStops(); return apiResponse.getResponseData().getResult() .stream() .filter(stopPoint -> "BUSTERM".equalsIgnoreCase(stopPoint.getStopAreaTypeCode())) // filter bus stops .collect(Collectors.toList()); } private List<JourneyPatternPointOnLine> findAllJourneyPatternsForBuses() { BaseModel<JourneyPatternPointOnLine> apiResponse = invokeTrafiklabApiForJourneyPatterns(); return apiResponse.getResponseData().getResult(); } private BaseModel<JourneyPatternPointOnLine> invokeTrafiklabApiForJourneyPatterns() { logger.info("Contacting trafiklab api for 'jour' models.."); ResponseEntity<BaseModel<JourneyPatternPointOnLine>> journeyPatternsResponse = restTemplate.exchange(journeyPatternsEndPointUrl, HttpMethod.GET, requestEntityWithCompressionHeaders(), new ParameterizedTypeReference<>() { }); return journeyPatternsResponse.getBody(); } private BaseModel<Line> invokeTrafiklabApiForBusLines() { logger.info("Contacting trafiklab api for 'line' models.."); ResponseEntity<BaseModel<Line>> lineResponse = restTemplate.exchange(lineEndPointUrl, HttpMethod.GET, requestEntityWithCompressionHeaders(), new ParameterizedTypeReference<>() { }); return lineResponse.getBody(); } private BaseModel<StopPoint> invokeTrafiklabApiForBusStops() { logger.info("Contacting trafiklab api for 'stop' models.."); ResponseEntity<BaseModel<StopPoint>> stopPointsResponse = restTemplate.exchange(stopPointsEndPointUrl, HttpMethod.GET, requestEntityWithCompressionHeaders(), new ParameterizedTypeReference<>() { }); return stopPointsResponse.getBody(); } private HttpEntity<?> requestEntityWithCompressionHeaders() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add(HttpHeaders.ACCEPT_ENCODING, "gzip"); return new HttpEntity<>(requestHeaders); } void setJourneyPatternsEndPointUrl(String journeyPatternsEndPointUrl) { this.journeyPatternsEndPointUrl = journeyPatternsEndPointUrl; } void setLineEndPointUrl(String lineEndPointUrl) { this.lineEndPointUrl = lineEndPointUrl; } void setStopPointsEndPointUrl(String stopPointsEndPointUrl) { this.stopPointsEndPointUrl = stopPointsEndPointUrl; } }
4dd1c7ffa5cdf070f37e582e52a167769039e505
[ "Markdown", "Java", "INI" ]
13
Java
Chaithu-Narayana/bus-lines-api
9cca955438ae7caf48b928fd2ed34c21251fb599
686836fa066e1b7f546a78f164b6a0bebb16b552
refs/heads/master
<repo_name>DDuongNguyen/Rails-RubberDucking-dumbo-web-051319<file_sep>/app/models/student.rb class Student < ApplicationRecord @@num = 5 has_many :ducks validates :name, presence: true, uniqueness: true validates :mod, presence: true, inclusion: { in:1..@@num, message: "Number can only be between 1..#{@@num}" },numericality: { only_integer: true } end <file_sep>/db/seeds.rb 7.times do Student.create(name: Faker::Name.name, mod: rand(1..5)) end 10.times do Duck.create(name: Faker::Dog.unique.meme_phrase, description: Faker::Dog.breed, student_id: Student.all.sample.id) end
888157e2b737b3b5dfd6388ca867cca9da93a211
[ "Ruby" ]
2
Ruby
DDuongNguyen/Rails-RubberDucking-dumbo-web-051319
3fc0f7e0a28d93382d20e685dae9a86606b524b8
1e37b22917b022368dbb4e7ddd6525cd6ae0c0fa
refs/heads/main
<file_sep>//Create variables here var dog,happyDog,dogI,database,foodS,foodStock; function preload() { //load images here dogHappy.loadImage("dogImg.png") dogI.loadImage("dogImg1.png") } function setup() { createCanvas(500, 500); var dog=createSprite(250,250,50,50); dog.addImage(dogHappy) foodStock=database.ref('Food'); foodStock.on("value",readStock) } function draw() { background(46, 139, 87) drawSprites(); //add styles here }
fd8ea4662924f63388ec970bfba3a963d182697a
[ "JavaScript" ]
1
JavaScript
ZaidAG/p34part5
789ec8774aca1ae9f38e810073861e548ce44516
d5f1bd0839e47e7b8b8ee5799ff730f3028fb9f9
refs/heads/main
<repo_name>jmelop/LibraryProject<file_sep>/src/Libreria.java import java.util.ArrayList; import java.util.Iterator; public class Libreria { ArrayList<Libro> libreria = new ArrayList<Libro>(); String nombre; public Libreria(String nombre) { this.nombre = nombre; } public String getNombre() { return nombre; } public int cantidadLibros() { return libreria.size(); } public void añadirLibro(Libro libro) { libreria.add(libro); } public Libro localizarLibro(String titulo) { Iterator<Libro> libro = libreria.iterator(); while (libro.hasNext()) { Libro libList = libro.next(); if (libList.getTitulo().equals(titulo)) { return libList; } } return null; } public boolean checkLibroAutor(String autor) { int i = 0; while (i < libreria.size()) { if (libreria.get(i).getAutor().equals(autor)) { return true; } i++; } return false; } public void borrarLibroAutor(String autor) { int i = 0; while (i < libreria.size()) { if (libreria.get(i).getAutor().equals(autor)) { libreria.remove(i); break; } else if (i >= libreria.size()) { System.out.println("Error, no existe ningún libro a borrar con el autor especificado"); } i++; } } public Libro obtenerLibrosPrestados() { for (Libro libro : libreria) { if (libro.estaPrestado()) { return libro; } } return null; } public void prestarLibroTitulo(String titulo) { Iterator<Libro> iter = libreria.iterator(); while (iter.hasNext()) { Libro libro = iter.next(); if (libro.getTitulo().equals(titulo) && !libro.estaPrestado()) { libro.prestar(); break; } else if (!iter.hasNext()) { System.out.println("Error, el libro no existe o ya se ecuentra prestado"); } } } } <file_sep>/src/Prestado.java public enum Prestado { SIPRESTADO, NOPRESTADO }
089066c587382fe333075b435a2748f3ca70e249
[ "Java" ]
2
Java
jmelop/LibraryProject
3db65b8255aadf62302e62a32a8b948077eaebbb
5bd78efff20028f74d40ef85b771025603f1c2e6
refs/heads/master
<file_sep>import {Injectable} from "@angular/core"; interface IResult { value: number; status : "S" | "F"; } @Injectable({providedIn : "root"}) export class Ex1Service { startResult : IResult; actionResult1 : IResult; actionResult2 : IResult; actionResult3 : IResult; sumResult : IResult; sumFn = this.sum.bind(this); start() : Promise<IResult>{ return Promise.all([ this.action(1000).then( ir => this.actionResult1 = ir ), this.action(2000).then( ir => this.actionResult2 = ir ), this.action(3000).then( ir => this.actionResult3 = ir ) ]) .then( values => this.sum(values) ) } action( ms : number) : Promise<IResult>{ return delay(ms).then( ms => ({ value : ms / 1000, status : ms % 2 === 0 ? 'S' : 'F' })); } sum( values:IResult[] ) : Promise<IResult>{ return delay(25) .then( () => { let sum = 0; values.forEach( v => sum += v.value ); this.sumResult = { value : sum, status : "S" }; return this.sumResult; } ); } } function delay(ms:number) : Promise<number> { return new Promise<number>( resolve => setTimeout( resolve , ms , ms ) ); } function bind(fn,obj) { return (...arg) => fn.apply(obj,arg); } /* * f() => this === window * {}.f() => this === {} * f.apply({} ,[]) => this === {} * f.call ({} ,a,b) => this === {} * * f.bind({}) => this === {} * f.bind({}) === () => { f() } * * */ <file_sep>import {interval, Observable, of, Subscription} from "rxjs"; import {switchMap, catchError, map, filter, tap} from "rxjs/operators"; export const flowAndUserPro = flow(3).pipe( map( r => r * 5), filter( r => r > 5) ); let div : HTMLDivElement; let handler = e => console.log(`e:${e}`); div.addEventListener('click', handler ); //... div.removeEventListener('click', handler); let div2: {click$:Observable<MouseEvent>}; let sub : Subscription = div2.click$.subscribe(e => console.log(`e:${e}`)); sub.unsubscribe(); flow(1).subscribe(); demo1(2000) .pipe( tap(result => console.log(`result: ${result}`) ) ) .subscribe(); function demo1(ms:number) { return interval(ms).pipe( // 0 - - 1 - - 2 - - 3 - - 4 switchMap(action2) // - 1 - x // - 2 - x // - 3 - x ); } export function flow( n: number ) : Observable<number> { return action(1).pipe( switchMap(action), switchMap(action), switchMap(action), catchError( error => of(-1)) ); } export function action(n:number) : Observable<number> { return new Observable<number>( observer => { n++; setTimeout( ()=> { observer.next(n); //observer.error(-1) observer.complete(); } ,1000 ); } ) } export function action2(n:number) : Observable<number> { return new Observable<number>( observer => { n++; setInterval( ()=> { observer.next(n); //observer.error(-1) //observer.complete(); } ,1000 ); } ) } <file_sep>import {Routes} from "@angular/router"; import {HomeComponent} from "./components/home/home.component"; import {LoginComponent} from "./components/login/login.component"; import {MyGuard} from "./services/my-guard.guard"; export const appRoutes: Routes = [ {path: '', redirectTo: 'home', pathMatch: 'full'}, {path: 'home', component: HomeComponent, data: {animation: 'FilterPage'}}, {path: 'login', component: LoginComponent, data: {animation: 'AboutPage'}}, { path: 'pb', data: {animation: 'HomePage'}, canLoad: [MyGuard], loadChildren: () => import( './phone-book/phone-book.module' ) .then(m => m.PhoneBookModule) }, /*{ // pb/asdasd path : 'pb' , component : PbShellComponent, children : [ // { path: 'eyal' , component : ContactComponent }, { path: ':name' , component : ContactComponent }, ] },*/ {path: '**', redirectTo: 'home'} ]; <file_sep>import { Component, OnInit } from '@angular/core'; import {SecurityService} from "../../services/security.service"; import {ActivatedRoute, Router} from "@angular/router"; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor( public security : SecurityService, private router : Router, private route : ActivatedRoute ) { } ngOnInit() { } async onLogin(name: string, password: string) { await this.security.login(name,password); const url = this.route.snapshot.params.url; if( url ) { this.router.navigate([ url , this.security.user.name.first ]); } else { this.router.navigate(['/']) } } } <file_sep>import {Injectable} from "@angular/core"; import {PbProxyService} from "./pb-proxy.service"; @Injectable({providedIn : 'root'}) export class PbBlService { contacts : hani.User[] = []; constructor( private proxy : PbProxyService) { } async load() { try{ console.log('start'); const c = await this.proxy.getContacts(); console.log('end' + c ) ; this.contacts = [ ... this.contacts, ... c ]; return this.contacts; } catch (e) { console.log(e); } } } <file_sep>import {NgModule} from "@angular/core"; import {CommonModule} from "@angular/common"; import {PbShellComponent} from './components/pb-shell/pb-shell.component'; import {ContactComponent} from './components/contact/contact.component'; import {RouterModule} from "@angular/router"; import {PbBlService} from "./services/pb-bl.service"; import {AppContextService} from "../services/app-context.service"; @NgModule({ declarations: [ PbShellComponent, ContactComponent ], imports: [ CommonModule, RouterModule.forChild([ { path: '', component: PbShellComponent, children: [ // { path: 'eyal' , component : ContactComponent }, {path: ':name', component: ContactComponent}, ] }, ]) ], providers : [PbBlService] }) export class PhoneBookModule { constructor(private appCtx : AppContextService , private bl : PbBlService) { appCtx.pb = bl; } } <file_sep>import {Injectable} from "@angular/core"; import {HttpClient} from "@angular/common/http"; import {map} from "rxjs/operators"; @Injectable({ providedIn : 'root' }) export class PbProxyService { constructor(private http: HttpClient) { } getContacts() : Promise<hani.User[]> { return this.http.get<hani.Respond>('https://randomuser.me/api/?results=7') .pipe( map( resp => resp.results ) ) .toPromise(); } delay(ms) : Promise<number> { return new Promise<number>( resolve => { setTimeout( resolve , ms , ms ); } ); } } <file_sep>import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {PreloadAllModules, RouterModule} from "@angular/router"; import { QuicklinkModule, QuicklinkStrategy } from 'ngx-quicklink'; import {AppComponent} from './app.component'; import { HomeComponent } from './components/home/home.component'; import { LoginComponent } from './components/login/login.component'; import {appRoutes} from "./app.routes"; import {HttpClientModule} from "@angular/common/http"; import {BrowserAnimationsModule} from "@angular/platform-browser/animations"; @NgModule({ declarations: [ AppComponent, HomeComponent, LoginComponent ], imports: [ BrowserModule, BrowserAnimationsModule, HttpClientModule, QuicklinkModule, RouterModule.forRoot( appRoutes ,{ useHash : true, preloadingStrategy : QuicklinkStrategy /*PreloadAllModules*/ }), // PhoneBookModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import {PbBlService} from "../../services/pb-bl.service"; @Component({ selector: 'app-pb-shell', templateUrl: './pb-shell.component.html', styleUrls: ['./pb-shell.component.css'] }) export class PbShellComponent implements OnInit { constructor(public bl : PbBlService) { this.bl.load() } ngOnInit() { } } <file_sep>flow(1); function flow(n:number) : void { action(n, (result : number) => { console.log(`r:${result}`); action(n, (result : number) => { console.log(`r:${result}`); action(n, (result : number) => { console.log(`r:${result}`); }); }); }); // ? } export function action(n:number,callback : (n:number)=> void) { setTimeout(()=>{ n++; callback( n ); },1000); } let div: HTMLDivElement; div.addEventListener('click', (e)=>{ }); <file_sep>import {fromEvent, Observable, Subject} from "rxjs"; import {bufferCount, bufferTime, debounceTime, filter, groupBy, map, switchMap, tap} from "rxjs/operators"; import {HttpClient} from "@angular/common/http"; declare type Stock = {value:number,symbol:string}; let ticks$ : Observable<Stock>; /*ticks$.pipe( groupBy( item => item.symbol ), bufferCount(2), map( (items:Stock[] ) => items[1].value - items[0].value) )*/ let input: HTMLInputElement; // let subject = new Subject(); // input.addEventListener('input', e => subject.next(e) ); let http: HttpClient; let auto$ = fromEvent(input,'input').pipe( map( e => e.target['value'] as string ), filter( inputStr => inputStr.length > 3 ), debounceTime(750), switchMap( search => http.get<string[]>(`http:ynet.co.il/?search=${search}`)), ); let click$ : Observable<MouseEvent>; let count : number; let pipe1 = click$.pipe( bufferTime(1000), map( events => events.length), tap( num => count = num ) ); // pipe1.subscribe(); <file_sep>import {Injectable} from "@angular/core"; import {HttpClient} from "@angular/common/http"; import {PbBlService} from "../phone-book/services/pb-bl.service"; @Injectable({ providedIn : 'root'}) export class SecurityService { user : hani.User; constructor( private http : HttpClient , private bl : PbBlService) { } async login( name : string , password : string ){ await Promise.all([ delay(3000) , this.bl.load() ]); this.user = this.bl.contacts[0]; return this.user; } logout(){ return this.user = null; } } function delay( ms ) : Promise<number> { return new Promise<number>( resolve => { setTimeout(resolve,ms,ms); }); } /*const delay2 = promisfiy(setTimeout); function promisfiy( fn ) : (...args) => Promise<any> { return (...args) => new Promise<any>( resolve => { fn.apply( this, [resolve, ...args ] ); }); }*/ <file_sep> let proxy : { getUsers : (id:number) => Promise<{id:number,name:string}> }; function demo(n:number) { return Promise.all([ action(n), action(n), action(n), ]).then() } function flow( n : number) : Promise<number | string > { return action(1) .then( r1 => action(r1) ) // f(r) => a(r) .then( action ) // a(r) .then( action ) .catch( error => { return Promise.reject('error'); } ) .then( r => r); } export function action( n: number) : Promise<number> { return new Promise<number>( ( resolve, reject ) =>{ setTimeout( ()=> { n++; resolve(n); } ,1000) } ) } <file_sep>import { Component } from '@angular/core'; import {Router, RouterOutlet} from "@angular/router"; import {SecurityService} from "./services/security.service"; import {slideInAnimation} from "./animations"; @Component({ selector: 'app-root', animations: [ // slideInAnimation ], template: ` <!-- <div class="layout" [ngStyle]="{ 'grid-template-rows' : getRows(5), 'grid-template-columns' : getRows(3) }">--> <div class="layout"> <nav class="nav"> <a routerLink="home" routerLinkActive="active">Home</a> <a routerLink="pb" routerLinkActive="active">Phone Book</a> <a routerLink="login" routerLinkActive="active">Login</a> <button routerLink="login" routerLinkActive="active">demo1</button> <button (click)="go('pb')" >demo2</button> <button>Change</button> </nav> <div class="main" [@routeAnimations]="prepareRoute(outlet)"> <router-outlet #outlet="outlet"></router-outlet> </div> <div class="footer"> <ng-container *ngIf="sec.user as u"> <img [src]="u.picture.thumbnail" style="height: 25px"> <span>{{u.name.title}}</span> <span>{{u.name.first}}</span> <span>{{u.name.last}}</span> </ng-container> </div> <div class="blabla"></div> </div> `, styles: [] }) export class AppComponent { title = 'day4'; constructor( private router: Router, public sec : SecurityService) { } go(path: string) { this.router.navigateByUrl(path); //this.router.navigate(['aa','bb','cc']); } getRows(number: number) { const array = new Array(number); array.fill('1fr'); return array.join(' '); } prepareRoute(outlet: RouterOutlet) { return outlet && outlet.activatedRouteData && outlet.activatedRouteData['animation']; } } <file_sep> let proxy : { getUsers : (id:number) => Promise<{id:number,name:string}> }; async function flow( n : number) : Promise<number | string > { try{ let r1 = await action(1); let r2 = await action(r1); let r3 = await action(r2); let r4:number[] = await Promise.all([action(r3),action(1)]); return r3; } catch (e) { return -1; } } export function action( n: number) : Promise<number> { return new Promise<number>( ( resolve, reject ) =>{ setTimeout( ()=> { n++; resolve(n); } ,1000) } ) } function all(promises:Promise<any>[]) : Promise<any[]> { return new Promise<any[]>( (resolve ,reject) => { let results : any[] = []; promises.forEach( p => p.then( r=> { results.push(r); if(results.length === promises.length ){ resolve(results); } } , error => reject(error))); } ) } <file_sep>import { Injectable } from '@angular/core'; import { CanLoad, Route, UrlSegment, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router'; import { Observable } from 'rxjs'; import {SecurityService} from "./security.service"; @Injectable({ providedIn: 'root' }) export class MyGuard implements CanLoad { constructor( private security : SecurityService, private router : Router ) { } canLoad( route: Route, segments: UrlSegment[]) { if( this.security.user ) return true; this.router.navigate([ '/login', { url : route.path } ]); return false; } } <file_sep><div *ngIf="user$ | async as user; else noUser"> <h3>{{user.name.title}} {{ user.name.first }} {{user.name.last}}</h3> <pre> {{user.location | json }} </pre> </div> <ng-template #noUser> <h3>No User found !!!</h3> </ng-template> <file_sep>import {Component, OnInit} from '@angular/core'; import {ActivatedRoute} from "@angular/router"; import {Observable} from "rxjs"; import {map} from "rxjs/operators"; import {PbBlService} from "../../services/pb-bl.service"; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.css'] }) export class ContactComponent implements OnInit { user$: Observable<hani.User>; constructor( private route: ActivatedRoute, private bl : PbBlService ) { console.log(`ContactComponent constructor`); this.user$ = route.params.pipe( map( params => params.name ), map( name => bl.contacts.find( c => c.name.first === name ) ) ); } ngOnInit() { } } <file_sep>import {Component, ElementRef, VERSION, ViewChild} from '@angular/core'; import {fromEvent, Observable, Subject} from "rxjs"; import {HttpClient} from "@angular/common/http"; import {map, scan, switchMap, tap} from "rxjs/operators"; @Component({ selector: 'app-root', template: ` <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center" class="content"> <h1>Welcome to {{title}} , Version ; {{Version}}!</h1> <span style="display: block">{{ title }} app is running!</span> <button (click)="getUsers(10)">Get users</button> </div> <img [src]="p.medium" *ngFor="let p of pic$ | async"> <app-ex1 #ex1></app-ex1> `, styles: [] }) export class AppComponent { title = 'day3'; @ViewChild('ex1',{read:ElementRef,static:true}) elmEx1; click$ = new Subject<number>(); pic:hani.Picture[] = []; pic$ : Observable<hani.Picture[]>; constructor(private http: HttpClient) { this.pic$ = this.click$.pipe( switchMap( num => this.http.get<hani.Respond>(`https://randomuser.me/api/?results=${num}`) ), map( r => r.results ), map( users => [ ...users.map( user => ({...user.picture}) ) ]), scan( (acc,value) => { return [ ...acc, ...value ] } ) ); } ngOnInit(){ //this.click$ = fromEvent(this.elmEx1,'click'); } get Version(){ return VERSION.full; } getUsers(number: number) { this.click$.next(number); /*this.http.get<hani.Respond>(`https://randomuser.me/api/?results=${number}`) .pipe( map( r => r.results ), map( users => [ ...users.map( user => ({...user.picture}) ) ]), //map( pic => pic[0]), tap( pic => { this.pic = pic; }) ).subscribe();*/ } }
1352a86ab8cf9c02afc8499be367cb6baeeeebfe
[ "TypeScript", "HTML" ]
19
TypeScript
eyalvardi/israports-04-11-2019
b06161a415d4cc2cdee52967586d2ca694874d16
11f723eca93a52707f5d69063d72d84a68ba4611
refs/heads/main
<file_sep>import random count = 0 win = False number = random.randint(1,30) while win == False: guess = int(input('Enter your number: ')) if guess != number: if guess >= number: print('try a lower number') count += 1 print(count) if count == 5: print('you used so much guesess') break elif guess <= number: print('try a higher number') count += 1 print(count) if count == 5: print('you used so much guesess') break elif guess == number: print('WOW, you won!') break
2163694d7cdca10a194c3f38195094d74db97aaa
[ "Python" ]
1
Python
merlinfrank/python
847e1be0e5673c096ac4bd3cbb530391412a26f9
6dcd6a96fd551b15b72a994ab39fef337621c225
refs/heads/master
<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package controllers; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import engine.core.factories.AbstractFactory; import engine.core.factories.ControllerFactory; import engine.core.mvc.controller.BaseController; import engine.utils.io.logging.Tracelog; import game.entities.concrete.AbstractChessEntity; import generated.DataLookup.DataLayerName; import models.PlayerModel; import models.TileModel; import views.PromotionView; /** * @author <NAME> {@literal <<EMAIL>>} */ public final class PromotionController extends BaseController { /** * The list of chess pieces available for promotion */ private final List<AbstractChessEntity> _promotionList = new ArrayList(); /** * The currently selected entity */ private AbstractChessEntity _selectedEntity; /** * The tile where the promotion will take place */ private TileModel _tile; /** * The player that is performing the promotion */ private PlayerModel _player; /** * Constructs a new instance of this class type * * @param viewClass The view to instantiate this controller with * */ public PromotionController(PromotionView viewClass) { super(viewClass); } /** * Sets the entity to be promoted * * @param tile The tile where the promotion will take place */ public void setTile(TileModel tile) { _tile = tile; } /** * Updates the promoted pieces */ public void updatePromotedPieces() { // Add the list of entities that can be used for the promotion _promotionList.clear(); _promotionList.add(AbstractChessEntity.createEntity(DataLayerName.BISHOP)); _promotionList.add(AbstractChessEntity.createEntity(DataLayerName.KNIGHT)); _promotionList.add(AbstractChessEntity.createEntity(DataLayerName.QUEEN)); _promotionList.add(AbstractChessEntity.createEntity(DataLayerName.ROOK)); // Set the player PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class); _player = playerController.getCurrentPlayer(); for(AbstractChessEntity entity : _promotionList) { entity.setPlayer(_player); } } /** * Sets the currently selected chess entity for the promotion * * @param selectedEntity The selected chess entity for the promotion */ public void setSelectedEntity(AbstractChessEntity selectedEntity) { _selectedEntity = selectedEntity; } /** * Applies the promotion based on the selected chess entity */ public void applyPromotion() { // If the selected entity and tile are both valid if(_selectedEntity != null && _tile != null && _tile.getEntity() != null && _tile.getEntity().isPromotable()) { // Get the player controller PlayerController controller = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class); // Get the player of the tile that is on the tile in question PlayerModel player = controller.getPlayer(_tile.getEntity().getTeam()); // Remove the entity that the player owns player.removeEntity(_tile.getEntity()); // Replace the entity on the tile with the selected entity _tile.setEntity(_selectedEntity); // Perform a cleanup so that this controller doesn't hold reference needlessly flush(); } else { Tracelog.log(Level.SEVERE, true, "Cannot promote the specified entity"); } } /** * Gets the promotion list of available promotions * * @return The list of available promotions * */ public List<AbstractChessEntity> getPromotionList() { return _promotionList; } @Override public boolean flush() { _promotionList.clear(); _selectedEntity = null; _player = null; _tile = null; return super.flush() && true; } }<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package game.entities.concrete; import java.util.ArrayList; import java.util.List; import engine.communication.internal.signal.arguments.SignalEventArgs; import game.components.MovementComponent; import game.components.MovementComponent.EntityMovements; import game.events.EntityEventArgs; import generated.DataLookup.DataLayerName; import models.TileModel; /** * This class represents a pawn in the chess game * * @author <NAME> {@literal <<EMAIL>>} */ class PawnEntity extends AbstractChessEntity { /** * Flag indicating if this pawn is exposed to an en-passent move */ private boolean _canReceiveEnPassent; /** * Constructs a new instance of this class type */ public PawnEntity() { super(DataLayerName.PAWN); } /** * Gets the double movement offered by pawns * * @return The double movement */ private EntityMovements[] getDoubleMovement() { return new EntityMovements[] { EntityMovements.UP, EntityMovements.UP }; } @Override public List<EntityMovements[]> getMovements() { return new ArrayList<EntityMovements[]>() {{ // This is the unit movement that all pawns support add(new EntityMovements[] { EntityMovements.UP }); // If this pawn has not moved yet, then expose the double unit movement if(!hasMovedOnce()) { add(getDoubleMovement()); } }}; } @Override public List<EntityMovements[]> getCapturableBoardMovements() { return new ArrayList<EntityMovements[]>() {{ // This is the unit movement that all pawns support add(new EntityMovements[] { EntityMovements.RIGHT, EntityMovements.UP }); add(new EntityMovements[] { EntityMovements.LEFT, EntityMovements.UP }); }}; } @Override public boolean isEnPassent() { return true; } @Override public boolean isEnPassentCapturable() { return _canReceiveEnPassent; } @Override public boolean isMovementContinuous() { return false; } @Override public boolean isMovementCapturable() { return false; } @Override public boolean isPromotable() { return true; } @Override public void update(SignalEventArgs signalEvent) { super.update(signalEvent); if(signalEvent instanceof EntityEventArgs) { EntityEventArgs<TileModel> modelEventArgs = (EntityEventArgs) signalEvent; // Remove the en-passent flag, the chance is lost if(_canReceiveEnPassent) { _canReceiveEnPassent = false; } else if(modelEventArgs.getSource().getEntity() == this && MovementComponent.compareMovements(modelEventArgs.movements, getDoubleMovement())) { // Indicate that this pawn can receive en-passent _canReceiveEnPassent = true; } } } }<file_sep>about = About about_message = About Chess checkmate_x = content/checkmate_x.png clear = Clear debug = Debug debug_window = Debugger Window exit = Exit file = File game_icon = content/chess-icon-16.png help = Help inspector = Inspector mem_clear = Mem Clear mem_print = Mem Print mem_recall = Mem Recall mem_store = Mem Store neighbor_tiles = Neighbors new_game = New Game new_game_debug = Debug New Game pieces = Pieces start = Start stop = Stop teams = Teams tile_identifier = Show Tile Identifier title = Chess quit = Quit quit_question = Quitting will end the current game session, are you sure?<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package views; import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.border.Border; import controllers.TileController; import engine.communication.internal.signal.ISignalReceiver; import engine.communication.internal.signal.arguments.SignalEventArgs; import engine.core.factories.AbstractSignalFactory; import engine.core.factories.ControllerFactory; import engine.core.graphics.RawData; import engine.core.mvc.view.PanelView; import models.TileModel; import resources.Resources; import resources.Resources.ResourceKeys; /** * This view represents the visual contents of a single tile in this game * * @author {@literal <NAME> <<EMAIL>>} * */ public class TileView extends PanelView { /** * The local identifier count for this tile */ private final JLabel _identifierTextField = new JLabel(); /** * This flag when set to true with perform a neighbor highlight on this tile when you mouse over it */ private boolean _highlightNeighbors; /** * The color of all the odd files */ public static final Color ODD_FILES_COLOR = new Color(209, 139, 71); /** * The Color of all the even files */ public static final Color EVEN_FILES_COLOR = new Color(255, 205, 158); /** * The color used when a tile is considered selected */ private static final Color SELECTED_COLOR = Color.LIGHT_GRAY; /** * The color used when a tile is in check */ private static final Color CHECKED_COLOR = Color.RED; /** * The default background color of this tile */ private final Color DEFAULT_BACKGROUND_COLOR; /** * The current background color of this tile */ private Color _currentBackgroundColor; /** * Normal border style of this view */ private final Border DEFAULT_BORDER_STYLE; /** * Event associated to show neighbors */ public static final String EVENT_SHOW_NEIGHBORS = "EVENT_SHOW_NEIGHBORS"; /** * Event associated to hiding neighbors */ public static final String EVENT_HIDE_NEIGHBORS = "EVENT_HIDE_NEIGHBORS"; /** * Event associated to showing the identifier of this tile */ public static final String EVENT_SHOW_IDENTIFIER = "EVENT_SHOW_IDENTIFIER"; /** * Event associated to hiding the identifier of this tile */ public static final String EVENT_HIDE_IDENTIFIER = "EVENT_HIDE_IDENTIFIER"; /** * Constructs a new instance of this class type * * @param tileColor the color of the tile */ public TileView(Color tileColor) { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); // Set the controller associated to this view getViewProperties().setListener(AbstractSignalFactory .getFactory(ControllerFactory.class) .get(TileController.class, false, this) ); // Set the color that has been specified DEFAULT_BACKGROUND_COLOR = tileColor; setBackground(DEFAULT_BACKGROUND_COLOR); // Set the default border color of this tile // which should be the same color as the default // background color of the tile // // Note: By having a border, we avoid artifact issues with // rendering an actual border on a particular tile when // no other tile has a border drawn DEFAULT_BORDER_STYLE = BorderFactory.createLineBorder(DEFAULT_BACKGROUND_COLOR, 2); setBorder(DEFAULT_BORDER_STYLE); } @Override public boolean flush() { boolean done = super.flush(); --TileModel._counter; return done; } @Override public void initializeComponents() { _identifierTextField.setVisible(false); _identifierTextField.setForeground(Color.RED); add(_identifierTextField); } @Override public void initializeComponentBindings() { // Add a mouse listener to handle when mousing over // a tile, this will highlight the // actual tile and properly displays the border of // the tile in the highlight effect this.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent event) { if(_highlightNeighbors) { getViewProperties().getEntity(TileController.class).showTileNeighborsDebug(true); } } @Override public void mouseExited(MouseEvent event) { if(_highlightNeighbors) { getViewProperties().getEntity(TileController.class).showTileNeighborsDebug(false); } } @Override public void mouseReleased(MouseEvent event) { TileController controller = getViewProperties().getEntity(TileController.class); controller.performSelect(); } }); } @Override public void registerSignalListeners() { registerSignalListener(EVENT_SHOW_NEIGHBORS, new ISignalReceiver<SignalEventArgs>() { @Override public void signalReceived(SignalEventArgs event) { _highlightNeighbors = true; } }); registerSignalListener(EVENT_HIDE_NEIGHBORS, new ISignalReceiver<SignalEventArgs>() { @Override public void signalReceived(SignalEventArgs event) { _highlightNeighbors = false; // Force the tile to hide its debug selection in case the mouse is already highlighting // some of the tiles getViewProperties().getEntity(TileController.class).showTileNeighborsDebug(false); } }); registerSignalListener(EVENT_SHOW_IDENTIFIER, new ISignalReceiver<SignalEventArgs>() { @Override public void signalReceived(SignalEventArgs event) { getViewProperties().setRedraw(true); _identifierTextField.setVisible(true); } }); registerSignalListener(EVENT_HIDE_IDENTIFIER, new ISignalReceiver<SignalEventArgs>() { @Override public void signalReceived(SignalEventArgs event) { getViewProperties().setRedraw(true); _identifierTextField.setVisible(false); } }); } @Override public void setBackground(Color backgroundColor) { // Before rendering a new background color, ensure that // the background color isn't already set to the specified // color if(backgroundColor != _currentBackgroundColor) { // Render the new background settings super.setBackground(backgroundColor); // Record the new background color change _currentBackgroundColor = backgroundColor; } } @Override public void update(SignalEventArgs signalEvent) { // Call the super implementation super.update(signalEvent); // Some calls are not necessarily from tile models, so prevent this from causing damage if(signalEvent.getSource() instanceof TileModel) { // Get the tile model of the source TileModel tileModel = (TileModel) signalEvent.getSource(); System.out.println("TileView::update::" + tileModel.toString()); _identifierTextField.setText(tileModel.toString()); // If the tile is in check then set the background accordingly if(tileModel.getEntity() != null && tileModel.getEntity().getIsChecked()) { this.setBackground(CHECKED_COLOR); } // If the tile model is in a selected state then update the // background accordingly else if(tileModel.getIsSelected() || tileModel.getIsHighlighted()) { // Set the background, and then set the border // because we want it to be selected this.setBackground(SELECTED_COLOR); } else { // Set the background back to the default state this.setBackground(DEFAULT_BACKGROUND_COLOR); } if(tileModel.getEntity() != null) { addRenderableContent(tileModel.getEntity()); if(tileModel.getEntity().getIsCheckMate()) { this.setBackground(DEFAULT_BACKGROUND_COLOR); addRenderableContent(new RawData(Resources.instance().getLocalizedData(ResourceKeys.CheckMate))); } } // Repaint the view repaint(); } } }<file_sep># Chess ![](README.gif) ### Description Chess is a game played against two players, competing to place their opponents king into a checkmate positions, where no further moves on the board can be made. ### Features The following features are the core functionalities that the game will offer. - [x] Base Game - [x] Guides - [x] Debugger - [x] En-Passent - [x] Castling - [x] Stalemate - [ ] Algebraic Notation Support - [ ] Player-versus-Player Online - [ ] Player-versus-Computer Offline - [ ] Audio Support - [ ] Animation Support<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package views; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import application.Application; import controllers.BoardController; import controllers.DebuggerSettingsController; import engine.core.factories.AbstractFactory; import engine.core.factories.AbstractSignalFactory; import engine.core.factories.ControllerFactory; import engine.core.mvc.view.DialogView; import generated.DataLookup.DataLayerName; import models.PlayerModel.PlayerTeam; import resources.Resources; import resources.Resources.ResourceKeys; /** * The view associated to the chess debugger * * @author {@literal <NAME> <<EMAIL>>} */ public class DebuggerSettingsView extends DialogView { /** * The list of pieces to select from on the UI */ private JComboBox<DataLayerName> _piecesList = new JComboBox(); /** * The list of players to select from on the UI */ private JComboBox<PlayerTeam> _teamList = new JComboBox(); /** * The start button that starts the debugging session */ private JButton _startButton = new JButton(Resources.instance().getLocalizedString(ResourceKeys.Start)); /** * The stop button that stops the debugging session */ private JButton _stopButton = new JButton(Resources.instance().getLocalizedString(ResourceKeys.Stop)); /** * The clear button that clears the board */ private JButton _clearButton = new JButton(Resources.instance().getLocalizedString(ResourceKeys.Clear)); /** * The memory store button takes a snapshot of the board configuration */ private JButton _memoryStore = new JButton(Resources.instance().getLocalizedString(ResourceKeys.MemStore)); /** * The memory recall will put the board back to its last saved state */ private JButton _memoryRecall = new JButton(Resources.instance().getLocalizedString(ResourceKeys.MemRecall)); /** * The memory clear button will clear the saved state of the board */ private JButton _memoryClear = new JButton(Resources.instance().getLocalizedString(ResourceKeys.MemClear)); /** * The memory print button will print the contents that are in memory to the console */ private JButton _memoryPrint = new JButton(Resources.instance().getLocalizedString(ResourceKeys.MemPrint)); /** * The inspector that will allow you to debug the contents of a tile */ private JCheckBox _inspector = new JCheckBox(); /** * Constructs a new instance of this class type */ public DebuggerSettingsView() { super(Application.instance(), Resources.instance().getLocalizedString(ResourceKeys.DebugWindow), 300, 300); // Prevent the properties window from being resized this.setResizable(false); // Sets this view to always be on top setAlwaysOnTop(true); // Specify the controller of this dialog getViewProperties().setListener(AbstractSignalFactory.getFactory(ControllerFactory.class).get(DebuggerSettingsController.class, true, this)); // Set the layout manager of this dialog to be a grid-like layout getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); } @Override public void initializeComponents() { // Populate the models held by the controller into the combo boxes. // Note: This needs to happen before setting the maximum size of each box // or the vertical spacing will not be done properly DebuggerSettingsController controller = getViewProperties().getEntity(DebuggerSettingsController.class); // Teams label and the list of teams JPanel teamsPanel = new JPanel(); JLabel teamsLabel = new JLabel(Resources.instance().getLocalizedString(ResourceKeys.Teams)); teamsPanel.add(teamsLabel); teamsPanel.add(_teamList); _teamList.setModel(controller.getTeamCollection()); getContentPane().add(teamsPanel); teamsPanel.setMaximumSize(teamsPanel.getPreferredSize()); // Pieces label and the list of pieces JPanel piecesPanel = new JPanel(); JLabel piecesLabel = new JLabel(Resources.instance().getLocalizedString(ResourceKeys.Pieces)); piecesPanel.add(piecesLabel); piecesPanel.add(_piecesList); _piecesList.setModel(controller.getEntityCollection()); getContentPane().add(piecesPanel); piecesPanel.setMaximumSize(piecesPanel.getPreferredSize()); // Memory panel for saving the board state JPanel memoryPanel = new JPanel(); memoryPanel.add(_memoryStore); memoryPanel.add(_memoryRecall); memoryPanel.add(_memoryClear); memoryPanel.add(_memoryPrint); getContentPane().add(memoryPanel); // Pieces label and the list of pieces JPanel inspectorPanel = new JPanel(); JLabel inspectorLabel = new JLabel(Resources.instance().getLocalizedString(ResourceKeys.Inspector)); inspectorPanel.add(inspectorLabel); inspectorPanel.add(_inspector); getContentPane().add(inspectorPanel); // Action buttons and other related actions for controlling the debugging scene JPanel actionPanel = new JPanel(); actionPanel.add(_startButton); actionPanel.add(_stopButton); actionPanel.add(_clearButton); getContentPane().add(actionPanel); // Set the states of the action buttons _startButton.setEnabled(true); _stopButton.setEnabled(false); _clearButton.setEnabled(true); } @Override public void initializeComponentBindings() { BoardController boardController = AbstractFactory.getFactory(ControllerFactory.class).get(BoardController.class); DebuggerSettingsController debuggerSettingsController = getViewProperties().getEntity(DebuggerSettingsController.class); _startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { _startButton.setEnabled(false); _piecesList.setEnabled(false); _teamList.setEnabled(false); _stopButton.setEnabled(true); _clearButton.setEnabled(false); _inspector.setEnabled(false); _memoryStore.setEnabled(false); _memoryClear.setEnabled(false); _memoryRecall.setEnabled(false); // Start the game boardController.startGame(); } }); _stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { _startButton.setEnabled(true); _piecesList.setEnabled(true); _teamList.setEnabled(true); _stopButton.setEnabled(false); _clearButton.setEnabled(true); _inspector.setEnabled(true); _memoryStore.setEnabled(true); _memoryClear.setEnabled(true); _memoryRecall.setEnabled(true); // Stop the game boardController.stopGame(); boardController.clearBoardHighlights(); } }); _clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { // Clear the board boardController.clearBoard(); } }); _inspector.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boardController.setIsInspecting(_inspector.isSelected()); } }); _memoryStore.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // add to the memory debuggerSettingsController.memoryStore(); } }); _memoryRecall.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Clear the board boardController.clearBoard(); // Recall the memory debuggerSettingsController.memoryRecall(); } }); _memoryClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Recall the memory debuggerSettingsController.memoryClear(); } }); _memoryPrint.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Print the contents that are in memory System.out.println(debuggerSettingsController.toString()); } }); } @Override public void render() { super.render(); // Positions this dialog at the middle-right of the application Dimension screenSize = getToolkit().getScreenSize(); setLocation((int)(screenSize.getWidth() - getWidth()), (int)((screenSize.getHeight() - getHeight()) / 2)); // Request focus on the window requestFocus(); } }<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package game.components; import java.awt.Dimension; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import controllers.PlayerController; import engine.core.factories.AbstractFactory; import engine.core.factories.ControllerFactory; import engine.utils.io.logging.Tracelog; import game.components.MovementComponent.EntityMovements; import game.components.MovementComponent.PlayerDirection; import game.entities.concrete.AbstractChessEntity; import models.PlayerModel; import models.PlayerModel.PlayerTeam; import models.TileModel; /** * This class represents the instructions for how the board game should operate * * @author <NAME> {@literal <<EMAIL>>} * */ public class BoardComponent { /** * The dimensions of the board game */ private final Dimension _dimensions; /** * The list of neighbors logically associated to a specified controller * * Key1: The tile model center * Key2: The TOP, BOTTOM, LEFT, RIGHT neighboring tiles of the specified key1 */ private final Map<TileModel, Map<EntityMovements, TileModel>> _neighbors = new LinkedHashMap(); /** * Constructs a new instance of this class type * * @param dimensions The board game dimensions */ public BoardComponent(Dimension dimensions) { _dimensions = dimensions; } /** * Adds the specified tile model into the neighbors list * * @param tileModel The tile model */ public void addTileEntity(TileModel tileModel) { // If what are trying to insert has already been inserted then something went wrong if(_neighbors.putIfAbsent(tileModel, null) != null) { Tracelog.log(Level.SEVERE, true, "Error: Tile model already exists in the list... cannot add this one in"); } // If we have enough neighboring elements, then its time to link them together if(_dimensions.width * _dimensions.height == _neighbors.size()) { generateLogicalTileLinks(); } } /** * Indicates if the specified tile contains an entity that has the ability to move forward * * @param tileModel The tile model in question * * @return TRUE if the specified tile contains an entity that has the ability to move forward */ public boolean canMoveForward(TileModel tileModel) { AbstractChessEntity entity = tileModel.getEntity(); if(entity != null) { return _neighbors.get(tileModel).get(PlayerDirection.getNormalizedMovement(entity.getTeam().DIRECTION, EntityMovements.UP)) != null; } return false; } /** * Logically attaches the list of tiles together by sub-dividing the list of tiles. * Note: Order matters in cases such as this, which is why insertion order was important * when I chose the data structure for the neighbors map */ private void generateLogicalTileLinks() { // Get the array representation of our tile models. // Note: This is done because it is easier to get a subset of an array // and because the neighbor data structure tracks the insertion // order at runtime which is what is important here. TileModel[] tiles = _neighbors.keySet().toArray(new TileModel[0]); // For every row that exists within our setup model for(int i = 0, rows = _dimensions.height, columns = _dimensions.width; i < rows; ++i) { // Link the tile rows together linkTiles( // Previous row i - 1 >= 0 ? Arrays.copyOfRange(tiles, (i - 1) * columns, ((i - 1) * columns) + columns) : null, // Current Row Arrays.copyOfRange(tiles, i * columns, (i * columns) + columns), // Next Row i + 1 >= 0 ? Arrays.copyOfRange(tiles, (i + 1) * columns, ((i + 1) * columns) + columns) : null ); } } /** * Gets all the neighbors associated to the particular model * * @param tileModel The tile model to use as a search for neighbors around it * * @return The list of tile models that neighbor the passed in tile model */ public List<TileModel> getAllNeighbors(TileModel tileModel) { // Get the list of neighbors associated to our tile model Map<EntityMovements, TileModel> tileModelNeighbors = _neighbors.get(tileModel); // This collection holds the list of all the neighbors List<TileModel> allNeighbors = new ArrayList(); // Go through every entry set in our structure for(Map.Entry<EntityMovements, TileModel> entry : tileModelNeighbors.entrySet()) { // Get the tile model TileModel tile = entry.getValue(); if(tile == null) { continue; } // Add our tile to the list allNeighbors.add(tile); // To get the diagonals, make sure that if we are on the top or bottom tile // that we fetch their respective tiles, and provided that they are valid // add them to our list. switch(entry.getKey()) { case UP: case DOWN: TileModel left = _neighbors.get(tile).get(EntityMovements.LEFT); if(left != null) { allNeighbors.add(left); } TileModel right = _neighbors.get(tile).get(EntityMovements.RIGHT); if(right != null) { allNeighbors.add(right); } break; } } // return the list of neighbors return allNeighbors; } /** * Gets all the board positions that the specified entity on the specified tile can move to * * @param tileModel The tile model * * @return All the board positions */ public Map<TileModel, EntityMovements[]> getBoardPositions(TileModel tileModel) { // Get a reference to the player controller PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true); // Get the list of positions that can be moved to Map<TileModel, EntityMovements[]> availablePositions = getBoardPositionsImpl(tileModel); // Go through the list of moves and scrub the ones that would result in my being in check for(Iterator<Map.Entry<TileModel, EntityMovements[]>> it = availablePositions.entrySet().iterator(); it.hasNext();) { Map.Entry<TileModel, EntityMovements[]> entry = it.next(); if(isMoveChecked(playerController.getPlayer(tileModel.getEntity().getTeam()), tileModel, entry.getKey())) { it.remove(); } } // If the current tile has an entity and it can be used to castle if(tileModel.getEntity() != null && !tileModel.getEntity().getIsChecked() && tileModel.getEntity().getIsCastlableFromCandidate()) { // Get the left-most rook castle candidate TileModel leftCandidate = getCastlableToEntity(tileModel, EntityMovements.LEFT); if(leftCandidate != null) { availablePositions.put( _neighbors.get(_neighbors.get(tileModel).get(EntityMovements.LEFT)).get(EntityMovements.LEFT), new EntityMovements[] {EntityMovements.LEFT, EntityMovements.LEFT} ); } // Get the right-most rook castle candidate TileModel rightCandidate = getCastlableToEntity(tileModel, EntityMovements.RIGHT); if(rightCandidate != null) { availablePositions.put( _neighbors.get(_neighbors.get(tileModel).get(EntityMovements.RIGHT)).get(EntityMovements.RIGHT), new EntityMovements[] {EntityMovements.RIGHT, EntityMovements.RIGHT} ); } } // Return back the list of available positions return availablePositions; } /** * Gets the castlable to entity in the specified movement direction * * @param from The from tile * @param movement The direction to move in * * @return The tile that can be castled with if any */ public TileModel getCastlableToEntity(TileModel from, EntityMovements movement) { // Get the list of castle candidates that can be castled to PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true); List<AbstractChessEntity> candidates = playerController.getPlayer(from.getEntity().getTeam()).getCastlableToCandidates(); // This represents the number of movements that the king needs // to ensure that there is no check int kingPositions = 0; TileModel temp = from; while((temp = _neighbors.get(temp).get(movement)) != null) { // If the first two moves would put you in check then // a valid castling cannot be performed if(++kingPositions <= 2 && isMoveChecked(from.getEntity().getPlayer(), from, temp)) { return null; } // If the entity exists make sure it is one of our candidates else if(temp.getEntity() != null) { if(candidates.contains(temp.getEntity()) && temp.getEntity().getIsCastlableToCandidate() && _neighbors.get(temp).get(movement) == null) { break; } else { return null; } } } return temp; } /** * Sets the new position of the castlable entity * * @param fromPosition The position of where the from would be AFTER it has been updated * @param castleableTo The position of the entity that the king will castle with * @param fromMovement The movement that resulted in the from position from arriving at its updated location */ public void setCastlableMovement(TileModel fromPosition, TileModel castleableTo, EntityMovements fromMovement) { if(fromMovement == EntityMovements.LEFT || fromMovement == EntityMovements.RIGHT) { AbstractChessEntity castleEntity = castleableTo.getEntity(); castleableTo.setEntity(null); TileModel newCastleLocation = _neighbors.get(fromPosition).get(MovementComponent.invert(fromMovement)); newCastleLocation.setEntity(castleEntity); } } /** * Gets the list of board positions that the specified tile can move on * * @param tileModel The tile model being played * * @return The list of tiles to move towards */ public Map<TileModel, EntityMovements[]> getBoardPositionsImpl(TileModel tileModel) { Map<TileModel, EntityMovements[]> allMoves = new HashMap(); // Attempt to get the en-passent moves of the specified tile for(Map.Entry<TileModel, EntityMovements[]> kvp : getEnPassentBoardPositions(tileModel).entrySet()) { allMoves.putIfAbsent(kvp.getKey(), kvp.getValue()); } // If tile model does not has a chess entity then // there are no moves to get AbstractChessEntity entity = tileModel.getEntity(); if(entity == null) { return allMoves; } // The flag indicating if the entity can capture enemy pieces with the same // movement as their allowed list of movements or if they have a separate list for that final boolean isMovementCapturable = entity.isMovementCapturable(); // Holds the list of regular movements and capturable movements which // are movements outside the general scope of a normal movement List<EntityMovements[]> movements = entity.getMovements(); List<EntityMovements[]> capturableMovements = new ArrayList(); // If this entity is an entity where its movements are different // from it's actual capture movements then add those into a separate // list so we can differentiate between both of them if(!isMovementCapturable) { capturableMovements.addAll(entity.getCapturableBoardMovements()); movements.addAll(capturableMovements); } // Go through the list of path movements for the entity for(EntityMovements[] movementPath : movements) { TileModel traverser = tileModel; do { // Temporary list to hold our entire path, and from there I // pick the last element List<TileModel> tiles = new ArrayList(); for(EntityMovements movement : movementPath) { // Normalize the movement w.r.t the player of the entity movement = PlayerDirection.getNormalizedMovement(entity.getTeam().DIRECTION, movement); // Get the movements of the tile from our position traverser = _neighbors.get(traverser).get(movement); // If the position is outside the board dimensions then clear the movement to get // to that location and exit the loop if(traverser == null) { tiles.clear(); break; } // If the entity contains movements that differ from their capture movements // and we are trying to use a regular movement then this is not legal. // As an example, without this code a pawn could do a capture on it's two move // movement, or it could hop over another enemy pawn if(!isMovementCapturable && traverser.getEntity() != null && !capturableMovements.contains(movementPath)) { tiles.clear(); break; } // Add the traversed tile to our constructed path tiles.add(traverser); } if(tiles.isEmpty()) { break; } // Get the last tile within our path (the endpoint) TileModel destinationTile = tiles.get(tiles.size() - 1); // If the entity contains movements that differ from their capture movements // then ensure that if we are trying to capture an enemy player that it only // ever is allowed if the movement is within the capture movement list // that the entity holds // Note: This line of code looks a little similar to the one above in the second for-each, however // they both do completely different things however they are both related to differences of // how a piece moves and captures if(!isMovementCapturable && (destinationTile.getEntity() == null || destinationTile.getEntity().getTeam().equals(entity.getTeam())) && capturableMovements.contains(movementPath)) { break; } // if the end tile is ourselves then do not consider it and stop if(destinationTile.getEntity() != null && destinationTile.getEntity().getTeam().equals(entity.getTeam())) { break; } // Add the last tile into our list of valid tiles allMoves.put(destinationTile, movementPath); // If the tile has an enemy player on it then stop here // If the tile is not continuous then we do not need to // continue with the same move if((destinationTile.getEntity() != null && !destinationTile.getEntity().getTeam().equals(entity.getTeam())) || !entity.isMovementContinuous()) { break; } } while(true); } return allMoves; } /** * Gets the list of checked positions of the specified player * * @param player The player to check for checked positions * * @return The list of checked positions */ public List<TileModel> getCheckedPositions(PlayerModel player) { PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true); PlayerModel enemy = playerController.getPlayer(player.getTeam() == PlayerTeam.BLACK ? PlayerTeam.WHITE : PlayerTeam.BLACK); // The list of enemy owned tiles that are checked by the specified player List<TileModel> checkedEntities = new ArrayList(); // Get the list of checkable entities owned by the enemy player List<AbstractChessEntity> checkableEntities = player.getCheckableEntities(); // Go through the list of enemy entities and see if any of them // can move to a position of that which is in the checkable entities list above for(AbstractChessEntity enemyEntity : enemy.getEntities()) { Map<TileModel, EntityMovements[]> positions = getBoardPositionsImpl(enemyEntity.getTile()); for(Map.Entry<TileModel, EntityMovements[]> movement : positions.entrySet()) { if(checkableEntities.contains(movement.getKey().getEntity())) { checkedEntities.add(movement.getKey()); } } } return checkedEntities; } /** * Gets the En-Passent movements of the specified tile * * @param source The tile to get the moves from * * @return The mappings of available moves for the specified tile */ public Map<TileModel, EntityMovements[]> getEnPassentBoardPositions(TileModel source) { Map<TileModel, EntityMovements[]> movements = new HashMap(); // Verify if the passed in source is a valid tile for performing an en-passent move if(source == null || source.getEntity() == null || !source.getEntity().isEnPassent()) { return movements; } AbstractChessEntity entity = source.getEntity(); PlayerDirection direction = entity.getTeam().DIRECTION; // Left En-Passent EntityMovements enPassentLeft = PlayerDirection.getNormalizedMovement(direction, EntityMovements.LEFT); TileModel capturableEnPassentLeft = _neighbors.get(source).get(enPassentLeft); if(capturableEnPassentLeft != null && capturableEnPassentLeft.getEntity() != null && !capturableEnPassentLeft.getEntity().getTeam().equals(source.getEntity().getTeam()) && capturableEnPassentLeft.getEntity().isEnPassentCapturable()) { EntityMovements enPassentBackwards = PlayerDirection.getNormalizedMovement(capturableEnPassentLeft.getEntity().getTeam().DIRECTION, EntityMovements.DOWN); TileModel capturableEnPassentPosition = _neighbors.get(capturableEnPassentLeft).get(enPassentBackwards); movements.put( capturableEnPassentPosition, PlayerDirection.getNormalizedMovement(direction, new EntityMovements[] { EntityMovements.UP, EntityMovements.LEFT }) ); } // Right En-Passent EntityMovements enPassentRight = PlayerDirection.getNormalizedMovement(direction, EntityMovements.RIGHT); TileModel capturableEnPassentRight = _neighbors.get(source).get(enPassentRight); if(capturableEnPassentRight != null && capturableEnPassentRight.getEntity() != null && !capturableEnPassentRight.getEntity().getTeam().equals(source.getEntity().getTeam()) && capturableEnPassentRight.getEntity().isEnPassentCapturable()) { EntityMovements enPassentBackwards = PlayerDirection.getNormalizedMovement(capturableEnPassentRight.getEntity().getTeam().DIRECTION, EntityMovements.DOWN); TileModel capturableEnPassentPosition = _neighbors.get(capturableEnPassentRight).get(enPassentBackwards); movements.put( capturableEnPassentPosition, PlayerDirection.getNormalizedMovement(direction, new EntityMovements[] { EntityMovements.UP, EntityMovements.RIGHT }) ); } return movements; } /** * Gets the enemy tile associated to the specified tile * * @param tile The tile of the entity doing the en-passent * * @return The enemy tile */ public TileModel getEnPassentEnemy(TileModel tile) { for(Map.Entry<TileModel, EntityMovements[]> kvp : getEnPassentBoardPositions(tile).entrySet()) { TileModel enemy = _neighbors.get(kvp.getKey()).get(PlayerDirection.getNormalizedMovement(tile.getEntity().getTeam().DIRECTION, EntityMovements.DOWN)); if(enemy.getEntity() != null && enemy.getEntity().isEnPassentCapturable()) { return enemy; } } return null; } /** * Verifies if a movement from the specified tile to the specified tile * will result in a check of the specified player * * @param player The player to verify for being in check * @param from The starting tile position * @param to The end tile position * * @return TRUE If the move would result in a check of the specified player, FALSE otherwise */ public boolean isMoveChecked(PlayerModel player, TileModel from, TileModel to) { // Hold temporary references to both entities of the tiles AbstractChessEntity tempEntityFrom = from.getEntity(); AbstractChessEntity tempEntityTo = to.getEntity(); // Suppress the update events for both tiles from.setSuppressUpdates(true); to.setSuppressUpdates(true); // Perform the logical steps of a movement from.setEntity(null); to.setEntity(null); to.setEntity(tempEntityFrom); PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true); // If there is a player piece there, then remove it from the player // temporarily if(tempEntityTo != null) { PlayerModel myPlayer = playerController.getPlayer(tempEntityTo.getTeam()); myPlayer.removeEntity(tempEntityTo); } // Check if the player is now in check List<TileModel> checkedPositions = getCheckedPositions(player); // Set back the piece belonging to the player of the 'to entity' if(tempEntityTo != null) { PlayerModel myPlayer = playerController.getPlayer(tempEntityTo.getTeam()); myPlayer.addEntity(tempEntityTo); } // Put back the entities into their tiles to.setEntity(null); from.setEntity(tempEntityFrom); to.setEntity(tempEntityTo); // Remove the suppressed flags from both tiles from.setSuppressUpdates(false); to.setSuppressUpdates(false); // Indicate if there were any checked positions found return !checkedPositions.isEmpty(); } /** * Links together the passed in rows * * @param topRow The top row * @param neutralRow the neutral row * @param bottomRow The bottom row */ private void linkTiles(TileModel[] topRow, TileModel[] neutralRow, TileModel[] bottomRow) { for(int i = 0, columns = _dimensions.width; i < columns; ++i) { // Represents the structural view of a particular tile Map<EntityMovements, TileModel> neighbors = new HashMap<EntityMovements, TileModel>(); // Populate the neighbors structure with the movement elements // Note: Diagonals can be fetched using these primitives neighbors.put(EntityMovements.UP, topRow == null ? null : topRow[i]); neighbors.put(EntityMovements.LEFT, i - 1 < 0 ? null : neutralRow[i - 1]); neighbors.put(EntityMovements.RIGHT, i + 1 >= columns ? null : neutralRow[i + 1]); neighbors.put(EntityMovements.DOWN, bottomRow == null ? null : bottomRow[i]); // Assign the mappings where we reference the neutral-neutral tile as the key _neighbors.put(neutralRow[i], neighbors); } } }<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package views.controls; import javax.swing.JButton; import game.entities.concrete.AbstractChessEntity; /** * A button class with the capability of caching data related to the abstract chess entity * * @author <NAME> {@literal <<EMAIL>>} * */ public class PromotionButton extends JButton { /** * The abstract chess entity associated to this button */ private AbstractChessEntity _entity; /** * Sets the chess entity * * @param entity The chess entity to set */ public void setChessEntity(AbstractChessEntity entity) { _entity = entity; } /** * Gets the chess entity * * @return The chess entity of this button */ public AbstractChessEntity getChessEntity() { return _entity; } }<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package menu; import java.awt.event.ActionEvent; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import engine.communication.internal.signal.arguments.SignalEventArgs; import engine.core.factories.AbstractFactory; import engine.core.factories.AbstractSignalFactory; import engine.core.factories.ViewFactory; import engine.core.menu.types.MenuItem; import resources.Resources; import resources.Resources.ResourceKeys; import views.TileView; /** * The item for debugging neighboring tiles based * * @author {@literal <NAME> <<EMAIL>>} * */ public class NeighboursItem extends MenuItem { /** * Constructs a new instance of this type * * @param parent The parent representing this item */ public NeighboursItem(JComponent parent) { // Create the menu item super(new JCheckBoxMenuItem(Resources.instance().getLocalizedString(ResourceKeys.NeighborTiles)), parent); } @Override protected void onReset() { super.onReset(); super.get(JCheckBoxMenuItem.class).setSelected(false); } @Override public void onExecute(ActionEvent actionEvent) { // Get the desired signal to be sent out String signal = get(JCheckBoxMenuItem.class).isSelected() ? TileView.EVENT_SHOW_NEIGHBORS : TileView.EVENT_HIDE_NEIGHBORS; // Send out a signal to all tile views to let them // know what to do for this debug mode AbstractFactory.getFactory(ViewFactory.class).multicastSignal( TileView.class, new SignalEventArgs(this, signal) ); } @Override public boolean enabled() { return AbstractSignalFactory.isRunning(); } }<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package controllers; import java.util.HashMap; import java.util.Map; import javax.swing.DefaultComboBoxModel; import engine.core.factories.AbstractFactory; import engine.core.factories.ControllerFactory; import engine.core.mvc.controller.BaseController; import game.entities.concrete.AbstractChessEntity; import generated.DataLookup; import generated.DataLookup.DataLayerName; import models.PlayerModel; import models.PlayerModel.PlayerTeam; import models.TileModel; import views.DebuggerSettingsView; /** * The controller associated to the debugger view * * @author <NAME> {@literal <<EMAIL>>} * */ public final class DebuggerSettingsController extends BaseController { /** * The memory mappings for keeping track of the last saved debugger state */ private final Map<PlayerTeam, Map<AbstractChessEntity, TileModel>> _memory = new HashMap(); /** * The list of entities */ public final DefaultComboBoxModel<DataLayerName> _entityCollection = new DefaultComboBoxModel(DataLookup.DataLayerName.values()); /** * The list of player teams */ public final DefaultComboBoxModel<PlayerTeam> _teamCollection = new DefaultComboBoxModel(PlayerModel.PlayerTeam.values()); /** * Constructs a new instance of this class type * * @param view The view associated to this controller * */ public DebuggerSettingsController(DebuggerSettingsView view) { super(view); // This hack removes unneeded layer name options _entityCollection.removeElement(DataLayerName.WHITE); _entityCollection.removeElement(DataLayerName.BLACK); } /** * Gets the entity collections * * @return The entity collection */ public DefaultComboBoxModel getEntityCollection() { return _entityCollection; } /** * Gets the team collections * * @return The team collection */ public DefaultComboBoxModel getTeamCollection() { return _teamCollection; } /** * Gets the currently selected entity value * * @return The currently selected entity value */ public DataLayerName getSelectedEntityItem() { Object selectedItem = _entityCollection.getSelectedItem(); return selectedItem != null && selectedItem instanceof DataLayerName ? (DataLayerName)selectedItem : null; } /** * Gets the currently selected team value * * @return The currently selected team value */ public PlayerTeam getSelectedTeamItem() { Object selectedItem = _teamCollection.getSelectedItem(); return selectedItem != null && selectedItem instanceof PlayerTeam ? (PlayerTeam)selectedItem : null; } /** * Performs a memory clear of the memory structure */ public void memoryClear() { _memory.clear(); } /** * Performs a memory recall of the current memory structure */ public void memoryRecall() { // Clear the board of its contents BoardController boardController = AbstractFactory.getFactory(ControllerFactory.class).get(BoardController.class); boardController.clearBoard(); // Get the player controller PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class); for(Map.Entry<PlayerTeam, Map<AbstractChessEntity, TileModel>> entry1 : _memory.entrySet()) { for(Map.Entry<AbstractChessEntity, TileModel> entry2 : entry1.getValue().entrySet()) { entry2.getValue().setEntity(entry2.getKey()); playerController.getPlayer(entry1.getKey()).addEntity(entry2.getKey()); } } } /** * Performs a memory store of the current state of the memory structure */ public void memoryStore() { // Clear the contents of the store memoryClear(); // Get the player controller PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class); // Go through the list of teams to perform the insertion for(PlayerTeam team : PlayerTeam.values()) { // Create a new entry for this team Map<AbstractChessEntity, TileModel> entry = new HashMap<AbstractChessEntity, TileModel>(); // Go through the entities of this player and insert each of them into the entry list for(AbstractChessEntity entity : playerController.getPlayer(team).getEntities()) { entry.put(entity, entity.getTile()); } // Insert the entry into the global memory list _memory.put(team, entry); } } @Override public void unregisterSignalListeners() { super.unregisterSignalListeners(); memoryClear(); } @Override public String toString() { // Create a string builder to store our strings StringBuilder builder = new StringBuilder(); // Go through the maps teams for(Map.Entry<PlayerTeam, Map<AbstractChessEntity, TileModel>> entry1 : _memory.entrySet()) { // Add the team name builder.append(entry1.getKey().toString() + "\n"); // Go through the mapping of chess entities and tile models and append them // into the string builder for(Map.Entry<AbstractChessEntity, TileModel> entry2 : entry1.getValue().entrySet()) { builder.append("Piece " + entry2.getKey().toString() + " is position on tile number " + entry2.getValue().toString() + "\n"); } } // Return the string return builder.toString(); } }<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package game.entities.concrete; import java.util.List; import game.core.AbstractEntity; import game.entities.interfaces.IChessEntity; import generated.DataLookup.DataLayerName; import models.PlayerModel; import models.PlayerModel.PlayerTeam; import models.TileModel; /** * This class represents the abstract functionality of a chess piece in the game * * @author <NAME> {@literal <<EMAIL>>} */ public abstract class AbstractChessEntity extends AbstractEntity implements IChessEntity { /** * The checked state of this entity */ private boolean _isChecked; /** * The check mate state of this entity */ private boolean _isCheckMated; /** * The player that owns this entity */ private PlayerModel _player; /** * The tile model that the chess entity is associated to */ private TileModel _tileModel; /** * Indicates if the pawn has moved at least once */ private boolean _hasMovedOnce = false; /** * Constructs a new instance of this class type * * @param dataLayerName The name of the layer */ protected AbstractChessEntity(DataLayerName dataLayerName) { super(dataLayerName.toString()); } /** * Creates an instance of a chess entity with respect to the provided data layer name * * @param dataLayerName The data layer name lookup * * @return A chess entity */ public static AbstractChessEntity createEntity(DataLayerName dataLayerName) { switch(dataLayerName) { case BISHOP: return new BishopEntity(); case KING: return new KingEntity(); case KNIGHT: return new KnightEntity(); case PAWN: return new PawnEntity(); case QUEEN: return new QueenEntity(); case ROOK: return new RookEntity(); default: return null; } } /** * Sets the specified player to this entity * * @param player The player to set to this entity */ public void setPlayer(PlayerModel player) { if(player != _player) { _player = player; List<String> names = getDataNames(); for(String name : names) { if(player.getDataValues().stream().anyMatch(z -> z.toString().equalsIgnoreCase(name))) { setActiveData(name); break; } } } } /** * Sets the tile model to associate to this chess entity * * @param tileModel The tile model */ public final void setTile(TileModel tileModel) { _tileModel = tileModel; } /** * Gets the tile model associated to this chess entity * * @return The tile model */ public final TileModel getTile() { return _tileModel; } /** * Gets the data layer name of this entity * * @return The data layer name from the data lookup table */ public final DataLayerName getDataLayerName() { return DataLayerName.valueOf(getLayerName()); } /** * @return The team of the player associated to this chess entity */ public final PlayerTeam getTeam() { return _player.getTeam(); } /** * Returns the player associated to this chess entity * * @return The player associated to this chess entity */ public final PlayerModel getPlayer() { return _player; } /** * Gets if the chess entity has moved at least once * * @return If the chess entity has moved at least once */ public final boolean hasMovedOnce() { return _hasMovedOnce; } /** * Sets if the chess piece has moved at least once. Once this is set to true * it can no longer be set back to false * * @param hasMovedOnce If the chess entity has moved at least once * */ public final void setHasMoved(boolean hasMovedOnce) { if(!_hasMovedOnce) { _hasMovedOnce = hasMovedOnce; } } /** * Sets the checked state of this entity * * Note: If this entity is not checkable then it will not matter if you * set the checked state * * @param isChecked The checked state */ public final void setChecked(boolean isChecked) { _isChecked = isChecked; } /** * Sets the check mate state of this entity * * Note: If this entity is not checkable then it will not matter if you * set the checked state * * @param isCheckMate The check mate state */ public final void setCheckMate(boolean isCheckMate) { _isCheckMated = isCheckMate; } /** * Gets the check mate state of this entity * * @return The check mate state of this entity */ public final boolean getIsCheckMate() { return getIsCheckable() && _isCheckMated; } /** * Gets the checked state of this entity * * @return The checked state of this entity */ public final boolean getIsChecked() { return getIsCheckable() && _isChecked; } @Override public void refresh() { _tileModel.refresh(); } }<file_sep>/** * <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package menu; import java.awt.event.ActionEvent; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import engine.core.menu.types.MenuItem; import resources.Resources; import resources.Resources.ResourceKeys; public class AboutItem extends MenuItem { public AboutItem(JComponent parent) { super(new JMenuItem(Resources.instance().getLocalizedString(ResourceKeys.About)), parent); } @Override public void onExecute(ActionEvent actionEvent) { JOptionPane.showMessageDialog( null, "https:/github.com/danielricci/Chess", Resources.instance().getLocalizedString(ResourceKeys.AboutMessage), JOptionPane.INFORMATION_MESSAGE ); } }
39a97e63be98bd6d92418e8fda48a44b6007d8de
[ "Markdown", "Java", "INI" ]
12
Java
danielricci/Chess
5d3fd5939ad04c44104be321ea885c65cc72485e
a975473429d8f2005bc292a18952b0fa590cda43
refs/heads/master
<repo_name>JaimeJacobo/practicing_node<file_sep>/playground/1-json.js const fs = require('fs') // const book = { // title: 'Ego is the Enemy', // author: '<NAME>' // } // const bookJSON = JSON.stringify(book) // fs.writeFileSync('1-json.json', bookJSON) //1. Read the file as buffer info const dataBuffer = fs.readFileSync('1-json.json'); //2. Convert the buffer info into JSON data(string) const dataJSON = dataBuffer.toString(); //3. Parse the JSON data const data = JSON.parse(dataJSON) //4. I change some value of the JSON file data.name = 'Lamata' //5. I stringify the new data and re-write it in the original JSON file //(Para sobreescribir un JSON file primero tenemos que "stringify it", y luego lo sobreescribimos) fs.writeFileSync('1-json.json', JSON.stringify(data)) // Instrucciones para coger un .json file y poderlo usar en nuestro js: // const dataBuffer = fs.readFileSync('1-json.json'); // const dataJSON = dataBuffer.toString(); // const data = JSON.parse(dataJSON) //Instrucciones para sobreescribir un .json // fs.writeFileSync('1-json.json', JSON.stringify(data)) <file_sep>/notes-app/app.js const validator = require('validator'); const chalk = require('chalk'); const yargs = require('yargs'); //Notes is an object that has the info of notes.js const notes = require('./notes.js'); //Create add command yargs.command({ command: 'add', describe: 'Add a new note', builder: { title: { describe: 'Note title', demandOption: true, type: 'string' }, body: { describe: 'Note of the book', demandOption: true, type: 'string' } }, handler(builder){ notes.addNote(builder.title, builder.body) } }) //Create remove command yargs.command({ command: 'remove', describe: 'Removing a note', builder: { title: { describe: 'Note title', demandOption: true, type: 'string' } }, handler(builder){ notes.removeNote(builder.title) } }) //Create list command yargs.command({ command: 'list', describe: 'Showing the list', handler(){ notes.listNotes(); } }) //Create read command yargs.command({ command: 'read', describe: 'Reading the list', builder: { title: { describe: 'note title', demandOption: true, type: 'string' } }, handler(builder){ notes.readNote(builder.title) } }) yargs.parse()<file_sep>/notes-app/notes.js const chalk = require('chalk'); const fs = require('fs') const addNote = (title, body) =>{ const data = loadNotes(); const duplicateNote = data.find((eachData)=>{ return eachData.title === title }) if(!duplicateNote){ data.push({ title: title, body: body }) updateData(data) } else { console.log(chalk.bgRed('Note title taken')) } }; const removeNote = (title)=>{ const data = loadNotes(); let filteredArray = data.filter((eachNote)=>{ return title !== eachNote.title }); if(data.length === filteredArray.length){ console.log(chalk.bgRed('There is no note with that title')) } else { updateData(filteredArray); console.log(chalk.bgGreen.black('Note removed succesfully')); } }; const listNotes = ()=>{ const data = loadNotes(); console.log(chalk.bgMagenta.black('Your notes')) data.forEach((note)=>{ console.log(note.title) }); } const readNote = (title)=>{ const data = loadNotes(); console.log(title) const matchedNote = data.find((eachData)=>{ return title === eachData.title }) if(matchedNote){ console.log(chalk.cyan('Title: ' + matchedNote.title.toUpperCase())) console.log(chalk.magenta('Body: ' + matchedNote.body)) } else { console.log(chalk.red('There is no note with that name title')) } } const loadNotes = () =>{ //If the JSON file already exists, use it try { const dataBuffer = fs.readFileSync('notes.json'); const dataJSON = dataBuffer.toString(); const data = JSON.parse(dataJSON); return data; //If the JSON file does not exist, return an empty array } catch (error){ console.log(chalk.red('The JSON file did not exist, but it is now created.')) return [] } } const updateData = (newData) =>{ fs.writeFileSync('notes.json', JSON.stringify(newData)) } //This modules are being exported as 'notes' module.exports = { addNote: addNote, removeNote: removeNote, listNotes: listNotes, readNote: readNote }
35574e499202f247947233a9e3fb8f698b957260
[ "JavaScript" ]
3
JavaScript
JaimeJacobo/practicing_node
6e0567842b0d8a119bae1cfb429642117088fdbc
924b4fd2946430c006403dc15ade2d7fc29450a5
refs/heads/master
<file_sep>#ifndef Parameters_class #define Parameters_class class Parameters{ public: int lx, ly, ns, orbs, IterMax, MCNorm, RandomSeed; int TBC_mx, TBC_my; int TBC_cellsX, TBC_cellsY; int lx_cluster, ly_cluster; double mus, mus_Cluster, Fill,pi,J_NN,J_NNN,J_HUND,k_const,lamda_12,lamda_66; bool Cooling_; bool ED_; bool Metropolis_Algorithm; bool Heat_Bath_Algorithm; /* SavingMicroscopicStates=1 NoOfMicroscopicStates=50 */ bool Saving_Microscopic_States; int No_Of_Microscopic_States; double temp_max, beta_min; double temp_min, beta_max; double d_Temp; int Last_n_sweeps_for_measurement; int Measurement_after_each_m_sweeps; double temp,beta,Eav,maxmoment; double WindowSize, AccCount[2]; char Dflag; void Initialize(string inputfile_); double matchstring(string file,string match); }; void Parameters::Initialize(string inputfile_){ maxmoment=1.0; double cooling_double; double metropolis_double; double ED_double; int SavingMicroscopicStates_int; cout << "____________________________________" << endl; cout << "Reading the inputfile: " << inputfile_ << endl; cout << "____________________________________" << endl; lx = int(matchstring(inputfile_,"Xsite")); ly = int(matchstring(inputfile_,"Ysite")); TBC_mx = int(matchstring(inputfile_,"TwistedBoundaryCond_mx")); TBC_my = int(matchstring(inputfile_,"TwistedBoundaryCond_my")); TBC_cellsX = int(matchstring(inputfile_,"TBC_cellsX")); TBC_cellsY = int(matchstring(inputfile_,"TBC_cellsY")); lx_cluster = int(matchstring(inputfile_,"Cluster_lx")); ly_cluster = int(matchstring(inputfile_,"Cluster_ly")); SavingMicroscopicStates_int = int (matchstring(inputfile_,"SavingMicroscopicStates")); assert(SavingMicroscopicStates_int==1 || SavingMicroscopicStates_int==0); if(SavingMicroscopicStates_int==1){ Saving_Microscopic_States=true; } else{ Saving_Microscopic_States=false; } No_Of_Microscopic_States = int(matchstring(inputfile_,"NoOfMicroscopicStates")); ns = lx*ly; cout << "TotalNumberOfSites = "<< ns << endl; orbs = int(matchstring(inputfile_,"Orbitals")); Fill = matchstring(inputfile_,"Fill"); cout << "TotalNumberOfParticles = "<< ns*Fill*orbs*2.0 << endl; IterMax = int(matchstring(inputfile_,"MaxMCsweeps")); MCNorm = 0.0; ; //matchstring(inputfile,"MCNorm") RandomSeed = matchstring(inputfile_,"RandomSeed"); Dflag = 'N'; J_NN=double(matchstring(inputfile_,"J_NN")); J_NNN=double(matchstring(inputfile_,"J_NNN")); J_HUND=double(matchstring(inputfile_,"J_HUND")); metropolis_double=double(matchstring(inputfile_,"Metropolis_Algo")); if(metropolis_double==1.0){ Metropolis_Algorithm=true; Heat_Bath_Algorithm=false; } else if(metropolis_double==0.0){ Metropolis_Algorithm=false; Heat_Bath_Algorithm=true; } else{ cout<<"ERROR: Metropolis_Algo can be only 1 (true) or 0 (false)"<<endl; assert(metropolis_double==0.0); } cooling_double=double(matchstring(inputfile_,"Cooling")); if(cooling_double==1.0){ Cooling_=true; temp_min = double(matchstring(inputfile_,"Temperature_min")); temp_max = double(matchstring(inputfile_,"Temperature_max")); d_Temp = double(matchstring(inputfile_,"dTemperature")); beta_max=double(11604.0/ temp_min); beta_min=double(11604.0/ temp_max); } else if(cooling_double==0.0){ Cooling_=false; temp = double(matchstring(inputfile_,"Temperature")); // temperature in kelvin beta=double(11604.0/ temp); //Beta which is (T*k_b)^-1 temp_min = temp; temp_max = temp; d_Temp=10.0;//arbitrary positive number } else{ cout<<"ERROR: Cooling can be only 1 (true) or 0 (false)"<<endl; assert(cooling_double==0.0); } ED_double=double(matchstring(inputfile_,"Perform_ED")); if(ED_double==1.0){ ED_=true; lx_cluster=lx; ly_cluster=ly; } else if(ED_double==0.0){ ED_=false; } else{ cout<<"ERROR: Perform_ED can be only 1 (true) or 0 (false)"<<endl; assert(ED_double==0.0); } Last_n_sweeps_for_measurement=int(matchstring(inputfile_,"Last_n_sweeps_for_measurement")); Measurement_after_each_m_sweeps=int(matchstring(inputfile_,"Measurement_after_each_m_sweeps")); pi=4.00*atan(double(1.0)); Eav=0.0; AccCount[0]=0; AccCount[1]=0; WindowSize=double(0.01); mus=0.25; cout << "____________________________________" << endl; } double Parameters::matchstring(string file,string match) { string test; string line; ifstream readFile(file); double amount; bool pass=false; while (std::getline(readFile, line)) { std::istringstream iss(line); if (std::getline(iss, test, '=') && pass==false) { // --------------------------------- if (iss >> amount && test==match) { // cout << amount << endl; pass=true; } else { pass=false; } // --------------------------------- if(pass) break; } } if (pass==false) { string errorout=match; errorout+="= argument is missing in the input file!"; throw std::invalid_argument(errorout); } cout << match << " = " << amount << endl; return amount; } #endif <file_sep>#include <math.h> #include "tensor_type.h" #include "ParametersEngine.h" #include "Coordinates.h" #include "random" #include <stdlib.h> #define PI acos(-1.0) #ifndef MFParams_class #define MFParams_class class MFParams{ public: // Define Fields Matrix<double> etheta, ephi; Matrix<double> etheta_avg, ephi_avg; // Constructor MFParams(Parameters& Parameters__, Coordinates& Coordinates__, mt19937_64& Generator__) :Parameters_(Parameters__),Coordinates_(Coordinates__), Generator_(Generator__) { //setupm_arr(); initialize(); } double random(); void FieldThrow(int site); void initialize(); void Adjust_MCWindow(); void Calculate_Fields_Avg(); void Read_classical_DOFs(string filename); Parameters &Parameters_; Coordinates &Coordinates_; mt19937_64 &Generator_; int lx_,ly_,ns_; uniform_real_distribution<double> dis_; //mt19937_64 mt_rand(Parameters_.RandomSeed); }; void MFParams::Adjust_MCWindow(){ double ratio; ratio=Parameters_.AccCount[0]/(Parameters_.AccCount[0]+Parameters_.AccCount[1]); //cout<<"ratio= "<< ratio << "temp= "<<Parameters_.temp << endl; Parameters_.AccCount[0]=0; Parameters_.AccCount[1]=0; Parameters_.WindowSize *= abs(1.0 + 1.0*(ratio-0.5)); //Parameters_.WindowSize =1.0; cout << "Ratio: " << ratio << " window size: "<<Parameters_.WindowSize<< endl; return; } // ---------- void MFParams::FieldThrow(int site){ int a,b; double Pi=Parameters_.pi; double MC_Window = Parameters_.WindowSize; a=Coordinates_.indx(site); b=Coordinates_.indy(site); ephi(a,b) += 2*Pi*(random()-0.5)*MC_Window; if( ephi(a,b) < 0.0) {ephi(a,b) += 2.0*Pi; } if( ephi(a,b) >=2.0*Pi) {ephi(a,b) -= 2.0*Pi;} etheta(a,b) += Pi*(random()-0.5)*MC_Window; if ( etheta(a,b) < 0.0 ) { etheta(a,b) = - etheta(a,b); ephi(a,b) = fmod( ephi(a,b)+Pi, 2.0*Pi ); } if ( etheta(a,b) > Pi ) { etheta(a,b) -= 2.0*Pi ; ephi(a,b) = fmod( ephi(a,b) + Pi, 2.0*Pi ); } } // ---------- double MFParams::random(){ /* double random_double; random_double=(rand()%RAND_MAX); random_double=random_double/RAND_MAX; return random_double; */ return dis_(Generator_); } void MFParams::initialize(){ lx_=Coordinates_.lx_; ly_=Coordinates_.ly_; // srand(Parameters_.RandomSeed); etheta_avg.resize(lx_,ly_); ephi_avg.resize(lx_,ly_); etheta.resize(lx_,ly_); ephi.resize(lx_,ly_); for(int j=0;j<ly_;j++){ for(int i=0;i<lx_;i++){ //ephi(i,j)=(0.5+0.5*pow(-1.0f,i))*Parameters_.pi + grnd()*0.2; //etheta(i,j)=0.5*Parameters_.pi + grnd()*0.2; //q=(pi,pi) // ephi(i,j)=0.0; //(0.5+0.5*pow(-1.0f,i))*Parameters_.pi + grnd()*0.2; // etheta(i,j)=0.5*(pow(-1.0,j+i) + 1.0 )*PI ;//+ grnd()*0.2; //q=(0,pi) //ephi(i,j)=0.0; //(0.5+0.5*pow(-1.0f,i))*Parameters_.pi + grnd()*0.2; //etheta(i,j)=0.5*(pow(-1.0,j) + 1.0 )*PI; //+ grnd()*0.2; //q=(0,0) // ephi(i,j)=0.0; //(0.5+0.5*pow(-1.0f,i))*Parameters_.pi + grnd()*0.2; // etheta(i,j)=0.0; //+ grnd()*0.2; //RANDOM ephi(i,j)=2.0*random()*PI; etheta(i,j)=random()*PI; } } } // ---------- void MFParams::Calculate_Fields_Avg(){ for(int j=0;j<ly_;j++){ for(int i=0;i<lx_;i++){ ephi_avg(i,j)= ephi_avg(i,j) + ephi(i,j); etheta_avg(i,j)=etheta_avg(i,j) + etheta(i,j) ; } } } // ---------- void MFParams::Read_classical_DOFs(string filename){ string tmp_str; double tmp_double; ifstream fl_in(filename.c_str()); fl_in >> tmp_str; for(int i=0;i<lx_;i++){ for(int j=0;j<ly_;j++){ fl_in>>tmp_double>>tmp_double>>etheta(i,j)>>ephi(i,j); } } } // ---------- #endif <file_sep>#include "ParametersEngine.h" #include "Coordinates.h" #include "MFParams.h" #include "Hamiltonian.h" #include "Observables.h" #include "tensor_type.h" #ifndef MCENGINE_H #define MCENGINE_H class MCEngine{ public: MCEngine(Parameters& Parameters__, Coordinates& Coordinates__, MFParams& MFParams__, Hamiltonian& Hamiltonian__, Observables& Observables__) : Parameters_(Parameters__),Coordinates_(Coordinates__), MFParams_(MFParams__), Hamiltonian_(Hamiltonian__), Observables_(Observables__), lx_(Parameters_.lx), ly_(Parameters_.ly), ns_(Parameters_.ns), orbs_(Parameters_.orbs), ED_(Parameters_.ED_) { } void RUN_MC(); double Prob (double muu, double mu_new); double ProbCluster (double muu, double mu_new); Parameters &Parameters_; Coordinates &Coordinates_; MFParams &MFParams_; Hamiltonian &Hamiltonian_; Observables &Observables_; const int lx_, ly_, ns_, orbs_; bool ED_; }; /* * *********** * Functions in Class MCEngine ------ * *********** */ void MCEngine::RUN_MC(){ complex<double> zero(0.0,0.0); bool Metropolis_Algo = Parameters_.Metropolis_Algorithm; bool Heat_Bath_Algo = Parameters_.Heat_Bath_Algorithm; int MC_sweeps_used_for_Avg=Parameters_.Last_n_sweeps_for_measurement; int Gap_bw_sweeps = Parameters_.Measurement_after_each_m_sweeps; double PrevE,CurrE,P_new,P12,muu_prev; double muu_prevCluster; double Curr_QuantE; double Prev_QuantE; double Curr_QuantECluster; double Prev_QuantECluster; int x,y,act; double saved_Params[2]; string File_Out_progress; string File_Out_theta_phi; double temp_=Parameters_.temp_max; double initial_mu_guess; int n_states_occupied_zeroT; double Curr_Cluster_CLE; //starting with a random guess while(temp_>=Parameters_.temp_min){ cout << "Temperature = " << temp_<<" is being done"<<endl; Parameters_.temp=temp_; Parameters_.beta=double(11604.0/temp_); for(int ix=0;ix<lx_;ix++){ for(int iy=0;iy<ly_;iy++){ Observables_.SiSjQ_Mean_(ix,iy)=zero; Observables_.SiSjQ_square_Mean_(ix,iy)=zero; Observables_.SiSj_square_Mean_(ix,iy)=0.0; Observables_.SiSj_Mean_(ix,iy)=0.0; } } Observables_.AVG_Total_Energy=0.0; Observables_.AVG_Total_Energy_sqr=0.0; Observables_.Nematic_order_square_mean_=0.0; Observables_.Nematic_order_mean_=0.0; MFParams_.etheta_avg.fill(0.0); MFParams_.ephi_avg.fill(0.0); char temp_char[50]; sprintf(temp_char,"%.1f",temp_); File_Out_progress = "output_Temp" + string(temp_char) + ".txt"; ofstream file_out_progress(File_Out_progress.c_str()); File_Out_theta_phi = "ThetaPhi_Temp" + string(temp_char) + ".txt"; ofstream File_Out_Theta_Phi(File_Out_theta_phi.c_str()); file_out_progress<< "Total "<<Parameters_.IterMax<<" sweeps are performed."<<endl; file_out_progress<<"First "<<Parameters_.IterMax - (Gap_bw_sweeps*(MC_sweeps_used_for_Avg - 1) + MC_sweeps_used_for_Avg)<< " sweeps are used for thermalization and every "<<Gap_bw_sweeps+1<<" in last "<< Gap_bw_sweeps*(MC_sweeps_used_for_Avg - 1) + MC_sweeps_used_for_Avg<< " sweeps are used for measurement."<<endl; act=1; Parameters_.WindowSize = 0.1; //2f + 0.003f*beta0 ; Parameters_.Eav=0.0; Parameters_.MCNorm=0; Parameters_.Dflag='N'; // flag to calculate only Eigenvalue //std::string name="Output/Conf_" + to_string(ltemp) + ".dat"; //Parameters_.beta = double(11604.0/ (Parameters_.temp +20.0) ); //cout << "TEMP " << Parameters_.temp << endl; file_out_progress<<"I_MC"<<setw(15)<<"S(0,1)"<<setw(15)<<"S(1,0)" <<setw(15)<<"S(0,Pi)"<<setw(15)<<"S(Pi,0)"<<setw(17)<<"S(0,0)"<<setw(17)<<"S(Pi,Pi)"<<setw(17)<< "S(Pi/2,Pi/2)"<<setw(17)<<"< N_total >" <<setw(15)<<"E_CL"<<setw(15)<<"E_QM"<<setw(15)<<"mu"<< endl; PrevE = Hamiltonian_.GetCLEnergy(); Hamiltonian_.InteractionsCreate(); Hamiltonian_.Diagonalize(Parameters_.Dflag); n_states_occupied_zeroT=Parameters_.ns*Parameters_.Fill*Parameters_.orbs*2.0; initial_mu_guess=0.5*(Hamiltonian_.eigs_[n_states_occupied_zeroT-1] + Hamiltonian_.eigs_[n_states_occupied_zeroT]); //initial_mu_guess=0.25; Parameters_.mus=Hamiltonian_.chemicalpotential(initial_mu_guess,Parameters_.Fill); Prev_QuantE = Hamiltonian_.E_QM(); muu_prev=Parameters_.mus; Hamiltonian_.copy_eigs(1); cout<<"Initial Classical Energy[Full System] = "<<PrevE<<endl; cout<<"Initial Quantum Energy[Full System] = "<<Prev_QuantE<<endl; cout<<"Initial Total Energy[Full System] = "<<PrevE+Prev_QuantE<<endl; cout<<"Initial mu="<<muu_prev<<endl; //for(int i=0;i<10;i++){ // cout<<i<<" "<<Hamiltonian_.eigs_[i]<<endl; // } int Confs_used=0; int measure_start=0; muu_prevCluster=muu_prev; if(ED_){ Prev_QuantECluster=Prev_QuantE; Hamiltonian_.eigsCluster_saved_=Hamiltonian_.eigs_saved_; } for(int count=0;count<Parameters_.IterMax;count++){ //if (count == 1){ // Parameters_.beta = double(11604.0/ Parameters_.temp); // PrevE = Hamiltonian_.GetCLEnergy(); // Hamiltonian_.InteractionsCreate(); // Hamiltonian_.Diagonalize(Parameters_.Dflag); // Hamiltonian_.copy_eigs(1); //muu = Hamiltonian_.chemicalpotential(Parameters_.mus,Parameters_.Fill); //Parameters_.mus = Parameters_.mus*0.4f + muu*0.6f; // } for(int i=0;i<ns_;i++) { // For each site //***Before change*************// if(ED_==false){ //TCA is used PrevE = Hamiltonian_.GetCLEnergy(); if(Parameters_.J_HUND !=0.0){ Hamiltonian_.InteractionsClusterCreate(i); Hamiltonian_.DiagonalizeCluster(Parameters_.Dflag); //n_states_occupied_zeroT=Parameters_.Fill*Hamiltonian_.eigsCluster_.size(); //initial_mu_guess=0.5*(Hamiltonian_.eigsCluster_[n_states_occupied_zeroT-1] + HamiltonianCluster_.eigs_[n_states_occupied_zeroT]) muu_prevCluster=Hamiltonian_.chemicalpotentialCluster(muu_prevCluster,Parameters_.Fill); Prev_QuantECluster = Hamiltonian_.E_QMCluster(); Hamiltonian_.copy_eigs_Cluster(1); } else{ assert(Parameters_.J_HUND==0.0); Parameters_.mus_Cluster=0.0; Curr_QuantECluster=0.0; } } else{ assert(ED_); } //*******************************// x=Coordinates_.indx(i); y=Coordinates_.indy(i); saved_Params[0]=MFParams_.etheta(x,y); saved_Params[1]=MFParams_.ephi(x,y); MFParams_.FieldThrow(i); CurrE = Hamiltonian_.GetCLEnergy(); if(Parameters_.J_HUND !=0.0){ Hamiltonian_.InteractionsClusterCreate(i); Hamiltonian_.DiagonalizeCluster(Parameters_.Dflag); Parameters_.mus_Cluster=Hamiltonian_.chemicalpotentialCluster(muu_prevCluster,Parameters_.Fill); Curr_QuantECluster = Hamiltonian_.E_QMCluster(); } else{ assert(Parameters_.J_HUND==0.0); Parameters_.mus_Cluster=0.0; Curr_QuantECluster=0.0; } //Ratio of Quantum partition functions /*P = [ Tr(exp(-beta(Hquant_new)))/Tr(exp(-beta(Hquant_old)))]* [exp(-beta*E_classical(New)) / exp(-beta*E_classical(old))] * [sin(Theta_i(New)) / sin(Theta_i(Old)) ]*/ /*exp(P12) = P P12 = log (P) */ //same mu-refrence is used, otherwise engine does not work properly if(Parameters_.J_HUND !=0.0){ P_new = ProbCluster(muu_prev, muu_prev); } else{ P_new = 0.0; } P12 = P_new - Parameters_.beta*((CurrE)-(PrevE)); //P12 = - Parameters_.beta*((CurrE)-(PrevE)); //cout<<P12<<endl; P12 += log ((sin(MFParams_.etheta(x,y))/sin(saved_Params[0]))); //---OR--- //P12 = exp(-Parameters_.beta*((CurrE+Curr_QuantE)-(PrevE+Prev_QuantE))); //P12*= (sin(MFParams_.etheta(x,y))/sin(saved_Params[0])); //Heat bath algorithm [See page-129 of Prof. Elbio's Book] //Heat bath algorithm works for small changes i.e. when P12~1.0 // if (Heat_Bath_Algo){ // P12 =P12/(1.0+P12); // } //Metropolis Algotithm // if (Metropolis_Algo){ // P12=min(1.0,P12); // } /* * VON NEUMANN's REJECTING METHOD: * Random number < P12 -----> ACCEPT * Random number > P12 -----> REJECT */ //ACCEPTED if(P12 > 0){ Parameters_.AccCount[0]++; act=1; if(ED_){ PrevE=CurrE; Prev_QuantECluster = Curr_QuantECluster; Hamiltonian_.copy_eigs_Cluster(1); muu_prevCluster=Parameters_.mus_Cluster; } } else if ( exp(P12) > ( 1.0 - MFParams_.random() ) ) { Parameters_.AccCount[0]++; act=1; if(ED_){ PrevE=CurrE; Prev_QuantECluster = Curr_QuantECluster; Hamiltonian_.copy_eigs_Cluster(1); muu_prevCluster=Parameters_.mus_Cluster; } } //REJECTED else{ Parameters_.AccCount[1]++; act=0; MFParams_.etheta(x,y) = saved_Params[0]; MFParams_.ephi(x,y) = saved_Params[1]; } // if ((act == 1) && (count<1000)) { //muu = Hamiltonian_.chemicalpotential(Parameters_.mus,Parameters_.Fill); //Parameters_.mus = Parameters_.mus*0.999 + muu*0.001; //Parameters_.mus = muu; //} }// site loop // if (act == 1) { // muu = Hamiltonian_.chemicalpotential(Parameters_.mus,Parameters_.Fill); // Parameters_.mus = Parameters_.mus*0.99f + muu*0.01f; // } if ( (count%10==0) ) { MFParams_.Adjust_MCWindow(); } if(count < (Parameters_.IterMax - (Gap_bw_sweeps*(MC_sweeps_used_for_Avg - 1) + MC_sweeps_used_for_Avg)) ){ if ( (count%10==0) ) { Observables_.SiSjFULL(); file_out_progress << int(1.0*count) <<setw(20)<<Observables_.SiSj(0,1) <<setw(16)<< Observables_.SiSj(1,0) <<setw(16)<< Observables_.SiSjQ(0,int(lx_/2)).real() <<setw(16)<< Observables_.SiSjQ(int(lx_/2),0).real() <<setw(16)<<Observables_.SiSjQ(0,0).real() <<setw(16)<< Observables_.SiSjQ(int(lx_/2),int(lx_/2)).real() <<setw(16)<< Observables_.SiSjQ(int(lx_/4),int(lx_/4)).real() <<setw(16)<< Hamiltonian_.ClusterDensity() <<setw(16)<< CurrE <<setw(16)<< Curr_QuantECluster<<setw(15)<<Parameters_.mus_Cluster<< endl; } } //Average and Std. deviation is calculated is done else{ if(measure_start==0){ measure_start++; file_out_progress<<"----------Measurement is started----------"<<endl; file_out_progress<<"I_MC Avg{S(pi,0)} Avg{S(0,pi)} std.dev{S(pi,0)} std.dev{S(0,pi)} Avg{S(1,0)} Avg{S(0,1)} std.dev{S(1,0)} std.dev{S(0,1)} Avg{Nematic_order} std.dev{Nematic_order} Avg{E_classical} std.dev{E_classical}"<<endl; } int temp_count=count - (Parameters_.IterMax - (Gap_bw_sweeps*(MC_sweeps_used_for_Avg - 1) + MC_sweeps_used_for_Avg)); int zero_or_not = temp_count % (Gap_bw_sweeps + 1); if( zero_or_not==0 ){ if((Parameters_.Saving_Microscopic_States==true) && (Confs_used<Parameters_.No_Of_Microscopic_States) ){ char Confs_char[50]; sprintf(Confs_char,"%d",Confs_used); string File_Out_theta_phi_microState = "ThetaPhi_Temp" + string(temp_char) + "MicroState" + string(Confs_char) +".txt"; ofstream File_Out_Theta_Phi_MicroState(File_Out_theta_phi_microState.c_str()); File_Out_Theta_Phi_MicroState<<"#x"<<setw(15)<<"y"<<setw(15)<<"Theta(x,y)"<<setw(15)<<"Phi(x,y)"<<endl; for(int ix=0;ix<lx_;ix++){ for(int iy =0;iy<ly_;iy++){ File_Out_Theta_Phi_MicroState<<ix<<setw(15)<<iy<<setw(15)<<MFParams_.etheta(ix,iy)<<setw(15)<<MFParams_.ephi(ix,iy)<<endl; }} } Confs_used=Confs_used+1; Observables_.SiSjFULL(); Observables_.SiSjQ_Average(); Observables_.SiSj_Average(); //Just Classical Energy Observables_.Total_Energy_Average(0.0, CurrE); MFParams_.Calculate_Fields_Avg(); //double MC_steps_Avg_insitu = (1.0 + 1.0*(count - (Parameters_.IterMax - MC_steps_used_for_Avg))); file_out_progress << int(1.0*count) <<setw(20)<< Observables_.SiSjQ_Mean(int(lx_/2),0).real()/(Confs_used*1.0) <<setw(16)<<Observables_.SiSjQ_Mean(0,int(lx_/2)).real()/(Confs_used*1.0) <<setw(16)<< sqrt( (( Observables_.SiSjQ_square_Mean(int(lx_/2),0)/(Confs_used*1.0) ) - ((Observables_.SiSjQ_Mean(int(lx_/2),0)*Observables_.SiSjQ_Mean(int(lx_/2),0) )/(Confs_used*Confs_used*1.0) ) ).real() ) <<setw(16)<< sqrt( (( Observables_.SiSjQ_square_Mean(0,int(lx_/2))/(Confs_used*1.0) ) - ((Observables_.SiSjQ_Mean(0,int(lx_/2))*Observables_.SiSjQ_Mean(0,int(lx_/2)) )/(Confs_used*Confs_used*1.0) ) ).real() ) <<setw(16)<< Observables_.SiSj_Mean(1,0)/(Confs_used*1.0) <<setw(16)<<Observables_.SiSj_Mean(0,1)/(Confs_used*1.0) <<setw(16)<< sqrt( (( Observables_.SiSj_square_Mean(1,0)/(Confs_used*1.0) ) - ((Observables_.SiSj_Mean(1,0)*Observables_.SiSj_Mean(1,0) )/(Confs_used*Confs_used*1.0) ) ) ) <<setw(16)<< sqrt( (( Observables_.SiSj_square_Mean(0,1)/(Confs_used*1.0) ) - ((Observables_.SiSj_Mean(0,1)*Observables_.SiSj_Mean(0,1) )/(Confs_used*Confs_used*1.0) ) ) ) <<setw(16)<< Observables_.Nematic_order_mean_/(Confs_used*1.0) <<setw(16)<< sqrt( (( Observables_.Nematic_order_square_mean_/(Confs_used*1.0) ) - ((Observables_.Nematic_order_mean_*Observables_.Nematic_order_mean_)/(Confs_used*Confs_used*1.0) ) ) ) <<setw(32)<< Observables_.AVG_Total_Energy/(Confs_used*1.0) <<setw(16)<< sqrt( (Observables_.AVG_Total_Energy_sqr/(Confs_used*1.0)) - ((Observables_.AVG_Total_Energy*Observables_.AVG_Total_Energy)/(Confs_used*Confs_used*1.0)) ) <<endl; } } }// Iter Loop file_out_progress << "Total "<<Confs_used<< " configurations were used were measurement"<<endl; temp_ = temp_ - Parameters_.d_Temp; File_Out_Theta_Phi<<"#x"<<setw(15)<<"y"<<setw(15)<<"Theta_avg(x,y)"<<setw(15)<<"Phi_avg(x,y)"<<endl; for(int ix=0;ix<lx_;ix++){ for(int iy =0;iy<ly_;iy++){ File_Out_Theta_Phi<<ix<<setw(15)<<iy<<setw(15)<<MFParams_.etheta_avg(ix,iy)/(Confs_used*1.0)<<setw(15)<<MFParams_.ephi_avg(ix,iy)/(Confs_used*1.0)<<endl; }} MFParams_.Read_classical_DOFs(File_Out_theta_phi); }//Temperature loop } // --------- double MCEngine::Prob(double muu, double mu_new){ double P=0.0; double X,Y,X2; for(int i=0;i<2*orbs_*ns_;i++){ X = Parameters_.beta*( (mu_new) - Hamiltonian_.eigs_[i]); Y = Parameters_.beta*( (muu) - Hamiltonian_.eigs_saved_[i]); //P += log(1 + exp(X)) - log(1 + exp(Y)); if(X>5){ P +=X; } else if(fabs(X)<0.001){ P += log(2.0 + X); } else if(X<-5){ P +=exp(X); } else{ P +=log(1.0 + exp(X)); } if(Y>5){ P -=Y; } else if(fabs(Y)<0.001){ P -= log(2.0 + Y); } else if(Y<-5){ P -=exp(Y); } else{ P -=log(1.0 + exp(Y)); } } return P; } // --------- double MCEngine::ProbCluster(double muu, double mu_new){ double P=0.0; double X,Y,X2; int ns = (Parameters_.lx_cluster)*(Parameters_.ly_cluster); for(int i=0;i<2*orbs_*ns;i++){ X = Parameters_.beta*( (mu_new) - Hamiltonian_.eigsCluster_[i]); Y = Parameters_.beta*( (muu) - Hamiltonian_.eigsCluster_saved_[i]); //P += log(1 + exp(X)) - log(1 + exp(Y)); if(X>5){ P +=X; } else if(fabs(X)<0.001){ P += log(2.0 + X); } else if(X<-5){ P +=exp(X); } else{ P +=log(1.0 + exp(X)); } if(Y>5){ P -=Y; } else if(fabs(Y)<0.001){ P -= log(2.0 + Y); } else if(Y<-5){ P -=exp(Y); } else{ P -=log(1.0 + exp(Y)); } } return P; } // --------- #endif // MCENGINE_H
06529752c3bfb9aaa00702eba922f20dda67f001
[ "C++" ]
3
C++
nkphys/Monte_Carlo_TCA
d93ef86e5a2c0c7e1b840984c4c074aea64fcd71
bfd7e783cf67b984129830031221a0e3d33ead84
refs/heads/master
<file_sep>from django.shortcuts import render, redirect import datetime import random def win_or_lose(): number = random.randrange(0, 101) if number >= 50: return True else: return False def index(request): if 'total' in request.session: pass else: request.session['total'] = 0 request.session['message'] = [] return render(request, 'Ninja_Gold_App/index.html') def money(request): if request.method == 'POST': date = datetime.datetime.now().strftime("(%Y/%m/%d %I:%M:%S %p)") if request.POST['action'] == 'farm': num = random.randrange(10,21) request.session['total'] += num request.session['message'].append("Earned "+str(num)+" from the Farm!"+str(date)) elif request.POST['action'] == 'cave': num = random.randrange(5,11) request.session['total'] += num request.session['message'].append("Earned "+str(num)+" gold from the Cave!"+str(date)) elif request.POST['action'] == 'house': num = random.randrange(2,6) request.session['total'] += num request.session['message'].append("Earned "+str(num)+" gold from the House!"+str(date)) elif request.POST['action'] == 'casino': if win_or_lose() == True: num = random.randrange(0,51) request.session['total'] += num request.session['message'].append("Earned "+str(num)+" gold from the Casino!"+str(date)) else: num = random.randrange(0,51) request.session['total'] -= num request.session['message'].append("Lost "+str(num)+" gold from the Casino!"+str(date)) return redirect('/') <file_sep>from django.shortcuts import render, redirect, HttpResponse def index(request): return render(request, 'disappearing_ninjas_app/index.html') def ninjas(request): return render(request, 'disappearing_ninjas_app/ninjas.html') def ninja(request, ninja_color): if(ninja_color == 'blue'): request.session['photo'] = '../static/disappearing_ninjas_app/images/leonardo.jpg' return render(request, 'disappearing_ninjas_app/ninja.html') elif(ninja_color == 'orange'): request.session['photo'] = '../static/disappearing_ninjas_app/images/michelangelo.jpg' return render(request, 'disappearing_ninjas_app/ninja.html') elif(ninja_color == 'red'): request.session['photo'] = '../static/disappearing_ninjas_app/images/raphael.jpg' return render(request, 'disappearing_ninjas_app/ninja.html') elif(ninja_color == 'purple'): request.session['photo'] = '../static/disappearing_ninjas_app/images/donatello.jpg' return render(request, 'disappearing_ninjas_app/ninja.html') else: request.session['photo'] = '../static/disappearing_ninjas_app/images/notapril.jpg' return render(request, 'disappearing_ninjas_app/ninja.html') <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Ninja Gold Game!</title> {% load staticfiles %} <link rel="stylesheet" href="{% static 'Ninja_Gold_App/css/style.css' %}"> </head> <body> <p> Your Gold: {{request.session.total}}</p> <div> <h3>Farm</h3> <p>(earn 10-20 gold)</p> <form action="/money" method="post"> {% csrf_token %} <input type="hidden" name="action" value="farm"> <input type="submit" name="farm"> </form> </div> <div> <h3>Cave</h3> <p>(earn 5-10 gold)</p> <form action="/money" method="post"> {% csrf_token %} <input type="hidden" name="action" value="cave"> <input type="submit" name="cave"> </form> </div> <div> <h3>House</h3> <p>(earn 2-5 gold)</p> <form action="/money" method="post"> {% csrf_token %} <input type="hidden" name="action" value="house"> <input type="submit" name="house"> </form> </div> <div> <h3>Casino</h3> <p>(earn or lose 0-50 gold)</p> <form action="/money" method="post"> {% csrf_token %} <input type="hidden" name="action" value="casino"> <input type="submit" name="casino"> </form> </div> <h4> Activities: </h4> <div id="bottom_div"> {% for item in request.session.message %} <p> {{item}} </p> {% endfor %} </div> </body> </html>
60906854a693d57e6f1c182e5a441f0122b86c6b
[ "Python", "HTML" ]
3
Python
SarBleakley/_pythonCohortNov7
5797f98d37c807b42406c589326ef0e03269732e
851f93d4369e6969aa2c5c55dddcd8e5c1714b98
refs/heads/master
<repo_name>Fogha/facebook-clone<file_sep>/README.old.md # Facebook-Clone A facebook clone built in reactJS and firebase <file_sep>/src/Components/StoryReel.js import React from "react"; import "./StoryReel.css"; import Story from "./Story"; export default function StoryReel() { return ( <div className="storyReel"> <Story image="https://images.squarespace-cdn.com/content/v1/58c6b9ec46c3c4e3b24027fd/1504723982308-IER9OGR1S4VQY5I8FBF5/ke17ZwdGBToddI8pDm48kLX6UassdUD58CKRaHROvot7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0iyqMbMesKd95J-X4EagrgUlmdw7pTZ07H-4SEUFING9eaA0gvzbF_MFLbXj3sjS1w/kristopher-roller-188180+copy.jpg?format=2500w" profileSrc="https://upload.wikimedia.org/wikipedia/commons/a/a9/Tom_Hanks_TIFF_2019.jpg" title="<NAME>" /> <Story image="https://media.istockphoto.com/photos/child-hands-formig-heart-shape-picture-id951945718?k=6&m=951945718&s=612x612&w=0&h=ih-N7RytxrTfhDyvyTQCA5q5xKoJToKSYgdsJ_mHrv0=" profileSrc="https://upload.wikimedia.org/wikipedia/commons/a/a9/Tom_Hanks_TIFF_2019.jpg" title="<NAME>" /> <Story image="https://www.filmibeat.com/ph-big/2019/07/ismart-shankar_156195627930.jpg" profileSrc="https://upload.wikimedia.org/wikipedia/commons/a/a9/Tom_Hanks_TIFF_2019.jpg" title="<NAME>" /> <Story image="https://www.filmibeat.com/ph-big/2019/07/ismart-shankar_156195627930.jpg" profileSrc="https://upload.wikimedia.org/wikipedia/commons/a/a9/Tom_Hanks_TIFF_2019.jpg" title="<NAME>" /> <Story image="https://www.filmibeat.com/ph-big/2019/07/ismart-shankar_156195627930.jpg" profileSrc="https://upload.wikimedia.org/wikipedia/commons/a/a9/Tom_Hanks_TIFF_2019.jpg" title="<NAME>" /> </div> ); } <file_sep>/src/firebase.js import firebase from "firebase"; const firebaseConfig = { apiKey: "<KEY>", authDomain: "facebook-clone-b151d.firebaseapp.com", databaseURL: "https://facebook-clone-b151d.firebaseio.com", projectId: "facebook-clone-b151d", storageBucket: "facebook-clone-b151d.appspot.com", messagingSenderId: "55373935739", appId: "1:55373935739:web:1c26ad6b87c7f098421ede", measurementId: "G-9KP6K32WQ5", }; const firebaseApp = firebase.initializeApp(firebaseConfig); const db = firebaseApp.firestore(); const auth = firebaseApp.auth(); const provider = new firebase.auth.GoogleAuthProvider(); export { auth, provider }; export default db;
76ba9a4f599685a0b3d3410de2f7cabc8847f296
[ "Markdown", "JavaScript" ]
3
Markdown
Fogha/facebook-clone
e6aac04b78121e548f220035da355198b569bed3
ca4446c917e23935a5a67c1a0923eed79e7b05bd
refs/heads/master
<file_sep>#include "service.hpp" #include "undocumented.hpp" #include <chrono> #include <iostream> #include <thread> #include <string_view> #pragma comment(lib, "advapi32.lib") using namespace std; /* * https://i.imgur.com/6xYweKo.png */ inline WNF_STATE_NAME WNF_RM_GAME_MODE_ACTIVE {{ 0xA3BC1075, 0x41C6033F }}; using night_light_settings = array<u8, 0x20>; template<u8 ...Bytes> auto set_night_light_setting() { static const array<u8, sizeof...(Bytes)> bytes{Bytes...}; constexpr auto registry_path = R"(Software\Microsoft\Windows\CurrentVersion\CloudStore\Store\Cache\DefaultAccount\$$windows.data.bluelightreduction.settings\Current)"; HKEY key_handle; nt_assert(RegOpenKeyEx(HKEY_CURRENT_USER, registry_path, 0, KEY_READ | KEY_WRITE, &key_handle)); nt_assert(RegSetValueEx(key_handle, "Data", 0, REG_BINARY, reinterpret_cast<const BYTE *>(bytes.data()), sizeof...(Bytes) * sizeof(u8))); } inline auto enable_night_light() { set_night_light_setting<0x02, 0x00, 0x00, 0x00, 0x46, 0x1b, 0x1b, 0xe9, 0x11, 0xef, 0xd3, 0x01, 0x00, 0x00, 0x00, 0x00, 0x43, 0x42, 0x01, 0x00, 0x02, 0x01, 0xca, 0x14, 0x0e, 0x15, 0x00, 0xca, 0x1e, 0x0e, 0x07, 0x00, 0xcf, 0x28, 0xbc, 0x3e, 0xca, 0x32, 0x0e, 0x14, 0x2e, 0x00, 0x00, 0xca, 0x3c, 0x0e, 0x06, 0x2e, 0x22, 0x00, 0x00>(); } inline auto disable_night_light() { set_night_light_setting<0x02, 0x00, 0x00, 0x00, 0xbb, 0x51, 0xcc, 0x45, 0x12, 0xef, 0xd3, 0x01, 0x00, 0x00, 0x00, 0x00, 0x43, 0x42, 0x01, 0x00, 0xca, 0x14, 0x0e, 0x15, 0x00, 0xca, 0x1e, 0x0e, 0x07, 0x00, 0xcf, 0x28, 0xbc, 0x3e, 0xca, 0x32, 0x0e, 0x14, 0x2e, 0x00, 0x00, 0xca, 0x3c, 0x0e, 0x06, 0x2e, 0x22, 0x00, 0x00>(); } inline auto toggle_night_light(const bool option) { if (option) { enable_night_light(); } else { disable_night_light(); } } /* * https://i.imgur.com/6HQQmUP.png */ inline auto get_nt_query_wnf_state_data() { HINSTANCE ntdll; assert(ntdll = GetModuleHandle("ntdll.dll")); FARPROC fptr; assert(fptr = GetProcAddress(ntdll, "NtQueryWnfStateData")); return reinterpret_cast<decltype(&NtQueryWnfStateData)>(fptr); } inline auto is_game_mode_on() { static const auto nt_query_wnf_state_data = get_nt_query_wnf_state_data(); WNF_CHANGE_STAMP change_stamp; DWORD process_id; ULONG buffer_size = sizeof(DWORD); nt_assert(nt_query_wnf_state_data(&WNF_RM_GAME_MODE_ACTIVE, nullptr, nullptr, &change_stamp, &process_id, &buffer_size)); return !!process_id; } auto worker() { using namespace chrono; auto last_game_mode_value = is_game_mode_on(); while (true) { const auto current_game_mode_value = is_game_mode_on(); if (current_game_mode_value != last_game_mode_value) { toggle_night_light(!current_game_mode_value); last_game_mode_value = current_game_mode_value; } this_thread::sleep_for(100ms); } } inline auto already_running() { CreateMutex(nullptr, TRUE, "Aurora_Instance_Mutex"); return GetLastError() == ERROR_ALREADY_EXISTS; } auto main(int /* argc */, char ** /* argv */) -> int { if (already_running()) { return 0; } worker(); return 0; } auto __stdcall WinMain(HINSTANCE /* instance */, HINSTANCE /* prev_instance */, LPSTR /* cmd_line */, int /* cmd_show */) -> int { if (already_running()) { return 0; } worker(); return 0; } /* SERVICE_INIT(Aurora, { using namespace chrono; auto last_game_mode_value = is_game_mode_on(); while (active()) { const auto current_game_mode_value = is_game_mode_on(); if (current_game_mode_value != last_game_mode_value) { last_game_mode_value = current_game_mode_value; } this_thread::sleep_for(100ms); } return 0; }) */ <file_sep>#pragma once #include <array> #include <atomic> #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <thread> #include <windows.h> using namespace std; #define SERVICE_INIT(service_name, implementation) \ static inline unique_ptr<service> service_name; \ \ static inline auto __stdcall ctrl_handler(DWORD ctrl_code) -> void \ { \ switch (ctrl_code) \ { \ case SERVICE_ACCEPT_SHUTDOWN: \ case SERVICE_CONTROL_STOP: \ if (!service_name->running) \ { \ return; \ } \ service_name->notify_stop(); \ SetEvent(service_name->stop_event); \ } \ } \ \ static inline auto __stdcall smain(DWORD argc, char **argv) -> void \ { \ /* register control handler*/ \ assert(service_name->status_handle = RegisterServiceCtrlHandler(#service_name, ctrl_handler)); \ \ /* tell service controller that we want to start*/ \ service_name->notify_start_pending(); \ \ /* do any more initialization that's left*/ \ service_name->initiate(); \ \ /* register stop event*/ \ assert(service_name->stop_event = CreateEvent(nullptr, TRUE, FALSE, nullptr)); \ \ /* tell service controller that we have started*/ \ service_name->notify_start(); \ \ /* wait for worker to stop */ \ service_name->join_thread(); \ /* if we do exit our worker thread, then we need to notify the service controller that we stopped */ \ service_name->notify_stop(); \ } \ \ auto main(int argc, char **argv) -> int \ { \ this_thread::sleep_for(5s); \ /* init the service class */ \ service_name = make_unique<service>( \ #service_name, \ [](auto active) implementation); \ \ /* register windows callbacks */ \ SERVICE_TABLE_ENTRY service_table[] = \ { \ {service_name->get_name().data(), reinterpret_cast<LPSERVICE_MAIN_FUNCTION>(smain)}, \ {nullptr, nullptr} \ }; \ \ assert(StartServiceCtrlDispatcher(service_table)); \ \ return 0; \ } struct service { template<typename Worker> service(string name, Worker &&worker): name{move(name)}, worker_thread{ [worker = forward<Worker>(worker), this] { while (!this->running) { this_thread::sleep_for(100ms); } worker([this] { return WaitForSingleObject(this->stop_event, 0) != WAIT_OBJECT_0; }); }} { worker_thread.detach(); } ~service() { CloseHandle(stop_event); } auto get_name() const { return name; } auto join_thread() { worker_thread.join(); } auto initiate() { ZeroMemory(&status, sizeof(status)); status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; status.dwWin32ExitCode = NO_ERROR; status.dwServiceSpecificExitCode = NO_ERROR; } auto report_status(DWORD current_state, DWORD controls_accepted = static_cast<DWORD>(-1), DWORD wait_hint = 0) { status.dwCurrentState = current_state; if (controls_accepted != static_cast<DWORD>(-1)) { status.dwControlsAccepted = controls_accepted; } status.dwWaitHint = wait_hint; return SetServiceStatus(status_handle, &status) ? true : false; } auto notify_start() { assert(report_status(SERVICE_RUNNING, status.dwControlsAccepted | (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN))); running = true; } auto notify_stop() { assert(report_status(SERVICE_STOP_PENDING, status.dwControlsAccepted & ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN), 0)); running = false; } auto notify_start_pending() { assert(report_status(SERVICE_START_PENDING, 0)); } atomic<bool> running{false}; SERVICE_STATUS status{}; SERVICE_STATUS_HANDLE status_handle{nullptr}; HANDLE stop_event{nullptr}; private: string name; thread worker_thread; }; <file_sep>#pragma once #include <windows.h> typedef struct _WNF_STATE_NAME { ULONG Data[2]; } WNF_STATE_NAME, *PWNF_STATE_NAME; typedef const WNF_STATE_NAME *PCWNF_STATE_NAME; typedef struct _WNF_TYPE_ID { GUID TypeId; } WNF_TYPE_ID, *PWNF_TYPE_ID; typedef const WNF_TYPE_ID *PCWNF_TYPE_ID; typedef ULONG WNF_CHANGE_STAMP, *PWNF_CHANGE_STAMP; NTSYSCALLAPI NTSTATUS NTAPI NtQueryWnfStateData( _In_ PCWNF_STATE_NAME StateName, _In_opt_ PCWNF_TYPE_ID TypeId, _In_opt_ const VOID* ExplicitScope, _Out_ PWNF_CHANGE_STAMP ChangeStamp, _Out_writes_bytes_to_opt_(*BufferSize, *BufferSize) PVOID Buffer, _Inout_ PULONG BufferSize); <file_sep>#pragma once #include <iostream> #include <string> #include <type_traits> using namespace std; #if defined(NDEBUG) #define assert(condition) \ (void)(condition); #else #define assert(condition) \ if (!(condition)) \ { \ exit(GetLastError()); \ } #endif #define nt_assert(success_condition) \ assert(SUCCEEDED(success_condition)) #define fn(fn_name) static const auto fn_name = [&] #define closure fn using u8 = unsigned char; using u16 = unsigned short; using u32 = unsigned int; using u64 = unsigned long long; using i8 = signed char; using i16 = signed short; using i32 = signed int; using i64 = signed long long; using f32 = float; using f64 = double;
547f08e6a3280044c6e5a0da6c161a9b35ee5bf5
[ "C++" ]
4
C++
nimashoghi/Aurora
0ebd25130be976c71201af1f2b0dc3eaa00a66ad
58f5a09e04a1c58094594f873436b469dba717ad
refs/heads/master
<file_sep>import math class DTNode: def __init__(self, decision): self.children = [] self.decision = decision def predict(self, input): if callable(self.decision): child = self.children[self.decision(input)] return child.predict(input) else: return self.decision def leaves(self): if not self.children: return 1 return sum([child.leaves() for child in self.children]) def partition_by_feature_value(feature_index, dataset): features = [] labels = {} for feature, label in dataset: if feature[feature_index] in labels: labels[feature[feature_index]].append((feature, label)) else: labels[feature[feature_index]] = [(feature, label)] partition = [label for label in labels.values()] def separator(x): i = 0 for item in labels.values(): for feature, label in item: if feature == x: return i i += 1 return separator, partition def p_k(dataset, classification): count = 0 for feature, label in dataset: if label == classification: count += 1 return count / len(dataset) def misclassification(dataset): all_classes = get_classifications(dataset) p_ks = [] for classification in all_classes: p_ks.append(p_k(dataset, classification)) return 1 - max(p_ks) def gini(dataset): # ∑k pk(1 - pk). all_classes = get_classifications(dataset) p_k_sum = 0 for classification in all_classes: p_k_sum += p_k(dataset, classification) * (1 - p_k(dataset, classification)) return p_k_sum def entropy(dataset): # -∑k pk log(pk). all_classes = get_classifications(dataset) p_k_sum = 0 for classification in all_classes: p_k_sum += p_k(dataset, classification) * (math.log(p_k(dataset, classification))) return -p_k_sum def get_classifications(dataset): classifications = [] for feature, label in dataset: classifications.append(label) return set(classifications) def objective(dataset, k, criterion): separator, partition = partition_by_feature_value(k, dataset) obj = float('-inf') if len(partition) != 1: obj = sum([(len(part)/len(dataset)) * criterion(part) for part in partition]) return obj def max_(items): maximum = max(items) return items.index(maximum) def train_tree(dataset, criterion): classes = get_classifications(dataset) all_labels = [x for _,x in dataset] all_features = [y for y,_ in dataset] most_common = max(set(all_labels), key=all_labels.count) if len(classes) == 1: return DTNode(classes.pop()) elif len(all_features) == 0: # Empty feature set return DTNode(classes[max_([p_k(k, dataset) for k in classes])]) obj_items = ([objective(dataset, k, criterion) for k in range(len(dataset[0][0]))]) split_index = obj_items.index(max(obj_items)) separator, partition = partition_by_feature_value(split_index, dataset) sub_tree = DTNode(separator) sub_tree.children = [train_tree(p, criterion) for p in partition] return sub_tree dataset = [ (("Sunny", "Hot", "High", "Weak"), False), (("Sunny", "Hot", "High", "Strong"), False), (("Overcast", "Hot", "High", "Weak"), True), (("Rain", "Mild", "High", "Weak"), True), (("Rain", "Cool", "Normal", "Weak"), True), (("Rain", "Cool", "Normal", "Strong"), False), (("Overcast", "Cool", "Normal", "Strong"), True), (("Sunny", "Mild", "High", "Weak"), False), (("Sunny", "Cool", "Normal", "Weak"), True), (("Rain", "Mild", "Normal", "Weak"), True), (("Sunny", "Mild", "Normal", "Strong"), True), (("Overcast", "Mild", "High", "Strong"), True), (("Overcast", "Hot", "Normal", "Weak"), True), (("Rain", "Mild", "High", "Strong"), False), ] t = train_tree(dataset, misclassification) print(t.predict(("Overcast", "Cool", "Normal", "Strong"))) print(t.predict(("Sunny", "Cool", "Normal", "Strong"))) <file_sep>import math def argmax(items): maximum = max(items) return items.index(maximum) def argmin(items): minimum = min(items) return items.index(minimum) class DTNode: def __init__(self, decision): self.decision = decision self.children = [] def predict(self, v): if callable(self.decision): return self.children[self.decision(v)].predict(v) return self.decision def leaves(self): if len(self.children) == 0: return 1 return sum([c.leaves() for c in self.children]) def partition_by_feature_value(index, data): order = list(set([d[0][index] for d in data])) separator = lambda f: order.index(f[index]) partition = [[] for _ in order] for val in data: partition[separator(val[0])].append(val) return (separator, partition) def proportion(classification, data): total = 0 for _, c in data: if c == classification: total += 1 return total / len(data) def classes(data): return list(set([d[1] for d in data])) def gini(data): H = 0 for k in classes(data): prop = proportion(k, data) H += prop*(1 - prop) return H def entropy(data): H = 0 for k in classes(data): prop = proportion(k, data) if prop != 0: H += prop*math.log(prop) return -H def misclassification(data): return 1 - max([proportion(k, data) for k in classes(data)]) def objective(criterion, k, data): separator, partition = partition_by_feature_value(k, data) if len(partition) == 1: return float('-inf') return sum([(len(p)/len(data)) * criterion(p) for p in partition]) def train_tree(data, criterion): classes = list(set([d[1] for d in data])) if len(classes) == 1: # All classified the same return DTNode(data[0][1]) if len(data[0]) == 0: # Empty feature set return DTNode(classes[argmax([proportion(k, data) for k in classes])]) split = argmax([objective(criterion, k, data) for k in range(len(data[0][0]))]) separator, partition = partition_by_feature_value(split, data) node = DTNode(separator) node.children = [train_tree(p, criterion) for p in partition] return node scale_dataset = [] with open('balance_scale.data', 'r') as f: for line in f.readlines(): out, *features = line.strip().split(",") scale_dataset.append((tuple(features), out)) car_dataset = [] with open('car.data', 'r') as f: for line in f.readlines(): *features, out = line.strip().split(",") car_dataset.append((tuple(features), out)) t = train_tree(scale_dataset, misclassification) print((len(scale_dataset)/t.leaves())) s = train_tree(car_dataset, misclassification) print((len(car_dataset)/s.leaves())) <file_sep> def matches(data, hypothesis): matched = [] for x, y in zip(data, hypothesis): matched_item = False if x == '?': matched_item = True elif x != '0' and (x == y or y == '0'): matched_item = True matched.append(matched_item) return all(matched) def min_generalizations(h, x): h_new = list(h) for i in range(len(h)): if not matches(h[i:i + 1], x[i:i + 1]): if h[i] != '0': h_new[i] = '?' else: h_new[i] = x[i] return [tuple(h_new)] def min_specializations(h, domains, x): results = [] for i in range(len(h)): if h[i] == "?": for domain in domains[i]: if x[i] != domain: h_new = h[:i] + (domain,) + h[i+1:] results.append(h_new) elif h[i] != "0": h_new = h[:i] + ('0',) + h[i+1:] results.append(h_new) return results def cea_trace(domains, training_examples): S = {('0',) * (len(domains))} G = {('?',) * (len(domains))} s_trace = [S] g_trace = [G] for data, output in training_examples: G = G.copy() S = S.copy() # if d is positive example if output: # Remove from G any hypotheses that do not match data G = {hyp for hyp in G.copy() if (matches(hyp, data))} for s in S.copy(): # For each hypothesis s in S that does not match data: if not matches(s, data): # Remove s from S S.remove(s) # Add to S all minimal generalisations, h of s such that: Splus = min_generalizations(s, data) for min in Splus: # 1. h matches data # 2. some member of G is more general than h if any([matches(g, min) for g in G]): S.add(min) # Remove from S any h that is more general than another hypothesis in S S.difference_update([h for h in S if any([matches(h, h1) for h1 in S if h != h1])]) # if d is negative example else: # Remove from S any hypotheses that match data S = {hyp for hyp in S if not (matches(hyp, data))} # For each hypothesis g in G that matches data: # Remove g from G # Add to G all minimal generalisations, h, of g such that: # 1. h does not match data # 2. some member of S is more specific than h # Remove from G any h that is more specific than another hypothesis in G for g in G.copy(): if matches(g, data): G.remove(g) Gminus = min_specializations(g, domains, data) for min in Gminus: if any([matches(min, s) for s in S]): G.add(min) # remove hypotheses less general than any other in G G.difference_update([h for h in G if any([matches(g1, h) for g1 in G if h != g1])]) # Update Traces g_trace.append(G) s_trace.append(S) return s_trace, g_trace def all_agree(S, G, x): return {matches(s, x) for s in S} == {matches(g, x) for g in G} domains = [ {'T', 'F'}, {'T', 'F'}, ] training_examples = [ (('F', 'F'), True), (('T', 'T'), False), ] S_trace, G_trace = cea_trace(domains, training_examples) S, G = S_trace[-1], G_trace[-1] print(S) print(G) print("(F, F)", all_agree(S, G, ('F', 'F')), "T") print("(T, T)", all_agree(S, G, ('T', 'T')), "T") print("(F, T)", all_agree(S, G, ('F', 'T')), "F") print("(T, F)", all_agree(S, G, ('T', 'F')), "F") print()
063f941ad217288162f67e2f617f67b812ac1faf
[ "Python" ]
3
Python
harryfeasey/machine_learning_1
fe1b46e7f18b1fd9d36ab11f008245d2c2772aae
c9a7198b07756c47bf089da2a0a18cc06bb614c8
refs/heads/master
<repo_name>slntopp/demo_tracker_server<file_sep>/ui/vue.config.js module.exports = { outputDir: '../app/public', assetsDir: '../static', css: { extract: false } }<file_sep>/README.md # Requests ## `POST /signup` Params: ``` username=..., // Any random username ``` Response: ```jsonc { "response" : { "token" : "..." // char[32] random token } } ``` ## `POST /write` Request: ``` token=..., // Ur token lat=0, // Latitude: float lng=0 // Longitude: float ``` Response: `""` - 200 ## `GET /read` Request: ``` token="...", // Ur token stime=0, // From which time to collect records as a timestamp etime=1500000000 // Till which time to collect records as a timestamp ``` Response: ```jsonc [ { "lat": 52, "lng": 28, "ts": 1588943717 }, { "lat": 53, "lng": 28, "ts": 1588943720 } ] ```<file_sep>/app/conf.py from os import getenv class Config(object): DEBUG = False MONGO_URI = getenv('DB') CSRF_ENABLED = False GOOGLE_MAPS_API_TOKEN = getenv('GOOGLE_MAPS_API_TOKEN')<file_sep>/requirements.txt Flask requests flask_pymongo gunicorn pytz python-dotenv<file_sep>/Dockerfile FROM python:3.8 ADD . /app WORKDIR /app RUN pip install -r requirements.txt ENTRYPOINT ["gunicorn","wsgi:app"]<file_sep>/wsgi.py #!/usr/bin/env python3.8 from dotenv import load_dotenv load_dotenv() from os import getenv from app import app if __name__ == "__main__": app.run(host=getenv('HOST'), port=getenv('PORT'))<file_sep>/app/__init__.py from flask import Flask import asyncio import json from bson.objectid import ObjectId from flask_pymongo import PyMongo from datetime import datetime class JSONEncoder(json.JSONEncoder): ''' extend json-encoder class ''' def default(self, o): if isinstance(o, ObjectId): return str(o) if isinstance(o, datetime): return str(o) return json.JSONEncoder.default(self, o) app = Flask(__name__, template_folder='public') app.config.from_object('app.conf.Config') # Loading conf from Config class in conf.py mongo = PyMongo(app) # Loadig mongo client using app.conf db = mongo.db.tracker app.json_encoder = JSONEncoder # Using custom encoder from app import routes # Loading routes<file_sep>/app/routes.py from os import urandom, getenv from datetime import datetime, timedelta from pytz import utc import json from app import app, db from flask import request, jsonify, render_template @app.route('/') def index(): data = request.args.to_dict() user = db.users.find_one({'token': data['token']}) return render_template('index.html', token=user['token']) @app.route('/signup', methods=['POST']) def register(): user = request.form.to_dict() user['token'] = urandom(32).hex() db.users.update({'username': user['username']}, {'$set': user}, upsert=True) return jsonify({'response': {'token': user['token'] }}) @app.route('/write', methods=['POST']) def write(): data = request.form.to_dict() user = db.users.find_one({'token': data['token']}) if user: db.cords.insert_one({ 'lat': float(data['lat']), 'lng': float(data['lng']), 'ts': int(datetime.timestamp(datetime.now())), 'user': user }) return '', 200 @app.route('/read', methods=['GET']) def read(): data = request.args.to_dict() if int(data['etime']) == -1: data['etime'] = int(datetime.timestamp(datetime.now())) cords = db.cords.find( { 'user.token': data['token'], 'ts': { '$gte': int(data['stime']), '$lte': int(data['etime']) } }, {'lat': 1, 'lng': 1, 'ts': 1, '_id': 0} ) cords = map(lambda el: {'lat': float(el['lat']), 'lng': float(el['lng']), 'ts': el['ts']}, cords) return jsonify(list(cords)) @app.route('/maps_token', methods=['GET']) def token(): return app.config['GOOGLE_MAPS_API_TOKEN'] if getenv('FLASK_ENV') == 'development': @app.route('/all', methods=['GET']) def all(): return jsonify({ "users": list(db.users.find()), "cords": list(db.cords.find()) })
d2582f23be14ef9f05df1d8196c8b8cd25671027
[ "JavaScript", "Markdown", "Python", "Text", "Dockerfile" ]
8
JavaScript
slntopp/demo_tracker_server
8fa86af8d00e2afefe86b37b493352345ed3a671
31b18c23f0913da847128759ffc7f8a687c83546
refs/heads/master
<file_sep>#ifndef CHECKERGAME_H #define CHECKRGAME_H class checkerGame { public: checkerGame(); void initBoard(); void printBoard(); void loopGame(); void writeBoard(int x,int y); int checkWin(); protected: char board[3][3] ; char turn; int trues = 1; private: }; #endif // !CHECKERGAME_H <file_sep># C-tic-tac-toe A tic-tac-toe I made with C++ <file_sep>#include <iostream> #include <cstdlib> #include "checkerGame.h" #include <conio.h> int main() { checkerGame game; std::cout << "Press any key to continue"; return 0; }<file_sep>#include "checkerGame.h" #include <iostream> #include <cstdlib> using namespace std; checkerGame::checkerGame() { initBoard(); loopGame(); int again = 0; system("CLS"); printBoard(); cout << "Do you want to play again?" << endl; cout << "1 = Yes 0 = No\n"; cin >> again; if (again == 1) { checkerGame(); } } void checkerGame::writeBoard(int x, int y) { if (turn == 'X') { if (board[x][y] == '.') { board[x][y] = 'X'; turn = 'O'; } } else { if (board[x][y] == '.') { board[x][y] = 'O'; turn = 'X'; } } } void checkerGame::loopGame() { if(trues == 1) { system("CLS"); printBoard(); int x; int y; cin >> x; cin >> y; x -= 1; y -= 1; writeBoard(x,y); trues = checkWin(); loopGame(); } } int checkerGame::checkWin() { for (int pos = 0; pos < 3; pos++) { if (board[pos][0] == board[pos][1] && board[pos][1] == board[pos][2] && board[pos][0] == 'X' || board[0][pos] == 'O') { return 0; } else if (board[0][pos] == board[1][pos] && board[1][pos] == board[2][pos] && board[0][pos] == 'X' || board[0][pos] == 'O') { return 0; } else { return 1; } } return 1; } void checkerGame::initBoard() { turn = 'X'; for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { board[x][y] = { '.' }; } } } void checkerGame::printBoard() { cout << "---------\n"; for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { cout << "|"; cout << board[x][y]; cout << "|"; } cout << endl; cout << "---------\n"; } }
2292f78edda27a1689d3f7ac7f13d2e9f296d5c7
[ "Markdown", "C++" ]
4
C++
Araknor99/C-tic-tac-toe
433205c257dbf7a0e24b0fefe7cf5ea66acce721
0713b032442e274ba5666e116b88ea4131db5972
refs/heads/master
<repo_name>youngahRoh/portfolio0<file_sep>/info.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,200;0,400;0,500;0,600;0,800;0,900;1,200;1,400;1,500;1,600;1,800;1,900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.css"> </head> <body> <nav id="nav"> <h1><a href="portfolio.html">PORTFOLIO</a></h1> <div class="mNav"> <div class="icon-wrap"> <div class="icon"></div> </div> </div> <ul class="menu"> <li class="active"><a href="#section1">ABOUTME</a></li> <li><a href="info.html">INFO</a></li> <li><a href="#section2">SKILES</a></li> <li><a href="#section4">PRODUCTS</a></li> <li><a href="#section5">web&app</a></li> <li><a href="#section6">CONTACT</a></li> </ul> </nav> <div class ="frame"> <div class="profile-section"> <div class="side"> <figure> <img id="profile-picture" src="2.jpg" width="500px"> </figure> </div> <div class="introduction"> <h2>ABOUT ME</h2> <p>"기획, 디자인, 개발 다 하는 인간 스타트업이 되도록 노력 중"<br>컴퓨터공학과 출신, UX 관점에서 제대로 된 서비스 기획을 하기 위해 Front-End를 공부 중입니다. Adobe Tool은 기초적인 경험이 있습니다. :) 정보의 평등과 지식 공유의 중요성에 공감하고 있습니다. 무엇이든 시작하면 제대로 하는 성격! 같이 즐겁게, 열정적으로 진짜 뭔가를 만들어봐요! </p> <h2>CAPABILITY</h2> <p id="capability">UX Research<br>UI Prototyping<br>Publishing with html/css</p> </div> </div> <h5 class="value-menu">MY VALUES</h5> <div class="value-section"> <div class="value"> <img class="value-icon" src="together.png"> <div class="value-intro"> <h4 class="value-name">GO TOGETHER</h4> <p class="value-exp">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora sunt veritatis ea placeat. Iure, quam laudantium pariatur eligendi error eos voluptatum eaque maxime. Necessitatibus, nihil. Deleniti vitae perspiciatis est vel.</p> </div> </div> <div class="value"> <img class="value-icon" src="partnership.png"> <div class="value-intro"> <h4 class="value-name">RESPONSIBILITY</h4> <p class="value-exp">Lorem ipsum dolor sit amet consectetur adipisicing elit. Fuga labore ad, perspiciatis ipsa veritatis neque et nostrum porro iste magnam dolorum similique laborum doloribus in possimus eveniet dicta voluptatum est!</p> </div> </div> <div class="value"> <img class="value-icon" src="dove.png"> <div class="value-intro"> <h4 class="value-name">COMMUNICATION</h4> <p class="value-exp">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas ipsa iste blanditiis enim. Vel minus perferendis praesentium architecto deserunt, ipsam dolore hic, ullam nulla aut magnam eveniet facilis explicabo odio.</p> </div> </div> </div> <footer class="footer"> <h3 class="contact">CONTACT ME</h3> <div class="links"> <a class="blog" href="https://kry-stal.tistory.com/">BLOG</a> <a class="instagram" href="https://github.com/youngahRoh">Github</a> </div> <p class="footer-comment"><br>Icons made by <a href="http://www.freepik.com/" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a></p> </footer> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script src="script.js"></script> </body> </html><file_sep>/script.js var nav = $("#nav ul li"); //버튼을 변수에 할당(저장) var cont = $("#contents > div"); //컨텐츠를 변수에 할당 //버튼ㅇ르 클릭했을 때 nav.click(function(e){ // e.preventDefault(); //# 기본기능을 차단 var target = $(this); //클릭한 타겟을 변수에 할당 var index = target.index(); //클릭한 타겟에 번호를 할당 //alert(index); var section = cont.eq(index); //eq 순서 나타내는 메소드 var offset = section.offset().top; //offset 맨 왼쪽 꼭지점 //alert(offset); $("html,body").animate({ scrollTop:offset },600,"easeInOutExpo"); }); /*$(window).scroll(function() { //스크롤이 되면 동작해라 var wScroll = $(this).scrollTop(); //offset값과 scrollTop값이 똑같으면 화면에 보임 if(wScroll >= cont.eq(0).offset().top) { nav.removeClass("active"); nav.eq(0).addClass("active"); } if(wScroll >= cont.eq(1).offset().top) { nav.removeClass("active"); nav.eq(1).addClass("active"); } if(wScroll >= cont.eq(2).offset().top) { nav.removeClass("active"); nav.eq(2).addClass("active"); } if(wScroll >= cont.eq(3).offset().top) { nav.removeClass("active"); nav.eq(3).addClass("active"); } if(wScroll >= cont.eq(4).offset().top) { nav.removeClass("active"); nav.eq(4).addClass("active"); } if(wScroll >= cont.eq(5).offset().top) { nav.removeClass("active"); nav.eq(5).addClass("active"); } }); */ $(".mNav").click(function(){ // $(".menu").css("display", "block") //$(".menu").show(); //hide() //$(".menu").fadeIn(); //fadeOut() //$(".menu").slideDown(); //slideUP() $(".menu").toggle(); //$(".menu").fadeToggle(); // $(".menu").slideToggle(); }); $(window).resize(function() { var wWidth = $(window).Width(); //this.wWidth()를 써도 됨 //화면 크기가 800이상일 때 style="display:none" 삭제 if (wWidth > 800 && $(".menu").is(":hidden") || $(".menu").is(":show")) { //is는 찾는거 800보다 크거나 메뉴가 숨겨져 있을때 스타일 제거 $(".menu").removeAttr("style"); } });
cef1590678d14c5eb83ea5ef9ef6331b3f629729
[ "JavaScript", "HTML" ]
2
HTML
youngahRoh/portfolio0
caf37c2d5e31165c1ee15a00750dff953e97060b
eb3c43e94ee8c2506395efac8bafdfc9648ff416
refs/heads/master
<repo_name>halforc/CameraClient<file_sep>/widget.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QMouseEvent> #include <QPen> #include <QFont> #include <QPainter> #include <QMenu> #include <QPixmap> #include <QPainterPath> #include "cameractrl.h" class Widget : public QWidget { Q_OBJECT public: explicit Widget(CameraCtrl* camCtrl, QWidget *parent = 0); ~Widget(); void setPicture(QPixmap& pic); protected: void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void paintEvent(QPaintEvent *event); private: QPoint dragPosition; QPixmap m_curPic; CameraCtrl* m_camCtrl; void drawXLine(); void drawYLine(); bool m_bROIFlag; QPoint ptTopLeft; QPoint ptBottomRight; QSize roiSize; QPoint lastPoint; QPoint endPoint; // bool m_bMoveFlag; int m_iChangeSizeFlag; QRect recTopLeft; QRect recBottomRight; QRect recTopRight; QRect recBottomLeft; QPainterPath recPath;//存储ROI区域 左上角和右下角 QRect rectArea; void updateRectsInfo(); public slots: void selectROI(QRect& rect); void rectROIChanged(QRect& rect); signals: void ROIRectChanged(QRect& rect,bool modifyCam); }; #endif // WIDGET_H <file_sep>/cameractrl.cpp #include "cameractrl.h" #include <QFile> CameraCtrl::CameraCtrl(QObject *parent) : QObject(parent) ,m_acqThread(nullptr) ,m_objThread(nullptr) { m_imageFormat[0] = XI_MONO8; m_imageFormat[1] = XI_MONO16; m_imageFormat[2] = XI_RAW8; m_imageFormat[3] = XI_RAW16; m_triggerSource[0] = XI_TRG_OFF; m_triggerSource[1] = XI_TRG_EDGE_RISING; m_triggerSource[2] = XI_TRG_EDGE_FALLING; m_triggerSource[3] = XI_TRG_SOFTWARE; m_triggerSource[4] = XI_TRG_LEVEL_HIGH; m_triggerSource[5] = XI_TRG_LEVEL_LOW; connect(this,SIGNAL(rectROIChanged(QRect&,bool)),this,SLOT(recROIChanged(QRect&,bool)),Qt::DirectConnection); } CameraCtrl::~CameraCtrl() { if(m_objThread) { if(m_acqThread) { m_acqThread->stop(); } qDebug() << "quit"; m_objThread->quit(); m_objThread->wait(); } if(m_xiCam.IsAcquisitionActive()){ m_xiCam.StopAcquisition(); m_xiCam.Close(); } } //open camera bool CameraCtrl::openCamera(unsigned long devID) { qDebug()<<"***open Camera"; if(devID > m_xiCam.GetNumberOfConnectedCameras()-1){ return false; } if(m_camStatus != camClose){ closeCamera(); } m_devInfo.curDevID = devID; m_xiCam.OpenByID(devID); m_xiCam.SetExposureTime(1000); m_xiCam.SetAcquisitionTimingMode(XI_ACQ_TIMING_MODE_FRAME_RATE);//设置帧率模式 m_xiCam.SetRegion_selector(0); // default is 0 m_xiCam.SetWidth(640); m_xiCam.SetHeight(512); m_xiCam.SetFrameRate(400.0f); m_xiCam.SetExposureTime(1000); qDebug()<<"***trigger source:"<<(int)m_xiCam.GetTriggerSource(); //开启采集线程 if(!m_objThread) { startObjThread(); } m_camStatus = camOnAsquistion; emit startAcquistionWork(); return true; } //close camera void CameraCtrl::closeCamera() { qDebug()<<"***close Camera"; if(m_objThread) { if(m_acqThread) { m_acqThread->stop(); } } if(m_xiCam.IsAcquisitionActive()){ m_xiCam.StopAcquisition(); m_xiCam.Close(); } m_camStatus = camClose; } QRect CameraCtrl::getROIRect() { QRect rect(0,0,1,1); if(m_camStatus != camClose){ rect = QRect(QPoint(m_xiCam.GetOffsetX(),m_xiCam.GetOffsetY()), QSize(m_xiCam.GetWidth(),m_xiCam.GetHeight())); } return rect; } CAMSTATUS CameraCtrl::getCameraStatus() { return m_camStatus; } int CameraCtrl::setROIOffsetX(int offsetX) { if(m_camStatus != camClose){ if(offsetX > m_xiCam.GetOffsetX_Maximum() || offsetX < m_xiCam.GetOffsetY_Maximum()) return -1; offsetX = (offsetX + m_xiCam.GetOffsetX_Increment()-1)/m_xiCam.GetOffsetX_Increment(); m_xiCam.SetOffsetX(offsetX); } return offsetX; } int CameraCtrl::setROIOffsetY(int offsetY) { if(m_camStatus != camClose){ if(offsetY > m_xiCam.GetOffsetY_Maximum() || offsetY < m_xiCam.GetOffsetY_Minimum()) return -1; offsetY = (offsetY + m_xiCam.GetOffsetY_Increment()-1)/m_xiCam.GetOffsetY_Increment(); m_xiCam.SetOffsetX(offsetY); } return offsetY; } int CameraCtrl::setROIWidth(int width) { if(m_camStatus != camClose){ if(width > m_xiCam.GetWidth_Maximum() || width < m_xiCam.GetWidth_Minimum()) return -1; width = (width + m_xiCam.GetWidth_Increment()-1)/m_xiCam.GetWidth_Increment(); m_xiCam.SetWidth(width); } return width; } int CameraCtrl::setROIHeight(int height) { if(m_camStatus != camClose){ if(height > m_xiCam.GetHeight_Maximum() || height < m_xiCam.GetHeight_Minimum()) return -1; height = (height + m_xiCam.GetHeight_Increment()-1)/m_xiCam.GetHeight_Increment(); m_xiCam.SetHeight(height); } return height; } void CameraCtrl::enableAutoExposure(bool flag) { if(flag) m_xiCam.EnableAutoExposureAutoGain(); else m_xiCam.DisableAutoExposureAutoGain(); } bool CameraCtrl::setImageFormat(int index) { m_xiCam.SetImageDataFormat(m_imageFormat[index]);//wait to complete... return true; } void CameraCtrl::setTriggetSource(int index) { m_xiCam.SetTriggerSource(m_triggerSource[index]); } void CameraCtrl::setTriggetSelector(int index) { } xiAPIplusCameraOcv *CameraCtrl::getCameraHandle() { return &m_xiCam; } void CameraCtrl::startObjThread() { if(m_objThread) { return; } m_objThread= new QThread(); m_acqThread = new AcquisitionThread(&m_xiCam); m_acqThread->moveToThread(m_objThread); connect(m_objThread,&QThread::finished,m_objThread,&QObject::deleteLater); connect(m_objThread,&QThread::finished,m_acqThread,&QObject::deleteLater); connect(this,SIGNAL(startAcquistionWork()),m_acqThread,SLOT(getImage())); connect(m_acqThread,SIGNAL(sendImage(cv::Mat&)),this,SIGNAL(getCameraImage(cv::Mat&)),Qt::DirectConnection); //录制 connect(this,SIGNAL(saveImage()),m_acqThread,SLOT(saveImageToFile()),Qt::DirectConnection); connect(this,SIGNAL(stopSaveImage()),m_acqThread,SLOT(stopSaveImageToFile()),Qt::DirectConnection); connect(this,SIGNAL(setStatus(int)),m_acqThread,SLOT(getStatus(int))); m_objThread->start(); qDebug()<<"ok"; } bool CameraCtrl::readDevParaFromXML(DEVICE_INFO *pDevInfo) { return true; } void CameraCtrl::writeDevParaToXML(xiAPIplusCameraOcv &cam) { } void CameraCtrl::startAcquistion() { //开启采集线程 if(!m_objThread) { startObjThread(); } m_camStatus = camOnAsquistion; emit startAcquistionWork(); } void CameraCtrl::stopAcquistion() { if(m_objThread) { if(m_acqThread) { m_acqThread->stop(); } } if(m_xiCam.IsAcquisitionActive()){ m_xiCam.StopAcquisition(); } } void CameraCtrl::initialCamera() { m_nDevNumber = m_xiCam.GetNumberOfConnectedCameras(); if(m_nDevNumber > 0){ xiGetDeviceInfoString(0,XI_PRM_DEVICE_NAME,m_camName,256); // m_xiCam.GetCameraName(m_camName,256); emit sendCameraInfo(m_camName,m_nDevNumber); } } void CameraCtrl::recROIChanged(QRect &rect, bool modifyCam) { // setROIOffsetX(rect.x()); // setROIOffsetY(rect.y()); // setROIWidth(rect.width()); // setROIHeight(rect.height()); // qDebug()<<"********CamCtrl roi rect"<<rect; } void CameraCtrl::getCameraPara() { // m_devInfo.curExposureTime = m_xiCam.GetExposureTime(); // m_devInfo.miniExposureTime = m_xiCam.GetExposureTime_Minimum(); // m_devInfo.maxExposureTime = m_xiCam.GetExposureTime_Maximum(); // m_devInfo.exposureTimeIncrement=m_xiCam.GetExposureTime_Increment(); // m_devInfo.curFrameRate = m_xiCam.GetFrameRate(); // m_devInfo.miniFrameRate = m_xiCam.GetFrameRate_Minimum(); // m_devInfo.maxFrameRate = m_xiCam.GetFrameRate_Maximum(); // m_devInfo.frameRateIncreament = m_xiCam.GetFrameRate_Increment(); // m_devInfo.ROIInfo.curOffsetX = m_xiCam.GetOffsetX(); // m_devInfo.ROIInfo.miniOffsetX = m_xiCam.GetOffsetX_Minimum(); // m_devInfo.ROIInfo.maxOffsetX = m_xiCam.GetOffsetX_Maximum(); // m_devInfo.ROIInfo.offsetXIncreament = m_xiCam.GetOffsetX_Increment(); // m_devInfo.ROIInfo.curOffsetY = m_xiCam.GetOffsetY(); // m_devInfo.ROIInfo.miniOffsetY = m_xiCam.GetOffsetY_Minimum(); // m_devInfo.ROIInfo.maxOffsetY = m_xiCam.GetOffsetY_Increment(); // m_devInfo.ROIInfo.offsetYIncreament = m_xiCam.GetOffsetY_Increment(); // m_devInfo.bIsAutoWhiteBlance = m_xiCam.IsWhiteBalanceAuto(); // m_devInfo.ROIInfo.curWidth = m_xiCam.GetWidth(); // m_devInfo.ROIInfo.miniWidth = m_xiCam.GetWidth_Minimum(); // m_devInfo.ROIInfo.maxWidth = m_xiCam.GetWidth_Maximum(); // m_devInfo.ROIInfo.widthIncrement = m_xiCam.GetWidth_Increment(); // m_devInfo.ROIInfo.curHeight = m_xiCam.GetHeight(); // m_devInfo.ROIInfo.miniHeight = m_xiCam.GetHeight_Minimum(); // m_devInfo.ROIInfo.maxHeight = m_xiCam.GetHeight_Maximum(); // m_devInfo.ROIInfo.heightIncrement = m_xiCam.GetHeight_Increment(); // m_devInfo.imageFormate = m_xiCam.GetImageDataFormat(); // m_devInfo.trggerSource = m_xiCam.GetTriggerSource(); // m_devInfo.trggerSelector = m_xiCam.GetTriggerSelector(); } <file_sep>/inputdebouncesetup.cpp #include "inputdebouncesetup.h" #include "ui_inputdebouncesetup.h" InputDebounceSetup::InputDebounceSetup(CameraCtrl *pCameraCtrl, QWidget *parent) : QDialog(parent), ui(new Ui::InputDebounceSetup), m_camctrl(pCameraCtrl) { ui->setupUi(this); setFixedSize(size()); m_pixmap.load("../XiMeaCameraCtrl/images/debouncer_big.png"); ui->lbImage->setPixmap(m_pixmap); ui->pbT0Settint->setText(QString::number(m_camctrl->getCameraHandle()->GetGPIDebounceFirstEdge_Maximum())+"us"); ui->pbT1Setting->setText(QString::number(m_camctrl->getCameraHandle()->GetGPIDebounceSecondEdge_Maximum())+"us"); } InputDebounceSetup::~InputDebounceSetup() { delete ui; } void InputDebounceSetup::on_pbClose_clicked() { this->close(); } void InputDebounceSetup::on_pbT0Setting_clicked() { } void InputDebounceSetup::on_pbT1Setting_clicked() { } <file_sep>/widget.cpp #include "widget.h" #include <QDesktopServices> #include <QMessageBox> #include <QDebug> #include <QPolygon> #define FRAME_SIZE 32 Widget::Widget(CameraCtrl* camCtrl, QWidget *parent) : QWidget(parent), m_bROIFlag(false), m_iChangeSizeFlag(-1), m_camCtrl(camCtrl) { this->setWindowOpacity(0.5); this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); this->setMouseTracking(true); this->setAttribute(Qt::WA_TranslucentBackground); this->setFixedSize(640+FRAME_SIZE * 2,512+FRAME_SIZE * 2);//+60 } Widget::~Widget() { } void Widget::setPicture(QPixmap &pic) { m_curPic = pic; } void Widget::mousePressEvent(QMouseEvent * event){ if (event->button() == Qt::LeftButton){ QRect rec(ptTopLeft,ptBottomRight); lastPoint = event->pos(); if(recTopLeft.contains(lastPoint)){ m_iChangeSizeFlag = 1; qDebug()<<"change size"; }else if(recTopRight.contains(lastPoint)){ m_iChangeSizeFlag = 2; }else if(recBottomLeft.contains(lastPoint)){ m_iChangeSizeFlag = 3; }else if(recBottomRight.contains(lastPoint)){ m_iChangeSizeFlag = 4; }else if(rec.contains(lastPoint)){ m_iChangeSizeFlag = 0; }else{ m_iChangeSizeFlag = -1; } } } void Widget::mouseReleaseEvent(QMouseEvent * event) { if (event->button() == Qt::LeftButton && (m_iChangeSizeFlag != -1)){ endPoint = event->pos(); ptTopLeft.setX((ptTopLeft.x() + 8)/16 * 16); ptTopLeft.setY((ptTopLeft.y() + 1)/2 * 2); int w = roiSize.width(); int h = roiSize.height(); w = (w + 8)/16 * 16; h = (h + 1)/2*2; ptBottomRight.setX(ptTopLeft.x()+w); ptBottomRight.setY(ptTopLeft.y()+h); roiSize.setWidth(w); roiSize.setHeight(h); update(); event->accept(); m_iChangeSizeFlag = -1; qDebug()<<"release"; updateRectsInfo(); emit ROIRectChanged(QRect(ptTopLeft-QPoint(FRAME_SIZE,FRAME_SIZE),roiSize),true); } } void Widget::mouseMoveEvent(QMouseEvent * event){ if(!m_bROIFlag) return; if(recTopLeft.contains(event->pos()) || recBottomRight.contains(event->pos())){ this->setCursor(Qt::SizeFDiagCursor); }else if(recTopRight.contains(event->pos()) || recBottomLeft.contains(event->pos())){ this->setCursor(Qt::SizeBDiagCursor); }else{ this->setCursor(Qt::ArrowCursor); } if (event->buttons() == Qt::LeftButton && m_iChangeSizeFlag != -1){ endPoint = event->pos(); QRect rectROI = QRect(ptTopLeft,ptBottomRight); QRect rect(FRAME_SIZE,FRAME_SIZE,640,512); switch(m_iChangeSizeFlag){ case 0: if(ptTopLeft.x() < rect.x()){ ptTopLeft.setX(rect.topLeft().x() + 1); ptBottomRight.setX(ptTopLeft.x()+rectROI.width()-1); qDebug()<<"not 1"; }else if(ptTopLeft.y() < rect.y()){ ptTopLeft.setY(rect.topLeft().y() + 1); ptBottomRight.setY(ptTopLeft.y()+rectROI.height()-1); }else if(ptBottomRight.x() > rect.bottomRight().x()){ qDebug()<<"not 2"; ptBottomRight.setX(rect.bottomRight().x() - 1); ptTopLeft.setX(ptBottomRight.x()-rectROI.width()+1); qDebug()<<"not 3"; }else if(ptBottomRight.y() > rect.bottomRight().y()){ ptBottomRight.setY(rect.bottomRight().y() - 1); ptTopLeft.setY(ptBottomRight.y()-rectROI.height()+1); qDebug()<<"not 4"; }else{ ptTopLeft = ptTopLeft + endPoint-lastPoint; ptBottomRight = ptBottomRight + endPoint-lastPoint; } // qDebug()<<"point:"<<ptTopLeft; lastPoint = endPoint; // qDebug()<<"move" << ptTopLeft; recPath.translate(endPoint-lastPoint); emit ROIRectChanged(QRect(ptTopLeft,roiSize),false); break; case 1: if(endPoint.x() >= rect.topLeft().x() && endPoint.x() <= ptBottomRight.x() - 160&& endPoint.y() >= rect.topLeft().y() && endPoint.y() <= ptBottomRight.y()-128){ ptTopLeft = endPoint;//TopLeft } break; case 2: if(endPoint.x() <= rect.topRight().x() && endPoint.x() >= ptTopLeft.x()+160&& endPoint.y() >= rect.topRight().y()&&endPoint.y() <= ptBottomRight.y()-128){ ptTopLeft.setY(endPoint.y());//TopRight ptBottomRight.setX(endPoint.x()); } break; case 3: if(endPoint.x() >= rect.bottomLeft().x() && endPoint.x() <= ptBottomRight.x()-160&& endPoint.y() <= rect.bottomLeft().y() && endPoint.y() >= ptTopLeft.y()+128){ ptTopLeft.setX(endPoint.x());//bottomleft ptBottomRight.setY(endPoint.y()); } break; case 4: if(endPoint.x() <= rect.bottomRight().x() && endPoint.x() >= ptTopLeft.x()+160&& endPoint.y() <= rect.bottomRight().y() && endPoint.y() >= ptTopLeft.y()+128){ ptBottomRight = endPoint;//bottomright } break; default: break; } if(m_iChangeSizeFlag != 0){ emit ROIRectChanged(QRect(ptTopLeft-QPoint(FRAME_SIZE,FRAME_SIZE),ptBottomRight),false); roiSize = QSize(QRect(ptTopLeft,ptBottomRight).size()); } update(FRAME_SIZE,FRAME_SIZE,640,512); event->accept(); } } void Widget::paintEvent(QPaintEvent *event){ QPainter p(this); p.fillRect(rect(), QColor(255,255,255,150)); p.drawPixmap(FRAME_SIZE,FRAME_SIZE,640,512,m_curPic); if(m_bROIFlag){ p.setPen(QPen(QColor("#ff0000"), 1, Qt::SolidLine)); // QRect rectROI = QRect(ptTopLeft,ptBottomRight); // QRect rect(FRAME_SIZE,FRAME_SIZE,640,512); // if (!rect.contains(rectROI)){ // qDebug()<<"not contains"; // } p.drawRect(QRect(ptTopLeft,ptBottomRight)); } drawXLine(); drawYLine(); int iwidth=this->width(); int iheight=this->height(); QPainter p2(this); p2.setPen(QPen(QColor("#ddd"), 1, Qt::SolidLine)); p2.drawRect(0,0,iwidth-1,iheight-1); } void Widget::drawXLine(){ QPainter p(this); p.setRenderHint(QPainter::Antialiasing, false); p.setPen(QPen(QColor("#000"), 1, Qt::SolidLine)); QString str; int lineHeight = 15; int mid = this->width() / 2; QFont font(QFont("Arial", 8, QFont::Bold)); p.setFont(font); p.drawText(mid - 3, 0, 25, 12, Qt::AlignLeft, QString::number(0)+"°"); p.drawLine(QPoint(mid, FRAME_SIZE), QPoint(mid, FRAME_SIZE-lineHeight)); p.drawText(mid - 3, 0 + 512 + 50, 25, 12, Qt::AlignLeft, QString::number(0)+"°"); p.drawLine(QPoint(mid, this->height()-FRAME_SIZE), QPoint(mid, this->height()-FRAME_SIZE+lineHeight)); for (int i = 0; mid - i > 0; i+=10) { if( i == 0) continue; if((mid - i) < FRAME_SIZE) break; if(i % 10 == 0){ lineHeight = 10; } if (i % 50 == 0) { p.setFont(QFont("Arial", 8, QFont::Bold)); str = QString::number(i/10); p.drawText( mid - i -3 * str.length(), 0, 25, 12, Qt::AlignLeft, "-"+str+"°"); p.drawText( mid + i -3 * str.length(), 0, 25, 12, Qt::AlignLeft, str+"°"); p.drawText( mid - i -3 * str.length(), 0 + 512+ 50, 25, 12, Qt::AlignLeft, "-"+str+"°"); p.drawText( mid + i -3 * str.length(), 0 +512 + 50, 25, 12, Qt::AlignLeft, str+"°"); lineHeight = 15; } p.drawLine(QPoint(mid - i, FRAME_SIZE), QPoint(mid - i, FRAME_SIZE-lineHeight)); p.drawLine(QPoint(mid + i, FRAME_SIZE), QPoint(mid + i, FRAME_SIZE-lineHeight)); p.drawLine(QPoint(mid - i, this->height() - FRAME_SIZE), QPoint(mid - i, this->height() - FRAME_SIZE+lineHeight)); p.drawLine(QPoint(mid + i, this->height() - FRAME_SIZE), QPoint(mid + i, this->height() - FRAME_SIZE+lineHeight)); p.drawLine(QPoint(mid - i, this->height() - FRAME_SIZE + 512), QPoint(mid - i, this->height() - FRAME_SIZE+lineHeight+ 512)); p.drawLine(QPoint(mid + i, this->height() - FRAME_SIZE+ 512), QPoint(mid + i, this->height() - FRAME_SIZE+lineHeight+ 512)); } QPolygon polygon1,polygon2; polygon1 << QPoint(mid, FRAME_SIZE); polygon1 << QPoint(mid-6, FRAME_SIZE-10); polygon1 << QPoint(mid+6, FRAME_SIZE-10); polygon2 << QPoint(mid, FRAME_SIZE+512); polygon2 << QPoint(mid-6, FRAME_SIZE+10+512); polygon2 << QPoint(mid+6, FRAME_SIZE+10+512); p.setBrush(Qt::red); p.drawConvexPolygon(polygon1); p.drawConvexPolygon(polygon2); p.setPen(QPen(QColor("#FFFFFF"), 1, Qt::SolidLine)); p.drawLine(QPoint(width()/2-15,height()/2),QPoint(width()/2+15,height()/2)); p.drawLine(QPoint(width()/2,height()/2-15),QPoint(width()/2,height()/2+15)); } void Widget::drawYLine(){ QPainter p(this); p.setRenderHint(QPainter::Antialiasing, false); p.setPen(QPen(QColor("#000"), 1, Qt::SolidLine)); int lineHeight = 15; QString str; int mid = this->height() / 2; QFont font(QFont("Arial", 8, QFont::Bold)); p.setFont(font); p.drawText(2, mid - 7, 25, 12, Qt::AlignLeft, QString::number(0)+"°"); p.drawLine(QPoint(FRAME_SIZE, mid), QPoint(FRAME_SIZE-lineHeight, mid)); p.drawText(640 + 2 + 50, mid - 7, 25, 12, Qt::AlignLeft, QString::number(0)+"°"); p.drawLine(QPoint(this->width()-FRAME_SIZE, mid), QPoint(this->width()-FRAME_SIZE+lineHeight, mid)); for (int i = 0; mid - i > 0; i+=10) { if(i == 0) continue; if((mid - i) < FRAME_SIZE || i == 0) break; if(i % 10 == 0){ lineHeight = 10; } if (i % 50 == 0 && i>0) { p.drawText(2, mid-i-7, 25, 12, Qt::AlignLeft, "-"+QString::number(i/10)+"°"); p.drawText(2, mid+i-7, 25, 12, Qt::AlignLeft, QString::number(i/10)+"°"); p.drawText(2+ 640 + 45, mid-i-7, 25 , 12, Qt::AlignLeft, "-"+QString::number(i/10)+"°"); p.drawText(2+ 640 + 45, mid+i-7, 25, 12, Qt::AlignLeft, QString::number(i/10)+"°"); lineHeight = 15; } p.drawLine(QPoint(FRAME_SIZE, mid - i), QPoint(FRAME_SIZE-lineHeight, mid - i)); p.drawLine(QPoint(FRAME_SIZE, mid + i), QPoint(FRAME_SIZE-lineHeight, mid + i)); p.drawLine(QPoint(this->width()-FRAME_SIZE, mid - i), QPoint(this->width()-FRAME_SIZE+lineHeight, mid - i)); p.drawLine(QPoint(this->width()-FRAME_SIZE, mid + i), QPoint(this->width()-FRAME_SIZE+lineHeight, mid + i)); p.drawLine(QPoint(this->width()-FRAME_SIZE+ 640, mid - i), QPoint(this->width()-FRAME_SIZE+lineHeight+ 640, mid - i)); p.drawLine(QPoint(this->width()-FRAME_SIZE+ 640, mid + i), QPoint(this->width()-FRAME_SIZE+lineHeight+ 640, mid + i)); } QPolygon polygon1,polygon2; polygon1 << QPoint(FRAME_SIZE,mid); polygon1 << QPoint(FRAME_SIZE-10,mid-6); polygon1 << QPoint(FRAME_SIZE-10,mid+6); polygon2 << QPoint(FRAME_SIZE+640,mid); polygon2 << QPoint(FRAME_SIZE+10+640,mid-6); polygon2 << QPoint(FRAME_SIZE+10+640,mid+6); p.setBrush(Qt::red); p.drawConvexPolygon(polygon1); p.drawConvexPolygon(polygon2); } void Widget::updateRectsInfo() { recTopLeft = QRect(QPoint(ptTopLeft.x()-2,ptTopLeft.y()-2),QSize(4,4)); recTopRight =QRect(QPoint(ptBottomRight.x()-2,ptTopLeft.y()-2),QSize(4,4)); recBottomLeft = QRect(QPoint(ptTopLeft.x()-2,ptBottomRight.y()-2),QSize(4,4)); recBottomRight = QRect(QPoint(ptBottomRight.x()-2,ptBottomRight.y()-2),QSize(4,4)); } void Widget::selectROI(QRect& rect) { m_bROIFlag = !m_bROIFlag; if(m_bROIFlag){ ptTopLeft = rect.topLeft() + QPoint(FRAME_SIZE,FRAME_SIZE); ptBottomRight = rect.bottomRight() + QPoint(FRAME_SIZE,FRAME_SIZE); roiSize = rect.size(); updateRectsInfo(); recPath.addRect(recTopLeft); recPath.addRect(recTopRight); recPath.addRect(recBottomLeft); recPath.addRect(recBottomRight); qDebug()<<"selectROI****"<<rect; } update(); } void Widget::rectROIChanged(QRect& rect) { ptTopLeft = rect.topLeft(); ptBottomRight = rect.bottomRight(); roiSize = rect.size(); update(); qDebug()<<"widget changed" << rect; } <file_sep>/acquisitionthread.h #ifndef ACQUISITIONTHREAD_H #define ACQUISITIONTHREAD_H #include <QObject> #include <QMutex> #include <QThread> #include <string> #include "./XiAPI/xiApiPlusOcv.hpp" #include "typedefine.h" class AcquisitionThread : public QObject { Q_OBJECT public: AcquisitionThread(QObject* parent = NULL); AcquisitionThread(xiAPIplusCameraOcv* cam, QObject* parent = NULL); ~AcquisitionThread(){} void stop(); public slots: void getImage(); void test(); void saveImageToFile(); void stopSaveImageToFile(); signals: void sendImage(cv::Mat& image); void message(QString str); private: //QThread m_thread; bool imageToStreamFile(cv::Mat image, QString filename); bool StreamFileToImage(QString filename, cv::Mat &image); void writeConfigFile(QString filename); xiAPIplusCameraOcv* m_xiCam; bool mStart; QMutex mutex; int m_nCount; int m_status; QString strPath; }; #endif // ACQUISITIONTHREAD_H <file_sep>/acquisitionthread.cpp #include "acquisitionthread.h" #include <QThread> #include <QDebug> #include <QMutexLocker> #include <fstream> #include <QDateTime> #include <QDir> #include <qxmlstream.h> #include <QTime> AcquisitionThread::AcquisitionThread(QObject *parent) : QObject(parent) { } AcquisitionThread::AcquisitionThread(xiAPIplusCameraOcv* cam, QObject *parent) : QObject(parent), m_xiCam(cam), m_nCount(0), m_status(camClose) { // m_thread.start(); // this->moveToThread(&m_thread); } void AcquisitionThread::stop() { QMutexLocker locker(&mutex); mStart = false; m_xiCam->StopAcquisition(); } void AcquisitionThread::getImage() { mStart = true; cv::Mat cv_mat_image; QString strName; XI_IMG_FORMAT format; { QMutexLocker locker(&mutex); m_xiCam->StartAcquisition(); m_status = camOnAsquistion; } while(true){ //qDebug()<<"status"<<m_status; if(m_status == camOnAsquistion){ { QMutexLocker locker(&mutex); if(!mStart) return; qDebug()<<"trigger source:"<<(int)m_xiCam->GetTriggerSource(); format = m_xiCam->GetImageDataFormat(); cv_mat_image = m_xiCam->GetNextImageOcvMat(); } if(m_status == camRecording){ if(m_nCount == 0){ QDateTime local(QDateTime::currentDateTime()); QString localTime = local.toString("yyyyMMddhhmmss"); qDebug()<<localTime; QDir dir; if(!dir.exists(localTime))//判断需要创建的文件夹是否存在 { qDebug()<<"Create File Dir"; dir.mkdir(localTime); //创建文件夹 } strPath = ".//"+localTime + "//"; } strName = strPath + "image "+ QString::number(m_nCount)+".dat"; imageToStreamFile(cv_mat_image,strName); QTime current_time =QTime::currentTime(); int msec = current_time.msec();//当前的毫秒 qDebug()<<QString::number(msec); qDebug()<<"save file "<<strName; m_nCount++; }else if(m_status == camStopRecord){ writeConfigFile(strPath + "configInfo.xml"); m_nCount = 0;//溢出问题 m_status = camOnAsquistion; }else{ if (format == XI_RAW16 || format == XI_MONO16) cv::normalize(cv_mat_image, cv_mat_image, 0, 65536, cv::NORM_MINMAX, -1, cv::Mat()); // 0 - 65536, 16 bit unsigned integer range emit sendImage(cv_mat_image); } } } } void AcquisitionThread::test() { qDebug()<<"test in asq thread"; message("send from acq thread"); } void AcquisitionThread::saveImageToFile() { qDebug()<<"save"; m_status = camRecording; } void AcquisitionThread::stopSaveImageToFile() { qDebug()<<"stop"; m_status = camStopRecord; } bool AcquisitionThread::imageToStreamFile(cv::Mat image, QString filename) { if (image.empty()) return false; QByteArray cpath = filename.toLocal8Bit(); const char *filenamechar = cpath.data(); FILE *fpw = fopen(filenamechar, "wb");//如果没有则创建,如果存在则从头开始写 if (fpw == NULL) { fclose(fpw); return false; } int channl = image.channels();//第一个字节 通道 int rows = image.rows; //四个字节存 行数 int cols = image.cols; //四个字节存 列数 fwrite(&channl, sizeof(char), 1, fpw); fwrite(&rows, sizeof(char), 4, fpw); fwrite(&cols, sizeof(char), 4, fpw); char* dp = (char*)image.data; if (channl == 3) { for (int i = 0; i < rows*cols; i++) { fwrite(&dp[i * 3], sizeof(char), 1, fpw); fwrite(&dp[i * 3 + 1], sizeof(char), 1, fpw); fwrite(&dp[i * 3 + 2], sizeof(char), 1, fpw); } } else if (channl == 1) { for (int i = 0; i < rows*cols; i++) { fwrite(&dp[i], sizeof(char), 1, fpw); } } fclose(fpw); return true; } bool AcquisitionThread::StreamFileToImage(QString filename, cv::Mat &image) { QByteArray cpath = filename.toLocal8Bit(); const char *filenamechar = cpath.data(); FILE *fpr = fopen(filenamechar, "rb"); if (fpr == NULL) { fclose(fpr); return false; } int channl(0); int imagerows(0); int imagecols(0); fread(&channl, sizeof(char), 1, fpr);//第一个字节 通道 fread(&imagerows, sizeof(char), 4, fpr); //四个字节存 行数 fread(&imagecols, sizeof(char), 4, fpr); //四个字节存 列数 if (channl == 3) { image = cv::Mat::zeros(imagerows,imagecols, CV_8UC3); char* pData = (char*)image.data; for (int i = 0; i < imagerows*imagecols; i++) { fread(&pData[i * 3], sizeof(char), 1, fpr); fread(&pData[i * 3 + 1], sizeof(char), 1, fpr); fread(&pData[i * 3 + 2], sizeof(char), 1, fpr); } } else if (channl == 1) { image = cv::Mat::zeros(imagerows, imagecols, CV_8UC1); char* pData = (char*)image.data; for (int i = 0; i < imagerows*imagecols; i++) { fread(&pData[i], sizeof(char), 1, fpr); } } fclose(fpr); return true; } void AcquisitionThread::writeConfigFile(QString filename) { QFile file(filename); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug()<<"open filed"; return; } QXmlStreamWriter xmlWriter(&file); xmlWriter.setAutoFormatting(true); xmlWriter.writeStartDocument(); //XiMea Cameara xmlWriter.writeStartElement("XiMea Cameara USB3.0 file info"); xmlWriter.writeTextElement(tr("frame number"),QString::number(m_nCount)); xmlWriter.writeTextElement(tr("first frame"),strPath + tr("image 0.dat")); xmlWriter.writeEndElement(); //相机参数 xmlWriter.writeEndDocument(); file.close(); } <file_sep>/inputdebouncesetup.h #ifndef INPUTDEBOUNCESETUP_H #define INPUTDEBOUNCESETUP_H #include <QDialog> #include <QPixmap> #include "cameractrl.h" namespace Ui { class InputDebounceSetup; } class InputDebounceSetup : public QDialog { Q_OBJECT public: explicit InputDebounceSetup(CameraCtrl* pCameraCtrl,QWidget *parent = 0); ~InputDebounceSetup(); private slots: void on_pbClose_clicked(); void on_pbT0Setting_clicked(); void on_pbT1Setting_clicked(); private: Ui::InputDebounceSetup *ui; CameraCtrl* m_camctrl; QPixmap m_pixmap; }; #endif // INPUTDEBOUNCESETUP_H <file_sep>/roidefine.cpp #include "roidefine.h" #include "ui_roidefine.h" #include <QDebug> ROIDefine::ROIDefine(QWidget *parent) : QDialog(parent), ui(new Ui::ROIDefine) { ui->setupUi(this); } ROIDefine::ROIDefine(CameraCtrl* camctrl, QWidget *parent) : QDialog(parent), ui(new Ui::ROIDefine), m_camCtrl(camctrl) { ui->setupUi(this); m_cam = m_camCtrl->getCameraHandle(); ui->offsetX->setMaximum(m_cam->GetOffsetX_Maximum()); ui->offsetX->setMinimum(m_cam->GetOffsetX_Minimum()); ui->offsetY->setMaximum(m_cam->GetOffsetY_Maximum()); ui->offsetY->setMinimum(m_cam->GetOffsetY_Minimum()); ui->Width->setMaximum(m_cam->GetWidth_Maximum()); ui->Width->setMinimum(m_cam->GetWidth_Minimum()); ui->Height->setMaximum(m_cam->GetHeight_Maximum()); ui->Height->setMinimum(m_cam->GetHeight_Minimum()); m_rectROI = QRect(QPoint(m_cam->GetOffsetX(),m_cam->GetOffsetX()), QSize(m_cam->GetWidth(),m_cam->GetHeight())); ui->offsetX->setValue(m_rectROI.x()); ui->offsetY->setValue(m_rectROI.y()); ui->Width->setValue(m_rectROI.width()); ui->Height->setValue(m_rectROI.height()); // ui->offsetX->setSingleStep(16); // ui->offsetY->setSingleStep(2); // ui->Width->setSingleStep(16); // ui->Height->setSingleStep(2); // ui->offsetX->setMaximum(640); // ui->offsetY->setRange(0,512); // ui->Width->setRange(160,640); // ui->Height->setRange(126,512); } ROIDefine::~ROIDefine() { delete ui; } void ROIDefine::on_pbOK_clicked() { emit notifyParent(m_rectROI,true); } void ROIDefine::on_pbCancel_clicked() { emit notifyParent(m_rectROI,false); } void ROIDefine::on_offsetX_valueChanged(int value) { qDebug()<<"on_offsetX_valueChanged"<<value; value = (value+8)/16 * 16; if(value > m_cam->GetOffsetX_Maximum()) value = m_cam->GetOffsetX_Maximum(); ui->offsetX->setValue(value); m_rectROI.setX(value); if(ui->offsetX->hasFocus()) emit ROIRectChanged(m_rectROI); } void ROIDefine::on_offsetY_valueChanged(int value) { // qDebug()<<"on_offsetY_valueChanged"<<value; value = (value + 1)/2 * 2; if(value > m_cam->GetOffsetY_Maximum()) value = m_cam->GetOffsetX_Maximum(); ui->offsetY->setValue(value); m_rectROI.setY(value); if(ui->offsetY->hasFocus()) emit ROIRectChanged(m_rectROI); } void ROIDefine::on_Width_valueChanged(int value) { // qDebug()<<"on_Width_valueChanged"<<value; value = (value+ 8)/16 * 16; if(value > m_cam->GetWidth_Maximum()) value = m_cam->GetWidth_Maximum(); ui->Width->setValue(value); m_rectROI.setWidth(value); if(ui->Width->hasFocus()) emit ROIRectChanged(m_rectROI); } void ROIDefine::on_Height_valueChanged(int value) { // qDebug()<<"on_Height_valueChanged"<<value; value = (value + 1)/2 * 2; if(value > m_cam->GetHeight_Maximum()) value = m_cam->GetHeight_Maximum(); ui->Height->setValue(value); m_rectROI.setHeight(value); if(ui->Height->hasFocus()) emit ROIRectChanged(m_rectROI); } void ROIDefine::changedROI(QRect &rect,bool flag) { ui->offsetX->setValue(rect.x()); ui->offsetY->setValue(rect.y()); ui->Width->setValue(rect.width()); ui->Height->setValue(rect.height()); qDebug()<<"ROIDefine roidefine"<<rect; if(flag){ m_camCtrl->getCameraHandle()->SetOffsetX(rect.x()); m_camCtrl->getCameraHandle()->SetOffsetY(rect.y()); m_camCtrl->getCameraHandle()->SetWidth(rect.width()); m_camCtrl->getCameraHandle()->SetHeight(rect.height()); } } <file_sep>/typedefine.h #ifndef TYPEDEFINE_H #define TYPEDEFINE_H #include "./XiAPI/xiApiPlusOcv.hpp" #include <QStringList> enum WORKSMODE{fileReplayMode,camAsquistionMode}; enum CAMSTATUS{camClose,camOnAsquistion,camRecording,camStopRecord}; typedef struct { int curOffsetX; int miniOffsetX;//OffsetX int maxOffsetX; int offsetXIncreament; int curOffsetY; int miniOffsetY;//OffsetY int maxOffsetY; int offsetYIncreament; int curWidth; int miniWidth;//width int maxWidth; int widthIncrement; int curHeight; int miniHeight;//height int maxHeight; int heightIncrement; }ROI_INFO,*pROI_INFO; typedef struct{ int curDevID; int curExposureTime; int miniExposureTime; //ExposureTime int maxExposureTime; int exposureTimeIncrement; float curFrameRate; float miniFrameRate; //framerate float maxFrameRate; float frameRateIncreament; ROI_INFO ROIInfo; bool bIsAutoWhiteBlance;//Auto White Blance XI_IMG_FORMAT imageFormate; XI_TRG_SOURCE trggerSource; XI_TRG_SELECTOR trggerSelector; //触发方式 }DEVICE_INFO,*PDEV_INFO; typedef struct{ int priority; int maxExposure; int maxGain; int targetLevel; }AEAG_PARA,*PAEAG_PARA; #endif // TYPEDEFINE_H <file_sep>/roidefine.h #ifndef ROIDEFINE_H #define ROIDEFINE_H #include <QDialog> #include "cameractrl.h" #include <QEvent> namespace Ui { class ROIDefine; } class ROIDefine : public QDialog { Q_OBJECT public: explicit ROIDefine(QWidget *parent = 0); ROIDefine(CameraCtrl *camctrl, QWidget *parent = 0); ~ROIDefine(); private slots: void on_pbOK_clicked(); void on_pbCancel_clicked(); void on_offsetX_valueChanged(int value); void on_offsetY_valueChanged(int value); void on_Width_valueChanged(int value); void on_Height_valueChanged(int value); public: void changedROI(QRect& rect, bool flag=false);//connected with camctrl - rectROIChanged signals: void ROIRectChanged(QRect& rect); void notifyParent(QRect rect,bool bSave); private: Ui::ROIDefine *ui; CameraCtrl* m_camCtrl; xiAPIplusCameraOcv* m_cam; QRect m_rectROI; }; #endif // ROIDEFINE_H <file_sep>/autoexposuresetup.h #ifndef AUTOEXPOSURESETUP_H #define AUTOEXPOSURESETUP_H #include <QDialog> #include "cameractrl.h" namespace Ui { class AutoExposureSetup; } class AutoExposureSetup : public QDialog { Q_OBJECT public: explicit AutoExposureSetup(CameraCtrl* camCtrl, QWidget *parent = 0); ~AutoExposureSetup(); private slots: void onPriorityChanged(int val); void onMaxExposureChanged(int val); void onMaxGainChanged(int val); void onTargetLevelChanged(int val); private: Ui::AutoExposureSetup *ui; CameraCtrl* m_camctrl; xiAPIplusCameraOcv* m_xiCam; QString formatExposureTimeShow(int val); }; #endif // AUTOEXPOSURESETUP_H <file_sep>/cameractlwidget.cpp #include "cameractlwidget.h" #include "ui_cameractlwidget.h" #include <QFile> #include <QDebug> #include "inputdebouncesetup.h" CameraCtlWidget::CameraCtlWidget(QWidget *parent) : QWidget(parent), m_wndParent(parent), ui(new Ui::CameraCtlWidget), m_camCtrl(nullptr), m_bIsRecording(false), m_bIsAutoExposure(false), m_wROIDefine(nullptr), m_wAutoExposureDlg(nullptr) { // //设置界面主题 // QFile file("..//XiMeaCameraCtrl//style//newstyle.qss"); // if(!file.open(QFile::ReadOnly)){ // qDebug()<<"open failed"; // } // QString styleSheet = QLatin1String(file.readAll()); // qApp->setStyleSheet(styleSheet); // file.close(); //固定窗口大小 ui->setupUi(this); this->setFixedSize(this->size()); ui->pbROI->setCheckable(true); ui->pbROI->setChecked(false); myTimer = new QTimer(this); tcpSocket=new QTcpSocket(this); //TCP connect(myTimer,SIGNAL(timeout()),this,SLOT(SendData())); QStringList list; list << tr("1280*1024")<<tr("640*512"); ui->comImageDPI->addItems(list); ui->comImageDPI->setCurrentIndex(0); list.clear(); list <<tr("Mono8")<<tr("Mono16")<<tr("Raw8") <<tr("Raw16"); ui->comImageType->addItems(list); ui->comImageType->setCurrentIndex(1); list.clear(); list<<tr("off")<<tr("Rising") <<tr("Falling edge")<<tr("Software"); ui->comTriggerSource->addItems(list); list.clear(); list<<tr("Frame start")<<tr("Exposure active") <<tr("Frame burst start")<<tr("Frame burst active") <<tr("Multitle exposure"); ui->comTriggerSelector->addItems(list); list.clear(); list<<tr("off")<<tr("Trigger"); ui->comGPI->addItems(list); list.clear(); list<<tr("Off")<<tr("On")<<tr("Frame active")<<tr("Frame active(neg.)") <<tr("Exposure active")<<tr("Exposure active(neg.)") <<tr("Frame trigger wait")<<tr("Frame trigger wait(neg.)") <<tr("Exposure pulse")<<tr("Exposure pulse(neg.)"); ui->comGPO->addItems(list); list.clear(); ui->pbDebounceSetup->setEnabled(false); ui->pbSWPing->setEnabled(false); m_camCtrl = new CameraCtrl(); connect(m_camCtrl,SIGNAL(getCameraImage(cv::Mat&)),this,SLOT(getCameraImage(cv::Mat&)),Qt::DirectConnection); connect(ui->comImageDPI,SIGNAL(currentIndexChanged(int)),this,SLOT(onComDPIChanged(int))); connect(ui->comImageType,SIGNAL(currentIndexChanged(int)),this,SLOT(onComImageTypeChanged(int))); connect(ui->comTriggerSelector,SIGNAL(currentIndexChanged(int)),this,SLOT(onComTriggerSelectorChanged(int))); connect(ui->comTriggerSource,SIGNAL(currentIndexChanged(int)),this,SLOT(onComTriggerSourceChanged(int))); connect(ui->checkAutoExposure,SIGNAL(clicked(bool)),this,SLOT(onEnableAutoExposure(bool))); connect(ui->checkDebounce,SIGNAL(clicked(bool)),this,SLOT(onEnableDebounce(bool))); } CameraCtlWidget::~CameraCtlWidget() { qDebug() << "start destroy widget"; if(m_camCtrl != nullptr){ delete m_camCtrl; m_camCtrl = nullptr; } qDebug() << "end destroy widget"; delete ui; } void CameraCtlWidget::on_test_clicked() { m_wndParent->close(); } void CameraCtlWidget::openCamera(unsigned long devID) { m_camCtrl->openCamera(devID); initial(); myTimer->start(40); } void CameraCtlWidget::closeCamera() { m_camCtrl->closeCamera(); myTimer->stop(); } void CameraCtlWidget::rectROIChanged(QRect &rect, bool flag) { // m_camCtrl->setROIOffsetX(rect.x()); // m_camCtrl->setROIOffsetY(rect.y()); // m_camCtrl->setROIWidth(rect.width()); // m_camCtrl->setROIHeight(rect.height()); if(m_wROIDefine){ m_wROIDefine->changedROI(rect); } qDebug()<<"CameraCtlWidget"<<rect; } void CameraCtlWidget::getCameraImage(cv::Mat &image) { myImage = Mat2QImage(image); m_curImage = QPixmap::fromImage(myImage); } void CameraCtlWidget::SendData() { blockSize=0; tcpSocket->abort(); tcpSocket->connectToHost("192.168.1.101",8888); QByteArray byte; QBuffer buf(&byte); myImage.save(&buf,"PNG"); QByteArray ss=qCompress(byte,1); QByteArray vv=ss.toBase64(); QByteArray ba; QDataStream out(&ba,QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_6); out<<(quint64)0; out<<vv; out.device()->seek(0); out<<(quint64)(ba.size()-sizeof(quint64)); tcpSocket->write(ba); emit updatePic(m_curImage); } void CameraCtlWidget::onComDPIChanged(int index) { if(camClose == m_camCtrl->getCameraStatus()) return; switch (index) { case 0: m_camCtrl->getCameraHandle()->SetDownsampling(XI_DWN_1x1); break; case 1: m_camCtrl->getCameraHandle()->SetDownsampling(XI_DWN_2x2); break; default: break; } updateFrameRateInfo(); } void CameraCtlWidget::onComImageTypeChanged(int index) { if(camClose == m_camCtrl->getCameraStatus()) return; qDebug()<<"onComImageTypeChanged"<<index; m_camCtrl->setImageFormat(index); } void CameraCtlWidget::on_pbDefine_clicked() { qDebug()<<"on_pbDefine_clicked"; if(nullptr != m_wROIDefine){ m_wROIDefine->close(); delete m_wROIDefine; m_wROIDefine = nullptr; }else{ m_wROIDefine = new ROIDefine(m_camCtrl,this); connect(this,SIGNAL(ROIRectChanged(QRect&,bool)),this,SLOT(rectROIChanged(QRect&,bool)),Qt::DirectConnection); connect(m_wROIDefine,SIGNAL(ROIRectChanged(QRect&)),this,SIGNAL(notifyWidgetAreaROI(QRect&)),Qt::DirectConnection); connect(m_wROIDefine,SIGNAL(notifyParent(QRect,bool)),this,SLOT(onReceiveDefine(QRect,bool))); m_wROIDefine->setModal(false); m_wROIDefine->show(); } emit selectROI(/*m_camCtrl->getROIRect()*/QRect(0,0,320,256)); } void CameraCtlWidget::on_pbROI_clicked() { static bool flag = false; flag = !flag; ui->pbROI->setChecked(flag); if(flag){ if(ui->comImageDPI->currentIndex() == 0){ m_camCtrl->getCameraHandle()->SetOffsetX(0); m_camCtrl->getCameraHandle()->SetOffsetY(0); m_camCtrl->getCameraHandle()->SetWidth(1280); m_camCtrl->getCameraHandle()->SetHeight(1024); } if(ui->comImageDPI->currentIndex() == 1){ m_camCtrl->getCameraHandle()->SetOffsetX(0); m_camCtrl->getCameraHandle()->SetOffsetY(0); m_camCtrl->getCameraHandle()->SetWidth(640); m_camCtrl->getCameraHandle()->SetHeight(512); } m_camCtrl->getCameraHandle()->SetRegion_selector(0); }else{ m_camCtrl->getCameraHandle()->SetOffsetX(rectROI.x()); m_camCtrl->getCameraHandle()->SetOffsetY(rectROI.y()); m_camCtrl->getCameraHandle()->SetWidth(rectROI.width()); m_camCtrl->getCameraHandle()->SetHeight(rectROI.height()); } } void CameraCtlWidget::on_pbSWPing_clicked() { m_camCtrl->getCameraHandle()->SetTriggerSoftware(1); myImage = Mat2QImage(m_camCtrl->getCameraHandle()->GetNextImageOcvMat()); m_curImage = QPixmap::fromImage(myImage); } void CameraCtlWidget::onReceiveDefine(QRect rect, bool bSave) { m_wROIDefine->close(); delete m_wROIDefine; m_wROIDefine = nullptr; if(bSave){ rectROI = rect; } emit selectROI(rectROI); } void CameraCtlWidget::on_pbAutoExposureSetup_clicked() { m_wAutoExposureDlg = new AutoExposureSetup(m_camCtrl,this); m_wAutoExposureDlg->setModal(false); m_wAutoExposureDlg->show(); } void CameraCtlWidget::on_pbDebounceSetup_clicked() { m_wInputDebounceSetup = new InputDebounceSetup(m_camCtrl, this); m_wInputDebounceSetup->setModal(true); m_wInputDebounceSetup->show(); } void CameraCtlWidget::onComTriggerSelectorChanged(int index) { qDebug()<<"onComTriggerSelectorChanged"<<index; } void CameraCtlWidget::onComTriggerSourceChanged(int index) { qDebug()<<"onComTriggerSourceChanged"<<index; m_camCtrl->stopAcquistion(); if(index == 3){ ui->pbSWPing->setEnabled(true); }else{ ui->pbSWPing->setEnabled(false); } m_camCtrl->setTriggetSource(index); m_camCtrl->getCameraHandle()->StartAcquisition(); } void CameraCtlWidget::onEnableAutoExposure(bool flag) { qDebug()<<flag; ui->sliderExposure->setEnabled(!flag); ui->sliderGain->setEnabled(!flag); m_camCtrl->enableAutoExposure(flag); m_bIsAutoExposure = flag; } void CameraCtlWidget::onEnableDebounce(bool flag) { ui->pbDebounceSetup->setEnabled(flag); if(flag){ m_camCtrl->getCameraHandle()->EnableGPIDebounce(); }else{ m_camCtrl->getCameraHandle()->DisableGPIDebounce(); } } void CameraCtlWidget::on_leExposure_textChanged(QString str) { qDebug()<<"on_leExposure_textChanged"<<str; } void CameraCtlWidget::on_leGain_textChanged(QString str) { qDebug()<<"onComTriggerSourceChanged"<<str; } void CameraCtlWidget::on_sliderExposure_valueChanged(int val) { qDebug()<<"onComTriggerSourceChanged"<<val; ui->leExposure->setText(QString::number(val)); m_camCtrl->getCameraHandle()->SetExposureTime(val); updateFrameRateInfo(); } void CameraCtlWidget::on_sliderGain_valueChanged(int val) { qDebug()<<"onComTriggerSourceChanged"<<val; ui->leGain->setText(QString::number(val)); m_camCtrl->getCameraHandle()->SetGain((float)val/10); updateFrameRateInfo(); } void CameraCtlWidget::on_pbApply_clicked() { int frameRate = ui->leFrameRate->text().toInt(); qDebug()<<"frame:"<<frameRate; if(frameRate > m_camCtrl->getCameraHandle()->GetFrameRate_Maximum()){ frameRate = m_camCtrl->getCameraHandle()->GetFrameRate_Maximum(); }else if(frameRate < m_camCtrl->getCameraHandle()->GetFrameRate_Minimum()){ frameRate = m_camCtrl->getCameraHandle()->GetFrameRate_Minimum() + 1; } ui->leFrameRate->setText(QString::number(frameRate)); m_camCtrl->getCameraHandle()->SetFrameRate(ui->leFrameRate->text().toFloat()); } void CameraCtlWidget::initial() { xiAPIplusCameraOcv* cam = m_camCtrl->getCameraHandle(); ui->leExposure->setText(QString::number(cam->GetExposureTime())); ui->sliderExposure->setRange(cam->GetExposureTime_Minimum(),10000/*cam->GetExposureTime_Maximum()*/); ui->sliderExposure->setSingleStep(100); ui->leGain->setText(QString::number(cam->GetGain())); ui->sliderGain->setRange(cam->GetGain_Minimum()*10,cam->GetGain_Maximum()*10); ui->sliderGain->setSingleStep(cam->GetGain_Increment()*10); updateFrameRateInfo(); } void CameraCtlWidget::updateFrameRateInfo() { QString str = QString("mini:%1 max:%2").arg((int)m_camCtrl->getCameraHandle()->GetFrameRate_Minimum()+1).arg( (int)m_camCtrl->getCameraHandle()->GetFrameRate_Maximum()); ui->lbFrame->setText(str); float frame = m_camCtrl->getCameraHandle()->GetFrameRate(); ui->leFrameRate->setText(QString::number(frame)); } QImage CameraCtlWidget::Mat2QImage(cv::Mat& cvImg) { QImage qImg; if(cvImg.channels() == 3){ cvtColor(cvImg,cvImg,CV_BGR2RGB); qImg = QImage((const uchar*)(cvImg.data), cvImg.cols,cvImg.rows, cvImg.cols * cvImg.channels(), QImage::Format_RGB888); } else if(cvImg.channels() == 1){ qImg = QImage((const uchar*)(cvImg.data), cvImg.cols,cvImg.rows, cvImg.cols * cvImg.channels(), QImage::Format_Indexed8); } else{ qImg = QImage((const uchar*)(cvImg.data), cvImg.cols,cvImg.rows, cvImg.cols * cvImg.channels(), QImage::Format_RGB888); } return qImg; } <file_sep>/cameractrl.h #ifndef CAMERACTRL_H #define CAMERACTRL_H #include <opencv2/imgproc/imgproc.hpp> #include <QPixmap> #include <QThread> #include <QDebug> #include <QTimer> #include "acquisitionthread.h" #include <QObject> class CameraCtrl : public QObject { Q_OBJECT public: explicit CameraCtrl(QObject *parent = 0); ~CameraCtrl(); void setDrawingRect(QRect& rect); QRect getDrawingRect(); void saveParaToFile(DEVICE_INFO& para,QString filename); DEVICE_INFO* getParaFromFile(QString filename); xiAPIplusCameraOcv* getCameraHandle(); public: CAMSTATUS m_camStatus; private: xiAPIplusCameraOcv m_xiCam; ulong m_nDevNumber; int m_curDevice; AcquisitionThread* m_acqThread; QThread* m_objThread; DEVICE_INFO m_devInfo; QPixmap m_curPic; QRect rectROI; int m_width; int m_hight; int m_offsetWidth; int m_offsetHeight; char m_camName[256]; XI_IMG_FORMAT m_imageFormat[4]; XI_TRG_SOURCE m_triggerSource[6]; void getCameraPara(); public: bool openCamera(unsigned long devID); void closeCamera(); QRect getROIRect(); CAMSTATUS getCameraStatus(); int setROIOffsetX(int offsetX); int setROIOffsetY(int offsetY); int setROIWidth(int width); int setROIHeight(int height); //auto exposure auto gain void enableAutoExposure(bool flag); bool setImageFormat(int index); void setTriggetSource(int index); void setTriggetSelector(int index); void startObjThread(); bool readDevParaFromXML(DEVICE_INFO *pDevInfo); void writeDevParaToXML(xiAPIplusCameraOcv &cam); void startAcquistion(); void stopAcquistion(); signals: void startAcquistionWork(); void getCameraImage(cv::Mat& image); void saveImage(); void stopSaveImage(); // void sendImage(QPixmap* pixmap); void sendCameraInfo(char* name,ulong number); void rectROIChanged(QRect& rect,bool modifyCam);//ROI changed sign,connected with widget and roidefine public slots: void initialCamera(); private slots: void recROIChanged(QRect &rect,bool modifyCam); }; #endif // CAMERACTRL_H <file_sep>/playercontrols.cpp /**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "playercontrols.h" #include <QSlider> #include <QStyle> #include <QToolButton> #include <QComboBox> #include <QDebug> #include <QLabel> PlayerControls::PlayerControls(QWidget *parent) : QWidget(parent) , status(camAsquistionMode) , camStatus(camClose) , playButton(0) , stopButton(0) , nextButton(0) , previousButton(0) , rateBox(0) { //设备控制条 comDevice = new QComboBox(this); recordButton = new QPushButton(tr("record"),this); // connect(recordButton,SIGNAL(clicked(bool)),this,SLOT(recordToFile())); //设置区 rWightCtlButton = new QPushButton(tr("setting"),this); rWightCtlButton->setCheckable(true); // connect(rWightCtlButton,SIGNAL(clicked(bool)),this,SLOT(showCameraSetting())); //文件控制 fileLabel = new QLabel("filename",this); fileLabel->hide(); //播放控制 playButton = new QToolButton(this); playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay)); connect(playButton, SIGNAL(clicked()), this, SLOT(playClicked())); stopButton = new QToolButton(this); stopButton->setIcon(style()->standardIcon(QStyle::SP_MediaStop)); stopButton->setEnabled(false); connect(stopButton, SIGNAL(clicked()), this, SIGNAL(stop())); nextButton = new QToolButton(this); nextButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward)); connect(nextButton, SIGNAL(clicked()), this, SIGNAL(next())); previousButton = new QToolButton(this); previousButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward)); connect(previousButton, SIGNAL(clicked()), this, SIGNAL(previous())); rateBox = new QComboBox(this); rateBox->addItem("0.5x", QVariant(0.5)); rateBox->addItem("1.0x", QVariant(1.0)); rateBox->addItem("2.0x", QVariant(2.0)); rateBox->setCurrentIndex(1); connect(rateBox, SIGNAL(activated(int)), SLOT(updateRate())); //文件列表 listButton = new QPushButton(tr("list"),this); listButton->setCheckable(true); listButton->hide(); //功能区 modeCahngeButton = new QPushButton(tr("Mode"),this); connect(modeCahngeButton,SIGNAL(clicked(bool)),this,SLOT(changeMode())); layout = new QHBoxLayout; layout->setMargin(0); layout->addWidget(comDevice); layout->addStretch(1); layout->setMargin(0); layout->addWidget(recordButton); layout->addWidget(stopButton); layout->addWidget(previousButton); layout->addWidget(playButton); layout->addWidget(nextButton); layout->addWidget(rateBox); layout->addStretch(1); layout->addWidget(modeCahngeButton); layout->addWidget(rWightCtlButton); setLayout(layout); recordButton->setEnabled(false); updateView(); } void PlayerControls::playClicked() { qDebug()<<"playClicked"; if(status == camAsquistionMode){ switch(camStatus){ case camClose: qDebug()<<"open camera"<<comDevice->currentIndex(); emit openCamera(0); camStatus = camOnAsquistion; playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause)); recordButton->setEnabled(true); break; case camOnAsquistion: qDebug()<<"close camera"; emit closeCamera(); camStatus = camClose; playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay)); recordButton->setEnabled(false); } }else if(status == fileReplayMode){ } // switch (status) { // case fileReplay: // emit fileReplay(); // case camClose: // emit camOpen(); // break; // case 0: // emit camPauseAsquistion(); // break; // case 1: // } } void PlayerControls::muteClicked() { } void PlayerControls::setPlaybackRate(float rate) { qDebug()<<"setPlaybackRate"; for (int i = 0; i < rateBox->count(); ++i) { if (qFuzzyCompare(rate, float(rateBox->itemData(i).toDouble()))) { rateBox->setCurrentIndex(i); return; } } rateBox->addItem(QString("%1x").arg(rate), QVariant(rate)); rateBox->setCurrentIndex(rateBox->count() - 1); } void PlayerControls::updateRate() { qDebug()<<"updateRate"; // emit changeRate(playbackRate()); } void PlayerControls::changeMode() { qDebug()<<" changeMode ....."<<status; if(status == camAsquistionMode){ status = fileReplayMode; }else if(status == fileReplayMode){ status = camAsquistionMode; } updateView(); } void PlayerControls::updateView() { qDebug()<<"changed mode"; if(status == fileReplayMode){ //回放 rateBox->show(); previousButton->setEnabled(true); nextButton->setEnabled(true); rWightCtlButton->setText(tr("list")); comDevice->hide(); disconnect(rWightCtlButton,SIGNAL(clicked(bool)),this,SLOT(showCameraSetting())); connect(rWightCtlButton,SIGNAL(clicked(bool)),this,SLOT(showFileList())); recordButton->setText(tr("open")); disconnect(recordButton,SIGNAL(clicked(bool)),this,SLOT(recordToFile())); recordButton->setEnabled(true); connect(recordButton,SIGNAL(clicked(bool)),this,SLOT(openReplayFile())); layout->replaceWidget(comDevice,fileLabel); fileLabel->show(); }else if(status == camAsquistionMode){ //视频采集 rateBox->hide(); previousButton->setEnabled(false); nextButton->setEnabled(false); rWightCtlButton->setText(tr("setting")); fileLabel->hide(); disconnect(rWightCtlButton,SIGNAL(clicked(bool)),this,SLOT(showFileList())); connect(rWightCtlButton,SIGNAL(clicked(bool)),this,SLOT(showCameraSetting())); recordButton->setText(tr("record")); disconnect(recordButton,SIGNAL(clicked(bool)),this,SLOT(openReplayFile())); connect(recordButton,SIGNAL(clicked(bool)),this,SLOT(recordToFile())); layout->replaceWidget(fileLabel,comDevice); comDevice->show(); } emit changeMode(status); } void PlayerControls::showFileList() { qDebug()<<"setting check status:"<<rWightCtlButton->isChecked(); bool flag = rWightCtlButton->isChecked(); rWightCtlButton->setChecked(!flag); qDebug()<<"listbutton check status:"<<rWightCtlButton->isChecked(); emit listFile(!flag); } void PlayerControls::showCameraSetting() { qDebug()<<"setting check status:"<<rWightCtlButton->isChecked(); bool flag = rWightCtlButton->isChecked(); rWightCtlButton->setChecked(!flag); qDebug()<<"setting check status:"<<rWightCtlButton->isChecked(); emit settingCamera(!flag); } void PlayerControls::recordToFile() { qDebug()<<"record"; if(camStatus == camRecording){ emit stopRecord(); camStatus = camOnAsquistion; recordButton->setText(tr("record")); }else if(camStatus == camOnAsquistion){ emit startRecord(); camStatus = camRecording; recordButton->setText(tr("stop")); } } void PlayerControls::openReplayFile() { qDebug()<<"open file"; } void PlayerControls::initialCameraInfo(char *camName, ulong camNumber) { if(camNumber > 0){ QString str(camName); for(ulong i = 0;i<camNumber;i++){ comDevice->addItem(str + QString::number(i+1)); emit openCamera(0); camStatus = camOnAsquistion; playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause)); recordButton->setEnabled(true); } }else{ comDevice->addItem(tr("No Device connected")); } } <file_sep>/maindlg.cpp #include "maindlg.h" #include "ui_maindlg.h" #include <QDebug> #include <QTabWidget> #include <QDockWidget> MainDlg::MainDlg(QWidget *parent) : QDialog(parent), ui(new Ui::MainDlg), m_camStatus(camClose), bRightWidgetShow(false) { //ui->setupUi(this); this->setWindowFlags(Qt::FramelessWindowHint);//去掉标题栏 camCtrl = new CameraCtlWidget(this); //显示区 picArea = new Widget(camCtrl->m_camCtrl,this); connect(picArea,SIGNAL(ROIRectChanged(QRect&,bool)),camCtrl,SIGNAL(ROIRectChanged(QRect&,bool)),Qt::DirectConnection); connect(camCtrl,SIGNAL(notifyWidgetAreaROI(QRect&)),picArea,SLOT(rectROIChanged(QRect&)),Qt::DirectConnection); //进度条 slider = new QSlider(Qt::Horizontal, this); labelDuration = new QLabel("framerate",this); QHBoxLayout * hLayout = new QHBoxLayout; hLayout->addWidget(labelDuration); hLayout->addWidget(slider); controls = new PlayerControls(this); //布局 layout = new QGridLayout; layout->setMargin(5); layout->setSpacing(5); layout->addWidget(picArea,0,0); layout->addLayout(hLayout,1,0); layout->addWidget(controls,2,0); connect(controls,SIGNAL(changeMode(int)),this,SLOT(changeMode(int)),Qt::DirectConnection); connect(controls,SIGNAL(listFile(bool)),this,SLOT(fileList(bool))); connect(controls,SIGNAL(settingCamera(bool)),this,SLOT(cameraSetting(bool))); layout->setSizeConstraint(QLayout::SetFixedSize); setLayout(layout); connect(controls,SIGNAL(openCamera(ulong)),camCtrl,SLOT(openCamera(ulong))); connect(controls,SIGNAL(closeCamera()),camCtrl,SLOT(closeCamera())); //connect(camCtrl->m_camCtrl,SIGNAL(getCameraImage(cv::Mat&)),this,SLOT(showImage(cv::Mat&)),Qt::DirectConnection); connect(camCtrl,SIGNAL(updatePic(QPixmap&)),this,SLOT(showImage(QPixmap&)),Qt::DirectConnection); //savefile connect(controls,SIGNAL(startRecord()),camCtrl->m_camCtrl,SIGNAL(saveImage())); connect(controls,SIGNAL(stopRecord()),camCtrl->m_camCtrl,SIGNAL(stopSaveImage())); //程序运行初始化 connect(camCtrl->m_camCtrl,SIGNAL(sendCameraInfo(char*,ulong)),controls,SLOT(initialCameraInfo(char*,ulong))); //ROI connect(camCtrl,SIGNAL(selectROI(QRect&)),picArea,SLOT(selectROI(QRect&))); //connect(camCtrl->m_camCtrl,SIGNAL(rectROIChanged(QRect&,bool)),picArea,SLOT(rectROIChanged(QRect&,bool)),Qt::DirectConnection); //程序布局 layout->addWidget(camCtrl,0,1); camCtrl->hide(); listFileWidget = new QListWidget(this); layout->addWidget(listFileWidget,0,2); listFileWidget->hide(); connect(this,SIGNAL(initialCamera()),camCtrl->m_camCtrl,SLOT(initialCamera())); emit initialCamera(); } MainDlg::~MainDlg() { delete ui; } void MainDlg::test() { } void MainDlg::changeMode(int status) { qDebug()<<"status:" << status; if(status == camAsquistionMode){ listFileWidget->hide(); camCtrl->show(); }else if(status == fileReplayMode){ camCtrl->hide(); listFileWidget->show(); } bRightWidgetShow = true; } void MainDlg::fileList(bool checkedFlag) { if(!bRightWidgetShow){ listFileWidget->show(); bRightWidgetShow = true; }else{ listFileWidget->hide(); bRightWidgetShow = false; } } void MainDlg::cameraSetting(bool checkedFlag) { if(!bRightWidgetShow){ camCtrl->show(); bRightWidgetShow = true; }else{ camCtrl->hide(); bRightWidgetShow = false; } } void MainDlg::showImage(QPixmap &image) { picArea->setPicture(image); picArea->update(20,20,650,522);//部分区域刷新30,30,642*512 } <file_sep>/autoexposuresetup.cpp #include "autoexposuresetup.h" #include "ui_autoexposuresetup.h" AutoExposureSetup::AutoExposureSetup(CameraCtrl* camCtrl, QWidget *parent) : QDialog(parent), ui(new Ui::AutoExposureSetup), m_camctrl(camCtrl) { ui->setupUi(this); m_xiCam = m_camctrl->getCameraHandle(); float priority = m_xiCam->GetAutoExposureAutoGainExposurePriority(); int maxExposure = m_xiCam->GetAutoExposureTopLimit(); float maxGain = m_xiCam->GetAutoGainTopLimit(); int targetLevel = m_xiCam->GetAutoExposureAutoGainTargetLevel(); ui->lbPriority->setText(QString::number(priority*100) + tr("%")); ui->lbMaxExposure->setText(QString::number(maxExposure)); ui->lbMaxGain->setText(QString::number(maxGain)); ui->lbTargetLevel->setText(QString::number(targetLevel)); ui->sliderPriority->setRange((int)(m_xiCam->GetAutoExposureAutoGainExposurePriority_Minimum()*100), (int)(m_xiCam->GetAutoExposureAutoGainExposurePriority_Maximum()*100)); ui->sliderPriority->setSingleStep((int)(m_xiCam->GetAutoExposureAutoGainExposurePriority_Increment()*100)); ui->sliderPriority->setValue(priority*100); qDebug()<<"range:"<<m_xiCam->GetAutoExposureAutoGainExposurePriority_Minimum()<<"-" <<m_xiCam->GetAutoExposureAutoGainExposurePriority_Minimum(); qDebug()<<"step:"<<m_xiCam->GetAutoExposureAutoGainExposurePriority_Increment(); qDebug()<<"priosity"<<priority; ui->sliderMaxExposure->setRange(m_xiCam->GetAutoExposureTopLimit_Minimum(), m_xiCam->GetAutoExposureTopLimit_Maximum()); ui->sliderMaxExposure->setSingleStep(m_xiCam->GetAutoExposureTopLimit_Increment()); ui->sliderMaxExposure->setValue(maxExposure); ui->sliderMaxGain->setRange((int)m_xiCam->GetAutoGainTopLimit_Minimum()*10, (int)m_xiCam->GetAutoGainTopLimit_Maximum()*10);//0.1 ui->sliderMaxGain->setSingleStep((int)m_xiCam->GetAutoGainTopLimit_Increment()*10); ui->sliderMaxGain->setValue(maxGain); ui->sliderTargetLevel->setRange(m_xiCam->GetAutoExposureAutoGainTargetLevel_Minimum(), m_xiCam->GetAutoExposureAutoGainTargetLevel_Maximum()); ui->sliderTargetLevel->setSingleStep(m_xiCam->GetAutoExposureAutoGainTargetLevel_Increment()); ui->sliderTargetLevel->setValue(targetLevel); connect(ui->sliderPriority,SIGNAL(valueChanged(int)),this,SLOT(onPriorityChanged(int))); connect(ui->sliderMaxExposure,SIGNAL(valueChanged(int)),this,SLOT(onMaxExposureChanged(int))); connect(ui->sliderMaxGain,SIGNAL(valueChanged(int)),this,SLOT(onMaxGainChanged(int))); connect(ui->sliderTargetLevel,SIGNAL(valueChanged(int)),this,SLOT(onTargetLevelChanged(int))); } AutoExposureSetup::~AutoExposureSetup() { delete ui; } void AutoExposureSetup::onPriorityChanged(int val) { ui->lbPriority->setText(QString::number(val) + tr("%")); float l = ((float)val)/100; qDebug()<<"priority:"<<l; m_xiCam->SetAutoExposureAutoGainExposurePriority(l); } void AutoExposureSetup::onMaxExposureChanged(int val) { ui->lbMaxExposure->setText(formatExposureTimeShow(val)); m_xiCam->SetAutoExposureTopLimit(val); } void AutoExposureSetup::onMaxGainChanged(int val) { float value = (float)val/10; ui->lbMaxGain->setText(QString::number(value)); m_xiCam->SetAutoGainTopLimit(value); } void AutoExposureSetup::onTargetLevelChanged(int val) { ui->lbTargetLevel->setText(QString::number(val)); m_xiCam->SetAutoExposureAutoGainTargetLevel(val); } QString AutoExposureSetup::formatExposureTimeShow(int val) { QString strValue; if(val >= 1000000){ strValue = QString::number((float)val/1000000) + tr("s"); }else if(val >= 1000){ strValue = QString::number((float)val/1000) + tr("ms"); }else{ strValue = QString::number(val) + tr("us"); } return strValue; } <file_sep>/cameractlwidget.h #ifndef CAMERACTLWIDGET_H #define CAMERACTLWIDGET_H #include <QWidget> #include <opencv2/imgproc/imgproc.hpp> #include<QtNetwork> #include<QTcpServer> #include<QTcpSocket> #include <QPixmap> #include <QThread> #include <QDebug> #include <QTimer> #include "acquisitionthread.h" #include "cameractrl.h" #include "roidefine.h" #include "autoexposuresetup.h" #include "inputdebouncesetup.h" namespace Ui { class CameraCtlWidget; } class CameraCtlWidget : public QWidget { Q_OBJECT public: explicit CameraCtlWidget(QWidget *parent = 0); ~CameraCtlWidget(); CameraCtrl* m_camCtrl; public slots: void on_test_clicked(); void openCamera(unsigned long devID); void closeCamera(); void rectROIChanged(QRect &rect,bool flag); private slots: void getCameraImage(cv::Mat& image); void onComDPIChanged(int index); void onComImageTypeChanged(int index); void on_pbDefine_clicked(); void on_pbROI_clicked(); void on_pbSWPing_clicked(); void onReceiveDefine(QRect rect,bool bSave); void on_pbAutoExposureSetup_clicked(); void on_pbDebounceSetup_clicked(); void onComTriggerSelectorChanged(int index); void onComTriggerSourceChanged(int index); void onEnableAutoExposure(bool flag); void onEnableDebounce(bool flag); void on_leExposure_textChanged(QString str); void on_leGain_textChanged(QString str); void on_sliderExposure_valueChanged(int val); void on_sliderGain_valueChanged(int val); void on_pbApply_clicked(); void SendData(); signals: void saveImage(); void stopSaveImage(); void dlgClose(); void updatePic(QPixmap& pic); void selectROI(QRect& rect); void ROIRectChanged(QRect& rect,bool flag); void notifyWidgetAreaROI(QRect& rect); private: Ui::CameraCtlWidget *ui; QWidget* m_wndParent; ROIDefine* m_wROIDefine; AutoExposureSetup* m_wAutoExposureDlg; AEAG_PARA* m_pAEAGPara; InputDebounceSetup* m_wInputDebounceSetup; void initial(); bool m_bIsRecording; bool m_bIsAutoExposure; DEVICE_INFO getDevInfo(xiAPIplus_Camera& cam); void updateFrameRateInfo(); void readDevParaFromXML(DEVICE_INFO *pDevInfo); void writeDevParaToXML(xiAPIplusCameraOcv &cam); QImage Mat2QImage(cv::Mat& cvImg); QPixmap m_curImage; QImage myImage; QRect rectROI; qint64 blockSize; QTcpSocket* tcpSocket; QTimer* myTimer; }; #endif // CAMERACTLWIDGET_H <file_sep>/maindlg.h #ifndef MAINDLG_H #define MAINDLG_H #include "cameractlwidget.h" #include <QDialog> #include <QPushButton> #include <QBoxLayout> #include <QLabel> #include <QSlider> #include <QStackedWidget> #include <QComboBox> #include <QListWidget> #include "playercontrols.h" #include <QPainter> #include <QTime> #include "widget.h" namespace Ui { class MainDlg; } class MainDlg : public QDialog { Q_OBJECT public: explicit MainDlg(QWidget *parent = 0); ~MainDlg(); signals: void initialCamera(); public slots: void showImage(QPixmap &image); private slots: void test(); void changeMode(int status);//回放和视频采集切换 void fileList(bool checkedFlag);//文件列表 void cameraSetting(bool checkedFlag);//相机设置界面 private: Ui::MainDlg *ui; //QLabel* picArea; Widget* picArea; QSlider *slider; QLabel *labelDuration; CameraCtlWidget* camCtrl; PlayerControls *controls; QListWidget* listFileWidget; int m_camStatus; QLabel* label; QGridLayout *layout; bool bRightWidgetShow; }; #endif // MAINDLG_H
fca7bff3c1d5c34b077cd24b488f687fe434f838
[ "C", "C++" ]
18
C++
halforc/CameraClient
66d3b2444bdc43adbcdbe20acb447e23c7cb526d
bc7f17f598fdb72891d18c8229cb6d3cbf69b0e5
refs/heads/main
<repo_name>anastasia-lgtm/newprojects<file_sep>/step_1.py print (5+5)<file_sep>/README.md # newprojects 123
dccc23684d02a641ffd1c3b46a6ace6cf236d1cd
[ "Markdown", "Python" ]
2
Python
anastasia-lgtm/newprojects
bd40bb78f7c8239607590434ffc45ee236bc11f1
5b553b55f885e0acfeadfbebf473ca81aac011ad
refs/heads/master
<repo_name>mateuszokroj1/FuncAnalyzer<file_sep>/FuncAnalyzer/Derivative.cs using Microsoft.CodeAnalysis.CSharp.Scripting; using System; using System.Collections.Generic; using System.Linq.Expressions; namespace FuncAnalyzer { public class Derivative { #region Constructor public Derivative(Expression<Func<double,double>> f) { PrimaryFunction = f; convertexpression(); } public Derivative(string f) { PrimaryFunction = CSharpScript.EvaluateAsync<Expression<Func<double,double>>>(f).Result; convertexpression(); } #endregion #region Properties public Expression<Func<double,double>> PrimaryFunction { get; protected set; } protected localexpression e; #endregion #region Methods protected void convertexpression() { } public Expression<Func<double,double>> GetDerivative() { ParameterExpression x = Expression.Parameter(typeof(double), "x"); return Expression.Lambda<Func<double,double>>(e.GetDerivative(x), x); } #endregion #region Classes protected class localexpression { public ParameterExpression parameter; public localexpression left; public localexpression right; public virtual Expression Original => Expression.Empty(); public virtual Expression GetDerivative(ParameterExpression param) { return Expression.Empty(); } } protected class constant : localexpression { public constant(double v) { value = v; } public double value; public override Expression Original => Expression.Constant(value); public override Expression GetDerivative(ParameterExpression param) { return Expression.Constant(0); } } protected class parameter : localexpression { public new ParameterExpression Original { get; set; } public override Expression GetDerivative(ParameterExpression param) { return Expression.Constant(1); } } protected class addition : localexpression { public addition(localexpression left, localexpression right) { } public override Expression Original => Expression.Add(left.Original, right.Original); public override Expression GetDerivative(ParameterExpression param) => Expression.Add(left.GetDerivative(param), right.GetDerivative(param)); public override string ToString() => left.ToString() + "+" + right.ToString(); } protected class substitution : localexpression { public substitution(localexpression left, localexpression right) { } public override Expression Original => Expression.Subtract(left.Original, right.Original); public override Expression GetDerivative(ParameterExpression param) => Expression.Subtract(left.GetDerivative(param), right.GetDerivative(param)); public override string ToString() => left.ToString() + "-" + right.ToString(); } protected class multiplication : localexpression { public multiplication(localexpression left, localexpression right) { } public override Expression Original => Expression.Multiply(left.Original, right.Original); public override Expression GetDerivative(ParameterExpression param) { if (left is constant & right is parameter) return left.Original; else if (left is constant & (!(right is constant) & !(right is parameter))) return Expression.Multiply(left.Original, right.GetDerivative(param)); else if(right is constant & (!(left is constant) & !(left is parameter))) return Expression.Multiply(right.Original, left.GetDerivative(param)); else return Expression.Add( Expression.Multiply(left.GetDerivative(param), right.Original), Expression.Multiply(left.Original, right.GetDerivative(param)) ); } public override string ToString() => left.ToString() + "*" + right.ToString(); } protected class division : localexpression { public division(localexpression left, localexpression right) { } public override Expression Original => Expression.Divide(left.Original, right.Original); public override Expression GetDerivative(ParameterExpression param) => Expression.Divide( Expression.Subtract( Expression.Multiply(left.GetDerivative(param),right.Original), Expression.Multiply(left.Original,right.GetDerivative(param))), Expression.Call(null, typeof(Math).GetMethod("Pow"), right.Original, Expression.Constant(2))); public override string ToString() => left.ToString() + "/" + right.ToString(); } protected class root : localexpression { public root(constant left, localexpression right) { if() } public override Expression Original { get { if (left is constant & (left as constant).value == 2.0) return Expression.Call(null, typeof(Math).GetMethod("Sqrt"), right.Original); else if (left is constant) return Expression.Call(null, typeof(Math).GetMethod("Pow"), right.Original, Expression.Divide(Expression.Constant(1), Expression.Constant((left as constant).value))); else if (left is parameter) return Expression.Call(null, typeof(Math).GetMethod("Pow"), right.Original, Expression.Divide(Expression.Constant(1), (left as parameter).parameter)); else throw new InvalidOperationException("Left value of root must be a natural"); } } public override Expression GetDerivative(ParameterExpression param) => Expression.Divide( Expression.Subtract( Expression.Multiply(left.GetDerivative(param), right.Original), Expression.Multiply(left.Original, right.GetDerivative(param))), Expression.Call(null, typeof(Math).GetMethod("Pow"), right.Original, Expression.Constant(2))); public override string ToString() => left.ToString() + "/" + right.ToString(); } #endregion } } <file_sep>/FuncAnalyzer/Range.cs using System; using System.Collections.Generic; using System.Linq; namespace FuncAnalyzer { public class Range { public Range() { } public bool IsValidValue(double value) { } public double Minimum { get { } } public double Maximum { get { } } public static readonly Range Natural = new Range(); } } <file_sep>/FuncAnalyzer/Analyzer.cs using System; using System.Collections.Generic; namespace FuncAnalyzer { /// <summary> /// Function analyzer /// </summary> public sealed class Analyzer { #region Constructor public Analyzer() { } #endregion #region Properties public Func<double,double> Function { get; private set; } public Range Definition { get; set; } public IEnumerable<double> ZeroPlaces { get { double x = 0, min = Definition.Minimum, max = Definition.Maximum; if (min == double.NegativeInfinity) min += 0.000000001; if (max == double.PositiveInfinity) max -= 0.000000001; do { try { x = zerosearch(min, max); } catch(ArgumentException) { yield break; } yield return x; min = x + 0.1; } while (x < max - 0.5); yield break; } } #endregion #region Methods private double zerosearch(double min, double max) { double x = 0, E = 0.000000001, fmin = 0, fmax = 0; if (!Definition.IsValidValue(min) || !Definition.IsValidValue(max)) throw new ArgumentOutOfRangeException("Min or max is out of function definition"); try { fmin = Function(min); fmax = Function(max); } catch (ArithmeticException) { throw new ArgumentOutOfRangeException("Min or max is out of function definition"); } if (fmin * fmax > 0) throw new ArgumentException("Empty result"); while(Math.Abs(min - max) > E) { x = (min-max) / 2.0; if (!Definition.IsValidValue(x)) max = x - E; if (Math.Abs(Function(x)) < E) break; if (fmin * Function(x) < 0) max = x; else { min = x; fmin = Function(x); } } return x; } #endregion } }
0a6adbcd505c3b7d175fb88cb58d8d97d9251e03
[ "C#" ]
3
C#
mateuszokroj1/FuncAnalyzer
88aa4bc5e5973dca626cd3922c941d9c20f6b3b6
84e791591ffc7a556146f65c4dca4a47291be237
refs/heads/master
<repo_name>monali-shinde/practice<file_sep>/assignment3.rb # ASSIGNMENT 3 # Create a calculator application which can perform add, sub, division and multiplication operation. Add exception handling for operations like divide which handles ZeroDivisionError exception printing some user friendly message. Add a method in this calculator which takes a number as argument and returns: # “positive” - if number is positive # “negative” - if number is negative # nil - if number is 0 class Calculator def initialize(a,b) @a = a @b = b end def add @a + @b end def sub @a - @b end def mul @a * @b end def division begin @a / @b rescue ZeroDivisionError => e "#{e.class}: #{e.message}" end end end class Argument def initialize argument @argument = argument end def check_number begin if @argument > 0 "positive" elsif @argument < 0 "negative" elsif @argument == 0 nil end rescue ArgumentError => ee "Invalid Input" end end end cal1 = Calculator.new(2,2) cal2 = Calculator.new(12,0) cal1.add cal1.sub cal1.mul cal1.division cal2.division arg1 = Argument.new "monali" arg1.check_number <file_sep>/assignment1.rb # Demonstrate the use of instance variables by creating one Ruby class for storing User data like name, city, phone class User @@count = 0 def initialize(name, city, phone) @@count += 1 @name = name @city = city @phone = phone end def self.user_count "There are #{@@count} user" end def user_data puts "name = #{@name},\ncity = #{@city},\nphone = #{@phone}" end end user1 = User.new 'Monali', 'Pune', 9874563210 user2 = User.new 'shinde', 'karad', 2145639870 puts user1.user_data puts user2.user_data puts User.user_count<file_sep>/assignment2.rb # ASSIGNMENT 2 # Create a Vehicle class with instance variable for wheel_count. Assume default value for wheel_count as 2. Create it’s child classes like Bike, Auto, Bus where: # wheel_count variable is inherited in case of Bike class, since bike also has 2 wheels which is same as that of Vehicle class # wheel_count variable is overridden in case of Auto and Bus class, since they have 3 and 4 wheels respectively class Vehicle def initialize @wheel_count = 2 end def wheel_count @wheel_count end def wheel_count=(value) @wheel_count = value end end class Bike < Vehicle def show @wheel_count end end class Auto < Vehicle def initialize @wheel_count = 3 end def show @wheel_count end end class Bus < Vehicle def initialize @wheel_count = 4 end def show @wheel_count end end bike = Bike.new bike.show bike.wheel_count bike.wheel_count = 10 bike.wheel_count auto = Auto.new auto.show bus = Bus.new bus.show
a1e17164f95a5ab499b6d4e42444cdae4cbd397f
[ "Ruby" ]
3
Ruby
monali-shinde/practice
9f6458f84b807decf0e9c107244de6901f82469d
1ab1e04c39149c81bad9aa4da39bd9e9c50ac5a7
refs/heads/master
<repo_name>kiyoung-Lee/C-Sharp_MVC_Model_Sample<file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewGrid.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using TypeLib.Service; namespace Mirero.Wiener.UiForm.LibView { public partial class LibViewGrid : DevExpress.XtraEditors.XtraUserControl, ISampleView { #region Controller I/F private IMireroController _iController; #endregion #region Implementation IView #region BindList Code public enProjectCode ProjectCode { get; private set; } public enUiTypeCode UiTypeCode { get; private set; } #endregion #region void UpdateView(object sender, EventArgs e) public void UpdateView(object sender, EventArgs e) { UiLibMessage msg = e as UiLibMessage; if (msg != null) { if (msg.Code is UiType.enEventCode) { UiType.enEventCode inCode = (UiType.enEventCode)msg.Code; switch (inCode) { case UiType.enEventCode.Redraw: { gridControl.Refresh(); gridView.RefreshData(); } break; } } } } #endregion #endregion #region Event Handler & Message public event EventHandler SendMessage; private UiLibMessage _sendMessageData; #endregion #region Binding List private IBindingList _bindList; public IBindingList _BindList { set { _bindList = value; } } #endregion #region Grid Control #endregion #region Creator public LibViewGrid(IMireroController iController, enProjectCode projectCode, enUiTypeCode uiTypeCode) { InitializeComponent(); #region View & Data Manager Mapping _iController = iController; ProjectCode = projectCode; UiTypeCode = uiTypeCode; #region TblGrid Assign if (_iController.AppMain.TblGridView.ContainsKey(uiTypeCode)) { if (_iController.AppMain.TblGridView[uiTypeCode] == null) _iController.AppMain.TblGridView[uiTypeCode] = new List<IMireroView>(); _iController.AppMain.TblGridView[uiTypeCode].Add(this); } else { _iController.AppMain.TblGridView.Add(uiTypeCode, new List<IMireroView>()); _iController.AppMain.TblGridView[uiTypeCode].Add(this); } #endregion if (_iController.AppMain.TblBindList.ContainsKey(ProjectCode)) { BindListCollection bindListCollection = _iController.AppMain.TblBindList[ProjectCode]; if (bindListCollection.TblBindList.ContainsKey(UiTypeCode)) { _bindList = bindListCollection.TblBindList[UiTypeCode] as IBindingList; } } #endregion _sendMessageData = new UiLibMessage(); gridControl.DataSource = _bindList; #region GridView Event Mapping this.Load += UiLoad; SendMessage += iController.CallBackFunc; _iController.SendMessage += UpdateView; this.Disposed += UiDisposed; #endregion } #endregion #region Implement Dispose private void UiDisposed(object sender, EventArgs e) { this.Load -= UiLoad; SendMessage -= _iController.CallBackFunc; _iController.SendMessage -= UpdateView; if (_iController.AppMain.TblGridView.ContainsKey(UiTypeCode)) _iController.AppMain.TblGridView[UiTypeCode].Remove(this); } #endregion #region Event Handler Available Check private bool IsAvailableEventHandler { get { return (object.ReferenceEquals(SendMessage, null) == false) ? true : false; } } #endregion #region Ui Event Process #region void UiLoad(object sender, EventArgs e) private void UiLoad(object sender, EventArgs e) { gridView.Columns.ToList().ForEach(colItem => { colItem.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False; }); } #endregion #endregion } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/UiType/enCheckField.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UiForm.Sample.UiType { public enum enCheckField { ParamModelName, ParamModelExpression, ParamFitName, ParamFitInitialValue, ParamFitPriorValue, ParamFitPosteriorValue, ParamFitPriorWidth, ParamFitPosteriorWidth, ParamFitTypeChange, HistoryName, SpectrumName, SolutionName } } <file_sep>/MVC_Sample_Solution/TypeLib.Service/ISampleView.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Service { public interface ISampleView { enProjectCode ProjectCode { get; } enUiTypeCode UiTypeCode { get; } bool Enabled { get; set; } bool Visible { get; set; } bool InvokeRequired { get; } void Refresh(); void UpdateView(object sender, EventArgs e); } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewResultLayout.cs using System; using TypeLib.Core; using TypeLib.Service; namespace Mirero.Wiener.UiForm.LibView { public partial class LibViewResultLayout : DevExpress.XtraEditors.XtraUserControl, ISampleView { #region Controller I/F private ISampleController _iController; #endregion #region Implementation IView #region BindList Code public enProjectCode ProjectCode { get; private set; } public enUiTypeCode UiTypeCode { get; private set; } public enChartCode ChartCode { get; private set; } #endregion #region void UpdateView(object sender, EventArgs e) public void UpdateView(object sender, EventArgs e) { } #endregion #endregion #region Event Handler & Message public event EventHandler SendMessage; private UiLibMessage _sendMessageData; #endregion #region Dock Pannel Getter public DockPanel getChartDockPanel { get {return dockPanelChart; } } public DockPanel getDataDockPanel { get { return dockPanelData; } } #endregion #region Creator public LibViewResultLayout(ISampleController iController) { InitializeComponent(); #region Default Initialize _sendMessageData = new UiLibMessage(); _iController = iController; //ProjectCode = projectcode; //UiTypeCode = uiTypeCode; //ChartCode = chartCode; this.Load += UiLoad; SendMessage += iController.CallBackFunc; _iController.SendMessage += UpdateView; this.Disposed += UiDisposed; #endregion } #endregion #region Implement Dispose private void UiDisposed(object sender, EventArgs e) { this.Load -= UiLoad; SendMessage -= _iController.CallBackFunc; _iController.SendMessage -= UpdateView; } #endregion #region Ui Event Process #region void UiLoad(object sender, EventArgs e) private void UiLoad(object sender, EventArgs e) { #region Menu Control UI var bitmap16 = UiLibImages.Bitmap16; #endregion #region Docking Panel UI #endregion #region Link Button Event #endregion } #endregion #region Event Function #endregion #endregion } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewDataModel.cs using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.IO; using TypeLib.Core; using TypeLib.DbLib; namespace Mirero.Wiener.UiForm.LibView { public class LibViewDataModel : IDataModel { private IDbProcess _iDb; private ConfigData _config; private Dictionary<string, object> _parameters = new Dictionary<string, object>(); public Dictionary<string, object> Parameters { get { return _parameters; } private set { _parameters = value; } } public bool InitDataModel(string option) { #region AppConfig File Load if (_config == null) { string fileURL = Path.Combine(Directory.GetCurrentDirectory(), "AppConfig.xml"); if (!File.Exists(fileURL)) { _config = new ConfigData() { Name = "LOADER_1", GroupName = "DISTRIBUTOR_1", DbInfo = new DbConnectionInfo() { IP = "192.168.60.214", PORT = "1521", SERVICE_NAME = "WIENER", USER = "wienermgr", PASSWORD = "<PASSWORD>" } }; _config.ToXmlFile(fileURL); } else { _config = UtilFuncFile.FromXML(typeof(ConfigData), fileURL) as ConfigData; if ((_config == null) || (string.IsNullOrEmpty(_config.Name)) || (string.IsNullOrEmpty(_config.DbInfo.IP)) || (string.IsNullOrEmpty(_config.DbInfo.PORT)) || (string.IsNullOrEmpty(_config.DbInfo.SERVICE_NAME)) || (string.IsNullOrEmpty(_config.DbInfo.USER)) || (string.IsNullOrEmpty(_config.DbInfo.PASSWORD))) { return false; } } } #endregion #region Parameter Table Initialize Parameters.Add("CONFIG_INFO", _config); #endregion #region DB Interface Initialize _iDb = DbClientORA.iQuery; _iDb.SetTCPConnectionString(_config.DbInfo.IP, _config.DbInfo.PORT, _config.DbInfo.SERVICE_NAME, _config.DbInfo.USER, _config.DbInfo.PASSWORD); #endregion return true; } public IList ExecuteCommand(string cmd, IList paramList) { #region Parameter Check if (!TblKnownParam.Table.ContainsKey(cmd) || !TblQueryContents.Table.ContainsKey(cmd)) { return null; } #endregion Dictionary<string, DbParameter> inParam = TblKnownParam.Table[cmd]; switch (cmd) { default: return null; } } } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/TblChartCode.cs using DevExpress.XtraCharts; using Mirero.Wiener.TypeLib.Client; using Mirero.Wiener.UiLib.ControlLib; using System.Collections.Generic; using TypeLib.Service; namespace Mirero.Wiener.UiForm.LibView { public static class TblChartCode { private static Dictionary<enChartCode, UiType.ChartData> _tblChartCode = new Dictionary<enChartCode, UiType.ChartData>(); static TblChartCode() { #region Material UiType.ChartData inData = new LibView.UiType.ChartData() { XAxis = UiLibWords.AXIS_WAVELENGTH, YAxis = UiLibWords.AXIS_NK }; inData.SereisDic.Add(UiLibWords.SERIES_N, new UiType.SeriesItem()); inData.SereisDic.Add(UiLibWords.SERIES_K, new UiType.SeriesItem()); _tblChartCode.Add(enChartCode.Material_NK, inData); inData = new LibView.UiType.ChartData() { XAxis = UiLibWords.AXIS_WAVELENGTH, YAxis = UiLibWords.AXIS_REAL_IMAGE }; inData.SereisDic.Add(UiLibWords.SERIES_REAL, new UiType.SeriesItem()); inData.SereisDic.Add(UiLibWords.SERIES_IMAGE, new UiType.SeriesItem()); _tblChartCode.Add(enChartCode.Material_RealImaginary, inData); #endregion #region Spectrum _tblChartCode.Add(enChartCode.MeasuredSpectrum_1, new LibView.UiType.ChartData()); _tblChartCode.Add(enChartCode.MeasuredSpectrum_2, new LibView.UiType.ChartData()); #endregion #region Jacobian _tblChartCode.Add(enChartCode.Jacobian_1, new LibView.UiType.ChartData()); _tblChartCode.Add(enChartCode.Jacobian_2, new LibView.UiType.ChartData()); #endregion #region Correlation _tblChartCode.Add(enChartCode.Measured_Correlation, new LibView.UiType.ChartData()); #endregion #region Fit - Monitoring inData = new LibView.UiType.ChartData() { XAxis = UiLibWords.AXIS_ITER, YAxis = UiLibWords.AXIS_QUALITY }; inData.SereisDic.Add(UiLibWords.SERIES_CHISQ, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_CHISQ].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_CHISQ_DOF, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_CHISQ_DOF].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_PVALUE, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_PVALUE].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_RHO, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_RHO].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_MU, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_MU].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_NU, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_NU].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_GOF, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_GOF].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_MSE, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_MSE].ChartType = ViewType.Point; _tblChartCode.Add(enChartCode.Fit_Monitoring, inData); #endregion #region Generate _tblChartCode.Add(enChartCode.GenerateResult_1, new LibView.UiType.ChartData()); _tblChartCode.Add(enChartCode.GenerateResult_2, new LibView.UiType.ChartData()); #endregion #region Train - Result _tblChartCode.Add(enChartCode.TrainResult_1, new LibView.UiType.ChartData()); _tblChartCode.Add(enChartCode.TrainResult_2, new LibView.UiType.ChartData()); #endregion #region Train - Validate _tblChartCode.Add(enChartCode.TrainValidate_1, new LibView.UiType.ChartData()); _tblChartCode.Add(enChartCode.TrainValidate_2, new LibView.UiType.ChartData()); #endregion #region Train - Quality inData = new LibView.UiType.ChartData() { XAxis = UiLibWords.AXIS_ITER, YAxis = UiLibWords.AXIS_QUALITY }; inData.SereisDic.Add(UiLibWords.SERIES_MSE_AUG, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_MSE_AUG].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_MSE_IN, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_MSE_IN].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_MSE_OUT, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_MSE_OUT].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_RHO, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_RHO].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_MU, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_MU].ChartType = ViewType.Point; inData.SereisDic.Add(UiLibWords.SERIES_NU, new UiType.SeriesItem()); inData.SereisDic[UiLibWords.SERIES_NU].ChartType = ViewType.Point; _tblChartCode.Add(enChartCode.Train_Monitoring, inData); #endregion } public static UiType.ChartData GetChartData(enChartCode code) { return (_tblChartCode.ContainsKey(code)) ? _tblChartCode[code] : null; } public static bool IsExist(enChartCode code) { return _tblChartCode.ContainsKey(code); } } } <file_sep>/MVC_Sample_Solution/TypeLib.Core/UiLibMessage.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Core { public class UiLibMessage : EventArgs { public const int LibView = 0x1000000; public const int MainFrame = 0x2000000; public Enum Code { get; set; } public List<object> Parameters { get; private set; } public UiLibMessage() { Parameters = new List<object>(); } public static string GetViewCode(string groupName, string viewName) { return string.Format("{0}::{1}", groupName, viewName); } } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/Templete_View.cs using System; using System.Windows.Forms; using TypeLib.Core; using TypeLib.Service; using UtilLib.ControlLib; namespace UiForm.Sample { public partial class Templete_View : Form, ISampleView { #region Controller I/F private ISampleController _iController; #endregion #region Implementation IView #region BindList Code public enProjectCode ProjectCode { get; private set; } public enUiTypeCode UiTypeCode { get; private set; } #endregion #region void UpdateView(object sender, EventArgs e) public void UpdateView(object sender, EventArgs e) { UiLibMessage msg = e as UiLibMessage; if (msg != null) { if (msg.Code is UiType.enEventCode) { UiType.enEventCode inCode = (UiType.enEventCode)msg.Code; switch (inCode) { } } } } #endregion #endregion #region Event Handler & Message public event EventHandler SendMessage; private UiLibMessage _sendMessageData; #endregion #region Selection Mode private bool _isManualMode; #endregion #region Grid Control #endregion #region Creator public Templete_View(ISampleController iController, enProjectCode projectcode, enUiTypeCode uiTypeCode) { InitializeComponent(); #region Default Initialize _sendMessageData = new UiLibMessage(); _iController = iController; ProjectCode = projectcode; UiTypeCode = uiTypeCode; this.Load += UiLoad; SendMessage += iController.CallBackFunc; _iController.SendMessage += UpdateView; this.Disposed += UiDisposed; #endregion } #endregion #region Implement Dispose private void UiDisposed(object sender, EventArgs e) { this.Load -= UiLoad; SendMessage -= _iController.CallBackFunc; _iController.SendMessage -= UpdateView; } #endregion #region Event Handler Available Check private bool IsAvailableEventHandler { get { return (object.ReferenceEquals(SendMessage, null) == false) ? true : false; } } #endregion #region Ui Event Process #region void UiLoad(object sender, EventArgs e) private void UiLoad(object sender, EventArgs e) { #region Menu Control UI var bitmap16 = UiLibImages.Bitmap16; #endregion #region Docking Panel UI #endregion #region Link Button Event #endregion } #endregion #region Event Function #endregion #endregion } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/UiType/SeriesItem.cs using DevExpress.XtraCharts; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; using UiForm.LibView.UiType; namespace UiForm.LibView.UiType { public class SeriesItem { //public ViewType ChartType { get; set; } public List<ChartValue> Datas { get; set; } public bool isVisible { get; set; } public Color SeriesColor { get; set; } public DashStyle DashStyle { get; set; } public int SeriesThickness { get; set; } public SeriesItem() { Datas = new List<ChartValue>(); isVisible = true; DashStyle = DashStyle.Solid; SeriesThickness = 3; } } } <file_sep>/MVC_Sample_Solution/TypeLib.Service/AppConfigurator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Service { public abstract class AppConfigurator { public ISampleView Owner { get; protected set; } public Dictionary<string, string> TblConfig { get; protected set; } public Dictionary<Type, object> TblBindProperty { get; protected set; } public Dictionary<enProjectCode, BindListCollection> TblBindList { get; protected set; } public Dictionary<string, ISampleController> TblSubController { get; protected set; } public Dictionary<enUiTypeCode, List<ISampleView>> TblGridView { get; protected set; } public Dictionary<enChartCode, List<ISampleView>> TblChartView { get; protected set; } public abstract void Init(); public abstract void StoreConfig(); public abstract void CallBackFunc(object sender, EventArgs e); public virtual List<string> GetRefMaterialList() { return null; } } } <file_sep>/MVC_Sample_Solution/TypeLib.Service/enProjectCode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Service { public enum enProjectCode { LibView_Main } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/UiLibFieldNames.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UtilLib.ControlLib { public static class UiLibFieldNames { private static Dictionary<string, string> _tblNameString; static UiLibFieldNames() { _tblNameString = new Dictionary<string, string>(); _tblNameString.Add("DeviceInfoView_IsLoad", " "); _tblNameString.Add("DeviceInfoView_RegisteredDate", "Date"); _tblNameString.Add("StepInfoView_IsLoad", " "); _tblNameString.Add("StepInfoView_RegisteredDate", "Date"); _tblNameString.Add("RecipeInfoView_IsLoad", " "); _tblNameString.Add("RecipeInfoView_RegisteredDate", "Date"); _tblNameString.Add("GridViewSolutions_IsLoad", " "); _tblNameString.Add("GridViewSolutions_RegisteredDate", "Date"); _tblNameString.Add("GridViewHistories_IsLoad", " "); _tblNameString.Add("GridViewHistories_RegisteredDate", "Date"); _tblNameString.Add("GridViewMaterials_IsLoad", " "); _tblNameString.Add("GridViewMaterials_DrawColor", "Color"); _tblNameString.Add("GridViewMaterials_RegisteredDate", "Date"); _tblNameString.Add("GridViewConditions_IsLoad", " "); _tblNameString.Add("GridViewConditions_RegisteredDate", "Date"); _tblNameString.Add("GridViewSpectrums_IsLoad", " "); _tblNameString.Add("GridViewSpectrums_RegisteredDate", "Date"); _tblNameString.Add("GridViewParametersFit_InitialValue", "Initial Value"); _tblNameString.Add("GridViewParametersFit_PriorValue", "Prior\nValue"); _tblNameString.Add("GridViewParametersFit_PriorWidth", "Prior\nWidth"); _tblNameString.Add("GridViewParametersFit_PosteriorValue", "Posterior\nValue"); _tblNameString.Add("GridViewParametersFit_PosteriorWidth", "Posterior\nWidth"); _tblNameString.Add("GridViewParametersMeta_VirtualValue", "Virtual Value"); _tblNameString.Add("GridViewParametersMeta_StepID", "Step ID"); _tblNameString.Add("GridViewParametersMeta_EquipID", "Equip ID"); _tblNameString.Add("GridViewParametersMeta_RecipeID", "Recipe ID"); _tblNameString.Add("GridViewParametersMeta_LotID", "Lot ID"); _tblNameString.Add("GridViewParametersMeta_SlotID", "Slot ID"); _tblNameString.Add("GridViewParametersMeta_SiteID", "Site ID"); _tblNameString.Add("GridViewParametersMeta_PointID", "Point ID"); _tblNameString.Add("GridViewSampling_Polar_Angle", "Polar_Angle\nValue"); _tblNameString.Add("GridViewSampling_Polar_Setting", "Polar_Angle\nSetting"); _tblNameString.Add("GridViewSampling_Azimuthal_Angle", "Azimuthal_Angle\nValue"); _tblNameString.Add("GridViewSampling_Azimuthal_Setting", "Azimuthal_Angle\nSetting"); _tblNameString.Add("GridViewSampling_Wavelength", "Wavelength\nValue"); _tblNameString.Add("GridViewSampling_Wavelength_Setting", "Wavelength\nSetting"); _tblNameString.Add("GridViewSampling_Offset", "Offset"); _tblNameString.Add("GridViewSampling_Scale", "Scale"); _tblNameString.Add("GridViewSampling_Weight", "Weight"); //_tblNameString.Add("GridViewResultSummary_", ""); } public static string GetColumnNameString(string moduleName, string propertyName) { string keyString = String.Format("{0}_{1}", moduleName, propertyName); if (_tblNameString.ContainsKey(keyString) == true) { return _tblNameString[keyString]; } return propertyName; } } } <file_sep>/MVC_Sample_Solution/TypeLib.Service/enEventCode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Service { public enum enEventCode : int { RootCall_Load = 0, RootCall_Unload, RootCall_MaterialChange, RootCall_Notify, RootCall_MaterialDelete, } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/MainAppConfigurator.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TypeLib.Core; using TypeLib.OriginType; using TypeLib.Service; namespace UiForm.Sample { public class MainAppConfigurator : AppConfigurator { public OriginType Type { get; private set; } public MainManagerSchedulerJob JobManager { get; private set; } public IDataModel iDataModel { get; private set; } #region override void CallBackFunc(object sender, EventArgs e) public override void CallBackFunc(object sender, EventArgs e) { UiLibMessage receiveMessage = e as UiLibMessage; if ((receiveMessage != null) && (receiveMessage.Code is enEventCode)) { switch ((enEventCode)receiveMessage.Code) { default: { DefaultRootCallMsg(receiveMessage); } break; } } } #endregion #region override void Init() public override void Init() { var DataModel = (SampleDataModel)iDataModel; DataModel.InitDataModel(string.Empty); //string configFileURL = Path.Combine(Directory.GetCurrentDirectory(), UiLibWords.FILE_CONFIG); //if (File.Exists(configFileURL)) //{ // ConfigData = UtilFuncFile.ObjectFromXmlFile<AppConfigurationData>(configFileURL); //} //else //{ // // Default Configuration // ConfigData = new AppConfigurationData(); // ConfigData.ToXmlFile<AppConfigurationData>(configFileURL); //} #region Configuration Object Initialize InitConfiguration(); #endregion if (TblSubController == null) { TblSubController = new Dictionary<string, ISampleController>(); } ISampleController controller = null; #region Network Initailze JobManager = new MainManagerSchedulerJob(DataModel); JobManager.ReportCallEvent += CallBackFunc; #endregion } #endregion #region override void StoreConfig() public override void StoreConfig() { } #endregion #region Creator public MainAppConfigurator(OriginType type, ISampleView owner) { Type = type; Owner = owner; iDataModel = new SampleDataModel(); TblConfig = new Dictionary<string, string>(); TblBindProperty = new Dictionary<Type, object>(); TblBindList = new Dictionary<enProjectCode, BindListCollection>(); TblSubController = new Dictionary<string, ISampleController>(); TblGridView = new Dictionary<enUiTypeCode, List<ISampleView>>(); TblChartView = new Dictionary<enChartCode, List<ISampleView>>(); } #endregion #region Implement Call Back Function private void DefaultRootCallMsg(UiLibMessage msg) { UiLibMessage sendMessageConfiguration = new UiLibMessage(); UiLibMessage sendMessageMaterial = new UiLibMessage(); UiLibMessage sendMessageMeasurement = new UiLibMessage(); UiLibMessage sendMessageJobManager = new UiLibMessage(); UiLibMessage sendMessageRecipe = new UiLibMessage(); UiLibMessage sendMessageStructure = new UiLibMessage(); UiLibMessage sendMessageGenerate = new UiLibMessage(); UiLibMessage sendMessageTrain = new UiLibMessage(); var inCode = (enEventCode)msg.Code; sendMessageConfiguration.Code = inCode; sendMessageConfiguration.Parameters.Clear(); sendMessageConfiguration.Parameters.AddRange(msg.Parameters); sendMessageMaterial.Code = inCode; sendMessageMaterial.Parameters.Clear(); sendMessageMaterial.Parameters.AddRange(msg.Parameters); sendMessageMeasurement.Code = inCode; sendMessageMeasurement.Parameters.Clear(); sendMessageMeasurement.Parameters.AddRange(msg.Parameters); sendMessageJobManager.Code = inCode; sendMessageJobManager.Parameters.Clear(); sendMessageJobManager.Parameters.AddRange(msg.Parameters); sendMessageRecipe.Code = inCode; sendMessageRecipe.Parameters.Clear(); sendMessageRecipe.Parameters.AddRange(msg.Parameters); sendMessageStructure.Code = inCode; sendMessageStructure.Parameters.Clear(); sendMessageStructure.Parameters.AddRange(msg.Parameters); sendMessageGenerate.Code = inCode; sendMessageGenerate.Parameters.Clear(); sendMessageGenerate.Parameters.AddRange(msg.Parameters); sendMessageTrain.Code = inCode; sendMessageTrain.Parameters.Clear(); sendMessageTrain.Parameters.AddRange(msg.Parameters); //TblSubController[UiLibWords.CONTROL_RECIPE].CallBackFunc(this, sendMessageRecipe); ////수정 kjh ControllerStructure 병합작업으로 아래 코드는 필요 없다고 생각. ////TblSubController[UiLibWords.CONTROL_MATERIAL].CallBackFunc(this, sendMessageMaterial); //TblSubController[UiLibWords.CONTROL_MEASUREMENT].CallBackFunc(this, sendMessageMeasurement); //TblSubController[UiLibWords.CONTROL_STRUCTRUE].CallBackFunc(this, sendMessageStructure); //TblSubController[UiLibWords.CONTROL_CONFIGURATION].CallBackFunc(this, sendMessageConfiguration); //TblSubController[UiLibWords.CONTROL_JOBMANAGER].CallBackFunc(this, sendMessageJobManager); //TblSubController[UiLibWords.CONTROL_GENERATE].CallBackFunc(this, sendMessageGenerate); //TblSubController[UiLibWords.CONTROL_TRAIN].CallBackFunc(this, sendMessageTrain); } #endregion #region Initialize Function private void InitConfiguration() { //if (!TblConfig.ContainsKey(UiLibWords.PROXY_CHECKTIME)) //{ // TblConfig.Add(UiLibWords.PROXY_CHECKTIME, "2000"); //} //if (!int.TryParse(TblConfig[UiLibWords.PROXY_CHECKTIME], out _checkTime)) //{ // _checkTime = 2000; //} //if (ConfigData.WorkLoadManager == null) //{ // ConfigData.WorkLoadManager = new ServerInformation() // { // Name = UiLibWords.PROXY_NAME, // Address = UiLibWords.PROXY_ADDRESS, // Port = 10534, // //Type = enServiceType.WorkLoad // }; // string configFileURL = Path.Combine(Directory.GetCurrentDirectory(), UiLibWords.FILE_CONFIG); // ConfigData.ToXmlFile<AppConfigurationData>(configFileURL); //} //foreach (var item in ConfigData.TblConfigurationData) //{ // if (TblConfig.ContainsKey(item.Key)) // { // TblConfig[item.Key] = item.Value; // } // else // { // TblConfig.Add(item.Key, item.Value); // } //} //if (TblConfig.ContainsKey(UiLibWords.KEY_WORKLOAD_NAME)) //{ // TblConfig[UiLibWords.KEY_WORKLOAD_NAME] = ConfigData.WorkLoadManager.Name; //} //else //{ // TblConfig.Add(UiLibWords.KEY_WORKLOAD_NAME, ConfigData.WorkLoadManager.Name); //} } #endregion } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/UiType/enEventCode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UiForm.Sample.UiType { public enum enEventCode { Redraw, RecipeManager_Load, Tree_Refresh, Tree_Group, Tree_New, Tree_SaveAs, Tree_Save, Tree_Del, Tree_Load, Tree_Update, } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/MenuItemInfo.cs using System; using System.Drawing; using System.Collections.Generic; namespace UtilLib.ControlLib { public class MenuItemInfo { public string ID { get; set; } public Bitmap Icon { get; set; } } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/IWaitFormShowable.cs using System; namespace UtilLib.ControlLib { public interface IWaitFormShowable { void Show(string caption, string message, object iController); void Ping(string message); void Hide(); bool IsAlive(); } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/TempleteController.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TypeLib.Core; using TypeLib.DbLib; using TypeLib.OriginType; using TypeLib.Service; using UtilLib.ControlLib; namespace UiForm.Sample { class TempleteController : ISampleController { #region Implementation IController for MVC Pattern public event EventHandler ParentCallEvent; public event EventHandler SendMessage; public AppConfigurator AppMain { get; set; } public IDataModel iDataModel { get; private set; } public IWaitFormShowable iWaitForm { get; set; } #region void Init() public void Init() { #region Bindding Object Generate #endregion } #endregion #region Get Bind Item public T GetBindItem<T>(enProjectCode projectCode, enUiTypeCode uiTypeCode) { if (AppMain.TblBindList.ContainsKey(projectCode) && AppMain.TblBindList[projectCode].TblBindList.ContainsKey(uiTypeCode)) { return (T)AppMain.TblBindList[projectCode].TblBindList[uiTypeCode]; } return default(T); } #endregion #region BindingList<T> GetBindList<T>(enProjectCode projectCode, enUiTypeCode uiTypeCode) public BindingList<T> GetBindList<T>(enProjectCode projectCode, enUiTypeCode uiTypeCode) { if (AppMain.TblBindList.ContainsKey(projectCode) && AppMain.TblBindList[projectCode].TblBindList.ContainsKey(uiTypeCode)) { return (BindingList<T>)AppMain.TblBindList[projectCode].TblBindList[uiTypeCode]; } return null; } #endregion #region bool InputValueCheck(Enum fieldId, string value) public bool InputValueCheck(Enum fieldId, string value) { bool retValue = false; UiType.enCheckField fieldType = (UiType.enCheckField)fieldId; switch (fieldType) { } return retValue; } #endregion #region bool UpdateValue(Enum fieldId, object value) bool UpdateValue(Enum fieldId, object value) { List<string> inList = value as List<string>; if ((_sendMessageData != null) && (inList != null)) { } return true; } #endregion #region void CallBackFunc(object sender, EventArgs e) public void CallBackFunc(object sender, EventArgs e) { UiLibMessage msg = e as UiLibMessage; if (msg != null) { if (msg.Code is enEventCode) { enEventCode inCode = (enEventCode)msg.Code; switch (inCode) { } } else { UiType.enEventCode inCode = (UiType.enEventCode)msg.Code; switch (inCode) { } } } } #endregion #endregion public OriginType Solution { get; set; } #region Creator public TempleteController(OriginType solution, IDbProcess DbConnection) { Solution = solution; #region DB Connection iDataModel = new SampleDataModel(); #endregion } #endregion #region Event Message private UiLibMessage _sendMessageData = new UiLibMessage(); private UiLibMessage _sendMessageDataParent = new UiLibMessage(); #endregion #region Detail Function for CallbackFunc private void SampleFunction(ISampleView sender, UiLibMessage msg) { } #endregion #region Private Function #endregion } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/ConfigurationHelper.cs using System.Windows.Forms; namespace UtilLib.ControlLib { //public interface IGridDataSourceLoadStateProvider //{ // bool IsRowOfLoadedItemAt(int rowHandle); //} //public interface IGridDataSourceItemCheckStateProvider //{ // GridCheckStateStateRowConfigurator.State GetRowState(int rowHandle); //} //public interface ITreeDataSourceLoadStateProvider //{ // bool IsNodeOfLoadedItemAt(TreeListNode node); //} //public static class FormUtil //{ // public static void AddDockUserControl(Control parent, XtraUserControl uiView, bool visible = true, DockStyle dockOption = DockStyle.Fill) // { // uiView.Dock = dockOption; // if (visible) // { // uiView.Show(); // } // else // { // uiView.Hide(); // } // parent.Controls.Add(uiView); // } //} //public class GridConfigurator //{ // private IGridDataSourceLoadStateProvider _provider; // public GridConfigurator(DevExpress.XtraGrid.Views.Grid.GridView grid, IGridDataSourceLoadStateProvider provider = null) // { // _provider = provider; // Configure(grid); // grid.RowStyle += GridOnRowStyle; // } // public static void Configure(GridView grid) // { // grid.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowForFocusedRow; // grid.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click; // grid.OptionsCustomization.AllowColumnMoving = false; // grid.OptionsSelection.EnableAppearanceFocusedCell = false; // grid.OptionsSelection.EnableAppearanceFocusedRow = false; // grid.OptionsSelection.EnableAppearanceHideSelection = false; // grid.OptionsView.ShowGroupPanel = false; // var color = UiLibColors.Color("GRID_SELECT_COLOR", grid.Appearance.FocusedRow.BackColor); // grid.Appearance.SelectedRow.BackColor = color; // grid.Appearance.HideSelectionRow.BackColor = color; // } // private void GridOnRowStyle(object sender, RowStyleEventArgs e) // { // var loaded = _provider != null && _provider.IsRowOfLoadedItemAt(e.RowHandle); // var selected = e.State.HasFlag(DevExpress.XtraGrid.Views.Base.GridRowCellState.Selected); // var focused = e.State.HasFlag(DevExpress.XtraGrid.Views.Base.GridRowCellState.Focused); // if (loaded) // { // e.Appearance.BackColor = UiLibColors.Color("GRID_FOCUS_COLOR"); // e.Appearance.BackColor2 = UiLibColors.Color("GRID_FOCUS_COLOR"); // } // else if (selected || focused) // { // e.Appearance.BackColor = UiLibColors.Color("GRID_SELECT_COLOR"); // e.Appearance.BackColor2 = UiLibColors.Color("GRID_SELECT_COLOR"); // } // } // // 추가적인 일괄 grid설정 // public static void ConfigureOpticaCommonGridView(GridView grid) // { // // Column Header가 제거되지 않도록 수정 등 // grid.OptionsCustomization.AllowColumnMoving = false; // grid.OptionsCustomization.AllowRowSizing = false; // grid.OptionsCustomization.AllowFilter = false; // } //} //public class GridCheckStateStateRowConfigurator //{ // public enum State // { // Unchecked, // Checked, // Grayed, // } // private IGridDataSourceItemCheckStateProvider _provider; // public GridCheckStateStateRowConfigurator(DevExpress.XtraGrid.Views.Grid.GridView grid, IGridDataSourceItemCheckStateProvider provider = null) // { // _provider = provider; // grid.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowForFocusedRow; // grid.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click; // grid.OptionsSelection.EnableAppearanceFocusedCell = false; // grid.OptionsSelection.EnableAppearanceFocusedRow = false; // grid.OptionsSelection.EnableAppearanceHideSelection = false; // grid.OptionsView.ShowGroupPanel = false; // var color = UiLibColors.Color("GRID_UNCHECKED_COLOR", grid.Appearance.FocusedRow.BackColor); // grid.Appearance.SelectedRow.BackColor = color; // grid.Appearance.HideSelectionRow.BackColor = color; // grid.RowStyle += GridOnRowStyle; // } // private void GridOnRowStyle(object sender, RowStyleEventArgs e) // { // var state = State.Unchecked; // if (_provider != null) // { // state = _provider.GetRowState(e.RowHandle); // } // var selected = e.State.HasFlag(DevExpress.XtraGrid.Views.Base.GridRowCellState.Selected); // var focused = e.State.HasFlag(DevExpress.XtraGrid.Views.Base.GridRowCellState.Focused); // var colorCode = "GRID_CHECKED_COLOR"; // switch (state) // { // case State.Checked: // colorCode = "GRID_CHECKED_COLOR"; // break; // case State.Unchecked: // colorCode = "GRID_UNCHECKED_COLOR"; // break; // default: // colorCode = "GRID_GRAYED_COLOR"; // break; // } // e.Appearance.BackColor = UiLibColors.Color(colorCode); // e.Appearance.BackColor2 = UiLibColors.Color(colorCode); // } //} //public class TreeListConfigurator //{ // private ITreeDataSourceLoadStateProvider _provider; // public TreeListConfigurator(DevExpress.XtraTreeList.TreeList treeList, ITreeDataSourceLoadStateProvider provider = null) // { // _provider = provider; // Configure(treeList); // treeList.NodeCellStyle += TreeListOnNodeCellStyle; // treeList.KeyDown += TreeListOnKeyDown; // } // private void TreeListOnKeyDown(object sender, KeyEventArgs e) // { // var treeList = sender as TreeList; // if (treeList == null) // return; // var focusedNode = treeList.FocusedNode; // switch (e.KeyData) // { // case Keys.Left: // e.Handled = true; // if (treeList.FocusedNode != null) // { // var nextNode = focusedNode.ParentNode; // if (nextNode != null) // { // treeList.Selection.Clear(); // treeList.FocusedNode = nextNode; // } // } // break; // case Keys.Right: // e.Handled = true; // if (focusedNode != null && // focusedNode.HasChildren) // { // var nextNode = focusedNode.FirstNode; // treeList.Selection.Clear(); // treeList.FocusedNode = nextNode; // } // break; // case (Keys.Control | Keys.Up): // case (Keys.Control | Keys.Left): // e.Handled = true; // if (focusedNode != null) // { // focusedNode.Expanded = false; // } // break; // case (Keys.Control | Keys.Down): // case (Keys.Control | Keys.Right): // e.Handled = true; // if (focusedNode != null) // { // focusedNode.Expanded = true; // } // break; // case (Keys.Control | Keys.Home): // e.Handled = true; // treeList.Selection.Clear(); // treeList.MoveFirst(); // break; // case (Keys.Control | Keys.End): // e.Handled = true; // treeList.Selection.Clear(); // treeList.MoveLast(); // break; // case (Keys.Home): // if (focusedNode != null && // focusedNode.ParentNode != null && // focusedNode.ParentNode.HasChildren) // { // treeList.Selection.Clear(); // treeList.FocusedNode = focusedNode.ParentNode.FirstNode; // } // e.Handled = true; // break; // case (Keys.End): // if (focusedNode != null && // focusedNode.ParentNode != null && // focusedNode.ParentNode.HasChildren) // { // treeList.Selection.Clear(); // treeList.FocusedNode = focusedNode.ParentNode.LastNode; // } // e.Handled = true; // break; // } // } // public static void Configure(TreeList treeList) // { // treeList.ShowButtonMode = DevExpress.XtraTreeList.ShowButtonModeEnum.ShowForFocusedRow; // treeList.OptionsSelection.EnableAppearanceFocusedCell = false; // treeList.OptionsSelection.EnableAppearanceFocusedRow = false; // } // private void TreeListOnNodeCellStyle(object sender, GetCustomNodeCellStyleEventArgs e) // { // var loaded = _provider != null && _provider.IsNodeOfLoadedItemAt(e.Node); // var selected = e.Node.Selected; // var focused = e.Node.Focused; // if (loaded) // { // e.Appearance.BackColor = UiLibColors.Color("GRID_FOCUS_COLOR"); // e.Appearance.BackColor2 = UiLibColors.Color("GRID_FOCUS_COLOR"); // } // else // { // if (selected || focused) // { // e.Appearance.BackColor = UiLibColors.Color("GRID_SELECT_COLOR"); // e.Appearance.BackColor2 = UiLibColors.Color("GRID_SELECT_COLOR"); // } // } // } //} } <file_sep>/MVC_Sample_Solution/TypeLib.Service/ISampleController.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TypeLib.Core; namespace TypeLib.Service { public interface ISampleController { event EventHandler ParentCallEvent; event EventHandler SendMessage; IDataModel iDataModel { get; } AppConfigurator AppMain { get; set; } T GetBindItem<T>(enProjectCode projectCode, enUiTypeCode uiTypeCode); BindingList<T> GetBindList<T>(enProjectCode projectCode, enUiTypeCode uiTypeCode); bool InputValueCheck(Enum fieldId, string value); void Init(); void CallBackFunc(object sender, EventArgs e); } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/Process/DbParameterSQL.cs using System; using System.Data; using System.Data.SqlClient; using System.Runtime.Serialization; namespace TypeLib.DbLib.Process { [DataContract] public class DbParameterSQL : DbParameter { [DataMember] public SqlDbType Type; } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewChartLayout.cs using System; using TypeLib.Core; using TypeLib.Service; namespace Mirero.Wiener.UiForm.LibView { public partial class LibViewChartLayout : DevExpress.XtraEditors.XtraUserControl, ISampleView { #region Controller I/F private IMireroController _iController; #endregion #region Implementation IView #region BindList Code public enProjectCode ProjectCode { get; private set; } public enUiTypeCode UiTypeCode { get; private set; } public enChartCode ChartCode_1 { get; private set; } public enChartCode ChartCode_2 { get; private set; } #endregion #region void UpdateView(object sender, EventArgs e) public void UpdateView(object sender, EventArgs e) { UiLibMessage msg = e as UiLibMessage; if (msg != null) { if (msg.Code is UiType.enEventCode) { UiType.enEventCode inCode = (UiType.enEventCode)msg.Code; switch (inCode) { } } } } #endregion #endregion #region Event Handler & Message public event EventHandler SendMessage; private UiLibMessage _sendMessageData; #endregion #region Selection Mode private bool _isManualMode; #endregion #region Chart Control //GridControl _gridControl; //GridView _gridView; LibViewChart Chart_1; LibViewChart Chart_2; #endregion #region Creator public LibViewChartLayout(ISampleController iController, enChartCode chartCode_1, enChartCode chartCode_2) { InitializeComponent(); #region Default Initialize _sendMessageData = new UiLibMessage(); _iController = iController; ChartCode_1 = chartCode_1; ChartCode_2 = chartCode_2; #region Docking Panel UI FormUtil.AddDockUserControl(splitContainerControl.Panel1, new UiForm.LibView.LibViewChart(_iController, ChartCode_1)); FormUtil.AddDockUserControl(splitContainerControl.Panel2, new UiForm.LibView.LibViewChart(_iController, ChartCode_2)); #endregion this.Load += UiLoad; SendMessage += iController.CallBackFunc; _iController.SendMessage += UpdateView; this.Disposed += UiDisposed; #endregion } public LibViewChartLayout(ISampleController iController, LibViewChart chart_1, LibViewChart chart_2) { InitializeComponent(); #region Default Initialize _sendMessageData = new UiLibMessage(); _iController = iController; Chart_1 = chart_1; Chart_2 = chart_2; #region Docking Panel UI FormUtil.AddDockUserControl(splitContainerControl.Panel1, Chart_1); FormUtil.AddDockUserControl(splitContainerControl.Panel2, Chart_2); #endregion this.Load += UiLoad; SendMessage += iController.CallBackFunc; _iController.SendMessage += UpdateView; this.Disposed += UiDisposed; #endregion } #endregion #region Implement Dispose private void UiDisposed(object sender, EventArgs e) { this.Load -= UiLoad; SendMessage -= _iController.CallBackFunc; _iController.SendMessage -= UpdateView; } #endregion #region Event Handler Available Check private bool IsAvailableEventHandler { get { return (object.ReferenceEquals(SendMessage, null) == false) ? true : false; } } #endregion #region Ui Event Process #region void UiLoad(object sender, EventArgs e) private void UiLoad(object sender, EventArgs e) { #region Link Event this.SizeChanged += LibViewChartLayout_SizeChanged; #endregion } #endregion #region Event Function #endregion #endregion #region void LibViewChartLayout_SizeChanged(object sender, EventArgs e) private void LibViewChartLayout_SizeChanged(object sender, EventArgs e) { splitContainerControl.SplitterPosition = splitContainerControl.Height / 2; } #endregion } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/UiType/ChartItem.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UiForm.LibView.UiType { public class ChartItem { public string yAxis { get; set; } public double xValue { get; set; } } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/UiLibWords.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UtilLib.ControlLib { public static class UiLibWords { public static List<string> BLOCK_PROPERTIES = new List<string>() {"_bcdx","_bcdy","_bposx","_bposy","_bposz","_brang","_brnd","_bvrndx", "_bvrndy","_ht","_htr","_mcdx","_mcdy","_mposx","_mposy","_mrang","_mrnd", "_tcdx","_tcdy","_tposx","_tposy","_trang","_trnd","_tvrndx","_tvrndy"}; public const string PostFix = "FakeDB"; public const string Spectrum = "Spectrum"; public const string Data = "Data"; public const string Input = "Input"; public const string Output = "Output"; public static string GetResultRootPath(string drivePath, string rootPath, long solutionId, string workItemId) { var rootDir = Path.Combine(drivePath, rootPath); var solPath = Path.Combine(rootDir, solutionId + @"\"); var resultRootPath = Path.Combine(solPath, workItemId + @"\"); return resultRootPath; } public static string GetGenerateResultPath(string genResultPath, long solutionId, string workItemId) { var solutionDir = genResultPath + solutionId + "/"; var resultDir = solutionDir + workItemId + "/Result/"; return resultDir; } public static string GetFFNNResultPath(long solutionId, string workItemId) { return solutionId + "/" + workItemId + "/Result/" + workItemId + ".result"; } } } <file_sep>/MVC_Sample_Solution/TypeLib.Service/enChartCode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Service { public enum enChartCode { } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/Process/DbClientORA.cs using System; using System.Data; using System.Data.OracleClient; //using Oracle.DataAccess; //using Oracle.DataAccess.Types; //using Oracle.DataAccess.Client; using System.Collections.Generic; using TypeLib.Core; namespace TypeLib.DbLib.Process { public class DbClientORA : IDbProcess { public const int ERR_STR_SIZE = 255; //private StringBuilder sqlText = new StringBuilder(); #region Singleton Pattern private static volatile DbClientORA _instance; private static object _syncRoot = new Object(); public static IDbProcess iQuery { get { if (_instance == null) { lock (_syncRoot) { if (_instance == null) { _instance = new DbClientORA(); } } } return _instance; } } private DbClientORA() { } #endregion private OracleParameter CreateParameter(string parameterName, OracleType oracleType, ParameterDirection direction) { OracleParameter param = new OracleParameter(parameterName, oracleType) { Direction = direction }; if (oracleType == OracleType.VarChar) { param.DbType = DbType.String; } return param; } public string ConnectionString { get; set; } public string SetTCPConnectionString(string host, string port, string servicename, string user, string pass) { ConnectionString = String.Format("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})" + "(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})));User Id={3};Password={4};", host, port, servicename, user, pass); return ConnectionString; } public int ExecuteQuery(string cmdString, Dictionary<string, DbParameter> cmdParam, IDbHandler handler, ref string errMsg) { int retValue = 0; errMsg = enErrorCode.SUCCESS.GetDescription(); #region Parameter Check if (string.IsNullOrEmpty(ConnectionString)) { errMsg = enErrorCode.TYPE_DB_INVALID_CONNECTION_STRING.GetDescription(); return (int)enErrorCode.TYPE_DB_INVALID_CONNECTION_STRING; } if (string.IsNullOrEmpty(cmdString) || !TblQueryContents.Table.ContainsKey(cmdString)) { errMsg = enErrorCode.TYPE_DB_INVALID_PRAMETER.GetDescription(); return (int)enErrorCode.TYPE_DB_INVALID_PRAMETER; } #endregion using (OracleConnection connection = new OracleConnection(ConnectionString)) { try { connection.Open(); using (OracleCommand sqlCommand = new OracleCommand()) { OracleTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); sqlCommand.Connection = connection; sqlCommand.Transaction = transaction; try { #region Command Text Generate sqlCommand.CommandText = TblQueryContents.Table[cmdString]; sqlCommand.CommandType = CommandType.Text; #endregion #region Default Output Parameter Generate sqlCommand.Parameters.Add(CreateParameter("PO_I_RETURN", OracleType.Int32, ParameterDirection.ReturnValue)); OracleParameter inParam = null; inParam = CreateParameter("PO_V_ERR", OracleType.Char, ParameterDirection.Output); inParam.Size = ERR_STR_SIZE; sqlCommand.Parameters.Add(inParam); sqlCommand.Parameters.Add(CreateParameter("PO_CUR", OracleType.Cursor, ParameterDirection.Output)); #endregion #region User Parameter Generate foreach (DbParameterORA param in cmdParam.Values) { if (param != null) { inParam = null; inParam = CreateParameter(param.Name, param.Type, param.Direction); if (param.Size > 0) { inParam.Size = param.Size; } if ((param.Direction == ParameterDirection.Input) || (param.Direction == ParameterDirection.InputOutput)) { inParam.Value = param.Value; } sqlCommand.Parameters.Add(inParam); } } #endregion #region Query Execute using (OracleDataReader dataReader = sqlCommand.ExecuteReader()) { try { retValue = Convert.ToInt32(sqlCommand.Parameters["PO_I_RETURN"].Value.ToString()); if (retValue == 0) { object[] inData = new object[dataReader.FieldCount]; while (dataReader.Read()) { for (int idx = 0; idx < dataReader.FieldCount; idx++) { inData[idx] = dataReader[idx]; } handler.HandlerQuery(inData); } } else { errMsg = string.Format("{0}", sqlCommand.Parameters["PO_V_ERR"].Value); } } catch (Exception ex) { throw new Exception(ex.Message); } } #endregion transaction.Commit(); } catch (Exception ex) { #region Rollback // Attempt to roll back the transaction. try { transaction.Rollback(); } catch (Exception ex2) { // This catch block will handle any errors that may have occurred // on the server that would cause the rollback to fail, such as // a closed connection. } #endregion throw new Exception(ex.Message); } } } catch (Exception ex) { retValue = 1; errMsg = ex.Message; } } return retValue; } public int ExecuteNonQuery(string cmdString, Dictionary<string, DbParameter> cmdParam, ref string errMsg) { int retValue = 0; errMsg = enErrorCode.SUCCESS.GetDescription(); #region Parameter Check if (string.IsNullOrEmpty(ConnectionString)) { errMsg = enErrorCode.TYPE_DB_INVALID_CONNECTION_STRING.GetDescription(); return (int)enErrorCode.TYPE_DB_INVALID_CONNECTION_STRING; } if (string.IsNullOrEmpty(cmdString) || !TblQueryContents.Table.ContainsKey(cmdString)) { errMsg = enErrorCode.TYPE_DB_INVALID_PRAMETER.GetDescription(); return (int)enErrorCode.TYPE_DB_INVALID_PRAMETER; } #endregion using (OracleConnection connection = new OracleConnection(ConnectionString)) { try { connection.Open(); using (OracleCommand sqlCommand = new OracleCommand()) { OracleTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); sqlCommand.Connection = connection; sqlCommand.Transaction = transaction; try { #region Command Text Generate sqlCommand.CommandText = TblQueryContents.Table[cmdString]; sqlCommand.CommandType = CommandType.Text; #endregion #region Default Output Parameter Generate sqlCommand.Parameters.Add(CreateParameter("PO_I_RETURN", OracleType.Int32, ParameterDirection.ReturnValue)); OracleParameter inParam = null; inParam = CreateParameter("PO_V_ERR", OracleType.Char, ParameterDirection.Output); inParam.Size = ERR_STR_SIZE; sqlCommand.Parameters.Add(inParam); #endregion #region User Parameter Generate foreach (DbParameterORA param in cmdParam.Values) { if (param != null) { inParam = null; inParam = CreateParameter(param.Name, param.Type, param.Direction); if (param.Size > 0) { inParam.Size = param.Size; } if ((param.Direction == ParameterDirection.Input) || (param.Direction == ParameterDirection.InputOutput)) { inParam.Value = param.Value; } sqlCommand.Parameters.Add(inParam); } } #endregion #region Query Execute sqlCommand.ExecuteNonQuery(); retValue = Convert.ToInt32(sqlCommand.Parameters["PO_I_RETURN"].Value.ToString()); if (retValue == 0) { } else { errMsg = string.Format("{0}", sqlCommand.Parameters["PO_V_ERR"].Value); } #endregion transaction.Commit(); } catch (Exception ex) { #region Rollback // Attempt to roll back the transaction. try { transaction.Rollback(); } catch (Exception ex2) { // This catch block will handle any errors that may have occurred // on the server that would cause the rollback to fail, such as // a closed connection. } #endregion throw new Exception(ex.Message); } } } catch (Exception ex) { retValue = 1; errMsg = ex.Message; } } return retValue; } public int ExecuteNonQueryEx(string cmdString, Dictionary<string, DbParameter> cmdParam, ref string errMsg) { int retValue = 0; errMsg = enErrorCode.SUCCESS.GetDescription(); #region Parameter Check if (string.IsNullOrEmpty(ConnectionString)) { errMsg = enErrorCode.TYPE_DB_INVALID_CONNECTION_STRING.GetDescription(); return (int)enErrorCode.TYPE_DB_INVALID_CONNECTION_STRING; } if (string.IsNullOrEmpty(cmdString) || !TblQueryContents.Table.ContainsKey(cmdString)) { errMsg = enErrorCode.TYPE_DB_INVALID_PRAMETER.GetDescription(); return (int)enErrorCode.TYPE_DB_INVALID_PRAMETER; } #endregion #region Output Parameter Name List List<string> outParamListName = new List<string>(); #endregion using (OracleConnection connection = new OracleConnection(ConnectionString)) { try { connection.Open(); using (OracleCommand sqlCommand = new OracleCommand()) { OracleTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); sqlCommand.Connection = connection; sqlCommand.Transaction = transaction; try { #region Command Text Generate sqlCommand.CommandText = TblQueryContents.Table[cmdString]; sqlCommand.CommandType = CommandType.Text; #endregion #region Default Output Parameter Generate sqlCommand.Parameters.Add(CreateParameter("PO_I_RETURN", OracleType.Int32, ParameterDirection.ReturnValue)); OracleParameter inParam = null; inParam = CreateParameter("PO_V_ERR", OracleType.Char, ParameterDirection.Output); inParam.Size = ERR_STR_SIZE; sqlCommand.Parameters.Add(inParam); #endregion #region User Parameter Generate inParam = null; foreach (DbParameterORA param in cmdParam.Values) { if (param != null) { inParam = null; inParam = CreateParameter(param.Name, param.Type, param.Direction); if (param.Size > 0) { inParam.Size = param.Size; } if ((param.Direction == ParameterDirection.Input) || (param.Direction == ParameterDirection.InputOutput)) { inParam.Value = param.Value; } if ((param.Direction == ParameterDirection.Output) || (param.Direction == ParameterDirection.InputOutput)) { outParamListName.Add(param.Name); } sqlCommand.Parameters.Add(inParam); } } #endregion #region Query Execute sqlCommand.ExecuteNonQuery(); retValue = Convert.ToInt32(sqlCommand.Parameters["PO_I_RETURN"].Value.ToString()); if (retValue == 0) { foreach (var outParamName in outParamListName) { if (sqlCommand.Parameters[outParamName].OracleType == OracleType.Char) { cmdParam[outParamName].Value = Convert.ToString(sqlCommand.Parameters[outParamName].Value).Trim(); } else { cmdParam[outParamName].Value = sqlCommand.Parameters[outParamName].Value; } } } else { errMsg = string.Format("{0}", sqlCommand.Parameters["PO_V_ERR"].Value); } #endregion transaction.Commit(); } catch (Exception ex) { #region Rollback // Attempt to roll back the transaction. try { transaction.Rollback(); } catch (Exception ex2) { // This catch block will handle any errors that may have occurred // on the server that would cause the rollback to fail, such as // a closed connection. } #endregion throw new Exception(ex.Message); } } } catch (Exception ex) { retValue = 1; errMsg = ex.Message; } } return retValue; } } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TypeLib.OriginType; using TypeLib.Service; namespace UiForm.Sample { public partial class Form1 : Form, ISampleView { #region Implementation IView #region BindList Code public enProjectCode ProjectCode { get; private set; } public enUiTypeCode UiTypeCode { get; private set; } #endregion #region void UpdateView(object sender, EventArgs e) public void UpdateView(object sender, EventArgs e) { } #endregion #endregion private OriginType _originType = new OriginType(); private MainAppConfigurator _controllerMain; #region Creator public Form1() { InitializeComponent(); } #endregion private void Init() { _controllerMain = new MainAppConfigurator(_originType, this); _controllerMain.Init(); } } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/Process/DbParameterORA.cs using System; using System.Data; using System.Data.OracleClient; using System.Runtime.Serialization; namespace TypeLib.DbLib.Process { [DataContract] public class DbParameterORA : DbParameter { [DataMember] public OracleType Type { get; set; } public void InitData() { Name = string.Empty; Size = 0; Direction = ParameterDirection.Input; Value = null; Type = OracleType.VarChar; } } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/GridViewColumnHeaderHelper.cs namespace UtilLib.ControlLib { //public class GridViewColumnHeaderHelper : GridPainter //{ // BandedGridView _View; // GridBand[] _Bands; // public GridViewColumnHeaderHelper(BandedGridView view, GridBand[] bands) // : base(view) // { // _View = view; // _Bands = bands; // _View.GridControl.Paint += new PaintEventHandler(GridControl_Paint); // _View.CustomDrawColumnHeader += new ColumnHeaderCustomDrawEventHandler(_View_CustomDrawColumnHeader); // _View.CustomDrawBandHeader += new BandHeaderCustomDrawEventHandler(_View_CustomDrawBandHeader); // } // void _View_CustomDrawBandHeader(object sender, BandHeaderCustomDrawEventArgs e) // { // if (_Bands.Contains(e.Band)) // e.Handled = true; // } // void _View_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e) // { // if (((e.Column is BandedGridColumn)) && (_Bands.Contains((e.Column as BandedGridColumn).OwnerBand))) // e.Handled = true; // } // void GridControl_Paint(object sender, PaintEventArgs e) // { // foreach (GridBand band in _Bands) // foreach (BandedGridColumn column in band.Columns) // DrawColumnHeader(new GraphicsCache(e.Graphics), column); // } // public void DrawColumnHeader(GraphicsCache cache, GridColumn column) // { // BandedGridViewInfo viewInfo = _View.GetViewInfo() as BandedGridViewInfo; // GridColumnInfoArgs colInfo = viewInfo.ColumnsInfo[column]; // GridBandInfoArgs bandInfo = getBandInfo(viewInfo.BandsInfo, (column as BandedGridColumn).OwnerBand); // if (colInfo == null || bandInfo == null) // return; // colInfo.Cache = cache; // int top = bandInfo.Bounds.Top; // Rectangle rect = colInfo.Bounds; // int delta = rect.Top - top; // rect.Y = top; // rect.Height += delta; // colInfo.Bounds = rect; // colInfo.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; // ElementsPainter.Column.CalcObjectBounds(colInfo); // ElementsPainter.Column.DrawObject(colInfo); // } // GridBandInfoArgs getBandInfo(GridBandInfoCollection bands, GridBand band) // { // GridBandInfoArgs info = bands[band]; // if (info != null) // return info; // else // foreach (GridBandInfoArgs bandInfo in bands) // { // if (bandInfo.Children != null) // { // info = getBandInfo(bandInfo.Children, band); // if (info != null) // return info; // } // } // return null; // } //} } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/UiLibImages.cs using System; using System.Drawing; using System.Collections.Generic; namespace UtilLib.ControlLib { public static class UiLibImages { public static Dictionary<string, Bitmap> Bitmap16; public static Dictionary<string, Bitmap> Bitmap32; public static Dictionary<string, Bitmap> Bitmap64; static UiLibImages() { // 16x16 images Bitmap16 = LoadImagesFrom(@"Mirero.Wiener.UiLib.ControlLib.Images._16x16."); Bitmap32 = LoadImagesFrom(@"Mirero.Wiener.UiLib.ControlLib.Images._32x32."); Bitmap64 = LoadImagesFrom(@"Mirero.Wiener.UiLib.ControlLib.Images._64x64."); } private static Dictionary<string, Bitmap> LoadImagesFrom(string prefix) { var images = new Dictionary<string, Bitmap>(StringComparer.OrdinalIgnoreCase); { var assembly = System.Reflection.Assembly.GetAssembly(typeof(UiLibImages)); var resources = assembly.GetManifestResourceNames(); foreach (var resource in resources) { if (!resource.StartsWith(prefix)) continue; // '-4' 는 확장자 제거용. var imageName = resource.Substring(prefix.Length, resource.Length - prefix.Length - 4); var stream = assembly.GetManifestResourceStream(resource); if (stream == null) continue; var bitmap = new Bitmap(stream); if (bitmap.Size.Equals(Size.Empty)) continue; images[imageName] = bitmap; } } return images; } } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/IDbHandler.cs using System; using System.Collections.Generic; namespace TypeLib.DbLib { public interface IDbHandler { bool HandlerQuery(params object[] fieldData); } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewChart.cs using System; using System.Collections.Generic; using System.Data; using System.Linq; using TypeLib.Core; using TypeLib.Service; namespace Mirero.Wiener.UiForm.LibView { public partial class LibViewChart : DevExpress.XtraEditors.XtraUserControl, ISampleView { #region Controller I/F private IMireroController _iController; #endregion #region Implementation IView #region BindList Code public enProjectCode ProjectCode { get; private set; } public enUiTypeCode UiTypeCode { get; private set; } public enChartCode ChartCode; private UiType.ChartData _chartData; #endregion #region void UpdateView(object sender, EventArgs e) public void UpdateView(object sender, EventArgs e) { UiLibMessage msg = e as UiLibMessage; if (msg != null) { if (msg.Code is UiType.enEventCode) { UiType.enEventCode inCode = (UiType.enEventCode)msg.Code; switch (inCode) { case UiType.enEventCode.Lib_Chart_BeginUpdate: chartControl.BeginInit(); break; case UiType.enEventCode.Lib_Chart_EndUpdate: chartControl.EndInit(); break; case UiType.enEventCode.Lib_ChangeChart: { _chartData = TblChartCode.GetChartData(ChartCode); Lib_ChangeChart(); } break; case UiType.enEventCode.Lib_Change_SeriesVisible: { _chartData = TblChartCode.GetChartData(ChartCode); Lib_Change_SeriesVisible(); } break; case UiType.enEventCode.Lib_Change_SereisThickness: { _chartData = TblChartCode.GetChartData(ChartCode); Lib_Change_SereisThickness(); } break; case UiType.enEventCode.Lib_Change_ChartLogScale: { _chartData = TblChartCode.GetChartData(ChartCode); Lib_Change_ChartLogScale(msg); } break; } } } } #endregion #endregion #region Event Handler & Message public event EventHandler SendMessage; private UiLibMessage _sendMessageData; #endregion public ChartControl GetChartControl { get { return chartControl; } } #region Creator public LibViewChart(IMireroController iController, enChartCode chartCode) { InitializeComponent(); #region Default Initialize _sendMessageData = new UiLibMessage(); _iController = iController; ChartCode = chartCode; _chartData = TblChartCode.GetChartData(chartCode); #region TblChart Assign if (_iController.AppMain.TblChartView.ContainsKey(chartCode)) { if (_iController.AppMain.TblChartView[chartCode] == null) _iController.AppMain.TblChartView[chartCode] = new List<IMireroView>(); _iController.AppMain.TblChartView[chartCode].Add(this); } else { _iController.AppMain.TblChartView.Add(chartCode, new List<IMireroView>()); _iController.AppMain.TblChartView[chartCode].Add(this); } #endregion this.Load += UiLoad; SendMessage += iController.CallBackFunc; _iController.SendMessage += UpdateView; this.Disposed += UiDisposed; #endregion } #endregion #region Implement Dispose private void UiDisposed(object sender, EventArgs e) { this.Load -= UiLoad; SendMessage -= _iController.CallBackFunc; _iController.SendMessage -= UpdateView; if (_iController.AppMain.TblChartView.ContainsKey(ChartCode)) _iController.AppMain.TblChartView[ChartCode].Remove(this); } #endregion #region Event Handler Available Check private bool IsAvailableEventHandler { get { return (object.ReferenceEquals(SendMessage, null) == false) ? true : false; } } #endregion #region Ui Event Process #region void UiLoad(object sender, EventArgs e) private void UiLoad(object sender, EventArgs e) { //chartControl.Legend.UseCheckBoxes = true; chartControl.Legend.Visible = false; //chartControl.CrosshairOptions.ShowCrosshairLabels = false; chartControl.CrosshairOptions.CrosshairLabelMode = CrosshairLabelMode.ShowForNearestSeries; chartControl.CustomDrawCrosshair += chartControl_CustomDrawCrosshair; chartControl.CacheToMemory = true; chartControl.RefreshDataOnRepaint = false; chartControl.RuntimeHitTesting = false; } #endregion #endregion #region Implement Call Back Function #region void InitChartView() private void Lib_ChangeChart() { try { if (_chartData == null) { return; } // Series Process chartControl.Series.Clear(); int idx = 0; foreach (var dicItem in _chartData.SereisDic) { var item = (SeriesItem)dicItem.Value; idx = chartControl.Series.Add(dicItem.Key, item.ChartType); switch (item.ChartType) { case ViewType.Line: { chartControl.Series[idx].DataSource = item.Datas; chartControl.Series[idx].ArgumentDataMember = "X"; chartControl.Series[idx].ValueDataMembers.AddRange(new string[] { "Y" }); chartControl.Series[idx].Visible = item.isVisible; if(dicItem.Value.SeriesColor != null) chartControl.Series[idx].View.Color = dicItem.Value.SeriesColor; (chartControl.Series[0].View as LineSeriesView).LineStyle.Thickness = item.SeriesThickness; (chartControl.Series[0].View as LineSeriesView).LineStyle.DashStyle = item.DashStyle; } break; case ViewType.RangeArea: { chartControl.Series[idx].DataSource = (item.Datas.Cast<UiType.ChartRangeValue>().ToList()); chartControl.Series[idx].ArgumentDataMember = "X"; chartControl.Series[idx].ValueDataMembers.AddRange(new string[] { "YErrorUpper", "YErrorUnder" }); chartControl.Series[idx].Visible = item.isVisible; if(dicItem.Value.SeriesColor != null) chartControl.Series[idx].View.Color = dicItem.Value.SeriesColor; } break; case ViewType.Point: { chartControl.Series[idx].DataSource = item.Datas; chartControl.Series[idx].ArgumentDataMember = "X"; chartControl.Series[idx].ValueDataMembers.AddRange(new string[] { "Y" }); chartControl.Series[idx].Visible = item.isVisible; } break; case ViewType.Bar: { chartControl.Series[idx].DataSource = item.Datas; chartControl.Series[idx].ArgumentDataMember = "X"; chartControl.Series[idx].ValueDataMembers.AddRange(new string[] { "Y" }); } break; } } if (chartControl.Diagram != null) { ((XYDiagram)chartControl.Diagram).EnableAxisXScrolling = true; ((XYDiagram)chartControl.Diagram).EnableAxisXZooming = true; ((XYDiagram)chartControl.Diagram).EnableAxisYScrolling = true; ((XYDiagram)chartControl.Diagram).EnableAxisYZooming = true; ((XYDiagram)chartControl.Diagram).AxisX.VisualRange.Auto = true; ((XYDiagram)chartControl.Diagram).AxisY.VisualRange.Auto = true; if(ChartCode == enChartCode.MeasuredSpectrum_1 || ChartCode == enChartCode.MeasuredSpectrum_2) ((XYDiagram)chartControl.Diagram).AxisY.WholeRange.SetMinMaxValues(-1, 1); } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } #endregion #region void Lib_Change_SeriesVisible() private void Lib_Change_SeriesVisible() { try { if (_chartData == null) { return; } // Series Process foreach (var dicItem in _chartData.SereisDic) { if (chartControl.Series.Any(item => item.Name.Equals(dicItem.Key))) { chartControl.Series[dicItem.Key].Visible = dicItem.Value.isVisible; if(_chartData.SereisDic[dicItem.Key].ChartType == ViewType.Line) (chartControl.Series[dicItem.Key].View as LineSeriesView).LineStyle.DashStyle = dicItem.Value.DashStyle; } } if (chartControl.Diagram != null) { ((XYDiagram)chartControl.Diagram).AxisX.VisualRange.Auto = true; ((XYDiagram)chartControl.Diagram).AxisY.VisualRange.Auto = true; } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } #endregion #region void Lib_Change_SereisThickness() private void Lib_Change_SereisThickness() { try { if (_chartData == null) { return; } // Series Process foreach (var dicItem in _chartData.SereisDic) { if (chartControl.Series.Any(item => item.Name.Equals(dicItem.Key))) { (chartControl.Series[dicItem.Key].View as LineSeriesView).LineStyle.Thickness = dicItem.Value.SeriesThickness; (chartControl.Series[dicItem.Key].View as LineSeriesView).LineStyle.DashStyle = dicItem.Value.DashStyle; } } if (chartControl.Diagram != null) { ((XYDiagram)chartControl.Diagram).AxisX.VisualRange.Auto = true; ((XYDiagram)chartControl.Diagram).AxisY.VisualRange.Auto = true; } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } #endregion #region void Lib_Change_ChartLogScale(UiLibMessage msg) private void Lib_Change_ChartLogScale(UiLibMessage msg) { try { if (_chartData != null && msg.Parameters.Count == 2) { if (chartControl.Diagram != null) { var ChartFlag = Convert.ToBoolean(msg.Parameters[0]); var LogBaseScale = Convert.ToInt32(msg.Parameters[1]); ((XYDiagram)chartControl.Diagram).AxisY.Logarithmic = ChartFlag; ((XYDiagram)chartControl.Diagram).AxisY.LogarithmicBase = LogBaseScale; } } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } #endregion #endregion #region Event Function #region void chartControl_CustomDrawCrosshair(object sender, CustomDrawCrosshairEventArgs e) private void chartControl_CustomDrawCrosshair(object sender, CustomDrawCrosshairEventArgs e) { foreach (CrosshairElement element in e.CrosshairElements) { var seriesName = element.Series.Name; SeriesPoint currentPoint = element.SeriesPoint; if (currentPoint.Tag.GetType() == typeof(ChartValue)) { ChartValue chartValue = (ChartValue)currentPoint.Tag; element.LabelElement.Text = seriesName + ": " + chartValue.Y.ToString(); } } } #endregion #endregion } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/IDbProcess.cs using System; using System.Collections.Generic; namespace TypeLib.DbLib { public interface IDbProcess { string ConnectionString { get; set; } string SetTCPConnectionString(string host, string port, string servicename, string user, string pass); int ExecuteQuery(string cmdString, Dictionary<string, DbParameter> cmdParam, IDbHandler handler, ref string errMsg); int ExecuteNonQuery(string cmdString, Dictionary<string, DbParameter> cmdParam, ref string errMsg); int ExecuteNonQueryEx(string cmdString, Dictionary<string, DbParameter> cmdParam, ref string errMsg); } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/TblQueryContents.cs using System; using System.Collections.Generic; namespace TypeLib.DbLib { public class TblQueryContents { public static Dictionary<string, string> Table = new Dictionary<string,string>(); static TblQueryContents() { #region Function Define(Except DB inline Function)_Job //F_SET_JOB : 0 [Success] / 1 [Fail] / 5 [ERR_TOO_MANY_ROWS] Table.Add(@"PKG_JOB.F_SET_JOB", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_SET_JOB(:PO_V_ERR, :PO_N_JOB_ID, " + @":PI_V_START_DATE, :PI_N_PROCESS_LIMIT_TIME, :PI_V_CURRENT_MODULE, :PI_N_WAFER_CNT_TOTAL, " + @":PI_N_WAFER_CNT_MISSING, :PI_V_STORAGE_IMAGE_PATH, :PI_N_PROCESS_PERCENT, :PI_V_STORAGE_RESULT_PATH, " + @":PI_CL_RV_MSG_DATA, :PI_V_JOB_KIND, :PI_V_JOB_TYPE); END;"); //F_SET_JOB_ASSIGN : 0 [Success] / 1 [Fail] / 3 [ERR_NOT_EXIST] Table.Add(@"PKG_JOB.F_SET_JOB_ASSIGN", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_SET_JOB_ASSIGN(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_RUNNER_ALIASE, :PI_N_RUNNER_MKL_THREAD_COUNT, :PI_N_RUNNER_CORE_COUNT, :PI_V_TRAINING_PATH); END;"); //F_SET_JOB_ADD : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB.F_SET_JOB_ADD", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_SET_JOB_ADD(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_N_CUSTOMER_FILE_COUNT); END;"); //F_GET_JOB_TYPE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB.F_GET_JOB_TYPE", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_GET_JOB_TYPE(:PO_V_ERR, :PO_V_JOB_TYPE, " + @":PI_N_JOB_ID); END;"); //F_GET_JOB_KIND : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB.F_GET_JOB_KIND", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_GET_JOB_KIND(:PO_V_ERR, :PO_V_JOB_KIND, " + @":PI_N_JOB_ID); END;"); //F_GET_JOB_ASSIGN : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB.F_GET_JOB_ASSIGN", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_GET_JOB_ASSIGN(:PO_V_ERR, :PO_CUR, " + @":PI_N_JOB_ID); END;"); //F_MODIFY_JOB_STATUS : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB.F_MODIFY_JOB_STATUS", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_MODIFY_JOB_STATUS(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_JOB_STATUS, :PI_V_CURRENT_MODULE, :PI_V_END_DATE); END;"); //F_SET_INSPECTION : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_STORE.F_SET_INSPECTION", @"BEGIN :PO_I_RETURN:=PKG_DATA_STORE.F_SET_INSPECTION(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_FILE_NAME, :PI_V_FILE_TIMESTAMP, " + @":PI_V_DEVICE_ID, :PI_V_EQUIP_ID, :PI_V_STEP_ID, :PI_V_LOT_ID, :PI_V_CAT_ID, " + @":PI_V_MATERIAL_ID, :PI_N_WAFER_CNT, :PI_V_STORAGE_PATH, :PI_V_LINE, :PI_V_PP_ID); END;"); //F_SET_WAFER : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_STORE.F_SET_WAFER", @"BEGIN :PO_I_RETURN:=PKG_DATA_STORE.F_SET_WAFER(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_WAFER_SEQ, :PI_V_PROCESS_ID, :PI_N_SLOT, :PI_V_STAGE_GROUP_ID, " + @":PI_N_GROUP_POINTS, :PI_V_WAFER_NAME, :PI_V_STAGE_NAME, :PI_N_WAFER_SIZE, :PI_N_CD_ORIENTATION_ANGLE, " + @":PI_N_WAFER_ANGLE, :PI_N_REAL_COORDINATES, :PI_N_USE_DIE_MAP, :PI_V_TIME_ACQUISITION); END;"); //F_SET_MEASURE_POINT : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_STORE.F_SET_MEASURE_POINT", @"BEGIN :PO_I_RETURN:=PKG_DATA_STORE.F_SET_MEASURE_POINT(:PO_V_ERR, :PO_V_WORK_ITEM_ID, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_SITE_ID, :PI_N_REF_DIE_X, :PI_N_REF_DIE_Y, " + @":PI_N_DIE_PITCH_X, :PI_N_DIE_PITCH_Y, :PI_N_MEASURE_DIE_X, :PI_N_MEASURE_DIE_Y, :PI_N_DIE_ROW, " + @":PI_N_DIE_COLOUMN, :PI_N_IN_DIE_POINT_TAG, :PI_N_DIE_SEQUENCE, :PI_N_MEASURE_X, :PI_N_MEASURE_Y, " + @":PI_V_FILE_NAME, :PI_V_FILE_TIMESTAMP, :PI_V_STORAGE_PATH, :PI_CL_MEASURE_DATA); END;"); //F_SET_RESULT_WORK_ITEM : 0 [Success] / 1 [Fail] / 3 [ERR_NOT_EXIST] Table.Add(@"PKG_DATA_ANALYSIS.F_SET_RESULT_WORK_ITEM", @"BEGIN :PO_I_RETURN:=PKG_DATA_ANALYSIS.F_SET_RESULT_WORK_ITEM(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_RESULT_ITEM_ID, :PI_N_RECIPE_ID, :PI_V_FILE_NAME, " + @":PI_V_STORAGE_PATH, :PI_V_STORAGE_IMAGE_PATH, :PI_V_RESULT_TYPE, :PI_L_FIT_RESULT_DATA); END;"); //F_GET_REWORK_JOB_LIST : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_ANALYSIS.F_GET_REWORK_JOB_LIST", @"BEGIN :PO_I_RETURN:=PKG_DATA_ANALYSIS.F_GET_REWORK_JOB_LIST(:PO_V_ERR, :PO_CUR); END;"); //F_GET_REWORK_ITEM_LIST : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_ANALYSIS.F_GET_REWORK_ITEM_LIST", @"BEGIN :PO_I_RETURN:=PKG_DATA_ANALYSIS.F_GET_REWORK_ITEM_LIST(:PO_V_ERR, :PO_CUR, " + @":PI_N_JOB_ID); END;"); //F_GET_REWORK_JOB_LIST_WIM : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_ANALYSIS.F_GET_REWORK_JOB_LIST_WIM", @"BEGIN :PO_I_RETURN:=PKG_DATA_ANALYSIS.F_GET_REWORK_JOB_LIST_WIM(:PO_V_ERR, :PO_CUR, " + @":PI_V_WORK_ITEM_MANAGER_ALIASE); END;"); //F_MODIFY_MEASURE_DATA_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_STORE.F_MODIFY_MEASURE_DATA_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_DATA_STORE.F_MODIFY_MEASURE_DATA_BLOCK(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_CL_MEASURE_DATA); END;"); #endregion #region Function Define(Except DB inline Function)_Process #region Communicator Status Message // F_COMMUNICATOR_START : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_COMMUNICATOR_START", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_COMMUNICATOR_START(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_COMMUNICATOR_ALIASE, :PI_V_PROCESS, :PI_N_PROCESS_PERCENT, :PI_V_COMMUNICATOR_START); END;"); // F_COMMUNICATOR_MODIFY : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_COMMUNICATOR_MODIFY", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_COMMUNICATOR_MODIFY(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_COMMUNICATOR_ALIASE, :PI_V_PROCESS, :PI_N_PROCESS_PERCENT, :PI_V_COMMUNICATOR_MODIFY); END;"); // F_COMMUNICATOR_END : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_COMMUNICATOR_END", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_COMMUNICATOR_END(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_COMMUNICATOR_ALIASE, :PI_V_STATUS, :PI_V_PROCESS, :PI_N_PROCESS_PERCENT, :PI_V_COMMUNICATOR_END); END;"); #endregion #region Loader Status Message //F_LOADER_START : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_LOADER_START", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_LOADER_START(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_LOADER_ALIASE, :PI_V_PROCESS, :PI_N_PROCESS_PERCENT, :PI_V_LOADER_START); END;"); //F_LOADER_MODIFY : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_LOADER_MODIFY", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_LOADER_MODIFY(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_LOADER_ALIASE, :PI_V_PROCESS, :PI_N_PROCESS_PERCENT, :PI_V_LOADER_MODIFY); END;"); //F_LOADER_END : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_LOADER_END", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_LOADER_END(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_LOADER_ALIASE, :PI_V_STATUS, :PI_V_PROCESS, :PI_N_PROCESS_PERCENT, :PI_V_LOADER_END); END;"); #endregion #region Work Item Manager Status Message //F_WORK_ITEM_MANAGER_START : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_START", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_START(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_WORK_ITEM_MANAGER_START); END;"); //F_WORK_ITEM_MANAGER_MODIFY : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_MODIFY", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_MODIFY(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_WORK_ITEM_MANAGER_MODIFY, :PI_V_STATUS); END;"); //F_WORK_ITEM_MANAGER_END : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_END", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_END(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_V_STATUS, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_WORK_ITEM_MANAGER_END); END;"); #endregion #region Runner Status Message //F_RUNNER_START : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_RUNNER_START", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_RUNNER_START(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_RUNNER_ALIASE, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_RUNNER_START); END;"); //F_RUNNER_MODIFY : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_RUNNER_MODIFY", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_RUNNER_MODIFY(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_RUNNER_ALIASE, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_RUNNER_MODIFY); END;"); //F_RUNNER_END : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_RUNNER_END", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_RUNNER_END(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID, :PI_V_RUNNER_ALIASE, :PI_V_STATUS, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_RUNNER_END); END;"); #endregion #region Deliverer Status Message //F_DELIVERER_START : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_DELIVERER_START", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_DELIVERER_START(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_DELIVERER_ALIASE, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_DELIVERER_START); END;"); //F_DELIVERER_MODIFY : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_DELIVERER_MODIFY", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_DELIVERER_MODIFY(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_DELIVERER_ALIASE, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_DELIVERER_MODIFY); END;"); //F_DELIVERER_END : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_PROCESS.F_DELIVERER_END", @"BEGIN :PO_I_RETURN:=PKG_JOB_PROCESS.F_DELIVERER_END(:PO_V_ERR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_V_DELIVERER_ALIASE, :PI_V_STATUS, :PI_V_PROCESS, " + @":PI_N_PROCESS_PERCENT, :PI_V_DELIVERER_END); END;"); #endregion //F_CHECK_DISTRIBUTION_FINISH : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_ANALYSIS.F_CHECK_DISTRIBUTION_FINISH", @"BEGIN :PO_I_RETURN:=PKG_DATA_ANALYSIS.F_CHECK_DISTRIBUTION_FINISH(:PO_V_ERR, :PO_IS_FINISH, " + @":PI_V_WORK_ITEM_ID); END;"); #endregion #region Function Define(Except DB inline Function)_Option //F_GET_OPTION : 0 [Success] / 1 [Fail] Table.Add(@"PKG_OPTION.F_GET_OPTION", @"BEGIN :PO_I_RETURN:=PKG_OPTION.F_GET_OPTION(:PO_V_ERR, :PO_CUR, " + @":PI_V_KEY, :PI_V_NAME, :PI_V_SUBNAME); END;"); #endregion #region Function Define(Except DB inline Function)_Stand //F_SET_EQUIP : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_STAND.F_SET_EQUIP", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_SET_EQUIP(:PO_V_ERR, " + @":PI_V_EQUIP_ID, :PI_V_EQUIP_MODEL, :PI_V_EQUIP_VERSION, :PI_V_DESCRIPTION, :PI_N_STATE); END;"); //F_SET_DEVICE : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_STAND.F_SET_DEVICE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_SET_DEVICE(:PO_V_ERR, " + @":PI_V_DEVICE_ID, :PI_V_DESIGN_RULE, :PI_V_DEVICE_PREFIX, :PI_V_DESCRIPTION, :PI_N_STATE); END;"); //F_SET_STEP : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_STAND.F_SET_STEP", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_SET_STEP(:PO_V_ERR, " + @":PI_V_STEP_ID, :PI_V_STEP_SEQ, :PI_V_MODE_TYPE, :PI_V_DESCRIPTION, :PI_N_STATE); END;"); //F_SET_SITE : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_STAND.F_SET_SITE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_SET_SITE(:PO_V_ERR, " + @":PI_V_SITE_ID, :PI_V_SITE_NAME, :PI_V_DESCRIPTION, :PI_N_STATE); END;"); //F_GET_DEVICE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_DEVICE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_DEVICE(:PO_V_ERR, :PO_CUR, " + @":PI_V_DEVICE_ID, :PI_N_FLAG); END;"); //F_GET_STEP : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_STEP", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_STEP(:PO_V_ERR, :PO_CUR, " + @":PI_V_STEP_ID, :PI_N_FLAG); END;"); //F_GET_SITE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_SITE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_SITE(:PO_V_ERR, :PO_CUR, " + @":PI_V_SITE_ID, :PI_N_FLAG); END;"); //F_GET_LOADER_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_LOADER_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_LOADER_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_LOADER_ALIASE, :PI_N_DIVISION); END;"); //F_GET_MANAGER_LOADER_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_MANAGER_LOADER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_MANAGER_LOADER_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_V_LOADER_ALIASE, :PI_N_DIVISION); END;"); //F_GET_DELIVERER_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_DELIVERER_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_DELIVERER_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_DELIVERER_ALIASE, :PI_N_DIVISION); END;"); //F_GET_MANAGER_DELIVERER_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_MANAGER_DELIVERER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_MANAGER_DELIVERER_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_V_DELIVERER_ALIASE, :PI_N_DIVISION); END;"); //F_GET_WORK_ITEM_MANAGER_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_WORK_ITEM_MANAGER_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_WORK_ITEM_MANAGER_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_N_DIVISION); END;"); //F_GET_RUNNER_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_RUNNER_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_RUNNER_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_RUNNER_ALIASE, :PI_N_DIVISION); END;"); //F_GET_MANAGER_RUNNER_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_MANAGER_RUNNER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_MANAGER_RUNNER_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_V_RUNNER_ALIASE, :PI_N_DIVISION); END;"); // F_GET_JOB_CHECKER_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_JOB_CHECKER_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_JOB_CHECKER_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_CHECKER_ALIASE, :PI_N_DIVISION); END;"); // F_GET_CHECKER_MGR_COMM_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_CHECKER_MGR_COMM_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_CHECKER_MGR_COMM_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_V_JOB_CHECKER_ALIASE, :PI_V_WORK_ITEM_MANAGER_ALIASE, :PI_V_COMMUNICATOR_ALIASE, :PI_N_DIVISION); END;"); // F_GET_CONFIGURATOR_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_CONFIGURATOR_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_CONFIGURATOR_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_CONFIGURATOR_ALIASE, :PI_N_DIVISION); END;"); //F_GET_NODE_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_NODE_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_NODE_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_NODE_ALIASE, :PI_N_DIVISION); END;"); //F_GET_RUNNER_NODE_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_RUNNER_NODE_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_RUNNER_NODE_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_V_RUNNER_ALIASE, :PI_V_NODE_ALIASE, :PI_N_DIVISION); END;"); //F_SET_PKG_PROCESS_SPEC : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_PKG_PROCESS_SPEC", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_PKG_PROCESS_SPEC(:PO_V_ERR, " + @":PI_V_DEVICE_ID, :PI_V_EQUIP_ID, :PI_V_STEP_ID, :PI_N_DEFECT_COUNT_MAX, :PI_N_DEFECT_IMAGE_COUNT, " + @":PI_N_IMAGE_SIZE_X, :PI_N_IMAGE_SIZE_Y, :PI_N_TARGET_YN, :PI_V_IMAGE_TYPE, :PI_N_DISTRIBUTOR_TYPE, " + @":PI_V_SOLUTION_INFO_PATH, :PI_N_STATE); END;"); //F_DEL_PKG_PROCESS_SPEC : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_DEL_PKG_PROCESS_SPEC", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_DEL_PKG_PROCESS_SPEC(:PO_V_ERR, " + @":PI_V_DEVICE_ID, :PI_V_EQUIP_ID, :PI_V_STEP_ID); END;"); //F_GET_RECIPE_RUNNER_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_RECIPE_RUNNER_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_RECIPE_RUNNER_INFO(:PO_V_ERR, " + @":PI_V_RECIPE_ID, :PI_V_RUNNER_ALIASE, :PI_N_DIVISION); END;"); //F_GET_RECIPE_RUNNER_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_RUNNER_LINK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_RUNNER_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID); END;"); //F_GET_DIVISION : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_DIVISION", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_DIVISION(:PO_V_ERR, :PO_CUR, " + @":PI_V_DIVISION); END;"); //F_GET_ACTOR : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_ACTOR", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_ACTOR(:PO_V_ERR, :PO_CUR, " + @":PI_V_ACTOR, :PI_V_DIVISION); END;"); //F_GET_STATUS : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_STATUS", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_STATUS(:PO_V_ERR, :PO_CUR, " + @":PI_V_STATUS, :PI_V_DIVISION); END;"); //F_GET_JUDGE_CODE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_JUDGE_CODE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_JUDGE_CODE(:PO_V_ERR, :PO_CUR, " + @":PI_V_ACTOR, :PI_V_STATUS, :PI_V_DIVISION); END;"); //F_GET_ERROR_CODE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_ERROR_CODE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_ERROR_CODE(:PO_V_ERR, :PO_CUR, " + @":PI_V_ACTOR, :PI_V_STATUS, :PI_V_DIVISION); END;"); //F_GET_WARNING_CODE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_STAND.F_GET_WARNING_CODE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_GET_WARNING_CODE(:PO_V_ERR, :PO_CUR, " + @":PI_V_ACTOR, :PI_V_STATUS, :PI_V_DIVISION); END;"); //F_SET_ERROR_CODE : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_STAND.F_SET_ERROR_CODE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_SET_ERROR_CODE(:PO_V_ERR, " + @":PI_V_ERROR_CODE, :PI_N_CODE_NUM, :PI_V_CODE_FULL, :PI_V_ACTOR, :PI_V_STATUS, :PI_V_DIVISION, " + @":PI_V_DESCRIPTION, :PI_N_STATE); END;"); //F_SET_WARNING_CODE : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_STAND.F_SET_WARNING_CODE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_SET_WARNING_CODE(:PO_V_ERR, " + @":PI_V_WARNING_CODE, :PI_N_CODE_NUM, :PI_V_CODE_FULL, :PI_V_ACTOR, :PI_V_STATUS, :PI_V_DIVISION, " + @":PI_V_DESCRIPTION, :PI_N_STATE); END;"); //F_SET_WORK_ITEM_MANAGER : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_WORK_ITEM_MANAGER", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_WORK_ITEM_MANAGER(:PO_V_ERR, " + @":PI_V_MANAGER_ALIASE, :PI_V_MANAGER_IP, :PI_V_MANAGER_PORT, :PI_V_MANAGER_USER, :PI_V_MANAGER_PW, " + @":PI_V_MONITORING_PATH, :PI_V_MONITORING_FILE_CODE, :PI_N_MONITORING_INTERVAL, :PI_N_WORKFLOW_COUNT, " + @":PI_V_RELATIVE_PATH_EXE, :PI_N_PROCESS_LIMIT_TIME, :PI_N_DIVISION, :PI_CL_SETUP_DATA, :PI_N_STATE); END;"); //F_SET_LOADER : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_LOADER", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_LOADER(:PO_V_ERR, " + @":PI_V_LOADER_ALIASE, :PI_V_LOADER_IP, :PI_V_LOADER_PORT, :PI_V_LOADER_USER, :PI_V_LOADER_PW, " + @":PI_V_MONITORING_PATH, :PI_V_MONITORING_FILE_CODE, :PI_N_MONITORING_INTERVAL, :PI_N_WORKFLOW_COUNT, " + @":PI_V_RELATIVE_PATH_EXE, :PI_N_PROCESS_LIMIT_TIME, :PI_N_DIVISION, :PI_CL_SETUP_DATA, :PI_N_STATE); END;"); //F_SET_MANAGER_LOADER_LINK : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_MANAGER_LOADER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_MANAGER_LOADER_LINK(:PO_V_ERR, " + @":PI_V_MANAGER_ALIASE, :PI_V_LOADER_ALIASE); END;"); //F_SET_RUNNER : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_RUNNER", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_RUNNER(:PO_V_ERR, " + @":PI_V_RUNNER_ALIASE, :PI_V_RUNNER_IP, :PI_V_RUNNER_PORT, :PI_V_RUNNER_USER, :PI_V_RUNNER_PW, " + @":PI_V_MONITORING_PATH, :PI_V_MONITORING_FILE_CODE, :PI_N_MONITORING_INTERVAL, :PI_N_WORKFLOW_COUNT, " + @":PI_V_RELATIVE_PATH_EXE, :PI_N_PROCESS_LIMIT_TIME, :PI_N_DIVISION, :PI_CL_SETUP_DATA, :PI_N_STATE); END;"); //F_SET_MANAGER_RUNNER_LINK : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_MANAGER_RUNNER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_MANAGER_RUNNER_LINK(:PO_V_ERR, " + @":PI_V_MANAGER_ALIASE, :PI_V_RUNNER_ALIASE); END;"); //F_SET_NODE : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_NODE", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_NODE(:PO_V_ERR, " + @":PI_V_NODE_ALIASE, :PI_CL_SETUP_DATA, :PI_N_STATE); END;"); //F_SET_RUNNER_NODE_LINK : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_RUNNER_NODE_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_RUNNER_NODE_LINK(:PO_V_ERR, " + @":PI_V_RUNNER_ALIASE, :PI_V_NODE_ALIASE); END;"); //F_SET_RECIPE_RUNNER_LINK : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_RECIPE_RUNNER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_RECIPE_RUNNER_LINK(:PO_V_ERR, " + @":PI_N_RECIPE_ID, :PI_V_RUNNER_ALIASE); END;"); //F_SET_DELIVERER : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_DELIVERER", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_DELIVERER(:PO_V_ERR, " + @":PI_V_DELIVERER_ALIASE, :PI_V_DELIVERER_IP, :PI_V_DELIVERER_PORT, :PI_V_DELIVERER_USER, :PI_V_DELIVERER_PW, " + @":PI_V_MONITORING_PATH, :PI_V_MONITORING_FILE_CODE, :PI_N_MONITORING_INTERVAL, :PI_N_WORKFLOW_COUNT, " + @":PI_V_RELATIVE_PATH_EXE, :PI_N_PROCESS_LIMIT_TIME, :PI_N_DIVISION, :PI_CL_SETUP_DATA, :PI_N_STATE); END;"); //F_SET_MANAGER_DELIVERER_LINK : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_MANAGER_DELIVERER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_MANAGER_DELIVERER_LINK(:PO_V_ERR, " + @":PI_V_MANAGER_ALIASE, :PI_V_DELIVERER_ALIASE); END;"); // F_GET_COMMUNICATOR_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_COMMUNICATOR_INFO", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_COMMUNICATOR_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_COMM_ALIASE, :PI_N_DIVISION); END;"); // F_GET_COMM_LOADER_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_COMM_LOADER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_COMM_LOADER_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_V_COMM_ALIASE, :PI_V_LOADER_ALIASE, :PI_N_DIVISION); END;"); // F_GET_COMM_DELIVERER_LINK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SYS_PROCESS.F_GET_COMM_DELIVERER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_GET_COMM_DELIVERER_LINK(:PO_V_ERR, :PO_CUR, " + @":PI_V_COMM_ALIASE, :PI_V_DELIVERER_ALIASE, :PI_N_DIVISION); END;"); // F_SET_COMMUNICATOR : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_COMMUNICATOR", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_COMMUNICATOR(:PO_V_ERR, " + @":PI_V_COMM_ALIASE, :PI_V_COMM_IP, :PI_V_COMM_PORT, :PI_V_COMM_USER, :PI_V_COMM_PW, " + @":PI_V_MONITORING_PATH, :PI_V_MONITORING_FILE_CODE, :PI_N_MONITORING_INTERVAL, :PI_N_WORKFLOW_COUNT, " + @":PI_V_RELATIVE_PATH_EXE, :PI_N_PROCESS_LIMIT_TIME, :PI_N_DIVISION, :PI_CL_SETUP_DATA, :PI_N_STATE); END;"); // F_SET_COMM_LOADER_LINK : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_COMM_LOADER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_COMM_LOADER_LINK(:PO_V_ERR, " + @":PI_V_COMM_ALIASE, :PI_V_LOADER_ALIASE); END;"); // F_SET_COMM_DELIVERER_LINK : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SYS_PROCESS.F_SET_COMM_DELIVERER_LINK", @"BEGIN :PO_I_RETURN:=PKG_SYS_PROCESS.F_SET_COMM_DELIVERER_LINK(:PO_V_ERR, " + @":PI_V_COMM_ALIASE, :PI_V_DELIVERER_ALIASE); END;"); #endregion #region Function Define(Except DB inline Function)_Recipe //F_SET_RECIPE_CONFIGURE : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_RECIPE.F_SET_RECIPE_CONFIGURE", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_SET_RECIPE_CONFIGURE(:PO_V_ERR, " + @":PI_V_DEVICE_ID, :PI_V_STEP_ID, :PI_V_SITE_ID, :PI_V_EQUIP_ID, :PI_V_RECIPE_ID, :PI_V_WRITE_USER, " + @":PI_N_STATE); END;"); //F_GET_RECIPE_CONFIGURE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_CONFIGURE", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_CONFIGURE(:PO_V_ERR, :PO_CUR, " + @":PI_V_DEVICE_ID, :PI_V_STEP_ID, :PI_V_SITE_ID, :PI_V_EQUIP_ID); END;"); //F_GET_RECIPE_CONFIGURE_APP : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_CONFIGURE_APP", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_CONFIGURE_APP(:PO_V_ERR, :PO_CUR, " + @":PI_V_DEVICE_ID, :PI_V_STEP_ID, :PI_V_SITE_ID, :PI_V_EQUIP_ID); END;"); //F_GET_RECIPE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID, :PI_N_RECIPE_PID, :PI_V_RECIPE_NAME); END;"); //F_GET_RECIPE_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_SET_RECIPE : 0 [Success] / 1 [Fail] / 3 [ERR_NOT_EXIST] / 4 [Duplicate] / 5 [ERR_TOO_MANY_ROWS] Table.Add(@"PKG_RECIPE.F_SET_RECIPE", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_SET_RECIPE(:PO_V_ERR, :PO_N_RECIPE_ID, :PO_N_RECIPE_PID," + @":PI_N_RECIPE_ID, :PI_N_RECIPE_PID, :PI_V_RECIPE_NAME, :PI_V_REVISION_VERSION, :PI_V_STORAGE_PATH, " + @":PI_N_USE_YN, :PI_N_LOCKING, :PI_V_REG_IP, :PI_CL_MODEL_PARAMETERS, :PI_CL_FIT_PARAMETERS, " + @":PI_CL_META_PARAMETERS, :PI_CL_REPORTING_PARAMETERS, :PI_CL_VALUE_PARAMETERS, :PI_CL_CONDITIONS, " + @":PI_CL_STRUCTURE, :PI_CL_INPUT_YAML, :PI_CL_RECIPE_TOTAL_DATA, :PI_V_KERNEL_TYPE, :PI_V_SPECTRUM_TYPE, " + @":PI_V_MEASURE_TYPE, :PI_N_STATE, :PI_V_SOL_ID, :PI_V_SOL_PID ); END;"); //F_GET_RECIPE_MODEL_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_MODEL_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_MODEL_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_FIT_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_FIT_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_FIT_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_META_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_META_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_META_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_REPORTING_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_REPORTING_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_REPORTING_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_VALUE_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_VALUE_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_VALUE_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_CONDITIONS_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_CONDITIONS_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_CONDITIONS_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_STRUCTURE_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_STRUCTURE_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_STRUCTURE_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_INPUT_YAML_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_INPUT_YAML_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_INPUT_YAML_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_TOTAL_DATA_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_TOTAL_DATA_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_TOTAL_DATA_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_MEASURE_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_MEASURE_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_MEASURE_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_RECIPE_ID); END;"); //F_GET_RECIPE_ENGINE : 0 [Success] / 1 [Fail] Table.Add(@"PKG_RECIPE.F_GET_RECIPE_ENGINE", @"BEGIN :PO_I_RETURN:=PKG_RECIPE.F_GET_RECIPE_ENGINE(:PO_V_ERR, :PO_CUR, " + @":PI_N_JOB_ID, :PI_V_WAFER_ID, :PI_N_POINT_ID); END;"); #endregion #region Function Define(Except DB inline Function)_SOLUTION //F_SET_MODEL_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_MODEL_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_MODEL_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_FIT_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_FIT_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_FIT_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_META_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_META_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_META_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_REPORTING_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_REPORTING_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_REPORTING_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_VALUE_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_VALUE_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_VALUE_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_CONDITION_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_CONDITION_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_CONDITION_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_STRUCTURE_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_STRUCTURE_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_STRUCTURE_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_YAML_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_YAML_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_YAML_INFO(:PO_V_ERR, " + @":PI_V_NAME, :PI_V_STORAGE_PATH, :PI_V_DATE, :PI_N_USE_YN, :PI_CL_BLOCK_DATA, :PI_V_DESCRIPTION, " + @":PI_V_WRITE_USER, :PI_N_STATE); END;"); //F_SET_SOLUTION_INFO : 0 [Success] / 1 [Fail] / 4 [Duplicate] Table.Add(@"PKG_SOLUTION.F_SET_SOLUTION_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_SET_SOLUTION_INFO(:PO_V_ERR, " + @":PI_ID, :PI_PID, :PI_V_NAME, :PI_V_VERSION, :PI_V_DATE, :PI_V_WRITE_USER, " + @":PI_N_SEQ_ID_MODEL, :PI_N_SEQ_ID_FIT, :PI_N_SEQ_ID_META, :PI_N_SEQ_ID_REPORTING, :PI_N_SEQ_ID_VALUE, " + @":PI_N_SEQ_ID_CONDITION, :PI_N_SEQ_ID_STRUCTURE, :PI_N_SEQ_ID_YAML, :PI_N_SEQ_ID_MATERIAL, :PI_CL_TOTAL_DATA, :PI_V_STORAGE_PATH, " + @":PI_N_STATE, :PI_N_DATA_MAKE_TYPE_FLAG); END;"); //F_GET_SOLUTION_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SOLUTION.F_GET_SOLUTION_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_GET_SOLUTION_INFO(:PO_V_ERR, :PO_CUR, " + @":PI_V_START_DATE, :PI_V_END_DATE, :PI_V_NAME); END;"); //F_DEL_SOLUTION_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SOLUTION.F_DEL_SOLUTION_INFO", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_DEL_SOLUTION_INFO(:PO_V_ERR, " + @":PI_N_SOL_ID, :PI_N_SOL_PID); END;"); //F_GET_SOLUTION_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_SOLUTION.F_GET_SOLUTION_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_SOLUTION.F_GET_SOLUTION_BLOCK(:PO_V_ERR, :PO_CUR, " + @":PI_N_SOL_ID, :PI_N_SOL_PID); END;"); #endregion #region Function Define(Except DB inline Function)_DELIVER // F_GET_RESULT_WORK_ITEM : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_DELIVER.F_GET_RESULT_WORK_ITEM", @"BEGIN :PO_I_RETURN:=PKG_DATA_DELIVER.F_GET_RESULT_WORK_ITEM(:PO_V_ERR, :PO_CUR, " + @":PI_V_WORK_ITEM_ID); END;"); // F_MODIFY_RESULT_DATA_BLOCK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_DELIVER.F_MODIFY_RESULT_DATA_BLOCK", @"BEGIN :PO_I_RETURN:=PKG_DATA_DELIVER.F_MODIFY_RESULT_DATA_BLOCK(:PO_V_ERR, " + @":PI_V_RESULT_TYPE, :PI_V_WORK_ITEM_ID, :PI_V_RESULT_ITEM_ID, :PI_CL_FIT_RESULT_DATA); END;"); #endregion #region get Rendezvous data (For Communicator) // F_GET_RV_MSG_BLOCK_IDBS : 0 [Success] / 1 [Fail] Table.Add(@"PKG_DATA_DELIVER.F_GET_RV_MSG_BLOCK_IDBS", @"BEGIN :PO_I_RETURN:=PKG_DATA_DELIVER.F_GET_RV_MSG_BLOCK_IDBS(:PO_V_ERR, :PO_CUR, " + @":PI_N_JOB_ID); END;"); #endregion #region Function Define(Except DB inline Function)_Monitor //F_SET_SYSTEM_STATUS : 0 [Success] / 1 [Fail] Table.Add(@"PKG_MONITOR.F_SET_SYSTEM_STATUS", @"BEGIN :PO_I_RETURN:=PKG_MONITOR.F_SET_SYSTEM_STATUS(:PO_V_ERR, " + @":PI_V_GROUP_ALIASE, :PI_V_ACTOR, :PI_V_ACTOR_ALIASE, " + @":PI_N_CPU_TOTAL, :PI_N_CPU_USED, :PI_V_CPU_UNIT, " + @":PI_N_MEMORY_TOTAL, :PI_N_MEMORY_USED, :PI_V_MEMORY_UNIT, " + @":PI_V_NETWORK_IP, :PI_V_NETWORK_TYPE, :PI_N_NETWORK_USED_RATIO, :PI_V_NETWORK_UNIT, " + @":PI_V_OS, :PI_CL_OTHER_DATA_BLOCK); END;"); //F_GET_SYSTEM_STATUS : 0 [Success] / 1 [Fail] Table.Add(@"PKG_MONITOR.F_GET_SYSTEM_STATUS", @"BEGIN :PO_I_RETURN:=PKG_MONITOR.F_GET_SYSTEM_STATUS(:PO_V_ERR, :PO_CUR, " + @":PI_V_GROUP_ALIASE, :PI_V_ACTOR, :PI_V_ACTOR_ALIASE); END;"); //F_DEL_SYSTEM_STATUS : 0 [Success] / 1 [Fail] Table.Add(@"PKG_MONITOR.F_DEL_SYSTEM_STATUS", @"BEGIN :PO_I_RETURN:=PKG_MONITOR.F_DEL_SYSTEM_STATUS(:PO_V_ERR, " + @":PI_V_GROUP_ALIASE); END;"); //F_SET_MONITOR_CONDITION : 0 [Success] / 1 [Fail] / 4 [중복데이터] Table.Add(@"PKG_MONITOR.F_SET_MONITOR_CONDITION", @"BEGIN :PO_I_RETURN:=PKG_MONITOR.F_SET_MONITOR_CONDITION(:PO_V_ERR, " + @":PI_V_GROUP_ALIASE, :PI_V_ACTOR, :PI_V_USER_ID, " + @":PI_CL_CONDITION_DATA_BLOCK, :PI_N_STATE); END;"); //F_GET_MONITOR_CONDITION : 0 [Success] / 1 [Fail] Table.Add(@"PKG_MONITOR.F_GET_MONITOR_CONDITION", @"BEGIN :PO_I_RETURN:=PKG_MONITOR.F_GET_MONITOR_CONDITION(:PO_V_ERR, :PO_CUR, " + @":PI_V_GROUP_ALIASE, :PI_V_ACTOR); END;"); //F_DEL_MONITOR_CONDITION : 0 [Success] / 1 [Fail] Table.Add(@"PKG_MONITOR.F_DEL_MONITOR_CONDITION", @"BEGIN :PO_I_RETURN:=PKG_MONITOR.F_DEL_MONITOR_CONDITION(:PO_V_ERR, " + @":PI_V_GROUP_ALIASE, :PI_V_ACTOR); END;"); #endregion #region Function Define(Offline Function) _JobManager //F_GET_JOB_PROCESS_INFO : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_INFO", @"BEGIN :PO_I_RETURN:=PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_INFO(:PO_V_ERR,:PO_CUR, " + @":PI_DA_START_DATE, :PI_DA_END_DATE); END;"); //F_GET_JOB_PROCESS_HIS : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_HIS", @"BEGIN :PO_I_RETURN:=PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_HIS(:PO_V_ERR,:PO_CUR, " + @":PI_DA_START_DATE, :PI_DA_END_DATE, :PI_SOL_ID, :PI_SOL_PID); END;"); //F_GET_JOB_PROCESS_QUICK : 0 [Success] / 1 [Fail] Table.Add(@"PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_QUICK", @"BEGIN :PO_I_RETURN:=PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_QUICK(:PO_V_ERR,:PO_CUR, " + @":PI_DA_START_DATE, :PI_DA_END_DATE, :PI_V_WORK_ITEM_MANAGER_ALIASE); END;"); //F_SET_JOB_OFFLINE : 0 [Success] / 1 [Fail] / 5 [ERR_TOO_MANY_ROWS] Table.Add(@"PKG_JOB.F_SET_JOB_OFFLINE", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_SET_JOB_OFFLINE(:PO_V_ERR, :PO_N_JOB_ID, " + @":PI_V_START_DATE, :PI_N_PROCESS_LIMIT_TIME, :PI_V_CURRENT_MODULE, :PI_N_WAFER_CNT_TOTAL, " + @":PI_N_WAFER_CNT_MISSING, :PI_V_STORAGE_IMAGE_PATH, :PI_N_PROCESS_PERCENT, :PI_V_STORAGE_RESULT_PATH, " + @":PI_CL_RV_MSG_DATA, :PI_V_JOB_KIND, :PI_V_JOB_TYPE, :PI_V_JOB_NAME); END;"); #endregion #region Function Define(Offline Function) _Job Table.Add(@"PKG_JOB.F_CHECK_JOB_RESULT_INFO", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_CHECK_JOB_RESULT_INFO(:PO_V_ERR,:PO_N_CNT," + @":PI_N_JOB_ID); END;"); Table.Add(@"PKG_JOB.F_DEL_JOB_DATA_VIRTUAL", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_DEL_JOB_DATA_VIRTUAL(:PO_V_ERR," + @":PI_N_JOB_ID); END;"); Table.Add(@"PKG_JOB.F_SET_JOB_RESTART_INIT", @"BEGIN :PO_I_RETURN:=PKG_JOB.F_SET_JOB_RESTART_INIT(:PO_V_ERR," + @":PI_N_JOB_ID); END;"); #endregion #region Function Define(offline Function) _Stand Exist Table.Add(@"PKG_STAND.F_EXIST_DEVICE", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_EXIST_DEVICE(:PO_V_ERR," + @":PO_N_CNT, :PI_V_DEVICE_ID); END;"); Table.Add(@"PKG_STAND.F_EXIST_STEP", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_EXIST_STEP(:PO_V_ERR," + @":PO_N_CNT, :PI_V_STEP_ID); END;"); Table.Add(@"PKG_STAND.F_EXIST_EQUIP", @"BEGIN :PO_I_RETURN:=PKG_STAND.F_EXIST_EQUIP(:PO_V_ERR," + @":PO_N_CNT, :PI_V_EQUIP_ID); END;"); #endregion #region etc // UpdateStatus Table.Add(@"UpdateStatus", @"UpdateStatus"); #endregion } } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewNCSChartLayout.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using DevExpress.XtraEditors; namespace Mirero.Wiener.UiForm.LibView { public partial class LibViewNCSChartLayout : DevExpress.XtraEditors.XtraUserControl { public LibViewNCSChartLayout() { InitializeComponent(); this.SizeChanged += LibViewNCSChartLayout_SizeChanged; } #region void LibViewNCSChartLayout_SizeChanged(object sender, EventArgs e) private void LibViewNCSChartLayout_SizeChanged(object sender, EventArgs e) { splitContainerControl.SplitterPosition = splitContainerControl.Height / 3; splitContainerControlSub.SplitterPosition = splitContainerControlSub.Height / 2; } #endregion } } <file_sep>/MVC_Sample_Solution/TypeLib.Service/BindListCollection.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Service { public class BindListCollection { public Dictionary<enUiTypeCode, object> TblBindList { get; private set; } public BindListCollection() { TblBindList = new Dictionary<enUiTypeCode, object>(); } } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/UiType/GridItemRevision.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using UtilLib.ControlLib; namespace UiForm.Sample.UiType { public class GridItemRevision : NotifyPropertyChangeBase { internal static InputValueCheck ValueChecker; #region Origin Data Field #endregion #region Value Check Flag internal bool IsUpdateField { get; set; } #endregion #region History Load Status private bool _isLoad; [DisplayName(" ")] public bool IsLoad { get { return _isLoad; } internal set { _isLoad = value; } } #endregion #region History Name public string Name { get; set; } #endregion #region Device Registered Date [DisplayName("Created Date")] public string RegisteredDate { get; set; } #endregion #region Creator public GridItemRevision() { } #endregion } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewProperty.cs using System; using TypeLib.Core; using TypeLib.Service; namespace Mirero.Wiener.UiForm.LibView { public partial class LibViewProperty : DevExpress.XtraEditors.XtraUserControl, ISampleView { #region Controller I/F private ISampleController _iController; #endregion #region Implementation IView #region BindList Code public enProjectCode ProjectCode { get; private set; } public enUiTypeCode UiTypeCode { get; private set; } #endregion #region void UpdateView(object sender, EventArgs e) public void UpdateView(object sender, EventArgs e) { UiLibMessage msg = e as UiLibMessage; if (msg != null) { if (msg.Code is UiType.enEventCode) { UiType.enEventCode inCode = (UiType.enEventCode)msg.Code; switch (inCode) { case UiType.enEventCode.Lib_Change_Config: propertyGridControl.Refresh(); break; case UiType.enEventCode.Lib_Change_SelectObj_TrainConfig: { Lib_Change_SelectObj_TrainConfig(); } break; } } } } #endregion #endregion #region Event Handler & Message public event EventHandler SendMessage; private UiLibMessage _sendMessageData; #endregion #region Selection Mode private bool _isManualMode; #endregion #region Bind Object private Type _bindType; private object _propertyItem; #endregion #region Grid Control //GridControl _gridControl; //GridView _gridView; public PropertyGridControl GetPropertyGrid { get { return propertyGridControl; } } public object GetSelectObject { get { return _propertyItem; } } #endregion #region Creator public LibViewProperty(ISampleController iController, Type bindType) { InitializeComponent(); #region Default Initialize _sendMessageData = new UiLibMessage(); _iController = iController; _bindType = bindType; if (_iController.AppMain.TblBindProperty.ContainsKey(_bindType)) { _propertyItem = _iController.AppMain.TblBindProperty[_bindType]; } this.Load += UiLoad; SendMessage += iController.CallBackFunc; _iController.SendMessage += UpdateView; this.Disposed += UiDisposed; #endregion } #endregion #region Implement Dispose private void UiDisposed(object sender, EventArgs e) { this.Load -= UiLoad; SendMessage -= _iController.CallBackFunc; _iController.SendMessage -= UpdateView; } #endregion #region Event Handler Available Check private bool IsAvailableEventHandler { get { return (object.ReferenceEquals(SendMessage, null) == false) ? true : false; } } #endregion #region Ui Event Process #region void UiLoad(object sender, EventArgs e) private void UiLoad(object sender, EventArgs e) { #region Data Binding if (_propertyItem != null) { propertyGridControl.SelectedObject = _propertyItem; propertyGridControl.ExpandAllRows(); } #endregion } #endregion #region Event Function private void Lib_Change_SelectObj_TrainConfig() { if (_iController.AppMain.TblBindProperty.ContainsKey(_bindType)) { _propertyItem = _iController.AppMain.TblBindProperty[_bindType]; } propertyGridControl.SelectedObject = _propertyItem; propertyGridControl.ExpandAllRows(); } #endregion #endregion } } <file_sep>/MVC_Sample_Solution/TypeLib.Core/UtilFuncFile.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml; namespace TypeLib.Core { public static class UtilFuncFile { #region Directory Exist Check & Create public static bool CheckDirectory(String dirURL) { //Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$"); //if (!driveCheck.IsMatch(dirURL.Substring(0, 3))) //{ // return false; //} //string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars()); //strTheseAreInvalidFileNameChars += @":/?*" + "\""; //Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]"); //if (containsABadCharacter.IsMatch(dirURL.Substring(3, dirURL.Length - 3))) //{ // return false; //} DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(dirURL)); if (!dir.Exists) dir.Create(); return true; } #endregion #region Directory Exist Check & Delete public static bool DeleteDirectory(String dirURL) { try { DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(dirURL)); if (dir.Exists) dir.Delete(true); } catch { return false; } return true; } #endregion #region XML Write #region static void ToXML(Type objType, object obj, string fileName) public static void ToXML(Type objType, object obj, string fileName) { DataContractSerializer serializer = new DataContractSerializer(objType); System.IO.StreamWriter sw = null; try { // ensure directory exists. string dir = System.IO.Path.GetDirectoryName(fileName); CheckDirectory(dir); // serialize. sw = new System.IO.StreamWriter(fileName); using (XmlTextWriter writer = new XmlTextWriter(sw)) { sw = null; writer.Formatting = Formatting.Indented; serializer.WriteObject(writer, obj); writer.Flush(); } } finally { if (sw != null) { sw.Dispose(); } } } #endregion #region static void ToXmlFile<T>(this T obj, string fileName) public static void ToXmlFile<T>(this T obj, string fileName) { ToXML(typeof(T), obj, fileName); } #endregion #region static string ToXMLString(Type objType, object obj) public static string ToXMLString(Type objType, object obj) { DataContractSerializer serializer = new DataContractSerializer(objType); System.IO.StringWriter sw = null; StringBuilder sb = new StringBuilder(); try { sw = new System.IO.StringWriter(sb); using (XmlTextWriter writer = new XmlTextWriter(sw)) { sw = null; writer.Formatting = Formatting.Indented; serializer.WriteObject(writer, obj); writer.Flush(); } return sb.ToString(); } catch (Exception e) { Console.WriteLine(e.Message); return null; } finally { if (sw != null) { sw.Dispose(); } } } #endregion #region static string XmlStringFrom(object obj) public static string XmlStringFrom(object obj) { return ToXMLString(obj.GetType(), obj); } #endregion #region static string ToXmlString<T>(this T obj) public static string ToXmlString<T>(this T obj) { return ToXMLString(typeof(T), obj); } #endregion #endregion #region XML Read #region static object FromXML(Type objType, string fileName) public static object FromXML(Type objType, string fileName) { DataContractSerializer deserializer = new DataContractSerializer(objType); System.IO.StreamReader sr = null; try { sr = new System.IO.StreamReader(fileName); using (XmlTextReader reader = new XmlTextReader(sr)) { sr = null; return deserializer.ReadObject(reader); } } catch (Exception ex) { return null; } finally { if (sr != null) { sr.Dispose(); } } } #endregion #region static T ObjectFromXmlFile<T>(string filePath) public static T ObjectFromXmlFile<T>(string filePath) { return (T)FromXML(typeof(T), filePath); } #endregion #region static object FromXMLString(Type objType, string inXmlString) public static object FromXMLString(Type objType, string inXmlString) { DataContractSerializer deserializer = new DataContractSerializer(objType); System.IO.StringReader sr = null; try { sr = new System.IO.StringReader(inXmlString); using (XmlTextReader reader = new XmlTextReader(sr)) { sr = null; return deserializer.ReadObject(reader); } } catch (Exception ex) { return null; } finally { if (sr != null) { sr.Dispose(); } } } #endregion #region static T ObjectFromXmlString<T>(string xmlString) public static T ObjectFromXmlString<T>(string xmlString) { return (T)FromXMLString(typeof(T), xmlString); } #endregion #endregion } } <file_sep>/MVC_Sample_Solution/TypeLib.Core/enErrorCode.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Core { public enum enErrorCode : int { [Description("Success")] SUCCESS = 0, [Description("Invalid DB Connection String")] TYPE_DB_INVALID_CONNECTION_STRING = 0x01010001, [Description("Invalid Input Parameter")] TYPE_DB_INVALID_PRAMETER = 0x01010002, } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/UiType/ChartData.cs using DevExpress.XtraCharts; using Mirero.Wiener.UiForm.LibView.UiType; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UiForm.LibView.UiType { public class ChartData { public string Name; public string XAxis; public string YAxis; public Dictionary<string, SeriesItem> SereisDic = new Dictionary<string, SeriesItem>(); } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/AppConfigurationData.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace UiForm.Sample { [DataContract] public class AppConfigurationData { //[DataMember] //public ServerInformation WorkLoadManager { get; set; } //[DataMember] //public ConfigData DbConfig { get; set; } //[DataMember] //public Dictionary<string, string> TblConfigurationData { get; set; } //public AppConfigurationData() //{ // TblConfigurationData = new Dictionary<string, string>(); // DbConfig = new ConfigData() // { // Name = "MainFrame", // GroupName = "MainFrame", // DbInfo = new DbConnectionInfo() // { // IP = UiLibWords.DB_IP, // PORT = UiLibWords.DB_PORT, // SERVICE_NAME = UiLibWords.DB_SERVICENAME, // USER = UiLibWords.DB_USER, // PASSWORD = <PASSWORD> // } // }; // TblConfigurationData = new Dictionary<string, string>() // { // {UiLibWords.KEY_PROXY_CHECK, UiLibWords.VALUE_PROXY_CHECK}, // {UiLibWords.KEY_WORKPATH, Directory.GetCurrentDirectory()}, // {UiLibWords.KEY_GENERATE_RESULTPATH, UiLibWords.VALUE_GENERATE_RESULTPATH}, // {UiLibWords.KEY_DRIVEPATH, UiLibWords.VALUE_DRIVEPATH }, // {UiLibWords.KEY_ROOTPATH, UiLibWords.VALUE_ROOTPATH }, // {UiLibWords.KEY_YAMLPATH, UiLibWords.VALUE_YAMLPATH }, // {UiLibWords.KEY_LOGPATH, UiLibWords.VALUE_LOGPATH }, // {UiLibWords.KEY_RESULTPATH, UiLibWords.VALUE_RESULTPATH }, // {UiLibWords.KEY_SPECTRUMPATH, UiLibWords.VALUE_SPECTRUMPATH }, // {UiLibWords.KEY_WORKLOAD_NAME,"" } // }; //} } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/UiType/enEventCode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UiForm.LibView.UiType { public enum enEventCode { Redraw, #region LibView Lib_ChangeChart, Lib_Change_Config, Lib_Change_SelectObj_TrainConfig, Lib_Change_SeriesVisible, Lib_Change_SereisThickness, Lib_Chart_BeginUpdate, Lib_Chart_EndUpdate, Lib_Change_ChartLogScale, #endregion } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/UiLibSeriesColorIndex.cs using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UtilLib.ControlLib { public static class UiLibSeriesColorIndex { static Dictionary<string, Color> ColorTable; static Random random; static UiLibSeriesColorIndex() { ColorTable = new Dictionary<string, Color>(); random = new Random(); } public static Color GetSeriesColor(string key) { if (ColorTable.ContainsKey(key)) return ColorTable[key]; else { var R = random.Next(1, 255); var G = random.Next(1, 255); var B = random.Next(1, 255); var retColor = Color.FromArgb(R, G, B); ColorTable.Add(key, retColor); return retColor; } } } } <file_sep>/MVC_Sample_Solution/TypeLib.Core/UtilExtensions.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace TypeLib.Core { public static class UtilExtensions { public static string GetDescription(this Enum value) { Type type = value.GetType(); string name = Enum.GetName(type, value); if (name != null) { FieldInfo field = type.GetField(name); if (field != null) { DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return attributes[0].Description; } else { return value.ToString(); } } } return null; } } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/LibViewInitializer.cs using System.ComponentModel; using TypeLib.OriginType; using TypeLib.Service; namespace Mirero.Wiener.UiForm.LibView { public class LibViewInitializer { public AppConfigurator AppMain { get; set; } public OriginType Solution { get; set; } #region void Init() public void Init() { #region Bindding Object Generate BindListCollection bindListCollection = new BindListCollection(); AppMain.TblBindList.Add(enProjectCode.LibView_Main, bindListCollection); #endregion } #endregion #region Creator public LibViewInitializer(OriginType solution) { Solution = solution; } #endregion } } <file_sep>/MVC_Sample_Solution/UiForm.LibView/UiType/ChartRangeValue.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UiForm.LibView.UiType { public class ChartRangeValue : ChartValue { public double YError { get; set; } public double YErrorUpper { get; set; } public double YErrorUnder { get; set; } } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/NotifyPropertyChangeBase.cs using System; using System.ComponentModel; namespace UtilLib.ControlLib { public delegate bool InputValueCheck(Enum fieldId, string value); public delegate bool UpdateValueCollection(Enum fieldId, object item); public abstract class NotifyPropertyChangeBase : INotifyPropertyChanged { #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion protected bool CheckPropertyChanged<T>(string propertyName, ref T oldValue, ref T newValue) { if (oldValue == null && newValue == null) { return false; } if ((oldValue == null && newValue != null) || !oldValue.Equals((T)newValue)) { oldValue = newValue; FirePropertyChanged(propertyName); return true; } return false; } protected void FirePropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/TblKnownParam.cs using System; using System.Data; using System.Data.OracleClient; using System.Collections.Generic; namespace TypeLib.DbLib { public class TblKnownParam { public static Dictionary<string, Dictionary<string, DbParameter>> Table = new Dictionary<string, Dictionary<string, DbParameter>>(); static TblKnownParam() { // Require Size Value for Output Parameter #region 함수정의(DB내부함수는제외)_Job #region Job Add Parameter Table.Add("PKG_JOB.F_SET_JOB", new Dictionary<string, DbParameter>() { {"PO_N_JOB_ID", new Process.DbParameterORA(){Name = "PO_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Output }}, {"PI_V_START_DATE", new Process.DbParameterORA(){Name = "PI_V_START_DATE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_PROCESS_LIMIT_TIME", new Process.DbParameterORA(){Name = "PI_N_PROCESS_LIMIT_TIME", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_CURRENT_MODULE", new Process.DbParameterORA(){Name = "PI_V_CURRENT_MODULE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_WAFER_CNT_TOTAL", new Process.DbParameterORA(){Name = "PI_N_WAFER_CNT_TOTAL", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_WAFER_CNT_MISSING", new Process.DbParameterORA(){Name = "PI_N_WAFER_CNT_MISSING", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_STORAGE_IMAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_IMAGE_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_STORAGE_RESULT_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_RESULT_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input}}, {"PI_CL_RV_MSG_DATA", new Process.DbParameterORA(){Name = "PI_CL_RV_MSG_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input}}, {"PI_V_JOB_KIND", new Process.DbParameterORA(){Name = "PI_V_JOB_KIND", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_JOB_TYPE", new Process.DbParameterORA(){Name = "PI_V_JOB_TYPE", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input}} }); #endregion #region Job Add Assignment Parameter Table.Add("PKG_JOB.F_SET_JOB_ASSIGN", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_RUNNER_MKL_THREAD_COUNT", new Process.DbParameterORA(){Name = "PI_N_RUNNER_MKL_THREAD_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_RUNNER_CORE_COUNT", new Process.DbParameterORA(){Name = "PI_N_RUNNER_CORE_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_TRAINING_PATH", new Process.DbParameterORA(){Name = "PI_V_TRAINING_PATH", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }} }); #endregion #region Job Add iteration count Table.Add("PKG_JOB.F_SET_JOB_ADD", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_CUSTOMER_FILE_COUNT", new Process.DbParameterORA(){Name = "PI_N_CUSTOMER_FILE_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Get Job type Table.Add("PKG_JOB.F_GET_JOB_TYPE", new Dictionary<string, DbParameter>() { {"PO_V_JOB_TYPE", new Process.DbParameterORA(){Name = "PO_V_JOB_TYPE", Type = OracleType.Char, Size = 50, Direction = ParameterDirection.Output }}, {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Get Job Kind Table.Add("PKG_JOB.F_GET_JOB_KIND", new Dictionary<string, DbParameter>() { {"PO_V_JOB_KIND", new Process.DbParameterORA(){Name = "PO_V_JOB_KIND", Type = OracleType.Char, Size = 20, Direction = ParameterDirection.Output }}, {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Get Job Assignment Table.Add("PKG_JOB.F_GET_JOB_ASSIGN", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Get Rework Job List Table.Add("PKG_DATA_ANALYSIS.F_GET_REWORK_JOB_LIST_WIM", new Dictionary<string, DbParameter>() { {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }} }); #endregion #region Inspection Add Parameter Table.Add("PKG_DATA_STORE.F_SET_INSPECTION", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_FILE_NAME", new Process.DbParameterORA(){Name = "PI_V_FILE_NAME", Type = OracleType.VarChar, Size = 100, Direction = ParameterDirection.Input }}, {"PI_V_FILE_TIMESTAMP", new Process.DbParameterORA(){Name = "PI_V_FILE_TIMESTAMP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_DEVICE_ID", new Process.DbParameterORA(){Name = "PI_V_DEVICE_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_EQUIP_ID", new Process.DbParameterORA(){Name = "PI_V_EQUIP_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input}}, {"PI_V_STEP_ID", new Process.DbParameterORA(){Name = "PI_V_STEP_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_LOT_ID", new Process.DbParameterORA(){Name = "PI_V_LOT_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input}}, {"PI_V_CAT_ID", new Process.DbParameterORA(){Name = "PI_V_CAT_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_MATERIAL_ID", new Process.DbParameterORA(){Name = "PI_V_MATERIAL_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_WAFER_CNT", new Process.DbParameterORA(){Name = "PI_N_WAFER_CNT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_STORAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input }}, {"PI_V_LINE", new Process.DbParameterORA(){Name = "PI_V_LINE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_PP_ID", new Process.DbParameterORA(){Name = "PI_V_PP_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}} }); #endregion #region Wafer Add Parameter Table.Add("PKG_DATA_STORE.F_SET_WAFER", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_SEQ", new Process.DbParameterORA(){Name = "PI_V_WAFER_SEQ", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_PROCESS_ID", new Process.DbParameterORA(){Name = "PI_V_PROCESS_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_SLOT", new Process.DbParameterORA(){Name = "PI_N_SLOT", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_STAGE_GROUP_ID", new Process.DbParameterORA(){Name = "PI_V_STAGE_GROUP_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_GROUP_POINTS", new Process.DbParameterORA(){Name = "PI_N_GROUP_POINTS", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_WAFER_NAME", new Process.DbParameterORA(){Name = "PI_V_WAFER_NAME", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_STAGE_NAME", new Process.DbParameterORA(){Name = "PI_V_STAGE_NAME", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_WAFER_SIZE", new Process.DbParameterORA(){Name = "PI_N_WAFER_SIZE", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_CD_ORIENTATION_ANGLE", new Process.DbParameterORA(){Name = "PI_N_CD_ORIENTATION_ANGLE", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_WAFER_ANGLE", new Process.DbParameterORA(){Name = "PI_N_WAFER_ANGLE", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_REAL_COORDINATES", new Process.DbParameterORA(){Name = "PI_N_REAL_COORDINATES", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_USE_DIE_MAP", new Process.DbParameterORA(){Name = "PI_N_USE_DIE_MAP", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_TIME_ACQUISITION", new Process.DbParameterORA(){Name = "PI_V_TIME_ACQUISITION", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); #endregion #region Measure Point Add Parameter Table.Add("PKG_DATA_STORE.F_SET_MEASURE_POINT", new Dictionary<string, DbParameter>() { {"PO_V_WORK_ITEM_ID", new Process.DbParameterORA(){Name = "PO_V_WORK_ITEM_ID", Type = OracleType.Char, Size = 40, Direction = ParameterDirection.Output }}, {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_SITE_ID", new Process.DbParameterORA(){Name = "PI_V_SITE_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_N_REF_DIE_X", new Process.DbParameterORA(){Name = "PI_N_REF_DIE_X", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_REF_DIE_Y", new Process.DbParameterORA(){Name = "PI_N_REF_DIE_Y", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_DIE_PITCH_X", new Process.DbParameterORA(){Name = "PI_N_DIE_PITCH_X", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_DIE_PITCH_Y", new Process.DbParameterORA(){Name = "PI_N_DIE_PITCH_Y", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_MEASURE_DIE_X", new Process.DbParameterORA(){Name = "PI_N_MEASURE_DIE_X", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_MEASURE_DIE_Y", new Process.DbParameterORA(){Name = "PI_N_MEASURE_DIE_Y", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_DIE_ROW", new Process.DbParameterORA(){Name = "PI_N_DIE_ROW", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_DIE_COLOUMN", new Process.DbParameterORA(){Name = "PI_N_DIE_COLOUMN", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_IN_DIE_POINT_TAG", new Process.DbParameterORA(){Name = "PI_N_IN_DIE_POINT_TAG", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_DIE_SEQUENCE", new Process.DbParameterORA(){Name = "PI_N_DIE_SEQUENCE", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_MEASURE_X", new Process.DbParameterORA(){Name = "PI_N_MEASURE_X", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_MEASURE_Y", new Process.DbParameterORA(){Name = "PI_N_MEASURE_Y", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_FILE_NAME", new Process.DbParameterORA(){Name = "PI_V_FILE_NAME", Type = OracleType.VarChar, Size = 256, Direction = ParameterDirection.Input}}, {"PI_V_FILE_TIMESTAMP", new Process.DbParameterORA(){Name = "PI_V_FILE_TIMESTAMP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_STORAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input}}, {"PI_CL_MEASURE_DATA", new Process.DbParameterORA(){Name = "PI_CL_MEASURE_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input}} }); #endregion #region Fit Result Add Parameter Table.Add("PKG_DATA_ANALYSIS.F_SET_RESULT_WORK_ITEM", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_RESULT_ITEM_ID", new Process.DbParameterORA(){Name = "PI_V_RESULT_ITEM_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_RECIPE_ID", new Process.DbParameterORA(){Name = "PI_N_RECIPE_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_FILE_NAME", new Process.DbParameterORA(){Name = "PI_V_FILE_NAME", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_STORAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input}}, {"PI_V_STORAGE_IMAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_IMAGE_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input }}, {"PI_V_RESULT_TYPE", new Process.DbParameterORA(){Name = "PI_V_RESULT_TYPE", Type = OracleType.VarChar, Size = 10, Direction = ParameterDirection.Input}}, {"PI_L_FIT_RESULT_DATA", new Process.DbParameterORA(){Name = "PI_L_FIT_RESULT_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input}} }); #endregion #region Measure Point Data Update Table.Add("PKG_DATA_STORE.F_MODIFY_MEASURE_DATA_BLOCK", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_CL_MEASURE_DATA", new Process.DbParameterORA(){Name = "PI_CL_MEASURE_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input}} }); #endregion #endregion #region 함수정의(DB내부함수는제외)_Process #region Communicator Status Message Parameter Table.Add("PKG_JOB_PROCESS.F_COMMUNICATOR_START", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_COMMUNICATOR_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMMUNICATOR_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_COMMUNICATOR_START", new Process.DbParameterORA(){Name = "PI_V_COMMUNICATOR_START", Type = OracleType.VarChar, Size = 19, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_COMMUNICATOR_MODIFY", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_COMMUNICATOR_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMMUNICATOR_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_COMMUNICATOR_MODIFY", new Process.DbParameterORA(){Name = "PI_V_COMMUNICATOR_MODIFY", Type = OracleType.VarChar, Size = 19, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_COMMUNICATOR_END", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_COMMUNICATOR_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMMUNICATOR_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_STATUS", new Process.DbParameterORA(){Name = "PI_V_STATUS", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_COMMUNICATOR_END", new Process.DbParameterORA(){Name = "PI_V_COMMUNICATOR_END", Type = OracleType.VarChar, Size = 19, Direction = ParameterDirection.Input}} }); #endregion #region Loader Status Message Parameter Table.Add("PKG_JOB_PROCESS.F_LOADER_START", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_START", new Process.DbParameterORA(){Name = "PI_V_LOADER_START", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_LOADER_MODIFY", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_MODIFY", new Process.DbParameterORA(){Name = "PI_V_LOADER_MODIFY", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_LOADER_END", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_STATUS", new Process.DbParameterORA(){Name = "PI_V_STATUS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_END", new Process.DbParameterORA(){Name = "PI_V_LOADER_END", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); #endregion #region Work Item Manager Status Message Parameter Table.Add("PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_START", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WORK_ITEM_MANAGER_START", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_START", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_MODIFY", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WORK_ITEM_MANAGER_MODIFY", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_MODIFY", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_STATUS", new Process.DbParameterORA(){Name = "PI_V_STATUS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_WORK_ITEM_MANAGER_END", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_STATUS", new Process.DbParameterORA(){Name = "PI_V_STATUS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WORK_ITEM_MANAGER_END", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_END", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); #endregion #region Runner Status Message Parameter Table.Add("PKG_JOB_PROCESS.F_RUNNER_START", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_START", new Process.DbParameterORA(){Name = "PI_V_RUNNER_START", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_RUNNER_MODIFY", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_MODIFY", new Process.DbParameterORA(){Name = "PI_V_RUNNER_MODIFY", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_RUNNER_END", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_STATUS", new Process.DbParameterORA(){Name = "PI_V_STATUS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_END", new Process.DbParameterORA(){Name = "PI_V_RUNNER_END", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); #endregion #region Deliverer Status Message Parameter Table.Add("PKG_JOB_PROCESS.F_DELIVERER_START", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_START", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_START", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_DELIVERER_MODIFY", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_MODIFY", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_MODIFY", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); Table.Add("PKG_JOB_PROCESS.F_DELIVERER_END", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_STATUS", new Process.DbParameterORA(){Name = "PI_V_STATUS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_PROCESS", new Process.DbParameterORA(){Name = "PI_V_PROCESS", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_END", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_END", Type = OracleType.VarChar, Direction = ParameterDirection.Input}} }); #endregion #region check status of the job finish (For deliverer Process) Table.Add("PKG_DATA_ANALYSIS.F_CHECK_DISTRIBUTION_FINISH", new Dictionary<string, DbParameter>() { {"PO_IS_FINISH", new Process.DbParameterORA(){Name = "PO_IS_FINISH", Type = OracleType.Int32, Direction = ParameterDirection.Output }}, {"PI_V_WORK_ITEM_ID", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_ID", Type = OracleType.VarChar, Size = 40, Direction = ParameterDirection.Input }} }); #endregion #region the information of related the Configurator Table.Add("PKG_JOB_PROCESS.F_CONFIGURATOR_START", new Dictionary<string, DbParameter>() { }); Table.Add("PKG_JOB_PROCESS.F_CONFIGURATOR_END", new Dictionary<string, DbParameter>() { }); #endregion #endregion #region 함수정의(DB내부함수는제외)_Stand #region Manager Information Set #region Communicator Set Table.Add("PKG_SYS_PROCESS.F_SET_COMMUNICATOR", new Dictionary<string, DbParameter>() { {"PI_V_COMM_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMM_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_COMM_IP", new Process.DbParameterORA(){Name = "PI_V_COMM_IP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_COMM_PORT", new Process.DbParameterORA(){Name = "PI_V_COMM_PORT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_COMM_USER", new Process.DbParameterORA(){Name = "PI_V_COMM_USER", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_COMM_PW", new Process.DbParameterORA(){Name = "PI_V_COMM_PW", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_PATH", new Process.DbParameterORA(){Name = "PI_V_MONITORING_PATH", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_FILE_CODE", new Process.DbParameterORA(){Name = "PI_V_MONITORING_FILE_CODE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_MONITORING_INTERVAL", new Process.DbParameterORA(){Name = "PI_N_MONITORING_INTERVAL", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_WORKFLOW_COUNT", new Process.DbParameterORA(){Name = "PI_N_WORKFLOW_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RELATIVE_PATH_EXE", new Process.DbParameterORA(){Name = "PI_V_RELATIVE_PATH_EXE", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_N_PROCESS_LIMIT_TIME", new Process.DbParameterORA(){Name = "PI_N_PROCESS_LIMIT_TIME", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_CL_SETUP_DATA", new Process.DbParameterORA(){Name = "PI_CL_SETUP_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Distributor Set Table.Add("PKG_SYS_PROCESS.F_SET_WORK_ITEM_MANAGER", new Dictionary<string, DbParameter>() { {"PI_V_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_MANAGER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MANAGER_IP", new Process.DbParameterORA(){Name = "PI_V_MANAGER_IP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MANAGER_PORT", new Process.DbParameterORA(){Name = "PI_V_MANAGER_PORT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MANAGER_USER", new Process.DbParameterORA(){Name = "PI_V_MANAGER_USER", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MANAGER_PW", new Process.DbParameterORA(){Name = "PI_V_MANAGER_PW", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_PATH", new Process.DbParameterORA(){Name = "PI_V_MONITORING_PATH", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_FILE_CODE", new Process.DbParameterORA(){Name = "PI_V_MONITORING_FILE_CODE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_MONITORING_INTERVAL", new Process.DbParameterORA(){Name = "PI_N_MONITORING_INTERVAL", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_WORKFLOW_COUNT", new Process.DbParameterORA(){Name = "PI_N_WORKFLOW_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RELATIVE_PATH_EXE", new Process.DbParameterORA(){Name = "PI_V_RELATIVE_PATH_EXE", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_N_PROCESS_LIMIT_TIME", new Process.DbParameterORA(){Name = "PI_N_PROCESS_LIMIT_TIME", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_CL_SETUP_DATA", new Process.DbParameterORA(){Name = "PI_CL_SETUP_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Loader Set Table.Add("PKG_SYS_PROCESS.F_SET_LOADER", new Dictionary<string, DbParameter>() { {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_IP", new Process.DbParameterORA(){Name = "PI_V_LOADER_IP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_PORT", new Process.DbParameterORA(){Name = "PI_V_LOADER_PORT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_USER", new Process.DbParameterORA(){Name = "PI_V_LOADER_USER", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_PW", new Process.DbParameterORA(){Name = "PI_V_LOADER_PW", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_PATH", new Process.DbParameterORA(){Name = "PI_V_MONITORING_PATH", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_FILE_CODE", new Process.DbParameterORA(){Name = "PI_V_MONITORING_FILE_CODE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_MONITORING_INTERVAL", new Process.DbParameterORA(){Name = "PI_N_MONITORING_INTERVAL", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_WORKFLOW_COUNT", new Process.DbParameterORA(){Name = "PI_N_WORKFLOW_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RELATIVE_PATH_EXE", new Process.DbParameterORA(){Name = "PI_V_RELATIVE_PATH_EXE", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_N_PROCESS_LIMIT_TIME", new Process.DbParameterORA(){Name = "PI_N_PROCESS_LIMIT_TIME", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_CL_SETUP_DATA", new Process.DbParameterORA(){Name = "PI_CL_SETUP_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Runner Set Table.Add("PKG_SYS_PROCESS.F_SET_RUNNER", new Dictionary<string, DbParameter>() { {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_IP", new Process.DbParameterORA(){Name = "PI_V_RUNNER_IP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_PORT", new Process.DbParameterORA(){Name = "PI_V_RUNNER_PORT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_USER", new Process.DbParameterORA(){Name = "PI_V_RUNNER_USER", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_PW", new Process.DbParameterORA(){Name = "PI_V_RUNNER_PW", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_PATH", new Process.DbParameterORA(){Name = "PI_V_MONITORING_PATH", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_FILE_CODE", new Process.DbParameterORA(){Name = "PI_V_MONITORING_FILE_CODE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_MONITORING_INTERVAL", new Process.DbParameterORA(){Name = "PI_N_MONITORING_INTERVAL", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_WORKFLOW_COUNT", new Process.DbParameterORA(){Name = "PI_N_WORKFLOW_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RELATIVE_PATH_EXE", new Process.DbParameterORA(){Name = "PI_V_RELATIVE_PATH_EXE", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_N_PROCESS_LIMIT_TIME", new Process.DbParameterORA(){Name = "PI_N_PROCESS_LIMIT_TIME", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_CL_SETUP_DATA", new Process.DbParameterORA(){Name = "PI_CL_SETUP_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Deliverer Set Table.Add("PKG_SYS_PROCESS.F_SET_DELIVERER", new Dictionary<string, DbParameter>() { {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_IP", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_IP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_PORT", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_PORT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_USER", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_USER", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_PW", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_PW", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_PATH", new Process.DbParameterORA(){Name = "PI_V_MONITORING_PATH", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_V_MONITORING_FILE_CODE", new Process.DbParameterORA(){Name = "PI_V_MONITORING_FILE_CODE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_MONITORING_INTERVAL", new Process.DbParameterORA(){Name = "PI_N_MONITORING_INTERVAL", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_WORKFLOW_COUNT", new Process.DbParameterORA(){Name = "PI_N_WORKFLOW_COUNT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_RELATIVE_PATH_EXE", new Process.DbParameterORA(){Name = "PI_V_RELATIVE_PATH_EXE", Type = OracleType.VarChar, Size = 255, Direction = ParameterDirection.Input }}, {"PI_N_PROCESS_LIMIT_TIME", new Process.DbParameterORA(){Name = "PI_N_PROCESS_LIMIT_TIME", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_CL_SETUP_DATA", new Process.DbParameterORA(){Name = "PI_CL_SETUP_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Node Set Table.Add("PKG_SYS_PROCESS.F_SET_NODE", new Dictionary<string, DbParameter>() { {"PI_V_NODE_ALIASE", new Process.DbParameterORA(){Name = "PI_V_NODE_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_CL_SETUP_DATA", new Process.DbParameterORA(){Name = "PI_CL_SETUP_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #endregion #region Manager Link Information Set #region Distributor - Loader Table.Add("PKG_SYS_PROCESS.F_SET_MANAGER_LOADER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_MANAGER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }} }); #endregion #region Distributor - Runner Table.Add("PKG_SYS_PROCESS.F_SET_MANAGER_RUNNER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_MANAGER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }} }); #endregion #region Distributor - Deliverer Table.Add("PKG_SYS_PROCESS.F_SET_MANAGER_DELIVERER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_MANAGER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }} }); #endregion #region Runner - Node Table.Add("PKG_SYS_PROCESS.F_SET_RUNNER_NODE_LINK", new Dictionary<string, DbParameter>() { {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_NODE_ALIASE", new Process.DbParameterORA(){Name = "PI_V_NODE_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }} }); #endregion #region Communciator - Loader Table.Add("PKG_SYS_PROCESS.F_SET_COMM_LOADER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_COMM_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMM_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }} }); #endregion #region Communciator - Deliverer Table.Add("PKG_SYS_PROCESS.F_SET_COMM_DELIVERER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_COMM_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMM_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }} }); #endregion #endregion #region Manager Information Query #region Loader Information Query Parameter Table.Add("PKG_SYS_PROCESS.F_GET_LOADER_INFO", new Dictionary<string, DbParameter>() { {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); Table.Add("PKG_SYS_PROCESS.F_GET_MANAGER_LOADER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Deliverer Information Query Parameter Table.Add("PKG_SYS_PROCESS.F_GET_DELIVERER_INFO", new Dictionary<string, DbParameter>() { {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); Table.Add("PKG_SYS_PROCESS.F_GET_MANAGER_DELIVERER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Distributor Information Query Parameter Table.Add("PKG_SYS_PROCESS.F_GET_WORK_ITEM_MANAGER_INFO", new Dictionary<string, DbParameter>() { {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Runner Information Query Parameter Table.Add("PKG_SYS_PROCESS.F_GET_RUNNER_INFO", new Dictionary<string, DbParameter>() { {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); Table.Add("PKG_SYS_PROCESS.F_GET_MANAGER_RUNNER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Node Information Query Parameter Table.Add("PKG_SYS_PROCESS.F_GET_NODE_INFO", new Dictionary<string, DbParameter>() { {"PI_V_NODE_ALIASE", new Process.DbParameterORA(){Name = "PI_V_NODE_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); Table.Add("PKG_SYS_PROCESS.F_GET_RUNNER_NODE_LINK", new Dictionary<string, DbParameter>() { {"PI_V_RUNNER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_RUNNER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_NODE_ALIASE", new Process.DbParameterORA(){Name = "PI_V_NODE_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Communicator Information Query Parameter Table.Add("PKG_SYS_PROCESS.F_GET_COMMUNICATOR_INFO", new Dictionary<string, DbParameter>() { {"PI_V_COMM_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMM_ALIASE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); Table.Add("PKG_SYS_PROCESS.F_GET_COMM_LOADER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_COMM_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMM_ALIASE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_V_LOADER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_LOADER_ALIASE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); Table.Add("PKG_SYS_PROCESS.F_GET_COMM_DELIVERER_LINK", new Dictionary<string, DbParameter>() { {"PI_V_COMM_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMM_ALIASE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_V_DELIVERER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_DELIVERER_ALIASE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region JobChecker Information Query Parameter Table.Add("PKG_SYS_PROCESS.F_GET_JOB_CHECKER_INFO", new Dictionary<string, DbParameter>() { {"PI_V_CHECKER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_CHECKER_ALIASE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); Table.Add("PKG_SYS_PROCESS.F_GET_CHECKER_MGR_COMM_LINK", new Dictionary<string, DbParameter>() { {"PI_V_JOB_CHECKER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_JOB_CHECKER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_COMMUNICATOR_ALIASE", new Process.DbParameterORA(){Name = "PI_V_COMMUNICATOR_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #region Configurator Information Query Paramenter Table.Add("PKG_SYS_PROCESS.F_GET_CONFIGURATOR_INFO", new Dictionary<string, DbParameter>() { {"PI_V_CONFIGURATOR_ALIASE", new Process.DbParameterORA(){Name = "PI_V_CONFIGURATOR_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_DIVISION", new Process.DbParameterORA(){Name = "PI_N_DIVISION", Type = OracleType.Int32, Direction = ParameterDirection.Input}} }); #endregion #endregion #endregion #region 함수정의(DB내부함수는제외)_Recipe #region Get Recipe Configure Table.Add("PKG_RECIPE.F_GET_RECIPE_CONFIGURE", new Dictionary<string, DbParameter>() { {"PI_V_DEVICE_ID", new Process.DbParameterORA(){Name = "PI_V_DEVICE_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_STEP_ID", new Process.DbParameterORA(){Name = "PI_V_STEP_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input}}, {"PI_V_SITE_ID", new Process.DbParameterORA(){Name = "PI_V_SITE_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input}}, {"PI_V_EQUIP_ID", new Process.DbParameterORA(){Name = "PI_V_EQUIP_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }} }); #endregion #region Get Recipe Table.Add("PKG_RECIPE.F_GET_RECIPE", new Dictionary<string, DbParameter>() { {"PI_N_RECIPE_ID", new Process.DbParameterORA(){Name = "PI_N_RECIPE_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_RECIPE_PID", new Process.DbParameterORA(){Name = "PI_N_RECIPE_PID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_RECIPE_NAME", new Process.DbParameterORA(){Name = "PI_V_RECIPE_NAME", Type = OracleType.VarChar, Direction = ParameterDirection.Input }} }); #endregion #region Get Recipe Data (For Runner Process) Table.Add("PKG_RECIPE.F_GET_RECIPE_ENGINE", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Get Runner Information for Recipe Execute (For Distributor Process) Table.Add("PKG_RECIPE.F_GET_RECIPE_RUNNER_LINK", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WAFER_ID", new Process.DbParameterORA(){Name = "PI_V_WAFER_ID", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_N_POINT_ID", new Process.DbParameterORA(){Name = "PI_N_POINT_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Set Recipe Data.. Table.Add("PKG_RECIPE.F_SET_RECIPE", new Dictionary<string, DbParameter>() { {"PO_N_RECIPE_ID", new Process.DbParameterORA(){Name = "PO_N_RECIPE_ID", Type = OracleType.Int32, Direction = ParameterDirection.Output }}, {"PO_N_RECIPE_PID", new Process.DbParameterORA(){Name = "PO_N_RECIPE_PID", Type = OracleType.Int32, Direction = ParameterDirection.Output}}, {"PI_N_RECIPE_ID", new Process.DbParameterORA(){Name = "PI_N_RECIPE_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_RECIPE_PID", new Process.DbParameterORA(){Name = "PI_N_RECIPE_PID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_RECIPE_NAME", new Process.DbParameterORA(){Name = "PI_V_RECIPE_NAME", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_REVISION_VERSION", new Process.DbParameterORA(){Name = "PI_V_REVISION_VERSION", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_STORAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_PATH", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_USE_YN", new Process.DbParameterORA(){Name = "PI_N_USE_YN", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_LOCKING", new Process.DbParameterORA(){Name = "PI_N_LOCKING", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_REG_IP", new Process.DbParameterORA(){Name = "PI_V_REG_IP", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_CL_MODEL_PARAMETERS", new Process.DbParameterORA(){Name = "PI_CL_MODEL_PARAMETERS", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_FIT_PARAMETERS", new Process.DbParameterORA(){Name = "PI_CL_FIT_PARAMETERS", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_META_PARAMETERS", new Process.DbParameterORA(){Name = "PI_CL_META_PARAMETERS", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_REPORTING_PARAMETERS", new Process.DbParameterORA(){Name = "PI_CL_REPORTING_PARAMETERS", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_VALUE_PARAMETERS", new Process.DbParameterORA(){Name = "PI_CL_VALUE_PARAMETERS", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_CONDITIONS", new Process.DbParameterORA(){Name = "PI_CL_CONDITIONS", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_STRUCTURE", new Process.DbParameterORA(){Name = "PI_CL_STRUCTURE", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_INPUT_YAML", new Process.DbParameterORA(){Name = "PI_CL_INPUT_YAML", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_CL_RECIPE_TOTAL_DATA", new Process.DbParameterORA(){Name = "PI_CL_RECIPE_TOTAL_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_V_KERNEL_TYPE", new Process.DbParameterORA(){Name = "PI_V_KERNEL_TYPE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_SPECTRUM_TYPE", new Process.DbParameterORA(){Name = "PI_V_SPECTRUM_TYPE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_MEASURE_TYPE", new Process.DbParameterORA(){Name = "PI_V_MEASURE_TYPE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_SOL_ID", new Process.DbParameterORA(){Name = "PI_V_SOL_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_SOL_PID", new Process.DbParameterORA(){Name = "PI_V_SOL_PID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Get Reporting Rule Data (For deliverer Process) Table.Add("PKG_RECIPE.F_GET_RECIPE_REPORTING_BLOCK", new Dictionary<string, DbParameter>() { {"PI_N_RECIPE_ID", new Process.DbParameterORA(){Name = "PI_N_RECIPE_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Get Recipe Conditions block Table.Add("PKG_RECIPE.F_GET_RECIPE_CONDITIONS_BLOCK", new Dictionary<string, DbParameter>() { {"PI_N_RECIPE_ID", new Process.DbParameterORA(){Name = "PI_N_RECIPE_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #endregion #region 함수정의(DB내부함수는제외)_Solution #region F_SET_SOLUTION_INFO Table.Add("PKG_SOLUTION.F_SET_SOLUTION_INFO", new Dictionary<string, DbParameter>() { {"PI_ID", new Process.DbParameterORA(){Name = "PI_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_PID", new Process.DbParameterORA(){Name = "PI_PID", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_NAME", new Process.DbParameterORA(){Name = "PI_V_NAME", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_VERSION", new Process.DbParameterORA(){Name = "PI_V_VERSION", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_DATE", new Process.DbParameterORA(){Name = "PI_V_DATE", Type = OracleType.VarChar, Size = 19, Direction = ParameterDirection.Input }}, {"PI_V_WRITE_USER", new Process.DbParameterORA(){Name = "PI_V_WRITE_USER", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_MODEL", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_MODEL", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_SEQ_ID_FIT", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_FIT", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_META", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_META", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_REPORTING", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_REPORTING", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_VALUE", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_VALUE", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_CONDITION", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_CONDITION", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_STRUCTURE", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_STRUCTURE", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_YAML", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_YAML", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_SEQ_ID_MATERIAL", new Process.DbParameterORA(){Name = "PI_N_SEQ_ID_MATERIAL", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_CL_TOTAL_DATA", new Process.DbParameterORA(){Name = "PI_CL_TOTAL_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input}}, {"PI_V_STORAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input}}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_DATA_MAKE_TYPE_FLAG", new Process.DbParameterORA(){Name = "PI_N_DATA_MAKE_TYPE_FLAG", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, }); #endregion #region F_GET_SOLUTION_INFO Table.Add("PKG_SOLUTION.F_GET_SOLUTION_INFO", new Dictionary<string, DbParameter>() { {"PI_V_START_DATE", new Process.DbParameterORA(){Name = "PI_V_START_DATE", Type = OracleType.VarChar, Size = 19, Direction = ParameterDirection.Input }}, {"PI_V_END_DATE", new Process.DbParameterORA(){Name = "PI_V_END_DATE", Type = OracleType.VarChar, Size = 19, Direction = ParameterDirection.Input }}, {"PI_V_NAME", new Process.DbParameterORA(){Name = "PI_V_NAME", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, }); #endregion #region F_DEL_SOLUTION_INFO Table.Add("PKG_SOLUTION.F_DEL_SOLUTION_INFO", new Dictionary<string, DbParameter>() { {"PI_N_SOL_ID", new Process.DbParameterORA(){Name = "PI_N_SOL_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_SOL_PID", new Process.DbParameterORA(){Name = "PI_N_SOL_PID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #region F_GET_SOLUTION_BLOCK Table.Add("PKG_SOLUTION.F_GET_SOLUTION_BLOCK", new Dictionary<string, DbParameter>() { {"PI_N_SOL_ID", new Process.DbParameterORA(){Name = "PI_N_SOL_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_N_SOL_PID", new Process.DbParameterORA(){Name = "PI_N_SOL_PID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #endregion #region 함수정의(DB내부함수는제외)_Deliverer #region Get result work item (For deliverer Process) Table.Add("PKG_DATA_DELIVER.F_GET_RESULT_WORK_ITEM", new Dictionary<string, DbParameter>() { {"PI_V_WORK_ITEM_ID", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_ID", Type = OracleType.VarChar, Size = 40, Direction = ParameterDirection.Input }} }); #endregion #region modify result data block (For deliverer Process) Table.Add("PKG_DATA_DELIVER.F_MODIFY_RESULT_DATA_BLOCK", new Dictionary<string, DbParameter>() { {"PI_V_RESULT_TYPE", new Process.DbParameterORA(){Name = "PI_V_RESULT_TYPE", Type = OracleType.VarChar, Size = 10, Direction = ParameterDirection.Input }}, {"PI_V_WORK_ITEM_ID", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_ID", Type = OracleType.VarChar, Size = 40, Direction = ParameterDirection.Input}}, {"PI_V_RESULT_ITEM_ID", new Process.DbParameterORA(){Name = "PI_V_RESULT_ITEM_ID", Type = OracleType.VarChar, Size = 10, Direction = ParameterDirection.Input}}, {"PI_CL_FIT_RESULT_DATA", new Process.DbParameterORA(){Name = "PI_CL_FIT_RESULT_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input }} }); #endregion #endregion #region get Rendezvous data (For Communicator) Table.Add("PKG_DATA_DELIVER.F_GET_RV_MSG_BLOCK_IDBS", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region 함수정의(DB내부함수는제외)_Option #region Get Option (For Communicator Process) Table.Add("PKG_OPTION.F_GET_OPTION", new Dictionary<string, DbParameter>() { {"PI_V_KEY", new Process.DbParameterORA(){Name = "PI_V_KEY", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_NAME", new Process.DbParameterORA(){Name = "PI_V_NAME", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input}}, {"PI_V_SUBNAME", new Process.DbParameterORA(){Name = "PI_V_SUBNAME", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }} }); #endregion #endregion #region 함수정의(DB내부함수는 제외)_Monitor #region Set System Status (F_SET_SYSTEM_STATUS) Table.Add("PKG_MONITOR.F_SET_SYSTEM_STATUS", new Dictionary<string, DbParameter>() { {"PI_V_GROUP_ALIASE", new Process.DbParameterORA(){Name = "PI_V_GROUP_ALIASE", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_ACTOR", new Process.DbParameterORA(){Name = "PI_V_ACTOR", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_ACTOR_ALIASE", new Process.DbParameterORA(){Name = "PI_V_ACTOR_ALIASE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_CPU_TOTAL", new Process.DbParameterORA(){Name = "PI_N_CPU_TOTAL", Type = OracleType.Number, Direction = ParameterDirection.Input }}, {"PI_N_CPU_USED", new Process.DbParameterORA(){Name = "PI_N_CPU_USED", Type = OracleType.Float, Direction = ParameterDirection.Input }}, {"PI_V_CPU_UNIT", new Process.DbParameterORA(){Name = "PI_V_CPU_UNIT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_MEMORY_TOTAL", new Process.DbParameterORA(){Name = "PI_N_MEMORY_TOTAL",Type = OracleType.Number, Direction = ParameterDirection.Input }}, {"PI_N_MEMORY_USED", new Process.DbParameterORA(){Name = "PI_N_MEMORY_USED", Type = OracleType.Number, Direction = ParameterDirection.Input }}, {"PI_V_MEMORY_UNIT", new Process.DbParameterORA(){Name = "PI_V_MEMORY_UNIT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_NETWORK_IP", new Process.DbParameterORA(){Name = "PI_V_NETWORK_IP", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_NETWORK_TYPE", new Process.DbParameterORA(){Name = "PI_V_NETWORK_TYPE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_NETWORK_USED_RATIO", new Process.DbParameterORA(){Name = "PI_N_NETWORK_USED_RATIO", Type = OracleType.Float, Direction = ParameterDirection.Input }}, {"PI_V_NETWORK_UNIT", new Process.DbParameterORA(){Name = "PI_V_NETWORK_UNIT", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_OS", new Process.DbParameterORA(){Name = "PI_V_OS", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_CL_OTHER_DATA_BLOCK", new Process.DbParameterORA(){Name = "PI_CL_OTHER_DATA_BLOCK", Type = OracleType.Clob, Direction = ParameterDirection.Input }} }); #endregion #region Get System Status (F_GET_SYSTEM_STATUS) Table.Add("PKG_MONITOR.F_GET_SYSTEM_STATUS", new Dictionary<string, DbParameter>() { {"PI_V_GROUP_ALIASE", new Process.DbParameterORA(){Name = "PI_V_GROUP_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_ACTOR", new Process.DbParameterORA(){Name = "PI_V_ACTOR", Type = OracleType.VarChar, Direction = ParameterDirection.Input}}, {"PI_V_ACTOR_ALIASE", new Process.DbParameterORA(){Name = "PI_V_ACTOR_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }} }); #endregion #region Del System Status (F_DEL_SYSTEM_STATUS) // Group 의 data를 모두 지우고, 다시 입력해야 한다. (monitoring은 무조건 갱신이기 때문에) Table.Add("PKG_MONITOR.F_DEL_SYSTEM_STATUS", new Dictionary<string, DbParameter>() { {"PI_V_GROUP_ALIASE", new Process.DbParameterORA(){Name = "PI_V_GROUP_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }} }); #endregion #region Set Monitor Condition (F_SET_MONITOR_CONDITION) Table.Add("PKG_MONITOR.F_SET_MONITOR_CONDITION", new Dictionary<string, DbParameter>() { {"PI_V_GROUP_ALIASE", new Process.DbParameterORA(){Name = "PI_V_GROUP_ALIASE", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_ACTOR", new Process.DbParameterORA(){Name = "PI_V_ACTOR", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_USER_ID", new Process.DbParameterORA(){Name = "PI_V_USER_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_CL_CONDITION_DATA_BLOCK", new Process.DbParameterORA(){Name = "PI_CL_CONDITION_DATA_BLOCK", Type = OracleType.Clob, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input }} }); #endregion #region Get Monitor Condition (F_GET_MONITOR_CONDITION) Table.Add("PKG_MONITOR.F_GET_MONITOR_CONDITION", new Dictionary<string, DbParameter>() { {"PI_V_GROUP_ALIASE", new Process.DbParameterORA(){Name = "PI_V_GROUP_ALIASE", Type = OracleType.VarChar, Direction = ParameterDirection.Input }}, {"PI_V_ACTOR", new Process.DbParameterORA(){Name = "PI_V_ACTOR", Type = OracleType.VarChar, Direction = ParameterDirection.Input }} }); #endregion #region Del Monitor Condition (F_DEL_MONITOR_CONDITION) Table.Add("PKG_MONITOR.F_DEL_MONITOR_CONDITION", new Dictionary<string, DbParameter>() { {"PI_V_GROUP_ALIASE", new Process.DbParameterORA(){Name = "PI_V_GROUP_ALIASE", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_ACTOR", new Process.DbParameterORA(){Name = "PI_V_ACTOR", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }} }); #endregion #endregion #region 함수정의 JobManager #region F_SET_DEVICE Table.Add("PKG_STAND.F_SET_DEVICE", new Dictionary<string, DbParameter>() { {"PI_V_DEVICE_ID", new Process.DbParameterORA(){Name = "PI_V_DEVICE_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_DESIGN_RULE", new Process.DbParameterORA(){Name = "PI_V_DESIGN_RULE", Type = OracleType.VarChar, Size = 300, Direction = ParameterDirection.Input }}, {"PI_V_DEVICE_PREFIX", new Process.DbParameterORA(){Name = "PI_V_DEVICE_PREFIX", Type = OracleType.VarChar, Size = 300, Direction = ParameterDirection.Input }}, {"PI_V_DESCRIPTION", new Process.DbParameterORA(){Name = "PI_V_DESCRIPTION", Type = OracleType.VarChar,Size = 50, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #region F_SET_STEP Table.Add("PKG_STAND.F_SET_STEP", new Dictionary<string, DbParameter>() { {"PI_V_STEP_ID", new Process.DbParameterORA(){Name = "PI_V_STEP_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_STEP_SEQ", new Process.DbParameterORA(){Name = "PI_V_STEP_SEQ", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_MODE_TYPE", new Process.DbParameterORA(){Name = "PI_V_MODE_TYPE", Type = OracleType.VarChar,Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_DESCRIPTION", new Process.DbParameterORA(){Name = "PI_V_DESCRIPTION", Type = OracleType.VarChar,Size = 50, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #region F_SET_EQUIP Table.Add("PKG_STAND.F_SET_EQUIP", new Dictionary<string, DbParameter>() { {"PI_V_EQUIP_ID", new Process.DbParameterORA(){Name = "PI_V_EQUIP_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_EQUIP_MODEL", new Process.DbParameterORA(){Name = "PI_V_EQUIP_MODEL", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_EQUIP_VERSION", new Process.DbParameterORA(){Name = "PI_V_EQUIP_VERSION", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_V_DESCRIPTION", new Process.DbParameterORA(){Name = "PI_V_DESCRIPTION", Type = OracleType.VarChar,Size = 50, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #region F_SET_RECIPE_CONFIGURE Table.Add("PKG_RECIPE.F_SET_RECIPE_CONFIGURE", new Dictionary<string, DbParameter>() { {"PI_V_DEVICE_ID", new Process.DbParameterORA(){Name = "PI_V_DEVICE_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_STEP_ID", new Process.DbParameterORA(){Name = "PI_V_STEP_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_SITE_ID", new Process.DbParameterORA(){Name = "PI_V_SITE_ID", Type = OracleType.VarChar, Size = 30, Direction = ParameterDirection.Input }}, {"PI_V_EQUIP_ID", new Process.DbParameterORA(){Name = "PI_V_EQUIP_ID", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_V_RECIPE_ID", new Process.DbParameterORA(){Name = "PI_V_RECIPE_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_WRITE_USER", new Process.DbParameterORA(){Name = "PI_V_WRITE_USER", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input }}, {"PI_N_STATE", new Process.DbParameterORA(){Name = "PI_N_STATE", Type = OracleType.Int32,Direction = ParameterDirection.Input }}, }); #endregion #region F_SET_JOB_OFFLINE Table.Add("PKG_JOB.F_SET_JOB_OFFLINE", new Dictionary<string, DbParameter>() { {"PO_N_JOB_ID", new Process.DbParameterORA(){Name = "PO_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Output }}, {"PI_V_START_DATE", new Process.DbParameterORA(){Name = "PI_V_START_DATE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_PROCESS_LIMIT_TIME", new Process.DbParameterORA(){Name = "PI_N_PROCESS_LIMIT_TIME", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_V_CURRENT_MODULE", new Process.DbParameterORA(){Name = "PI_V_CURRENT_MODULE", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input }}, {"PI_N_WAFER_CNT_TOTAL", new Process.DbParameterORA(){Name = "PI_N_WAFER_CNT_TOTAL", Type = OracleType.Int32, Direction = ParameterDirection.Input}}, {"PI_N_WAFER_CNT_MISSING", new Process.DbParameterORA(){Name = "PI_N_WAFER_CNT_MISSING", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_STORAGE_IMAGE_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_IMAGE_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input}}, {"PI_N_PROCESS_PERCENT", new Process.DbParameterORA(){Name = "PI_N_PROCESS_PERCENT", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_V_STORAGE_RESULT_PATH", new Process.DbParameterORA(){Name = "PI_V_STORAGE_RESULT_PATH", Type = OracleType.VarChar, Size = 500, Direction = ParameterDirection.Input}}, {"PI_CL_RV_MSG_DATA", new Process.DbParameterORA(){Name = "PI_CL_RV_MSG_DATA", Type = OracleType.Clob, Direction = ParameterDirection.Input}}, {"PI_V_JOB_KIND", new Process.DbParameterORA(){Name = "PI_V_JOB_KIND", Type = OracleType.VarChar, Size = 20, Direction = ParameterDirection.Input}}, {"PI_V_JOB_TYPE", new Process.DbParameterORA(){Name = "PI_V_JOB_TYPE", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input}}, {"PI_V_JOB_NAME", new Process.DbParameterORA(){Name = "PI_V_JOB_NAME", Type = OracleType.VarChar, Size = 50, Direction = ParameterDirection.Input}}, }); #endregion #endregion #region 함수정의 Job #region F_CHECK_JOB_RESULT_INFO Table.Add("PKG_JOB.F_CHECK_JOB_RESULT_INFO", new Dictionary<string, DbParameter>() { {"PO_N_CNT", new Process.DbParameterORA(){Name = "PO_N_CNT", Type = OracleType.Int32, Direction = ParameterDirection.Output }}, {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #region F_DEL_JOB_DATA_VIRTUAL Table.Add("PKG_JOB.F_DEL_JOB_DATA_VIRTUAL", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #region F_SET_JOB_RESTART_INIT Table.Add("PKG_JOB.F_SET_JOB_RESTART_INIT", new Dictionary<string, DbParameter>() { {"PI_N_JOB_ID", new Process.DbParameterORA(){Name = "PI_N_JOB_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #endregion #region 함수정의 _JobMonitoring #region F_GET_JOB_PROCESS_INFO Table.Add("PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_INFO", new Dictionary<string, DbParameter>() { {"PI_DA_START_DATE", new Process.DbParameterORA(){Name = "PI_DA_START_DATE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_DA_END_DATE", new Process.DbParameterORA(){Name = "PI_DA_END_DATE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, }); #endregion #region F_GET_JOB_PROCESS_HIS Table.Add("PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_HIS", new Dictionary<string, DbParameter>() { {"PI_DA_START_DATE", new Process.DbParameterORA(){Name = "PI_DA_START_DATE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_DA_END_DATE", new Process.DbParameterORA(){Name = "PI_DA_END_DATE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_SOL_ID", new Process.DbParameterORA(){Name = "PI_SOL_ID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, {"PI_SOL_PID", new Process.DbParameterORA(){Name = "PI_SOL_PID", Type = OracleType.Int32, Direction = ParameterDirection.Input }}, }); #endregion #region F_GET_JOB_PROCESS_QUICK Table.Add("PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_QUICK", new Dictionary<string, DbParameter>() { {"PI_DA_START_DATE", new Process.DbParameterORA(){Name = "PI_DA_START_DATE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_DA_END_DATE", new Process.DbParameterORA(){Name = "PI_DA_END_DATE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, {"PI_V_WORK_ITEM_MANAGER_ALIASE", new Process.DbParameterORA(){Name = "PI_V_WORK_ITEM_MANAGER_ALIASE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }}, }); #endregion #endregion #region 함수정의 _Stand Exist Table.Add("PKG_STAND.F_EXIST_DEVICE", new Dictionary<string, DbParameter>() { { "PO_N_CNT", new Process.DbParameterORA() { Name = "PO_N_CNT", Type = OracleType.Int32, Direction = ParameterDirection.Output } }, { "PI_V_DEVICE_ID", new Process.DbParameterORA() { Name = "PI_V_DEVICE_ID", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input } }, }); Table.Add("PKG_STAND.F_EXIST_STEP", new Dictionary<string, DbParameter>() { { "PO_N_CNT", new Process.DbParameterORA() { Name = "PO_N_CNT", Type = OracleType.Int32, Direction = ParameterDirection.Output } }, { "PI_V_STEP_ID", new Process.DbParameterORA() { Name = "PI_V_STEP_ID", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input } }, }); Table.Add("PKG_STAND.F_EXIST_EQUIP", new Dictionary<string, DbParameter>() { { "PO_N_CNT", new Process.DbParameterORA() { Name = "PO_N_CNT", Type = OracleType.Int32, Direction = ParameterDirection.Output } }, { "PI_V_EQUIP_ID", new Process.DbParameterORA() { Name = "PI_V_EQUIP_ID", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input } }, }); #endregion #region etc Table.Add("UpdateStatus", new Dictionary<string, DbParameter>() { {"PI_NONE", new Process.DbParameterORA(){Name = "PI_NONE", Type = OracleType.VarChar, Size = 2000, Direction = ParameterDirection.Input }} }); #endregion } } } <file_sep>/MVC_Sample_Solution/UiLib.ControlLib/UiLibColors.cs using System; using System.Drawing; using System.Collections.Generic; namespace UtilLib.ControlLib { public static class UiLibColors { public static Dictionary<string, Color> ColorTable { get; private set; } static UiLibColors() { ColorTable = new Dictionary<string, Color>(); ColorTable.Add("GRID_FOCUS_COLOR", System.Drawing.Color.Orange); ColorTable.Add("GRID_SELECT_COLOR", System.Drawing.Color.DodgerBlue); ColorTable.Add("GRID_CHECKED_COLOR", System.Drawing.Color.Orange); ColorTable.Add("GRID_UNCHECKED_COLOR", System.Drawing.Color.SteelBlue); ColorTable.Add("GRID_GRAYED_COLOR", System.Drawing.Color.LightGray); } public static Color Color(string name, Color defaultColor = default(Color)) { return ColorTable.ContainsKey(name) ? ColorTable[name] : defaultColor; } } } <file_sep>/MVC_Sample_Solution/TypeLib.Core/IDataModel.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TypeLib.Core { public interface IDataModel { bool InitDataModel(string option); Dictionary<string, object> Parameters { get; } IList ExecuteCommand(string cmd, IList paramList); } } <file_sep>/MVC_Sample_Solution/TypeLib.DbLib/DbParameter.cs using System.Data; using System.Runtime.Serialization; using TypeLib.DbLib.Process; namespace TypeLib.DbLib { [DataContract] [KnownType(typeof(DbParameterORA))] [KnownType(typeof(DbParameterSQL))] public abstract class DbParameter { [DataMember] public string Name { get; set; } [DataMember] public int Size { get; set; } [DataMember] public ParameterDirection Direction { get; set; } [DataMember] public object Value { get; set; } } } <file_sep>/MVC_Sample_Solution/UiForm.Sample/MainManagerSchedulerJob.cs using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading; using System.Threading.Tasks; using TypeLib.Core; namespace UiForm.Sample { public class MainManagerSchedulerJob : IDisposable { private int _id; private int _pid; #region Schedule Period Time protected int _checkTime; #endregion #region Report Event Handler public event EventHandler ReportCallEvent; #endregion #region Report Event Message private UiLibMessage _sendProxyMessageData = new UiLibMessage(); private UiLibMessage _sendJobCheckMessageData = new UiLibMessage(); #endregion #region Syncronized Context SynchronizationContext syncContext; #endregion #region Thread Object Thread proxyThread = null; Thread jobCheckThread = null; #endregion #region Thread Event Object protected ManualResetEvent _proxyThreadHandle; protected ManualResetEvent _jobCheckThreadHandle; #endregion #region Lock Object private readonly object _workLoadSeerviceLock = new Object(); private readonly object _workLoadSeerviceInfoLock = new Object(); private readonly object _jobCheckThreadLock = new Object(); #endregion #region Proxy Thread Variable protected int _threadStatusProxy = 0; protected int _threadStatusJobCheck = 0; #endregion #region WorkLoad Manager Server Proxy Table private bool _workLoadServiceAlive; //private ServerInformation _workLoadServiceInfo; //private WienerServiceProxyCommonServer _workLoadService; #endregion #region Configuration private static AppConfigurationData _config; #endregion #region iDataModel public IDataModel iDataModel { get; private set; } #endregion #region Implementation IDisposable public void Dispose() { if (this._proxyThreadHandle != null) { _proxyThreadHandle.Set(); _proxyThreadHandle.Dispose(); Interlocked.Exchange(ref _threadStatusProxy, 0); proxyThread.Join(); _proxyThreadHandle = null; } if (_jobCheckThreadHandle != null) { _jobCheckThreadHandle.Set(); _jobCheckThreadHandle.Dispose(); Interlocked.Exchange(ref this._threadStatusJobCheck, 0); jobCheckThread.Join(); _jobCheckThreadHandle = null; } } #endregion #region Creator public MainManagerSchedulerJob(IDataModel DataModel) { syncContext = SynchronizationContext.Current; #region DB Connection iDataModel = DataModel; #endregion } #endregion #region Implementation IWorkManagerJob #region bool StartManager(int checkTime, AppConfigurationData config) public bool StartManager(int checkTime, AppConfigurationData config) { //_checkTime = checkTime; //_config = config; //#region Service Information Setting //if ((_config == null) || (_config.WorkLoadManager == null)) //{ // return false; //} //lock (_workLoadSeerviceInfoLock) //{ // _workLoadServiceInfo = _config.WorkLoadManager; //} //#endregion //#region Proxy Thread Start //if (this._threadStatusProxy == 0) //{ // _proxyThreadHandle = new ManualResetEvent(true); // proxyThread = new Thread(this.WorkThreadProxy); // proxyThread.Start(); //} //#endregion //#region Job Check Thread Start //if (_threadStatusJobCheck == 0) //{ // _jobCheckThreadHandle = new ManualResetEvent(true); // jobCheckThread = new Thread(this.JobCheckThread); // jobCheckThread.Start(); //} //#endregion return true; } #endregion #region bool StopManager() public bool StopManager() { #region Proxy Thrad Stop if (this._threadStatusProxy > 0) { _proxyThreadHandle.Reset(); Interlocked.Exchange(ref this._threadStatusProxy, 0); _proxyThreadHandle.Dispose(); _proxyThreadHandle = null; } #endregion return true; } #endregion public void SetSolutionId(int id, int Pid) { _id = id; _pid = Pid; } #region void StartPollingThread() public void StartPollingThread() { // Polling 시작 Interlocked.Exchange(ref _threadStatusJobCheck, 1); _jobCheckThreadHandle.Set(); } #endregion #endregion #region Implementation WorkThreadProxy protected void WorkThreadProxy(object threadParam) { //#region 스레드 시작 상태 플레그 설정 //if (this._threadStatusProxy == 0) //{ // Interlocked.Exchange(ref this._threadStatusProxy, 1); //} //#endregion //WienerServiceCallback callbackObj = new WienerServiceCallback(); //AsyncWienerServiceCallback callbackHandler = new AsyncWienerServiceCallback(syncContext, callbackObj); //callbackObj.ReportCallEvent += this.CallBackFunc; //InstanceContext instanceContext = new InstanceContext(callbackHandler); //WienerServiceProxyCommonServer proxy = new WienerServiceProxyCommonServer(instanceContext, UtilFuncNet.InitNetTcpBinding(), new EndpointAddress(this._workLoadServiceInfo.GetServerURL("DISTRIBUTOR_2"))); //while (this._threadStatusProxy == 1) //{ // try // { // _proxyThreadHandle.WaitOne(); // if (proxy.State == CommunicationState.Opened) // { // var tt = proxy.IsAlive(); // this._workLoadServiceAlive = true; // if (ReportCallEvent != null) // { // _sendProxyMessageData.Parameters.Clear(); // _sendProxyMessageData.Code = enEventCode.RootCall_Alive; // ReportCallEvent(this, _sendProxyMessageData); // } // Thread.Sleep(_checkTime); // continue; // } // if (proxy.State != CommunicationState.Created) // { // proxy = null; // proxy = new WienerServiceProxyCommonServer(instanceContext, UtilFuncNet.InitNetTcpBinding(), new EndpointAddress(this._workLoadServiceInfo.GetServerURL("DISTRIBUTOR_2"))); // } // //var config = ItemConfiguration.Instance; // //proxy.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(config.MasterUser, config.MasterPassword); // proxy.Open(); // lock (_workLoadSeerviceLock) // { // _workLoadService = proxy; // } // this._workLoadServiceAlive = true; // if (ReportCallEvent != null) // { // _sendProxyMessageData.Parameters.Clear(); // _sendProxyMessageData.Code = enEventCode.RootCall_Connect; // ReportCallEvent(this, _sendProxyMessageData); // } // Console.WriteLine("{0} : Client Connect OK", this._workLoadServiceInfo.GetServerURL("DISTRIBUTOR_2")); // Thread.Sleep(_checkTime); // } // catch (Exception ex) // { // if (proxy != null) // { // proxy.Abort(); // proxy.Close(); // (proxy as IDisposable).Dispose(); // _workLoadService = null; // } // this._workLoadServiceAlive = false; // if (ReportCallEvent != null) // { // _sendProxyMessageData.Parameters.Clear(); // _sendProxyMessageData.Code = enEventCode.RootCall_Disconnect; // ReportCallEvent(this, _sendProxyMessageData); // } // Thread.Sleep(_checkTime); // //Console.WriteLine("{0} : Client Connect Fail : {1}", serverInfo.GetServerURL("AgentService"), ex.Message); // } //} //if (proxy != null) //{ // proxy.Close(); // (proxy as IDisposable).Dispose(); // proxy = null; // _workLoadService = null; // this._workLoadServiceAlive = false; // if (ReportCallEvent != null) // { // _sendProxyMessageData.Parameters.Clear(); // _sendProxyMessageData.Code = enEventCode.RootCall_Disconnect; // ReportCallEvent(this, _sendProxyMessageData); // } //} //Console.WriteLine("{0} : Connect Manager Thread Exit", this._workLoadServiceInfo.GetServerURL("DISTRIBUTOR_2")); } #endregion #region Implementation JobCheckThread protected void JobCheckThread(object threadParam) { //#region 스레드 시작 상태 플레그 설정 //if (_threadStatusJobCheck == 0) //{ // Interlocked.Exchange(ref _threadStatusJobCheck, 2); //} //#endregion //while (_threadStatusJobCheck > 0) //{ // try // { // if (_threadStatusJobCheck > 1) // { // _jobCheckThreadHandle.Reset(); // _jobCheckThreadHandle.WaitOne(); // } // if (_threadStatusJobCheck == 1) // { // if (_id >= 0 && _pid >= 0) // { // var jobProcessHis = new DbGetJobProcessHis(); // //int lastMonth = DateTime.Now.Month - 1; // //string startDate = DateTime.Now.ToString("yyyy-" + lastMonth + "-dd 00:00:01"); // //string endDate = DateTime.Now.AddMinutes(5).ToString(WienerTime.Format); // DB 시간 여유 맞춤 // string startDate = UtilFuncDate.GetStringEndOfDay(UtilFuncDate.GetPreviousMonthDate(DateTime.Now), WienerTime.Format);// 한달 전의 00:00:01 // string endDate = UtilFuncDate.GetStringEndOfDay(DateTime.Now, WienerTime.Format); // 다음 날의 00:00:00 // lock (_jobCheckThreadLock) // { // //DateTime start = Convert.ToDateTime(startDate); // //jobProcessHis.StartDate = start.ToString(WienerTime.Format); // jobProcessHis.StartDate = startDate; // jobProcessHis.EndDate = endDate; // jobProcessHis.SolId = _id; // jobProcessHis.SolPid = _pid; // } // var jobList = iDataModel.ExecuteCommand("PKG_JOB_MONITOR_OFFLINE.F_GET_JOB_PROCESS_HIS", new[] { jobProcessHis }).Cast<JobHistory>().ToList(); // _sendJobCheckMessageData.Parameters.Clear(); // _sendJobCheckMessageData.Code = enEventCode.RootCall_DB_PollingJob; // _sendJobCheckMessageData.Parameters.Add(jobList); // ReportCallEvent(this, _sendJobCheckMessageData); // // 동작중인 Job이 없으면 Polling 중지 // if (jobList.Any(jobItem => jobItem.STATUS == enJobStatus.Waiting || jobItem.STATUS == enJobStatus.Running) == false) // Interlocked.Exchange(ref _threadStatusJobCheck, 2); // Thread.Sleep(500); // } // } // } // catch (Exception e) // { // Console.WriteLine(e.Message.ToString()); // } //} } #endregion #region void CallBackFunc(object sender, EventArgs e) public void CallBackFunc(object sender, EventArgs e) { } #endregion } }
62ba23da151af8eb6cce9bdb84711d33b9a8c7f0
[ "C#" ]
53
C#
kiyoung-Lee/C-Sharp_MVC_Model_Sample
65336768c37d970cb6bbc09fe9cdae8a2deadba0
ddd778ed89faf9bc214c381e965a6a0d872d988e
refs/heads/master
<file_sep>#' Import Code to the Databricks Workspace #' #' This function allows you to import .R and .Rmd files into Databricks as an R notebook. This will work whether the files #' are on your local machine, on DBFS, or from an instance of RStudio that is hosted on a Databricks cluster. #' #' The API endpoint for importing files to the workspace is '2.0/workspace/import'. For all details on API calls please see the official documentation at \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param local_file A string representing the path to a .R or .Rmd file. Generated by \code{\link{create_job}} or via the Databricks web interface. #' @param workspace A string representing the web workspace of your Databricks instance. E.g., "https://eastus2.azuredatabricks.net" or "https://company.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in Databricks or via the Databricks REST API 2.0. If none is provided, netrc will be used. #' @param overwrite Replace an existing notebook? Defaults to 'true', a string. #' @param verbose If true, will pretty print the success or failure of the request. Defaults to TRUE. #' @return The API response. #' #' @examples #' ## Import an R script from your local machine to a Notebook on Databricks #' import_to_workspace(file = "C:/my_files/my_r_program.R", #' notebook_path = "/Shared/R/my_r_program", #' workspace = "https://company.cloud.databricks.com", #' token = "<KEY>") #' #' import_to_workspace <- function(file, notebook_path, workspace, token = NULL, overwrite = "false", verbose = T) { ## Parameters for file upload files <- list( path = notebook_path, language = "R", content = httr::upload_file(file), overwrite = overwrite ) if (is.null(token)) { ## Using netrc by default use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/workspace/import"), body = files)}) } else { ## Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) ## Make request res <- httr::POST(url = paste0(workspace, "/api/2.0/workspace/import"), httr::add_headers(.headers = headers), body = files) } if (verbose == T) { ## Successful request message if (res$status_code[1] == 200) { message(paste0( "Status: ", res$status_code[1], "\n\nObject: ", file, " was added to the workspace at ", notebook_path )) } ## Unsuccessful request message else { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } ## Return API response res } <file_sep>--- title: "Databricks Cluster Management with `bricksteR`" author: "<NAME>, Solutions Archcitect, Databricks" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true toc_depth: 4 vignette: > %\VignetteIndexEntry{Vignette Title} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo = FALSE, message=FALSE} workspace <- "https://field-eng.cloud.databricks.com" cluster_id <- "0915-154850-quits57" library(bricksteR) terminate_response <- terminate_cluster(cluster_id, workspace) ``` ## Cluster Management In this vignette, we explore how to manage Databricks clusters programmatically. In keeping with the theme of `bricksteR`, hopefully these functions will let you leverage Databricks more effectively without having to leave your IDE. #### Databricks Clusters 101 What happens when we create a Databricks cluster? First, we describe the computational resources needed and their configuration. Then, if we are using the UI we click on 'Create Cluster'. At this point Databricks fetches VMs (or 'instances') from the public cloud provider to materialize the cluster in your cloud account. Within a few minutes, you have an Apache Spark cluster at your disposal. This is, incidentally, the moment when you begin to be billed for Databricks and the public cloud provider. We'll come back to that. What happens when we terminate a Databricks cluster? We simply release the computational resources back to the public cloud provider *and we persist the cluster configuration for reuse*. This is also when you are no longer billed by Databricks or the public cloud provider. In this system, what matters more - the individual machines that make up the cluster or the description of the cluster? It is clear that individual VMs are essentially ephemeral, and as such they don't matter as much as the cluster specification does. As long as we have that configuration handy, we can always re-instantiate the same environment. **Note:** Before we start using any functions, make sure you've reviewed how to [authenticate](https://github.com/RafiKurlansik/bricksteR#authentication)! In this vignette I'll be using a `.netrc` file. #### Starting and Restarting To begin using the Clusters API you simply need a `cluster_id` and the URL to your Databricks workspace. We can start a cluster that is currently in a 'terminated' state by using `start_cluster()`: ```{r} library(bricksteR) cluster_id <- "0915-154850-quits57" start_response <- start_cluster(cluster_id, workspace) ``` If we need to restart the cluster, this is also trivially simple. Be careful though - if you haven't [saved your work](https://github.com/marygracemoesta/R-User-Guide/blob/master/Getting_Started/DBFS.md) it will be lost. ```{r, echo = F} # Waiting for cluster to come online before restarting Sys.sleep(300) ``` ```{r} restart_response <- restart_cluster(cluster_id, workspace) ``` Restarting a cluster becomes particularly relevant if you decide to leverage bricksteR for package management. See the *Library Management* vignette for more. #### Clusters List Another handy function is `clusters_list()`, which will provide detailed information on all of the clusters in the workspace. There's a *lot* of information available from this API, so it's best to assign it to a variable and work with the data.frame that gets returned. ``` # Not run response <- clusters_list(workspace) # Access the data.frame clusters <- response$response_df # Get active clusters active <- clusters[clusters$state == "RUNNING", c("cluster_id", "state", "start_time")] ``` As we'll see in the next section, it can be useful to know which machines are running and for how long. #### Terminating > *"Last one out, hit the lights..."* To save on costs, it's a good practice to shut down the cluster at the end of your work day. Be mindful of your teammates if you are sharing a cluster though! To turn off the cluster just use `terminate_cluster()`: ```{r} terminate_response <- terminate_cluster(cluster_id, workspace) ``` #### Cleaning Up Resources The default configuration of a cluster is to auto-terminate after 120 minutes, which is great for those times you forget to turn off the cluster at the end of the day (or week...). However, in the case of clusters that have [RStudio Server installed](https://github.com/marygracemoesta/R-User-Guide/blob/master/Developing_on_Databricks/RStudio_integrations.md) on them, auto-terminate must be disabled. It can save quite a bit of money to utilize `terminate_cluster()` to clean up any long running resources that have been left on. To do so we'll use revisit `clusters_list()`, filtering any results for long running machines without auto-terminate. We can tell if a cluster has auto-terminate disabled if its auto-terminate minutes is set to 0. ```{r} # Get list of active clusters response <- clusters_list(workspace) ## Get active clusters clusters <- response$response_df active <- clusters[clusters$state == "RUNNING", c("cluster_id", "autotermination_minutes", "state", "start_time")] ## Check how long clusters have been running active$start_time <- as.POSIXct(active$start_time/1000, origin = "1970-01-01") active$uptime <- Sys.time() - active$start_time ## Filter for clusters with 0 minutes auto-termination to_terminate <- active[active$autotermination_minutes == 0] ``` With a single call to `terminate_cluster()`, we can shut down these long running resources. If we wind up with a list of clusters that should be terminated, we can use `lapply()` to take care of all of them at once. ```r # To terminate these clusters, we'll apply the terminate_cluster function # to each cluster_id in a list termination_list <- as.list(to_terminate$cluster_id) termination_responses <- lapply(termination_list, terminate_cluster, workspace) ``` If we put this code in its own script and [run it as a job](https://github.com/RafiKurlansik/bricksteR#automating-r-jobs-on-databricks-with-brickster), we can effectively monitor and automate the termination of extraneous resources in our Databricks workspace! ## Conclusion At this point you are equipped with the knowledge and functions to access and manage Databricks clusters programmatically. As mentioned before, `clusters_list()` returns quite a lot of information so if you are looking to analyze how your team is using Databricks more broadly, this is great dataset to look into. If you have any questions, feel free to reach out to me (<EMAIL>) or file a [GitHub](https://github.com/RafiKurlansik/bricksteR) issue. <file_sep>#' #' Curate a shared or personal library of packages #' #' Helper function to manage package installation across libraries #' #' `curate()` lets you easily install packages into different libraries. It will #' manage the copying of packages to a path on DBFS, which will persist them from #' session to session on Databricks. #' #' @param pkg String, name of package to install or a valid URL if using GitHub/Gitlab #' @param repo Where to pull the package from. Default is https://cloud.r-project.org. If NULL, specify #' the path to a source file in `pkgs`. #' @param version The desired version of the package to install. Defaults to latest. #' @param dest_lib String, the path to the library where packages will be installed. Default #' is the first path on `.libPaths()`. It's recommended to use `set_library()` prior to #' `curate()` #' @param git_provider String, one of "github" or "gitlab". Default is NULL. #' @param ... Additional arguments to be passed to `install.packages`, #' `remotes::install_version`, `remotes::install_github`, and `remotes::install_gitlab`. #' Use this to pass authentication variables to git providers. #' #' @return The user library path #' @examples #' # Setting user library first #' set_library("/dbfs/rk/my_packages") #' curate(pkg = "broom") #' #' # Install version, setting user library #' curate(pkg = "broom", version = "0.4.2", lib = set_library("/dbfs/rk/my_old_packages")) #' #' # Install GitHub #' curate(repo = "RafiKurlansik/bricksteR") #' #' # Install Gitlab #' curate(repo = "jimhester/covr") #' @export curate <- function(pkg, repos = "https://cloud.r-project.org", version = NULL, dest_lib = .libPaths()[1], git_provider = NULL, ...) { # Set up temp directory for installation tmp_dir <- tempfile() dir.create(tmp_dir) set_library(tmp_dir, r_version = F) if(is.null(version) && is.null(git_provider)){ # Normal installation install.packages(pkgs = pkg, repos = repos, lib = tmp_dir, ...) # Remove tmp_dir from .libPaths() .libPaths(c(.libPaths()[-1])) system(paste0("cp -r ", tmp_dir, "/* ", dest_lib)) cat(c("Package: ", pkg, " installed in ", dest_lib)) } # Check for install from version control if(!is.null(git_provider)) { git_provider <- tolower(git_provider) if(!(git_provider %in% c("gitlab", "github"))) { stop("Check your git_provider parameter, only \"gitlab\" or \"github\" are supported") } # Install GitHub if(git_provider == "github") { remotes::install_github(repo = pkg, lib = tmp_dir, dependencies = T, ...) # Remove tmp_dir from .libPaths() .libPaths(c(.libPaths()[-1])) system(paste0("cp -r ", tmp_dir, "/* ", dest_lib)) cat(c("\n\nRemote GitHub package installed from ", pkg, " in ", dest_lib)) } else { # Install Gitlab remotes::install_gitlab(repo = pkg, lib = tmp_dir, dependencies = T, ...) # Remove tmp_dir from .libPaths() .libPaths(c(.libPaths()[-1])) system(paste0("cp -r ", tmpDir, "/* ", dest_lib)) cat(c("\n\nRemote Gitlab package installed from ", pkg, " in ", dest_lib)) } } # Check for installing a version if(!is.null(version)) { remotes::install_version(package = pkg, version = version, repos = "https://cloud.r-project.org", lib = tmp_dir, ...) # Remove tmp_dir from .libPaths() .libPaths(c(.libPaths()[-1])) # Copy package from tmp_dir to first on .libPaths() system(paste0("cp -r ", tmp_dir, "/* ", dest_lib)) cat(c("Version ", version, " of ", pkg, " installed in ", dest_lib)) } # Clean up temp directory system(paste0("rm -r ", tmp_dir)) } <file_sep>#' #' Get the status of libraries on Databricks clusters #' #' Get a list of libraries and their statuses for Databricks clusters. #' #' By default will return library statuses for *all* clusters. If a `cluster_id` #' is supplied, will return the status for that cluster alone. You can #' locate the cluster ID in the URL of the cluster configuration page. #' For example: #' #' https://mycompany.cloud.databricks.com/#/setting/clusters/xxxx-xxxxx-xxxxxx/ #' #' Where xxxx-xxxxx-xxxxxx is the cluster ID. #' #' The API endpoints for getting library statuses are #' '2.0/libraries/all-cluster-statuses' and '2.0/libraries/cluster-status'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param cluster_id A string containing the unique id for an online #' Databricks cluster #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed #' @return A list with three elements: #' \itemize{ #' \item \emph{response} - The full API response, including status code. #' \item \emph{response_list} - The JSON result transformed into a list. #' \item \emph{response_df} - The JSON result transformed into a dataframe. #' } #' If the details of jobs are not needed, use the \emph{response_tidy} #' dataframe. #' @examples #' # For all clusters #' library_statuses <- get_library_statuses(workspace = workspace) #' #' # For a single cluster #' cluster_id <- "0818-155203-cheese22" #' library_statuses <- get_library_statuses(cluster_id = cluster_id, workspace = workspace) #' @export get_library_statuses <- function(cluster_id = NULL, workspace, token = NULL, verbose = T, ...) { if(is.null(cluster_id)) { # Make request for all statuses, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/libraries/all-cluster-statuses")) }) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::GET(url = paste0(workspace, "/api/2.0/libraries/all-cluster-statuses"), httr::add_headers(.headers = headers) ) } } else { # Make request for all statuses, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/libraries/cluster-status?cluster_id=", cluster_id)) }) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::GET(url = paste0(workspace, "/api/2.0/libraries/cluster-status?cluster_id=", cluster_id), httr::add_headers(.headers = headers) ) } } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nLibrary statuses retrieved." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response reslist <- list(response = res, response_json = suppressMessages(jsonlite::prettify(res)), response_list = jsonlite::fromJSON(rawToChar(res$content)), response_df = as.data.frame(jsonlite::fromJSON(rawToChar(res$content))) ) reslist } <file_sep>#' #' Uninstall Packages (libraries) on a Databricks Cluster #' #' Set libraries to be uninstalled on a cluster. The libraries aren’t #' uninstalled until the cluster is restarted. Uninstalling libraries #' that are not installed on the cluster has no impact but is not an error. #' You can locate the cluster ID in the URL of the cluster configuration page. #' For example: #' #' https://mycompany.cloud.databricks.com/#/setting/clusters/xxxx-xxxxx-xxxxxx/ #' #' Where xxxx-xxxxx-xxxxxx is the cluster ID. #' #' The API endpoint for uninstalling libraries is #' '2.0/libraries/uninstall'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param cluster_id A string containing the unique id for an online #' Databricks cluster. #' @param package A string with the name of the package to uninstall. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @return The API response. #' #' @examples #' # Cluster to install on #' workspace <- "https://mydb.cloud.databricks.com" #' cluster_id <- "0818-155203-cheese22" #' #' # Uninstall package #' libraries_uninstall(package = "broom", cluster_id, workspace) #' #' # Check installation status #' get_library_statuses(cluster_id, workspace) #' @export libraries_uninstall <- function(cluster_id, package, workspace, token = NULL, verbose = T, ...) { payload <- paste0( '{"cluster_id": "', cluster_id, '", "libraries": [{ "cran": { "package": "', package,'" } }] }' ) # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/libraries/uninstall"), httr::content_type_json(), body = payload)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/libraries/uninstall"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nRequest successful. Packages will be uninstalled upon cluster restart. \n Use restart_cluster() to finish uninstalling." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response res } <file_sep>--- title: "Package Management for Databricks Clusters" author: "<NAME>, Sr. Solutions Architect, Databricks" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true toc_depth: 4 vignette: > %\VignetteIndexEntry{Vignette Title} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo = FALSE, message=FALSE} workspace <- "https://field-eng.cloud.databricks.com" ``` ## Degrees of Environment Control > *"It's the wild west out here!"* To tame the rich open source ecosystem we must ask ourselves - how should we best organize R packages on Databricks? Any organizational strategy needs to account for the following scenarios at a minimum: * A "sandbox" environment for development * Which packages are *system* (or shared) packages vs. *user* packages in the sandbox * Package versioning for production jobs The openness of the sandbox environment will vary across organizations, but in every case where more than one user will be on the system you'll need to think about sharing - which packages are users going to share across the system, and which will be isolated to each user? If you aren't careful here, one user can easily install a package that breaks another users' code. **A recommended practice is to agree upon core, shared packages and then allow each user to install their own packages in a personal folder.** Lastly, prior to promoting code to run as part of a production job, you'll need to ensure that package updates don't break anything. In this case both code and dependencies need to be tightly version controlled. This vignette only focuses on setting up the development environment, so we'll save that for another time. With that said, here's how the `bricksteR` package can help manage packages in the development environment. ## R Packages and Libraries <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Biblioth%C3%A8que_de_l%27Assembl%C3%A9e_Nationale_%28Lunon%29.jpg/1200px-Biblioth%C3%A8que_de_l%27Assembl%C3%A9e_Nationale_%28Lunon%29.jpg" width = 600 height = 400> Let's start with an analogy. The books at your local library are shared by the larger community - anyone in town can walk into the library and access its books. At home you likely have a personal library, which may include books that are not available to everyone in town. The R packages you know and love are similar to books - they live in a *library*! This may be a shared, common library, or your own personal library. Where are these libraries located? R libraries live in directories on the filesystem, and when you use `library()` R will look for packages there. Furthermore, when you use `install.packages()` R will install the package in your library. There is a special function to show the libraries that R is currently aware of - `.libPaths()`. From the official documentation: ``` .libPaths gets/sets the library trees within which packages are looked for. ``` This means that by modifying `.libPaths()` we can effectively tell R when to add a package to our common, shared library or to our own personal library. ### Setting the Library `bricksteR` contains the `set_library()` function to update the path that R looks to install and load packages from. It takes a single argument, `path`, that points to the library location. ```{r, eval=FALSE} # Install and load bricksteR devtools::install_github("RafiKurlansik/bricksteR") library(bricksteR) # Set the path to a personal folder set_library(path = "/dbfs/home/[email protected]/my_r_packages") # See it added to the paths that R searched for packages .libPaths() ``` **For admins**, you can use this function to install into a shared, system-wide library. **For individual users**, this will let you curate your personal library and avoid collisions with other packages on the system. If someone installs a version of a package that conflicts with your work - no problem! If using a personal library, R will have no idea about what that other user is doing. Remember, problems generally only crop up when we install (and overwrite) packages into the shared folder. ### Curate a Library On Databricks, we recommend installing packages into a personal folder located on DBFS. This is because DBFS points to cloud storage and will persist packages through a cluster restart, from cluster to cluster, and will generally be faster than installing many packages every time a cluster comes online. To facilitate a smooth installation onto cloud storage `bricksteR` offers the `curate()` function! `curate()` serves two key purposes: 1. Provide a single, simple interface to the common functions used to install packages in R. Today it supports `install.packages`, `install_github`, `install_gitlab`, and `install_version`. 2. Ensure that packages are safely installed and copied to DBFS to persist. Here a few quick examples of how it is used. ```{r, eval = FALSE} # Don't forget to set_library()! set_library(path = "/dbfs/home/[email protected]/my_r_packages") # Install latest version of broom into personal library curate("broom") # Install older version of ggplot2 curate("ggplot2", version = "3.0.0", dependencies = F) # Install a package from GitHub curate(pkg = "RafiKurlansik/bricksteR", git_provider = "github", force = T) # Check results dir("/dbfs/home/<EMAIL>/my_r_packages") ``` You can learn more by checking out the documentation (`?curate` in RStudio), or inspecting the [source code on GitHub](https://github.com/RafiKurlansik/bricksteR/blob/master/R/curate.R). ### Removing a Library Let's say you set the wrong library and want to tell R to ignore it. You can use `remove_library()` to do so. ``` remove_library(path = "/dbfs/home/[email protected]/my_r_packages") ``` ## Installing Packages with the Databricks REST API **Note: This section is best used by smaller teams or single user clusters.** If you are managing a large shared environment, stick to the first method described above. This section explores the use of the Databricks REST API to programmatically manage R packages and their versions. For additional discussion please see the [Package Management](https://github.com/marygracemoesta/R-User-Guide/blob/master/Developing_on_Databricks/package_management.md) section of the [R User Guide to Databricks](https://github.com/marygracemoesta/R-User-Guide). ### Installing Packages on Interactive Clusters In the simplest case one can always use `install.packages()` in their code but there are two tradeoffs - the package will not be installed across the cluster (only where the code was run), and it will not be added to the configuration going forward. When the cluster is restarted you'll have to run `install.packages()` again. #### Adding a Single Package When you use `libraries_install()` from `bricksteR`, the package is installed across the cluster and added to its configuration going forward. ```{r} library(bricksteR) # Cluster to install on cluster_id <- "0208-155424-fish21" lib_response <- libraries_install(cluster_id, package = "broom", workspace = workspace) ``` `libraries_install` will use [RStudio Public Package Manager](https://packagemanager.rstudio.com/client/#/repos/1/overview) (RPPM) as the default repo. This is because RStudio has graciously decided to share linux binaries with the community, and Databricks Runtime uses Ubuntu 16.04. #### Multiple Packages and Their Versions If you want to install a list of packages at one time, you can do so with a `data.frame` containing the package names and versions. In this example we use a snapshot from RPPM to choose the version of the second two packages from those dates. ```{r} pkg_df <- data.frame(package = c("torch", "merTools", "plyr"), repo = c("https://packagemanager.rstudio.com/all/__linux__/xenial/latest", "https://packagemanager.rstudio.com/all/__linux__/xenial/318", "https://packagemanager.rstudio.com/all/__linux__/xenial/236")) # Apply libraries_install() to each row of our pkg_df results <- apply(pkg_df, 1, function(x) { libraries_install(package = x['package'], repo = x['repo'], cluster_id, workspace) }) ``` As you can see, we can check on the status of their installation by using `get_library_statuses()`. ```{r} lib_statuses <- get_library_statuses(cluster_id, workspace) lib_statuses$response_df ``` #### Custom Packages If you aren't pulling your R package from a public repo, you'll need to [upload it to DBFS](https://github.com/marygracemoesta/R-User-Guide/blob/master/Developing_on_Databricks/package_management.md#custom-packages) first. You can do this with `bricksteR` by using the DBFS wrappers. ``` # Copy local source file to DBFS dbfs_mv(from = "/Users/rafi.kurlansik/mypkg.tar.gz", to = "/dbfs/rafi.kurlansik/pkgs/) # Install on cluster install_response <- libraries_install(cluster_id, package = "/dbfs/rafi.kurlansik/pkgs/mypkg.tar.gz", repo = NULL, workspace = workspace) ``` ### Uninstalling Packages `libraries_uninstall()` will remove the package from cluster configuration, pending a restart. ```{r} uninstall_response <- libraries_uninstall(cluster_id, package = "merTools", workspace) ``` ## Conclusion By using `libraries_install()` and `libraries_uninstall()` for interactive clusters and (coming soon) `configure_job()` for jobs, you can easily tune the dependencies for your clusters and build the environments you want - be they stable or chaotic. If you have any questions, feel free to reach out to me (<EMAIL>) or file a [GitHub](https://github.com/RafiKurlansik/bricksteR) issue. <file_sep>#' Delete a job on Databricks #' #' Delete the job and send an email to the addresses specified in #' JobSettings.email_notifications. No action occurs if the job #' has already been removed. After the job is removed, neither #' its details or its run history is visible via the Jobs UI or API. #' #' The job is guaranteed to be removed upon completion of this request. #' However, runs that were active before the receipt of this request #' may still be active. They will be terminated asynchronously. #' The API endpoint for deleting a job is '2.0/jobs/delete'. For all details #' on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param job_id A number representing the unique identifier of a job on Databricks. #' @param name Optional. A string representing the name of the job. If multiple #' jobs share the same name, you'll need to rename the jobs or provide #' the unique job ID. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, netrc will be used. #' @param verbose If true, will pretty print the success or failure of the #' request and add a `job_id` variable to the R environment. Defaults to TRUE. #' @return The API response. #' @examples #' delete_job(job_id = 206, #' workspace = "https://dbc-z64b06b4-d212.cloud.databricks.com", #' token = "<PASSWORD>") #' delete_job <- function(job_id = NULL, name = NULL, workspace, token = NULL, verbose = T) { ## If name provided, call jobs_list to find the job ID if (!is.null(name)) { jobs_tidy <- jobs_list(workspace = workspace, token = token, verbose = F)$response_tidy matches <- jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ] ## If there is more than one job with the same name if (length(matches$settings.name) > 1){ message(paste0("Found multiple jobs with name \"", name, "\":\n")) message(paste0( capture.output( jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ]), collapse = "\n")) return(message( paste0("\n\nPlease use a job ID or give the job a unique name.\n", "Too many jobs with that name.") )) } ## If no matches found else if (length(matches$settings.name) < 1) { message(paste0("No job with name \"", name, "\" found.\n Please try a different name.")) return("Couldn't find a job with that name.") } ## If exact match fetch the job id job_id <- paste0('{ "job_id": ', matches$job_id, ' }') message(paste0("Job \"", name, "\" found with ", job_id, ".")) } ## If no name provided, use job_id param else{ job_id <- paste0('{ "job_id": ', job_id, ' }') } ## Make request with netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/jobs/delete"), httr::content_type_json(), body = job_id)}) } else { ## Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) ## Make request res <- httr::POST(url = paste0(workspace, "/api/2.0/jobs/delete"), httr::add_headers(.headers = headers), httr::content_type_json(), body = job_id) } ## Handle API response statuses if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\n", job_id, " has been deleted.")) } else { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } <file_sep>#' #' List all jobs in a Databricks workspace. #' #' Fetches all of the details for jobs in the authenticated workspace. #' See also \code{runs_list} to learn more about a particular job run. #' #' The API endpoint for running a job is '2.0/jobs/list'. For all #' details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If true, will pretty print the success or failure of the #' request. Defaults to TRUE. #' @return A list with four elements: #' \itemize{ #' \item \emph{response} - The full API response, including status code. #' \item \emph{response_list} - The JSON result transformed into a list. #' \item \emph{response_df} - The JSON result transformed into a dataframe. #' \item \emph{response_tidy} - A simple dataframe with the job ID, name, #' time of creation, and who created it. #' } #' If the details of jobs are not needed, use the \emph{response_tidy} #' dataframe. #' @examples #' jobs <- jobs_list(workspace = "https://eastus2.azuredatabricks.net", #' token = "<PASSWORD>") #' #' ## Get data in different formats #' jobs_json <- jobs$response_json #' jobs_list <- jobs$response_list #' jobs_df <- jobs$response_df #' jobs_list <- function(workspace, token = NULL, verbose = T) { ## Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) jobs <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/jobs/list/")) }) } else { ## Bearer Authentication headers <- c( Authorization = paste("Bearer", token) ) jobs <- httr::GET(url = paste0(workspace, "/api/2.0/jobs/list/"), httr::add_headers(.headers = headers)) } ## Objects to return, including tidy jobs list jobs_list <- jsonlite::fromJSON(rawToChar(jobs$content)) jobs_df <- jsonlite::fromJSON(rawToChar(jobs$content), flatten = T)$jobs jobs_tidy <- jobs_df[, c("job_id", "settings.name", "created_time", "creator_user_name")] jobs_tidy$created_time <- as.POSIXlt(jobs_tidy$created_time/1000, origin = '1970-01-01') ## Handling successful API response if (jobs$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", jobs$status_code[1], "\nNumber of jobs: ", length(jsonlite::fromJSON( rawToChar(jobs$content))$jobs$job_id) )) } } ## Else status not 200 else { if (verbose == T) { message(paste0( "Status: ", jobs$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(jobs) )) } jobs_list <- NA jobs_df <- NA jobs_tidy <- NA } ## Return complete response, list, and dataframe of results reslist <- list(response = jobs, response_list = jobs_list, response_df = jobs_df, response_tidy = jobs_tidy) reslist } <file_sep>#' #' List the contents of a path on DBFS #' #' List the contents of a directory, or the details of a file. If the directory #' does not exist a RESOURCE_DOES_NOT_EXIST exception will be thrown. #' #' When calling list on a large directory, the list operation will time out after #' approximately 60s. We strongly recommend using list only on directories containing #' less than 10K files and discourage using the DBFS REST API for operations that #' list more than 10k files. Instead, we recommend that you perform such operations #' in the context of a cluster, using File system utilities, which provides the same #' functionality without timing out. #' #' The API endpoint for listing a path on DBFS is '2.0/dbfs/list'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param path A string representing the path to list in DBFS #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed #' @return The API response #' @examples #' # No need to include /dbfs/ #' path <- "/rk/data" #' #' dbfs_ls(path = path, workspace = workspace) #' @export dbfs_ls <- function(path, workspace, token = NULL, verbose = T, ...) { # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/dbfs/list?path=", path)) }) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::GET(url = paste0(workspace, "/api/2.0/dbfs/list?path=", path), httr::add_headers(.headers = headers) ) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nListing \"", path, "\":" )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response reslist <- list(response = res, data = as.data.frame(jsonlite::fromJSON(rawToChar(res$content)))) reslist } <file_sep>#' #' Terminate a Databricks cluster. #' #' Will terminate an online Databricks cluster. This is distinct from the `permanent-delete` #' API endpoint, which will remove the cluster from the clusters UI. Please note that #' any unsaved work will be lost unless persisted to a storage environment separate #' from the cluster. You can locate the cluster ID in the URL of the cluster configuration #' page. For example: #' #' https://mycompany.cloud.databricks.com/#/setting/clusters/xxxx-xxxxx-xxxxxx/ #' #' Where xxxx-xxxxx-xxxxxx is the cluster ID. #' #' The API endpoint for terminating a cluster is '2.0/clusters/delete'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param cluster_id A string containing the unique id for an online Databricks cluster #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed to \code{data.table::fread} which is used to #' parse the API response. #' @return The API response #' @examples #' workspace <- "https://myworkspace.cloud.databricks.com" #' cluster_id <- "0818-155203-cheese22" #' #' terminate_cluster(workspace = workspace, cluster_id = cluster_id) #' @export terminate_cluster <- function(cluster_id, workspace, token = NULL, verbose = T, ...) { payload <- paste0('{"cluster_id": "', cluster_id, '"}') # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/clusters/delete"), httr::content_type_json(), body = payload)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/clusters/delete"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nCluster \"", cluster_id, "\" terminated." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } # Return response res } <file_sep>#' Create a new Job on Databricks #' #' This function will create a new job on Databricks, but will not run it. To #' run a job, see \code{\link{run_job}} or \code{\link{runs_submit}}. #' #' The API endpoint for creating a job is '2.0/jobs/create'. For all details #' on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param name A string representing the name of the job. It is encouraged #' to choose a unique name for each job. #' @param notebook_path A string representing the path to a Databricks notebook in the #' workspace. #' @param file The path to a local .R or .Rmd file. Will be imported to the #' workspace at the \emph{notebook_path}. #' @param job_config A JSON formatted string or file specifying the details of the job, i.e., the #' name, cluster spec, and so on. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, netrc will be used. #' @param verbose If true, will pretty print the success or failure of the #' request and add a `job_id` variable to the R environment. Defaults to TRUE. #' @param ... additional arguments to be passed, i.e., overwrite = 'false' when #' importing a file to run as a job. #' @return A list with two elements - the complete API response and the job ID. #' @examples #' # Default JSON used #' create_job(path = "/Shared/R/brickster_tutorial", # A notebook in the workspace #' workspace = "https://dbc-z64b06b4-d212.cloud.databricks.com", # The workspace of your Databricks instance #' token = "<PASSWORD>") # The valid auth token #' #' # Passing custom JSON #' job_config <- '{"name": "New R Job", #' "new_cluster": { #' "spark_version": "7.3.x-scala2.12", #' "node_type_id": "i3.xlarge", #' "aws_attributes": { #' "availability": "ON_DEMAND" #' }, #' "num_workers": 2, #' "email_notifications": { #' "on_start": [], #' "on_success": [], #' "on_failure": [] #' }, #' "notebook_task": { #' "notebook_path": "/Shared/R/brickster_tutorial" #' } #' } #' }' #' #' # Specifying the path now unnecessary #' create_job(job_config, #' workspace = "https://dbc-z64b06b4-d212.cloud.databricks.com", #' token = "<PASSWORD>") create_job <- function(name = "R Job", file = NULL, notebook_path, job_config = "default", workspace, token = NULL, verbose = T, ...) { # Import R file to workspace if needed if (!is.null(file)) { import_response <- import_to_workspace(file = file, notebook_path = notebook_path, overwrite = ..., workspace = workspace, token = token, verbose = F) # If import fails, exit if (import_response$status_code[1] != 200) { return(message(paste0( "Unable to import file. Please check the response code:\n\n", jsonlite::prettify(import_response) ))) } } # Check for job config in JSON file if (file.exists(job_config)) { job_config <- toJSON(fromJSON(job_config), auto_unbox = T) } # Default small cluster spec if (job_config == "default") { job_config <- paste0('{ "name": "', name, '", "new_cluster": { "spark_version": "7.3.x-scala2.12", "node_type_id": "i3.xlarge", "num_workers": 2 }, "email_notifications": { "on_start": [], "on_success": [], "on_failure": [] }, "notebook_task": { "notebook_path": "', notebook_path, '" } }') } # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/jobs/create"), httr::content_type_json(), body = job_config)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/jobs/create"), httr::add_headers(.headers = headers), httr::content_type_json(), body = job_config) } # Handling successful API request if (res$status_code[1] == 200) { job_id <- jsonlite::fromJSON(rawToChar(res$content))[[1]] if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nJob \"", name, "\" created.", "\nJob ID: ", job_id )) } } # Handling unsuccesful request else { job_id <- NA if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } # Return response reslist <- list(response = res, job_id = job_id) } <file_sep> #' Reset the configuration of a Job on Databricks #' #' This function will reset the configuration of an existing job #' on Databricks. #' #' The API endpoint for creating a job is '2.0/jobs/create'. For all details #' on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param job_id A number representing the unique identifier of a job on Databricks. #' @param name A string representing the name of the job. It is encouraged #' to choose a unique name for each job. #' @param new_config A JSON formatted string or file specifying the details of #' the job, i.e., the name, cluster spec, and so on. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If true, will pretty print the success or failure of the #' request. Defaults to TRUE. #' @return The complete API response. #' @examples #' # JSON string or file path can be passed #' new_config <- "/configs/nightly_model_training.json" #' #' reset_job(job_id = 30198, new_config, workspace) #' #' # Reset by name #' reset_job(name = "My R Job", new_config, workspace, token = "<PASSWORD>") reset_job <- function(job_id = NULL, name = NULL, new_config, workspace, token = NULL, verbose = T) { # If name provided, call jobs_list to find the job ID if (!is.null(name)) { jobs_tidy <- jobs_list(workspace = workspace, token = token, verbose = F)$response_tidy matches <- jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ] # If there is more than one job with the same name if (length(matches$settings.name) > 1){ message(paste0("Found multiple jobs with name \"", name, "\":\n")) message(paste0( capture.output( jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ]), collapse = "\n")) return(message(paste0("\n\nPlease use a job ID or give the job a unique name.\n"))) } # If no matches found else if (length(matches$settings.name) < 1) { message(paste0("No job with name \"", name, "\" found.\n Please try a different name.")) return("Couldn't find a job with that name.") } # If matched, set job_id and name for consistency between file and webapp config_list <- jsonlite::fromJSON(new_config) config_list$job_id <- matches$job_id config_list$new_settings$name <- name message(paste0("Job \"", name, "\" found with ", matches$job_id, ".")) } else { # Set the job_id for the config config_list <- jsonlite::fromJSON(new_config) config_list$job_id <- job_id new_config <- jsonlite::toJSON(config_list, auto_unbox = T) } # Make request with netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/jobs/reset"), httr::content_type_json(), body = new_config)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Make request res <- httr::POST(url = paste0(workspace, "/api/2.0/jobs/reset"), httr::add_headers(.headers = headers), httr::content_type_json(), body = new_config) } # Handling successful API response if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nJob Name:", name, "\nJob ID: ", job_id, "\nJob settings updated. Use jobs_list() for more information." )) } } else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } # Return response res } <file_sep>#' #' Get the status of a job run on Databricks #' #' Fetches the status of a job run on Databricks, whether it has completed or #' not. Includes details about start time, cluster spec, task, and more. #' #' The API endpoint for running a job is '2.0/jobs/runs/get'. For all #' details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param run_id A number representing a valid run id generating by launching #' a job on Databricks. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If true, will pretty print the success or failure of the #' request and add a run_id variable to the R environment. Defaults to TRUE. #' @return A list with four elements: #' \itemize{ #' \item \emph{response} - The full API response, including status code. #' \item \emph{response_json} - The JSON result. #' \item \emph{response_list} - The JSON result transformed into a list. #' \item \emph{response_df} - The JSON result transformed into a dataframe. #' } #' @examples #' res <- get_run_status(run_id = 2932371, #' workspace = "https://eastus2.azuredatabricks.net", #' token = "<PASSWORD>") #' #' ## Get data in different formats #' resjson <- res$response_json #' reslist <- res$response_list #' res_df <- res$response_df #' get_run_status <- function(run_id, workspace, token = NULL, verbose = TRUE) { ## Make request with netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/jobs/runs/get?run_id=", run_id))}) } else { ## Use Bearer Authentication headers <- c( Authorization = paste("Bearer", token) ) ## Make request res <- httr::GET(url = paste0(workspace, "/api/2.0/jobs/runs/get?run_id=", run_id), httr::add_headers(.headers = headers)) } if (verbose == T) { ## Successful request message if (res$status_code[1] == 200) { message(paste0( "Status: ", res$status_code[1], "\nRun ID: ", jsonlite::fromJSON(rawToChar(res$content))$run_id, "\nNumber in Job: ", jsonlite::fromJSON(rawToChar(res$content))$number_in_job, "\n\nYou can check the status of this run at: \n ", jsonlite::fromJSON(rawToChar(res$content))$run_page_url )) } ## Unsuccessful request message else { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } ## Return list of values reslist <- list(response = res, response_json = jsonlite::prettify(res), response_list = jsonlite::fromJSON(rawToChar(res$content)), response_df = as.data.frame(jsonlite::fromJSON(rawToChar(res$content)))) reslist } <file_sep>#' #' List runs for a job from most recently to least. #' #' Fetches all of the completed and active runs for a given job in the last 60 days. #' Runs expire after 60 days, so see \code{runs_export} to save run results before expiry. #' #' The API endpoint for running a job is '2.0/jobs/runs/list'. For all #' details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param job_id A number representing a valid run id generating by launching #' a job on Databricks. #' @param name Optional. A string representing the name of the job. If multiple #' jobs share the same name, you'll need to rename the jobs or provide #' the unique job ID. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param offset The number of the first run to return, relative to the most #' recent run. Defaults to 0 (the most recent run). #' @param limit The number of runs to return. Should be greater than 0 and #' less than 150. If 0 is used, the service will use the maximum limit. #' @param active_only A string. If 'true', only active runs will be #' included in the results. Cannot be true while completed_only is true. #' @param completed_only A string. If 'true', only completed runs will be #' included in the results. Cannot be true while active_only is true. #' @param verbose If true, will pretty print the success or failure of the #' request and add a run_id variable to the R environment. Defaults to TRUE. #' @return A list with four elements: #' \itemize{ #' \item \emph{response} - The full API response, including status code. #' \item \emph{response_json} - The JSON result. #' \item \emph{response_list} - The JSON result transformed into a list. #' \item \emph{response_df} - The JSON result transformed into a dataframe. #' } #' @examples #' ## Get runs by Job ID #' res <- runs_list(job_id = 206, #' workspace = "https://eastus2.azuredatabricks.net", #' token = "<PASSWORD>") #' #' ## Get runs by Job name #' res <- runs_list(name = "My Other Unique Job Name", workspace = workspace, token = token) #' #' ## Get data in different formats #' resjson <- res$response_json #' reslist <- res$response_list #' res_df <- res$response_df #' runs_list <- function(job_id = NULL, name = NULL, workspace, token = NULL, offset = 0, limit = 20, active_only = "false", completed_only = "false", verbose = TRUE) { ## If name provided, call jobs_list to find the job ID if (!is.null(name)) { jobs_tidy <- jobs_list(workspace = workspace, token = token, verbose = F)$response_tidy matches <- jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ] ## If there is more than one job with the same name if (length(matches$settings.name) > 1){ message(paste0("Found multiple jobs with name \"", name, "\":\n")) message(paste0( capture.output( jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ]), collapse = "\n")) message(paste0("\n\nPlease use a job ID or give the job a unique name.\n")) stop("Too many jobs with that name.") } ## If no matches found else if (length(matches$settings.name) < 1) { message(paste0("No job with name \"", name, "\" found.\n Please try a different name.")) stop("Couldn't find a job with that name.") } ## If exact match fetch the job id for the run config job_id <- matches$job_id message(paste0("Job \"", name, "\" found with ", matches$job_id, ".")) } ## Make request with netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/jobs/runs/list/?job_id=", job_id, "&active_only=", active_only, "&completed_only=", completed_only, "&offset=", offset, "&limit=", limit))}) } else { ## Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) ## Make request res <- httr::GET(url = paste0(workspace, "/api/2.0/jobs/runs/list/?job_id=", job_id, "&active_only=", active_only, "&completed_only=", completed_only, "&offset=", offset, "&limit=", limit), httr::add_headers(.headers = headers)) } if (verbose == T) { ## Successful request message if (res$status_code[1] == 200) { message(paste0( "Status: ", res$status_code[1], "\nJob ID: ", unique(jsonlite::fromJSON(rawToChar(res$content))$runs$job_id), "\nNumber of runs: ", length(jsonlite::fromJSON(rawToChar(res$content))$runs$run_id), "\n\nAre there more runs to list? \n ", jsonlite::fromJSON(rawToChar(res$content))$has_more )) } ## Unsuccessful request message else { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } ## Return list of values reslist <- list(response = res, response_json = jsonlite::prettify(res), response_list = jsonlite::fromJSON(rawToChar(res$content)), response_tidy = as.data.frame( jsonlite::fromJSON( rawToChar(res$content)))[, c("runs.job_id", "runs.run_id", "runs.creator_user_name", "runs.run_page_url")] ) reslist } <file_sep>#' #' Create an execution context for running commands on Databricks. #' #' This function provides the context for executing remote commands on an existing #' Databricks cluster via REST API. The output is intended to be passed to #' \code{databricks_execute}. #' #' The API endpoint for creating the execution context is is '1.2/contexts/create'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param cluster_id A string containing the ID of an active Databricks cluster. #' @param language The language to execute commands in. The default is 'r', but #' can also be set to 'python', 'scala' and 'sql'. #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If true, will pretty print the success or failure of the #' request. Defaults to FALSE. #' @return A list with five elements: #' \itemize{ #' \item \emph{language} - The language to execute commands in. #' \item \emph{cluster_id} - ID of the active Databricks cluster. #' \item \emph{context_id} - ID of the execution context on the cluster. #' \item \emph{workspace} - The URL of the Databricks workspace. #' \item \emph{token} - The token used to authenticate. #' } #' @examples #' # Using netrc #' context <- create_execution_context(workspace = "https://eastus2.azuredatabricks.net", #' language = "r", #' cluster_id = "1017-337483-jars232") #' #' ## Use the context to execute a command on Databricks #' command <- "iris[1, ]" #' databricks_execute(command, context) #' create_execution_context <- function(workspace, cluster_id, language = 'r', token = NULL, verbose = F) { payload <- paste0('{ "language": "', language, '", "clusterId": "', cluster_id, '" }') ## Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/1.2/contexts/create"), httr::content_type_json(), body = payload) }) } else { ## Bearer Authentication headers <- c( Authorization = paste("Bearer", token) ) res <- httr::POST(url = paste0(workspace, "/api/1.2/contexts/create"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } ## Extract execution ID from response context_id <- jsonlite::fromJSON(rawToChar(res$content))$id if (verbose == T) { ## Successful request message if (res$status_code[1] == 200) { message(paste0( "Status: ", res$status_code[1], "\n\nExecution Context ID ", context_id, " created. " )) } ## Unsuccessful request message else { return(message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) ))) } } ## Return the values necessary for command execution endpoint context <- list(language = language, cluster_id = cluster_id, context_id = context_id, workspace = workspace, token = token) context } <file_sep># `brickster`: The R SDK for Databricks `brickster` has moved! **Please see https://github.com/zacdav-db/brickster for an upgraded and improved SDK.** You are going to love what you find! ______ Questions or feedback? Feel free to contact me at <<EMAIL>>. <file_sep>#' #' Set the User Library Path #' #' Set the path for where R will install packages. #' #' To persist packages on Databricks use a path that begins with `/dbfs/`. #' This is designed to be used in conjunction with `bricksteR::curate()`. #' For shared clusters where users prefer package isolation, each user should #' create their own path for package installation. If building a central #' shared repo of packages, set the path to a common directory. #' #' @param lib_path A string representing the path to install packages in DBFS #' @param r_version boolean. Should the current version of R be added as a directory in #' the path? Defaults to FALSE. #' #' @return The user library path #' @examples #' #' path <- "/dbfs/rk/my_packages" #' #' set_library(lib_path = path) #' @export set_library <- function(lib_path = "/dbfs/Rlib", r_version = F){ # If using default, add random path to avoid package collisions if (lib_path == '/dbfs/Rlib') { if(r_version == T) { user_lib_path <- file.path(lib_path, round(rnorm(1, sd = 10000)), getRversion()) } else { user_lib_path <- file.path(lib_path, round(rnorm(1, sd = 10000))) } } if (r_version == T){ user_lib_path <- file.path(lib_path, getRversion()) } else { user_lib_path <- file.path(lib_path) } if (file.exists(user_lib_path) == F) { dir.create(user_lib_path, recursive = TRUE) } search_path <- .libPaths() if (user_lib_path %in% search_path) { search_path <- setdiff(search_path, user_lib_path) } # adding user specified library path into search paths search_path <- c(user_lib_path, search_path) .libPaths(search_path) cat(c("Library: ", user_lib_path, " added. \n\nUse .libPaths() to see all libraries.\n\n")) } #' @rdname set_library #' #' @param user_lib_path A string representing the path to be removed from .libPaths() #' @return The removed library path #' @examples #' #' remove_library(path) #' @export remove_library <- function(lib_path){ search_path <- .libPaths() if (lib_path %in% search_path) { search_path <- setdiff(search_path, lib_path) .libPaths(search_path) } cat(c("Library: ", lib_path, " removed. \n\nUse .libPaths() to see all libraries.\n\n")) } <file_sep>#' #' List all clusters in a Databricks workspace. #' #' Fetches all of the details for clusters in the authenticated workspace. #' #' The API endpoint for running a job is '2.0/clusters/list'. For all #' details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If true, will pretty print the success or failure of the #' request. Defaults to TRUE. #' @return A list with two elements: #' \itemize{ #' \item \emph{response} - The full API response, including status code. #' \item \emph{response_df} - The JSON result transformed into a dataframe. #' } #' @examples #' clusters <- clusters_list(workspace = "https://eastus2.azuredatabricks.net", #' token = "<PASSWORD>") #' #' ## Get active clusters #' df <- clusters$df #' active <- df[df$state == "RUNNING", c("cluster_id", "state")] clusters_list <- function(workspace, token = NULL, verbose = T) { ## Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) clusters <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/clusters/list/")) }) } else { ## Bearer Authentication headers <- c( Authorization = paste("Bearer", token) ) clusters <- httr::GET(url = paste0(workspace, "/api/2.0/clusters/list/"), httr::add_headers(.headers = headers)) } ## Objects to return clusters_df <- jsonlite::fromJSON(rawToChar(clusters$content), flatten = T)$clusters ## Handling successful API response if (clusters$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", clusters$status_code[1], "\nNumber of clusters: ", nrow(jsonlite::fromJSON(rawToChar(clusters$content))$clusters) )) } } ## Else status not 200 else { if (verbose == T) { message(paste0( "Status: ", clusters$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(clusters) )) } } ## Return complete response, list, and dataframe of results reslist <- list(response = clusters, response_df = clusters_df) reslist } <file_sep>#' #' Read data from DBFS #' #' Return the contents of a file. If the file does not exist, this call #' throws an exception with RESOURCE_DOES_NOT_EXIST. #' #' The API endpoint for reading files from DBFS is '2.0/dbfs/read'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param path Absolute path to a file on DBFS #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed #' @return The API response and the base6-encoded contents of the file read. #' @examples #' # No need to include /dbfs/ #' file_path <- "/tmp/iris.json" #' #' res <- dbfs_read(path = file_path, workspace = workspace) #' #' data <- res$data #' #' # Decode from base64 #' tidy_data <- jsonlite::fromJSON(rawToChar(jsonlite::base64_dec(data))) #' @export dbfs_read <- function(path, workspace, token = NULL, verbose = T, ...) { # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/dbfs/read?path=", path)) }) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::GET(url = paste0(workspace, "/api/2.0/dbfs/read?path=", path), httr::add_headers(.headers = headers)) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nFile \"", path, "\" read from DBFS successfully." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response reslist <- list( response = res, data = jsonlite::fromJSON(rawToChar(res$content))$data ) } <file_sep>#' #' Upload a file to DBFS #' #' Upload a file through the use of multipart form post. It is mainly #' used for streaming uploads, but can also be used as a convenient #' single call for data upload. #' #' The API endpoint for putting files on DBFS is '2.0/dbfs/put'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param local_file Path to the file for upload #' @param destination_path A string representing the destination path in DBFS #' @param overwrite Boolean ('true', 'false') that specifies whether to overwrite existing files. #' Defaults to 'false' #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed #' @return The API response #' @examples #' # No need to include /dbfs/ #' file <- "my_model.rds" #' destination_path <- "/models/my_model.rds" #' #' dbfs_put(file = file, destination_path = destination_path, workspace = workspace) #' @export dbfs_put <- function(local_file, destination_path, overwrite = 'false', workspace, token = NULL, verbose = T, ...) { params <- list( path = destination_path, contents = httr::upload_file(local_file), overwrite = overwrite ) # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/dbfs/put"), httr::add_headers(`Content-Type`="multipart/form-data"), body = params) }) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token), `Content-Type`="multipart/form-data" ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/dbfs/put"), httr::add_headers(.headers = headers), body = params) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nFile \"", local_file, "\" uploaded to \"", destination_path, "\" successfully." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response res } <file_sep>#' Run an existing job on Databricks. #' #' Takes a job_id and executes it on Databricks. Must create a job first. #' #' The API endpoint for running a job is '2.0/jobs/run-now'. For all #' details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param job_id A number. Generated by \code{\link{create_job}} or via #' the Databricks web interface. #' @param name Optional. A string representing the name of the job. If multiple #' jobs share the same name, you'll need to rename the jobs or provide #' the unique job ID. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, netrc #' will be used. #' @param verbose If true, will pretty print the success or failure of the #' request and add a run_id variable to the R environment. Defaults to TRUE. #' @return The API response. #' #' @examples #' # Run a job #' run_job(job_id = 206, workspace = 'https://eastus2.azuredatabricks.net', token = 'dapi1903210980d9a0ads0g9fas') #' #' # Run a job by name #' run_job(name = "My Unique Job Name", workspace = workspace, token = token) #' run_job <- function(job_id = NULL, name = NULL, workspace, token = NULL, verbose = T) { # If name provided, call jobs_list to find the job ID if (!is.null(name)) { jobs_tidy <- jobs_list(workspace = workspace, token = token, verbose = F)$response_tidy matches <- jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ] # If there is more than one job with the same name if (length(matches$settings.name) > 1){ message(paste0("Found multiple jobs with name \"", name, "\":\n")) message(paste0( capture.output( jobs_tidy[grepl(pattern = paste0("^", name,"$"), jobs_tidy$settings.name), ]), collapse = "\n")) return(message(paste0("\n\nPlease use a job ID or give the job a unique name.\n"))) } # If no matches found else if (length(matches$settings.name) < 1) { message(paste0("No job with name \"", name, "\" found.\n Please try a different name.")) stop("Couldn't find a job with that name.") } # If exact match fetch the job id for the run config run_config <- paste0('{ "job_id": ', matches$job_id, ' }') message(paste0("Job \"", name, "\" found with ", matches$job_id, ".")) } # If no name provided, use job_id param else{ run_config <- paste0('{ "job_id": ', job_id, ' }') } # Make request with netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/jobs/run-now"), httr::content_type_json(), body = run_config)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Make request res <- httr::POST(url = paste0(workspace, "/api/2.0/jobs/run-now"), httr::add_headers(.headers = headers), httr::content_type_json(), body = run_config) } # Handling successful API response if (res$status_code[1] == 200) { run_id <- jsonlite::fromJSON(rawToChar(res$content))$run_id number_in_job <- jsonlite::fromJSON(rawToChar(res$content))$number_in_job if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nRun ID: ", run_id, "\nNumber in Job: ", number_in_job )) } } else { run_id <- NA number_in_job <- NA if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } # Return response reslist <- list(run_response = res, run_id = run_id, number_in_job = number_in_job) } <file_sep>#' #' Remote execution of commands on a Databricks cluster. #' #' This function sends commands to an execution context on an existing #' Databricks cluster via REST API. It requires a context_id from #' \code{create_execution_context}. Commands must be compatible with the #' language of the execution context - 'r', 'python', 'scala', or 'sql'. #' Will attempt to return a data.frame but if the execution hasn't finished will return #' the status of execution. If your command does not return a data.frame output may #' vary considerably, or fail. #' #' The API endpoint for creating the execution context is is '1.2/commands/execute'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param command A string containing commands for remote execution on Databricks. #' @param context The list generated by \code{create_execution_context} #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed to \code{data.table::fread} which is used to #' parse the API response. #' @return A list with two components: #' \itemize{ #' \item \emph{response} - The full API response. #' \item \emph{data} - The data as a data.frame. #' } #' @examples #' # Using netrc #' context <- create_execution_context(workspace = "https://eastus2.azuredatabricks.net", #' language = "r", #' cluster_id = "1017-337483-jars232") #' #' ## Use the context to execute a command on Databricks #' command <- "iris[1, ]" #' result <- databricks_execute(command, context) #' #' ## Access dataframe #' result$data #' databricks_execute <- function(command, context, verbose = F, ...) { payload <- paste0('{ "language": "', context$language, '", "clusterId": "', context$cluster_id, '", "contextId": "', context$context_id, '", "command": "', command, '" }') ## Send command via REST, using netrc for auth by default if (is.null(context$token)) { use_netrc <- httr::config(netrc = 1) execute_response <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/1.2/commands/execute"), httr::content_type_json(), body = payload) }) } else { ## Bearer Authentication headers <- c( Authorization = paste("Bearer", context$token) ) execute_response <- httr::POST(url = paste0(workspace, "/api/1.2/commands/execute"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } ## Extract command ID from response command_id <- jsonlite::fromJSON(rawToChar(execute_response$content))$id # If the command hasn't finished executing, poll the API until it has repeat{ # Get result from status endpoint with command_id if (is.null(context$token)) { use_netrc <- httr::config(netrc = 1) status_response <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/1.2/commands/status", "?clusterId=", context$cluster_id, "&contextId=", context$context_id, "&commandId=", command_id)) }) # Share status message( "Command Status: ", jsonlite::fromJSON(rawToChar(status_response$content))$status ) } else { status_response <- httr::GET(url = paste0(workspace, "/api/1.2/commands/status", "?clusterId=", context$cluster_id, "&contextId=", context$context_id, "&commandId=", command_id), httr::add_headers(.headers = headers)) message( "Command Status: ", jsonlite::fromJSON(rawToChar(status_response$content))$status ) } if (jsonlite::fromJSON(rawToChar(status_response$content))$status == "Finished") { break } # If execution hasn't finished, wait a second and try again Sys.sleep(1) } # could make this nested to account for both API calls used in this function if (verbose == T) { ## Successful request message if (status_response$status_code[1] == 200) { message(paste0( "Response Code: ", status_response$status_code[1], "\nCommand Status: ", jsonlite::fromJSON(rawToChar(status_response$content))$status, "\nCommand ID: ", command_id )) } ## Unsuccessful request message else { return(message(paste0( "Status: ", status_response$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(status_response) ))) } } # Try to extract HTML snippet from API response tryCatch( { txt <- xml2::read_html(jsonlite::fromJSON(rawToChar(status_response$content))$results$data) %>% rvest::html_children() %>% xml2::xml_text() # Convert text to data.table if returning a data frame df <- suppressWarnings(suppressMessages(data.table::setDF(data.table::fread(txt, drop = ...)))) results <- list(response = status_response, data = df) results }, error = function(e) { cat("There was a problem parsing the results - output must be a data.frame. Please check your code and try again.") jsonlite::prettify(status_response) } ) } <file_sep>#' #' Retrieve the information for a cluster. #' #' Will retrieve detailed information on a Databricks cluster. You can locate the cluster ID in #' the URL of the cluster configuration page. For example: #' #' https://mycompany.cloud.databricks.com/#/setting/clusters/xxxx-xxxxx-xxxxxx/ #' #' Where xxxx-xxxxx-xxxxxx is the cluster ID. #' #' The API endpoint for terminating a cluster is '2.0/clusters/get'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param cluster_id A string containing the unique id for an online Databricks cluster #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed to \code{data.table::fread} which is used to #' parse the API response. ##' @return A list with four elements: #' \itemize{ #' \item \emph{response} - The full API response, including status code. #' \item \emph{response_json} - The JSON result. #' \item \emph{response_list} - The JSON result transformed into a list. #' \item \emph{response_df} - The JSON result transformed into a dataframe. #' } #' @examples #' workspace <- "https://myworkspace.cloud.databricks.com" #' cluster_id <- "0818-155203-cheese22" #' #' get_cluster_status(workspace = workspace, cluster_id = cluster_id) #' @export get_cluster_status <- function(cluster_id, workspace, token = NULL, verbose = T, ...) { # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/clusters/get/?cluster_id=", cluster_id), encoding = "UTF-8")}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::GET(url = paste0(workspace, "/api/2.0/clusters/get/?cluster_id=", cluster_id), httr::add_headers(.headers = headers), encoding = "UTF-8") } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nCluster \"", cluster_id, "\" status retrieved." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) )) } } # Clean up datetimes in API response response_df = as.data.frame(jsonlite::fromJSON(rawToChar(res$content))) response_df$driver.start_timestamp <- as.POSIXct(response_df$driver.start_timestamp/1000, origin = "1970-01-01") response_df$executors.start_timestamp <- as.POSIXct(response_df$executors.start_timestamp/1000, origin = "1970-01-01") response_df$start_time <- as.POSIXct(response_df$start_time/1000, origin = "1970-01-01") response_df$last_state_loss_time <- as.POSIXct(response_df$last_state_loss_time/1000, origin = "1970-01-01") response_df$last_activity_time <- as.POSIXct(response_df$last_activity_time/1000, origin = "1970-01-01") reslist <- ## Return list of values reslist <- list(response = res, response_json = suppressMessages(jsonlite::prettify(res)), response_list = jsonlite::fromJSON(rawToChar(res$content)), response_df = response_df ) } <file_sep>library(testthat) library(bricksteR) test_check("bricksteR") <file_sep>#' #' Install Packages (libraries) on a Databricks Cluster #' #' Packages installed this way will be added to the cluster configuration #' going forward. When you restart the cluster they will show up in the UI. #' Cluster cannot be in a terminated state to use this function. You can #' locate the cluster ID in the URL of the cluster configuration page. #' For example: #' #' https://mycompany.cloud.databricks.com/#/setting/clusters/xxxx-xxxxx-xxxxxx/ #' #' Where xxxx-xxxxx-xxxxxx is the cluster ID. #' #' The API endpoint for installing libraries is #' '2.0/libraries/install'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param cluster_id A string containing the unique id for an online #' Databricks cluster. #' @param package A string with the name of the package to install. #' @param repo A string representing the repo hosting the package. #' Defaults to RStudio Public Package Manager #' (https://packagemanager.rstudio.com/all/__linux__/xenial/latest) for R #' packages. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @return The API response. #' #' @examples #' # Cluster to install on #' workspace <- "https://mydb.cloud.databricks.com" #' cluster_id <- "0818-155203-cheese22" #' #' # Install package #' libraries_install(package = "broom", cluster_id, workspace) #' #' # Check installation status #' get_library_statuses(cluster_id, workspace) #' @export libraries_install <- function(cluster_id, package, repo = "https://packagemanager.rstudio.com/all/__linux__/xenial/latest", workspace, token = NULL, verbose = T, ...) { payload <- paste0( '{"cluster_id": "', cluster_id, '", "libraries": [{ "cran": { "package": "', package,'", "repo": "', repo, '" } }] }' ) # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/libraries/install"), httr::content_type_json(), body = payload)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/libraries/install"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nLibraries installing. Use get_library_statuses() to check status." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response res } <file_sep>#' #' Create a path on DBFS #' #' Create the given directory and necessary parent directories if they do not exist. #' If there exists a file (not a directory) at any prefix of the input path, this #' call throws an exception with RESOURCE_ALREADY_EXISTS. If this operation fails #' it may have succeeded in creating some of the necessary parent directories. #' #' The API endpoint for creating a path on DBFS is '2.0/dbfs/mkdirs'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param path A string representing the path to create in DBFS #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed #' @return The API response #' @examples #' # No need to include /dbfs/ #' path <- "/rk/data/new_dir" #' #' dbfs_mkdirs(path = path, workspace = workspace) #' @export dbfs_mkdirs <- function(path, workspace, token = NULL, verbose = T, ...) { payload <- paste0('{"path": "', path, '"}') # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/dbfs/mkdirs"), httr::content_type_json(), body = payload)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/dbfs/mkdirs"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nCreated \"", path, "\":" )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response res } <file_sep>#' Export a Notebook or Directory from a Databricks Workspace #' #' Export a notebook or contents of an entire directory. If path does not #' exist, this call returns an error RESOURCE_DOES_NOT_EXIST. You can export #' a directory only in DBC format. If the exported data exceeds the size #' limit, this call returns an error MAX_NOTEBOOK_SIZE_EXCEEDED. This API #' does not support exporting a library. #' The API endpoint for importing files to the workspace is #' '2.0/workspace/import'. For all details on API calls please see the #' official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param workspace_path A string representing the path to notebook or folder #' in the Databricks workspace. #' @param format A string. This specifies the format of the exported file. #' By default, this is SOURCE. However it may be one of: SOURCE, HTML, #' JUPYTER, DBC. The value is case sensitive. #' @param direct_download A string. Flag to enable direct download. If #' 'true', the response will be the exported file itself. Otherwise, the #' response contains content as base64 encoded string. Defaults to 'true'. #' @param filename Optional string representing the path to save the file locally. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://company.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param verbose If true, will pretty print the success or failure of the request. Defaults to TRUE. #' @return The API response. If \emph{filename} is provided, will write the #' file to disk. #' #' @examples #' # Export a notebook as HTML #' export_from_workspace(workspace_path = "/Shared/R_Notebook", #' format = "HTML", #' filename = "/Desktop/r_notebook.html", #' direct_download = 'true', #' workspace = workspace, #' token = token) #' #' # Export a directory as DBC #' export_from_workspace(workspace_path = "/Shared/", #' format = "DBC", #' filename = "/Desktop/shared.dbc", #' direct_download = 'true', #' workspace = workspace, #' token = token) export_from_workspace <- function(workspace_path, format, direct_download = 'true', filename = NULL, workspace, token = NULL, verbose = T) { if (is.null(token)) { ## Using netrc by default use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::GET(url = paste0(workspace, "/api/2.0/workspace/export?format=", format, "&path=", utils::URLencode(workspace_path), "&direct_download=", direct_download), httr::content_type_json()) }) } else { ## Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) ## Make request res <- httr::GET(url = paste0(workspace, "/api/2.0/workspace/export?format=", format, "&path=", utils::URLencode(workspace_path), "&direct_download=", direct_download), httr::add_headers(headers), httr::content_type_json()) } if (verbose == T) { ## Successful request message if (res$status_code[1] == 200) { message(paste0( "Status: ", res$status_code[1], "\n\nWorkspace object: ", workspace_path, " was exported successfully. " )) } ## Unsuccessful request message else { return(message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(res) ))) } } if (!is.null(file)) { conn <- file(filename, "wb") writeBin(httr::content(res, as = "text"), conn) close(conn) message(paste0("File downloaded here: ", filename)) } ## Return API response res } <file_sep>--- title: "Automating R Jobs on Databricks with bricksteR" author: "<NAME>, Solutions Architect, Databricks" date: "`r Sys.Date()`" output: rmarkdown::github_document vignette: > %\VignetteIndexEntry{Vignette Title} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( warning = FALSE, collapse = TRUE, comment = "#>" ) ``` While Databricks supports R users through interactive notebooks and a hosted instance of RStudio Server, it can be cumbersome to convert R files into production jobs. `bricksteR` makes it easy to quickly turn .R and .Rmd files into automated jobs that run on Databricks by using the [Databricks REST API](https://docs.databricks.com/dev-tools/api/latest/). Here are some highlights of what you can do with `bricksteR`: * Import any .R or .Rmd file into the Databricks Workspace, from anywhere * Create and run a new job in a single function * Check on the status of a job run by *name* or id * Use JSON files or strings for job configurations ## Table of Contents * [Installation & Authentication](#installation) * [Importing R Scripts to Databricks](#importing-r-scripts-to-databricks) * [Jobs](#jobs) + [Create and Run a Job](#create-and-run-a-job) + [View Jobs and Runs](#view-jobs-and-runs) + [Reset a Job](#reset-a-job) + [Delete a Job](#delete-a-job) * [Export from Databricks](#export-from-databricks) ## Installation The first thing you'll need to get started is to install the package from GitHub. ```{r echo=T, results='hide', message=FALSE} devtools::install_github("RafiKurlansik/bricksteR") library(bricksteR) ``` #### Authentication You will need an [Access Token](https://docs.databricks.com/dev-tools/api/latest/authentication.html#authentication) in order to authenticate with the Databricks REST API. If you are working locally or using [DB Connect](https://docs.databricks.com/dev-tools/databricks-connect.html#databricks-connect), a good way to authenticate is to use a [.netrc](https://docs.databricks.com/dev-tools/api/latest/authentication.html#store-token-in-netrc-file-and-use-in-curl) file. By default, `bricksteR` will look for the `.netrc` file before checking for a token in the function call. If you don't already have one, create a .netrc file in your home directory that looks like this: ``` machine <databricks-instance> login token password <personal-access-token-value> ``` You can also authenticate by [passing a token to Bearer authentication](https://docs.databricks.com/dev-tools/api/latest/authentication.html#pass-token-to-bearer-authentication). To be clear, **it is not recommended to store your credentials directly in your code**. If you are working on Databricks in a notebook, you can use `dbutils.secrets.get()` to avoid printing your token. Finally, you will need to identify the workspace URL of your Databricks instance. On AWS this typically has the form `https://dbc-a64b1209f-d811.cloud.databricks.com`, or if you have a vanity URL it may look more like `https://mycompany.cloud.databricks.com`. On Azure it will have the form `https://eastus2.azuredatabricks.net`, or whichever region your instance is located in. ```{r message=FALSE} workspace <- "https://field-eng.cloud.databricks.com" # If running in a Databricks Notebook # token <- dbutils.secrets.get(scope = "bricksteR", key = "rest_api") ``` ## Importing R Scripts to Databricks A common use case is moving R scripts or R Markdown files to Databricks to run as a notebook. We can automate this process using `import_to_workspace()`. ```{r} import_to_workspace(file = "/Users/rafi.kurlansik/RProjects/AnRMarkdownDoc.Rmd", notebook_path = "/Users/<EMAIL>/AnRMarkdownDoc", workspace = workspace, overwrite = 'true') ``` ## Jobs ### Create and Run a Job Now that the file is in our workspace, we can create a job that will run it as a [Notebook Task](https://docs.databricks.com/dev-tools/api/latest/jobs.html#jobsnotebooktask). ```{r} new_job <- create_job(notebook_path = "/Users/[email protected]/AnRMarkDownDoc", name = "Beer Sales Forecasting Job", job_config = "default", workspace = workspace) job_id <- new_job$job_id ``` Each job requires a `job_config`, which is a JSON file or JSON formatted string specifying (at a minimum) the task and type of infrastructure required. If no config is supplied, a 'default' cluster is created with 1 driver and 2 workers. Here's what that default configuration looks like: ```r # Default JSON configs job_config <- paste0('{ "name": ', name,' "new_cluster": { "spark_version": "5.3.x-scala2.11", "node_type_id": "r3.xlarge", "aws_attributes": { "availability": "ON_DEMAND" }, "num_workers": 2 }, "email_notifications": { "on_start": [], "on_success": [], "on_failure": [] }, "notebook_task": { "notebook_path": ', notebook_path, ' } }') ``` Where `name` is the name of your job and `notebook_path` is the path to the notebook in your workspace that will be run. Creating a job by itself will not actually execute any code. If we want our beer forecast - and we do - then we'll need to actually run the job. We can run the job by id, or by name. ```{r} # Specifying the job_id run_job(job_id = job_id, workspace = workspace, token = NULL) # Specifying the job name run_job(name = "Beer Sales Forecasting Job", workspace = workspace, token = NULL) ``` Running a job by name is convenient, but there's nothing stopping you from giving two jobs the same name on Databricks. The way `bricksteR` handles those conflicts today is by forcing you to use the unique Job ID or rename the job you want to run with a distinct moniker. If you want to run a job immediately, one option is to use the `create_and_run_job()` function: ```{r} # By specifying a local file we implicitly import it running_new_job <- create_and_run_job(file = "/Users/rafi.kurlansik/agg_and_widen.R", name = "Lager Sales Forecasting Job", notebook_path = "/Users/[email protected]/agg_and_widen", job_config = "default", workspace = workspace, overwrite = 'true') ``` ### View Jobs and Runs There are two handy functions that will return a list of Jobs and their runs - `jobs_list()` and `runs_list()`. One of the objects returned is a concise R dataframe that allows for quick inspection. ```{r} jobs <- jobs_list(workspace = workspace) beer_runs <- runs_list(name = "Lager Sales Forecasting Job", workspace = workspace) head(jobs$response_tidy) head(beer_runs$response_tidy) ``` ### Reset a Job If you need to update the config for a job, use `reset_job()`. ```{r eval=FALSE} # JSON string or file path can be passed new_config <- "/Users/rafi.kurlansik/Desktop/nightly_model_training.json" reset_job(job_id = job_id, new_config = new_config, workspace = workspace) ``` ### Delete a Job If you need to clean up a job from the workspace, use `delete_job()`. ```{r} delete_job(job_id = job_id, workspace = workspace) ``` ## Export from Databricks To export notebooks from Databricks, use `export_from_workspace()`. ```{r eval = F} export_from_workspace(workspace_path = "/Users/<EMAIL>ik<EMAIL>.com/AnRMarkdownDoc", format = "SOURCE", filename = "/Users/rafi.kurlansik/RProjects/anotherdoc.Rmd", workspace = workspace) ``` Passing a `filename` will save the exported data to your local file system. Otherwise it will simply be returned as part of the API response. ## Future Plans That's about all there is to it to get started with automating R on Databricks! Whether you are using `blastula` to email a report or are spinning up a massive cluster to perform ETL or model training, these APIs will make it easy for you to define, schedule, and monitor those jobs from R. In 2020 I'd like to add support for DBFS operations, and provide additional tools for managing libraries. _________ Questions or feedback? Feel free to contact me at [<EMAIL>](mailto:<EMAIL>). <file_sep>#' #' Move a file or directory on DBFS #' #' Move a file from one location to another location *within* DBFS. This will #' not move files from your local system to DBFS. See `dbfs_put()` and #' `dbfs_read()` to work with your local filesystem. #' #' If the source file does not exist, this call throws an exception with #' RESOURCE_DOES_NOT_EXIST. If there already exists a file in the #' destination path, this call throws an exception with #' RESOURCE_ALREADY_EXISTS. If the given source path is a directory, #' this call always recursively moves all files. #' #' The API endpoint for moving files or directories on DBFS is '2.0/dbfs/move'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param from A string representing the source path in DBFS #' @param to A string representing the destination path in DBFS #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed #' @return The API response #' @examples #' # No need to include /dbfs/ #' source_path <- "/data/my_model.rds" #' destination_path <- "/models/my_model.rds" #' #' dbfs_mv(from = source_path, to = destination_path, workspace = workspace) #' @export dbfs_mv <- function(from, to, workspace, token = NULL, verbose = T, ...) { payload <- paste0('{"source_path": "', from, '", "destination_path": "', to,'"}') # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/dbfs/move"), httr::content_type_json(), body = payload)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/dbfs/move"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nMoved \"", from, "\" to \"", to, "\" successfully." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response res } <file_sep>#' #' Delete a file or directory on DBFS #' #' Delete the file or directory (optionally recursively delete all files in #' the directory). This call throws an exception with IO_ERROR if the path is #' a non-empty directory and recursive is set to false or on other similar errors. #' When you delete a large number of files, the delete operation is done in increments. #' The call returns a response after approximately 45s with an error message #' (503 Service Unavailable) asking you to re-invoke the delete operation until the #' directory structure is fully deleted. #' #' The API endpoint for creating a path on DBFS is '2.0/dbfs/delete'. #' For all details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param path A string representing the path to delete in DBFS #' @param recursive Should the deletes be recursive or not? Defaults to 'false' #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used #' @param verbose If TRUE, will print the API response to the console. Defaults to #' FALSE. #' @param ... Additional options to be passed #' @return The API response #' @examples #' # No need to include /dbfs/ #' path <- "/rk/data/new_dir" #' #' dbfs_rm(path = path, workspace = workspace) #' @export dbfs_rm <- function(path, recursive = 'false', workspace, token = NULL, verbose = T, ...) { payload <- paste0('{"path": "', path, '", "recursive": "', recursive,'"}') # Make request, using netrc by default if (is.null(token)) { use_netrc <- httr::config(netrc = 1) res <- httr::with_config(use_netrc, { httr::POST(url = paste0(workspace, "/api/2.0/dbfs/delete"), httr::content_type_json(), body = payload)}) } else { # Authenticate with token headers <- c( Authorization = paste("Bearer", token) ) # Using token for authentication instead of netrc res <- httr::POST(url = paste0(workspace, "/api/2.0/dbfs/delete"), httr::add_headers(.headers = headers), httr::content_type_json(), body = payload) } # Handling successful API request if (res$status_code[1] == 200) { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nDeleted \"", path, "\" successfully." )) } } # Handling unsuccessful request else { if (verbose == T) { message(paste0( "Status: ", res$status_code[1], "\nThe request was not successful:\n\n", suppressMessages(jsonlite::prettify(res)) )) } } # Return response res } <file_sep>#' Create and run a job on Databricks #' #' Single function to both create a job and immediately run it. Each call #' will register a new job in the Databricks Jobs UI, so for subsequent runs #' it is best to submit the job_id to \code{run_job}. #' #' Uses '2.0/jobs/create', '2.0/jobs/run-now' and '2.0/runs/get' API endpoints. For all #' details on API calls please see the official documentation at #' \url{https://docs.databricks.com/dev-tools/api/latest/}. #' #' @param name A string representing the name of the job. It is encouraged #' to choose a unique name for each job. #' @param notebook_path A string representing the path to a Databricks notebook in the #' workspace. #' @param file The path to a local .R or .Rmd file. Will be imported to the #' workspace at the \emph{notebook_path}. #' @param job_config A JSON formatted string or file specifying the details of the job, i.e., the #' name, cluster spec, and so on. #' @param workspace A string representing the web workspace of your Databricks #' instance. E.g., "https://eastus2.azuredatabricks.net" or #' "https://demo.cloud.databricks.com". #' @param token A valid authentication token generated via User Settings in #' Databricks or via the Databricks REST API 2.0. If none is provided, #' netrc will be used. #' @param ... additional arguments to be passed, i.e., overwrite = 'false' when #' importing a file to run as a job. #' @return A list with three elements containing the values of \code{create_job}, #' \code{run_job}, and \code{get_run_status}: #' \itemize{ #' \item \emph{job} - The full API response, including status code. #' \item \emph{run} - The JSON result. #' \item \emph{run_status} - The JSON result transformed into a list. #' } #' @examples #' results <- create_and_run_job(name = "Forecasting Report", #' notebook_path = "/Shared/forecasting_report_notebook". #' workspace = "https://eastus2.azuredatabricks.net", #' token = "<PASSWORD>") #' #' # Get each response #' job <- results$job #' run <- results$run #' run_status <- results$run_status #' #' create_and_run_job <- function(name = "R Job", file = NULL, notebook_path, job_config = "default", workspace, token = NULL, ...) { # Check for JSON file with job config if (file.exists(job_config)) { job_config <- toJSON(fromJSON(job_config), auto_unbox = T) } # Create the job job <- create_job(name = name, file = file, notebook_path = notebook_path, job_config = job_config, workspace = workspace, token = token, verbose = F, overwrite = ...) if (length(job) < 2) { return(message("Unable to create job, please check API response.")) } # Run using job_id from create_job() run <- run_job(job_id = job$job_id[[1]], workspace = workspace, token = token, verbose = F) # Get status using run_id from run_job() run_status <- get_run_status(run_id = run$run_id, workspace = workspace, token = token, verbose = F) # Handling create job request if (job$response$status_code == 200) { message(paste0( "Job \"", name, "\" successfully created... \nThe Job ID is: ", job$job_id[[1]] )) } else { return(message(paste0( "Status: ", job$response$status_code[1], "\nThe request was not successful:\n\n", jsonlite::prettify(job) ))) } # Handling run job request if (run$run_response$status_code == 200) { message(paste0( "\nRun successfully launched... \nThe run_id is: ", run$run_id )) } else { return(message(paste0( "Status: ", run$status_code[1], "\nUnable to launch run:\n\n", jsonlite::prettify(run$run_response) ))) } # Handling run status request if (run_status$response$status_code == 200) { message(paste0( "\nYou can check the status of this run at: \n ", run_status$response_list$run_page_url )) } else { return(message(paste0( "Status: ", run_status$response$status_code[1], "\n Unable to get status of run: \n\n", jsonlite::prettify(run_status$response) ))) } # Return the output of all API calls in a list reslist <- list(job = job, run = run, run_status = run_status) reslist }
e04c0d423fde5be2567111b6983cc91e63c93232
[ "Markdown", "R", "RMarkdown" ]
31
R
RafiKurlansik/bricksteR
9199ab34dda462601186c25cf8655483f0bbe408
b42b3b3556ef3394b7e7801568a8e228083ad336
refs/heads/main
<repo_name>zJoaoP/Javascript-Evaluator<file_sep>/src/components/Header/Header.jsx import React from 'react'; import { Wrapper, Title, Description } from 'components/Header/style'; export default function Header() { return ( <Wrapper id="header-wrapper"> <Title>Exercícios JS</Title> <Description>https://github.com/zJoaoP/Javascript-Evaluator</Description> </Wrapper> ); } <file_sep>/src/service/problems.js const problems = [ { name: 'Hello, World!', description: 'Escreva "Hello, World!" no terminal. Lembre-se de usar o <strong>console.log(str)</strong> para isso.\n\nÉ de graça :)', contexts: [{}], outputs: ['Hello, World!\n'], }, { name: 'Soma simples', description: 'Escreva um script capaz de imprimir a soma de duas variáveis <strong>A</strong> e <strong>B</strong> no console.', contexts: [ { A: 2, B: 3 }, { A: 0, B: 0 }, ], outputs: ['5\n', '0\n'], }, { name: 'Reverso', description: 'Escreva um script capaz de inverter a ordem de um vetor chamado <strong>V</strong>.\nConsidere que ele já foi devidamente inicializado.', contexts: [{ V: [1, 2, 3] }], outputs: ['3,2,1\n'], }, { name: 'Produto Escalar', description: 'Escreva um script capaz de imprimir o produto escalar de dois vetores <strong>U</strong> e <strong>V</strong>.', contexts: [ { U: [1, 2, 3], V: [4, 5, 6] }, { U: [1, 0], V: [3, 4] }, ], outputs: ['32\n', '3\n'], }, ]; const api = { fetchProblems: () => new Promise((resolve) => setTimeout(() => resolve(problems), 1000)), }; export default api; <file_sep>/src/helpers/evaluation.js /* eslint-disable */ export default function evaluate(js, context) { function foo() { console.log(this); } foo(); let output = ''; const log = console.log; console.log = (text) => { output += `${text}\n`; }; function scopedEval(expr) { const evaluator = Function.apply(null, [ ...Object.keys(context), 'expr', 'return eval(expr)', ]); return evaluator.apply(null, [...Object.values(context), expr]); } try { scopedEval(js); } catch (e) { console.log = log; return e; } console.log = log; return output; } <file_sep>/src/views/Home.jsx import React from 'react'; import ProblemSection from 'components/ProblemSection/ProblemSection'; import Header from 'components/Header/Header'; import api from 'service/problems'; export default function Home() { const [problems, setProblems] = React.useState([]); const [loading, setLoading] = React.useState(false); React.useEffect(() => { setLoading(true); api.fetchProblems().then((response) => setProblems(response)); setLoading(false); return () => {}; }, [problems]); return ( <div id="home"> <Header /> {!loading && <ProblemSection problems={problems} />} </div> ); } <file_sep>/src/components/CaseViewer/CaseViewer.jsx import PropTypes from 'prop-types'; import React from 'react'; import { Row, Col } from 'antd'; import { CaseCard, CaseTypography, } from 'components/CaseViewer/style'; export default function CaseViewer({ context, output, result }) { return ( <Row> <Col xs={24} md={8}> <CaseCard title="Entrada"> {Object.keys(context).map((k) => ( <CaseTypography key={k}>{`${k}: ${context[k]}`}</CaseTypography> ))} </CaseCard> </Col> <Col xs={24} md={8}> <CaseCard title="Saída Esperada">{output}</CaseCard> </Col> <Col xs={24} md={8}> <CaseCard title="Saída Obtida">{result}</CaseCard> </Col> </Row> ); } CaseViewer.propTypes = { context: PropTypes.objectOf(PropTypes.any).isRequired, output: PropTypes.string.isRequired, result: PropTypes.string.isRequired, }; <file_sep>/src/App.jsx import React from 'react'; import GlobalStyle from 'GlobalStyle'; import Home from 'views/Home'; import 'antd/dist/antd.css'; function App() { return ( <div id="app"> <GlobalStyle /> <Home /> </div> ); } export default App; <file_sep>/README.md <!-- PROJECT SHIELDS --> <!-- *** I'm using markdown "reference style" links for readability. *** Reference links are enclosed in brackets [ ] instead of parentheses ( ). *** See the bottom of this document for the declaration of the reference variables *** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use. *** https://www.markdownguide.org/basic-syntax/#reference-style-links --> [![Contributors][contributors-shield]][contributors-url] [![Forks][forks-shield]][forks-url] [![Stargazers][stars-shield]][stars-url] [![Issues][issues-shield]][issues-url] [![MIT License][license-shield]][license-url] [![LinkedIn][linkedin-shield]][linkedin-url] <!-- PROJECT LOGO --> <br /> <p align="center"> <h1 align="center">JS Evaluator</h3> <p align="center"> Here is the "big brain place", but i'm sleepy and I'll let it for later. <br /> <a href="https://javascript-evaluator.netlify.app/">View Demo</a> · <a href="https://github.com/zJoaoP/Javascript-Evaluator/issues">Report Bug</a> · <a href="https://github.com/zJoaoP/Javascript-Evaluator/issues">Request Feature</a> </p> </p> <!-- TABLE OF CONTENTS --> <details open="open"> <summary><h2 style="display: inline-block">Table of Contents</h2></summary> <ol> <li> <a href="#about-the-project">About The Project</a> <ul> <li><a href="#built-with">Built With</a></li> </ul> </li> <li> <a href="#getting-started">Getting Started</a> <ul> <li><a href="#installation">Installation</a></li> </ul> </li> <li><a href="#roadmap">Roadmap</a></li> <li><a href="#contributing">Contributing</a></li> <li><a href="#license">License</a></li> <li><a href="#contact">Contact</a></li> </ol> </details> <!-- ABOUT THE PROJECT --> ## About The Project It's a simple application to evaluate javascript codes like <a href="">URI Online Judge</a> and <a href="">SPOJ</a>, but with two major differences: 1. The developer / student don't need to perform any input sanitisation. (All variables described in the problem statement are already initialized before script evaluation) 2. All test cases are visible. It can be changed, but this application was planned to be friendly to new javascript programmers (and was written by one :P) ### Built With * [ReactJS](https://reactjs.org/) * [Ant Design](https://ant.design/) * [CodeMirror](https://codemirror.net/) <!-- GETTING STARTED --> ## Getting Started To get a local copy up and running follow these simple steps. ### Installation 1. Clone the repo ```sh git clone https://github.com/zJoaoP/Javascript-Evaluator.git ``` 2. Install NPM packages ```sh npm install ``` <!-- ROADMAP --> ## Roadmap See the [open issues](https://github.com/zJoaoP/Javascript-Evaluator/issues) for a list of proposed features (and known issues). <!-- CONTRIBUTING --> ## Contributing Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**. 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request <!-- LICENSE --> ## License Distributed under the MIT License. See `LICENSE` for more information. <!-- CONTACT --> ## Contact <NAME> - <EMAIL> Project Link: [https://github.com/zJoaoP/Javascript-Evaluator](https://github.com/zJoaoP/Javascript-Evaluator) <!-- MARKDOWN LINKS & IMAGES --> <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> [contributors-shield]: https://img.shields.io/github/contributors/zJoaoP/Javascript-Evaluator.svg?style=for-the-badge [contributors-url]: https://github.com/zJoaoP/Javascript-Evaluator/graphs/contributors [forks-shield]: https://img.shields.io/github/forks/zJoaoP/Javascript-Evaluator.svg?style=for-the-badge [forks-url]: https://github.com/zJoaoP/Javascript-Evaluator/network/members [stars-shield]: https://img.shields.io/github/stars/zJoaoP/Javascript-Evaluator.svg?style=for-the-badge [stars-url]: https://github.com/zJoaoP/Javascript-Evaluator/stargazers [issues-shield]: https://img.shields.io/github/issues/zJoaoP/Javascript-Evaluator.svg?style=for-the-badge [issues-url]: https://github.com/zJoaoP/Javascript-Evaluator/issues [license-shield]: https://img.shields.io/github/license/zJoaoP/Javascript-Evaluator.svg?style=for-the-badge [license-url]: https://github.com/zJoaoP/Javascript-Evaluator/blob/master/LICENSE.txt [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 [linkedin-url]: https://linkedin.com/in/zJoaoP <file_sep>/src/components/ProblemCard/style.js import styled from 'styled-components'; import { Card, Input, Typography, Button } from 'antd'; const { TextArea } = Input; export const CustomCard = styled(Card)` max-width: 900px; width: 90%; margin-top: 8px; `; export const Description = styled(Typography)` margin-bottom: 24px; `; export const ErrorDescription = styled(Typography)` color: ${(props) => props.color}; `; export const CodeWrapper = styled.div` margin-bottom: 16px; `; export const EvaluationResult = styled(Typography)` color: ${(props) => props.color}; text-align: center; font-weight: bold; width: 50%; `; export const CodeTextArea = styled(TextArea)``; export const SubmitWrapper = styled.div` justify-content: space-between; align-items: center; display: flex; flex-grow: 1; margin-top: 16px; `; export const SubmitButton = styled(Button)` width: 50%; `; export default { CustomCard, }; <file_sep>/src/components/ProblemSection/ProblemSection.jsx import PropTypes from 'prop-types'; import React from 'react'; import ProblemCard from 'components/ProblemCard/ProblemCard'; import { Wrapper } from 'components/ProblemSection/style'; export default function ProblemSection({ problems }) { return ( <Wrapper> {problems.map((problem) => ( <ProblemCard key={problem.name} name={problem.name} description={problem.description} contexts={problem.contexts} outputs={problem.outputs} /> ))} </Wrapper> ); } ProblemSection.propTypes = { problems: PropTypes.arrayOf(PropTypes.object).isRequired, }; <file_sep>/src/components/CaseViewer/style.js import styled from 'styled-components'; import { Card, Typography } from 'antd'; export const CaseCard = styled(Card)` flex-grow: 1; height: 100%; `; export const CaseTypography = styled(Typography)` white-space: pre-wrap; `; export default { CaseTypography, CaseCard, };
08162d5ae26f25d2a4fc4035fbe8f4e22d3bb9a5
[ "JavaScript", "Markdown" ]
10
JavaScript
zJoaoP/Javascript-Evaluator
ea023c6ead4e3e6270db4b97d82e281150e768d1
3000503ed14cdb4bfdf2ec5b54ed57b8c96bbd75
refs/heads/master
<file_sep>package com.example.asus.learningenglish; import android.app.AlertDialog; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.Objects; public class StudyActivity extends AppCompatActivity { private TextView q_search; private TextView q_chinese; private EditText vocabulary; private Button word_back; private Button word_next; private Button word_new; private Cursor cursor_control; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_study); Objects.requireNonNull(getSupportActionBar()).hide(); q_search = this.findViewById(R.id.q_search); q_search.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); q_chinese = this.findViewById(R.id.q_chinese); q_chinese.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); Button search = findViewById(R.id.btn_search); search.setOnClickListener(findVocabulary); search.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); vocabulary = findViewById(R.id.et_vocabulary); word_back = findViewById(R.id.word_back); word_next = findViewById(R.id.word_next); word_new = findViewById(R.id.word_new); word_new.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); vocabularyViewer(); vocabularyEditor(); } private void vocabularyEditor() { word_new.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openDialog(); } }); } private void openDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = View.inflate(this,R.layout.study_newword,null); final EditText get_english = view.findViewById(R.id.get_english); final EditText get_chinese = view.findViewById(R.id.get_chinese); get_english.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); get_chinese.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); builder.setView(view); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String new_english = get_english.getText().toString().toLowerCase(); String new_chinese = get_chinese.getText().toString(); Cursor cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE + " where english ='" + new_english + "';", null); cursor.moveToFirst(); if (cursor.getCount() > 0) { MainActivity.db.execSQL("update " + DBOpenHelper.DATABASE_TABLE + " set chinese='" + new_chinese + "' where english='" + new_english + "'"); } else { Cursor cursor_insert = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE,null); cursor_insert.moveToLast(); int id = cursor_insert.getInt(cursor.getColumnIndex("id")) + 1; MainActivity.db.execSQL("insert into " + DBOpenHelper.DATABASE_TABLE + " values('" + Integer.toString(id) + "','" + new_english + "','" + new_chinese + "');"); cursor_insert.close(); } cursor_control = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE,null); cursor_control.moveToFirst(); cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE + " where english ='" + new_english + "';", null); cursor.moveToFirst(); q_search.setText(cursor.getString(1)); q_chinese.setText(cursor.getString(2)); cursor.close(); } }).show(); } private void vocabularyViewer() { cursor_control = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE,null); cursor_control.moveToFirst(); cursor_control.moveToNext(); q_chinese.setText(cursor_control.getString(cursor_control.getColumnIndex("chinese"))); q_search.setText(cursor_control.getString(cursor_control.getColumnIndex("english"))); word_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkCursor(0); cursor_control.moveToPrevious(); q_chinese.setText(cursor_control.getString(cursor_control.getColumnIndex("chinese"))); q_search.setText(cursor_control.getString(cursor_control.getColumnIndex("english"))); } }); word_next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkCursor(1); cursor_control.moveToNext(); q_chinese.setText(cursor_control.getString(cursor_control.getColumnIndex("chinese"))); q_search.setText(cursor_control.getString(cursor_control.getColumnIndex("english"))); } }); } //單字檢視器 private void checkCursor(int check) { Cursor cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE, null); cursor.moveToLast(); if(cursor_control.getString(cursor_control.getColumnIndex("id")).equals("0") ) { cursor_control.moveToNext(); cursor_control.moveToNext(); } else if (cursor_control.getString(cursor_control.getColumnIndex("id")).equals(cursor.getString(cursor.getColumnIndex("id")))) { cursor_control.moveToPrevious(); } else if (cursor_control.getString(cursor_control.getColumnIndex("id")).equals("1") && check == 0) { cursor_control.moveToNext(); } cursor.close(); } //檢查curcor是否可以移動 private View.OnClickListener findVocabulary = new View.OnClickListener() { @Override public void onClick(View v) { String input_str = vocabulary.getText().toString().toLowerCase(); Cursor cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE + " where english ='" + input_str + "';", null); cursor.moveToFirst(); if (cursor.getCount() > 0) { String word_english = cursor.getString(1); String word_chinese = cursor.getString(2); q_chinese.setText(word_chinese); q_search.setText(word_english); } else { q_chinese.setText("查無此單字"); q_search.setText(""); } cursor.close(); } }; @Override protected void onPause() { super.onPause(); } }<file_sep>package com.example.asus.learningenglish; import android.database.Cursor; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Objects; public class RecordActivity extends AppCompatActivity { TextView record_score; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_record); Objects.requireNonNull(getSupportActionBar()).hide(); TextView record_title = findViewById(R.id.record_title); record_title.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); record_score = findViewById(R.id.record_score); record_score.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); TextView record_q_index = findViewById(R.id.record_q_index); record_q_index.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); TextView record_player = findViewById(R.id.record_player); record_player.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); Button btn_reset = findViewById(R.id.btn_reset); Cursor cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE ,null); cursor.moveToFirst(); record_score.setText(cursor.getString(cursor.getColumnIndex("chinese"))); record_player.setText(String.format("by %s", cursor.getString(cursor.getColumnIndex("english")))); cursor.close(); btn_reset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.db.execSQL("update " + DBOpenHelper.DATABASE_TABLE + " set chinese='0' where id='0'"); record_score.setText("0"); } }); } @Override protected void onPause() { super.onPause(); } } <file_sep>package com.example.asus.learningenglish; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { static String DATABASE_TABLE = "myWord"; public DBOpenHelper(Context context) { super(context, "myWord.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (id,english,chinese);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } <file_sep>package com.example.asus.learningenglish; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import java.util.Objects; public class MenuActivity extends AppCompatActivity { private TextView player_name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); Objects.requireNonNull(getSupportActionBar()).hide(); player_name = findViewById(R.id.player_name); player_name.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); player_name.setText(getName()); Button btn_game = findViewById(R.id.btn_game); btn_game.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); Button btn_study = findViewById(R.id.btn_study); btn_study.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); Button btn_record = findViewById(R.id.btn_record); btn_record.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); changeActivity(btn_game, 0); changeActivity(btn_study, 1); changeActivity(btn_record, 2); player_name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openDialog(); } }); } private void openDialog() { final EditText setName = new EditText(this); new AlertDialog.Builder(this).setTitle("Your name:").setView(setName).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String newName = setName.getText().toString(); if (!newName.equals("")) { MainActivity.db.execSQL("update " + DBOpenHelper.DATABASE_TABLE + " set english='" + newName + "' where id='0'"); player_name.setText(newName); } } }).show(); } private String getName() { Cursor cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE ,null); cursor.moveToFirst(); String name = cursor.getString(cursor.getColumnIndex("english")); cursor.close(); return name; } private void changeActivity(Button btn_click, final int check_target) { btn_click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); switch (check_target) { case 0: intent.setClass(MenuActivity.this, GameActivity.class); break; case 1: intent.setClass(MenuActivity.this, StudyActivity.class); break; case 2: intent.setClass(MenuActivity.this, RecordActivity.class); break; default: break; } startActivity(intent); } }); } } <file_sep>package com.example.asus.learningenglish; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Typeface; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.Objects; import java.util.Random; import pl.droidsonroids.gif.GifDrawable; import pl.droidsonroids.gif.GifImageView; public class GameActivity extends AppCompatActivity { private int right; private int q_number = 1; private TextView q_index; private TextView q_question; private TextView answer1; private TextView answer2; private TextView answer3; private TextView answer4; private TextView game_count; private TextView cheat; private CountDownTimer count; private GifImageView gif_normal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); Objects.requireNonNull(getSupportActionBar()).hide(); q_index = findViewById(R.id.q_index); q_index.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); q_question = findViewById(R.id.q_question); answer1 = findViewById(R.id.answer1); answer2 = findViewById(R.id.answer2); answer3 = findViewById(R.id.answer3); answer4 = findViewById(R.id.answer4); game_count = findViewById(R.id.game_count); game_count.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); gif_normal = findViewById(R.id.gif_normal); cheat = findViewById(R.id.cheat); cheat.setTypeface(Typeface.createFromAsset(getAssets(), "setofont.ttf")); count = new CountDownTimer(11000, 1000) { @SuppressLint("DefaultLocale") @Override public void onTick(long millisUntilFinished) { game_count.setText(String.format("%2d", millisUntilFinished / 1000)); } @Override public void onFinish() { loseScreen(); } }.start(); right = questionCreate(); answer1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (right == 1) { winScreen(); } else { loseScreen(); } } }); answer2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (right == 2) { winScreen(); } else { loseScreen(); } } }); answer3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (right == 3) { winScreen(); } else { loseScreen(); } } }); answer4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (right == 4) { winScreen(); } else { loseScreen(); } } }); gif_normal.setOnClickListener(new View.OnClickListener() { @SuppressLint("DefaultLocale") @Override public void onClick(View v) { //小雞給提示 try { GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.chikenshock); gifDrawable.setLoopCount(1); gif_normal.setImageDrawable(gifDrawable); int random = Integer.parseInt(randomNumber(8)); switch (random) { case 1: cheat.setText("1"); break; case 2: cheat.setText("2"); break; case 3: cheat.setText("3"); break; case 4: cheat.setText("4"); break; default: cheat.setText(String.format("%d", right)); break; } } catch (Exception e) { e.printStackTrace(); } } }); } private int questionCreate() { String wrong_index; String[] wrong_answer = new String[3]; String right_answer = null; Cursor cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE, null); cursor.moveToLast(); int db_length = cursor.getInt(cursor.getColumnIndex("id")); String index = randomNumber(db_length); cursor = MainActivity.db.query("myWord", new String[]{"id", "english", "chinese"}, "id=?", new String[]{index}, null, null, null); while (cursor.moveToNext()) { String id = cursor.getString(0); String word = cursor.getString(1); right_answer = cursor.getString(2); q_question.setText(word); Log.v("GameQuestion", id + " " + word + " " + right_answer + " " + index); if (right_answer != null) { break; } } for (int i = 0; i < 3; i++) { do { wrong_index = randomNumber(db_length); } while (wrong_index.equals(index)); cursor = MainActivity.db.query("myWord", new String[]{"id", "chinese"}, "id=?", new String[]{wrong_index}, null, null, null); while (cursor.moveToNext()) { String id = cursor.getString(0); wrong_answer[i] = cursor.getString(1); Log.v("GameAnswer", id + " " + wrong_answer[i]); } } int place = Integer.parseInt(randomNumber(4)); switch (place) { case 1: answer1.setText(String.format("1. %s", right_answer)); answer2.setText(String.format("2. %s", wrong_answer[0])); answer3.setText(String.format("3. %s", wrong_answer[1])); answer4.setText(String.format("4. %s", wrong_answer[2])); break; case 2: answer1.setText(String.format("1. %s", wrong_answer[0])); answer2.setText(String.format("2. %s", right_answer)); answer3.setText(String.format("3. %s", wrong_answer[1])); answer4.setText(String.format("4. %s", wrong_answer[2])); break; case 3: answer1.setText(String.format("1. %s", wrong_answer[0])); answer2.setText(String.format("2. %s", wrong_answer[1])); answer3.setText(String.format("3. %s", right_answer)); answer4.setText(String.format("4. %s", wrong_answer[2])); break; case 4: answer1.setText(String.format("1. %s", wrong_answer[0])); answer2.setText(String.format("2. %s", wrong_answer[1])); answer3.setText(String.format("3. %s", wrong_answer[2])); answer4.setText(String.format("4. %s", right_answer)); break; default: Log.v("MY_ERROR_MESSAGE", "Answer's place error!"); break; } cursor.close(); return place; } //產生題目 private void winScreen() { cheat.setText(""); right = questionCreate(); q_index.setText(String.format("Q%s.", Integer.toString(++q_number))); count.start(); } //答對執行的動作 private void loseScreen() { count.cancel(); checkScore(); Toast.makeText(this,"答對了" + (q_number-1) + "題",Toast.LENGTH_LONG).show(); finish(); } //答錯執行的動作 private String randomNumber(int range) { Random random = new Random(); return Integer.toString(random.nextInt(range) + 1); } //獲得字串隨機數 private void checkScore() { Cursor cursor = MainActivity.db.rawQuery("select * from " + DBOpenHelper.DATABASE_TABLE ,null); cursor.moveToFirst(); int score = cursor.getInt(cursor.getColumnIndex("chinese")); if(q_number > score) { MainActivity.db.execSQL("update " + DBOpenHelper.DATABASE_TABLE + " set chinese='" + String.valueOf(q_number - 1) + "' where id='0'"); } Log.v("BEST SCORE",String.valueOf(score)); cursor.close(); } //更新最佳紀錄 @Override protected void onPause() { super.onPause(); count.cancel(); } //若中途離開則關閉計時器 }
836cdd90d01cf3dd7b21a4f079630139675785c3
[ "Java" ]
5
Java
aiyzod/vocabulary_test
ce1aad2a0d6ccc2432ea37bc065f8035bae2137a
ff8f06c21c26cec5d0dd72f62c74297ea9b347be
refs/heads/master
<file_sep>java -jar CFD_1_Java.jar 1 1 500000 293<file_sep>java -jar CFD_1_Java.jar << EOF 15 5 3000 293 100 7 EOF
7c344391b70778958b8a4a688ddd25c5097e6459
[ "Shell" ]
2
Shell
khuang93/CFD_1_Java
41892b094838655dcb2903b79dd603420bc70dd0
55f19312e20dd6dcc3e41ca002c82363e7540887
refs/heads/master
<repo_name>javier206/AppSoccer_Xamarin_Forms_and_ASP_Core<file_sep>/Soccer.Web/Data/Entities/TournamentEntity.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Soccer.Web.Data.Entities { public class TournamentEntity { public int Id { get; set; } public string Name { get; set; } [DisplayFormat(DataFormatString = "yyyy/MM/dd", ApplyFormatInEditMode =false)] public DateTime StartDate { get; set; } [DisplayFormat(DataFormatString = "yyyy/MM/dd", ApplyFormatInEditMode = false)] public DateTime StartDateLocal => StartDate.ToLocalTime(); [DataType(DataType.DateTime)] [Display(Name = "End Date")] [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = false)] public DateTime EndDate { get; set; } [DataType(DataType.DateTime)] [Display(Name = "End Date")] [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = false)] public DateTime EndDateLocal => EndDate.ToLocalTime(); [DisplayName("Is Active?")] public bool IsActive { get; set; } [DisplayName("Logo")] public string LogoPath { get; set; } public ICollection<GroupEntity> Groups { get; set; } } } <file_sep>/Soccer.Web/Data/Entities/MatchEntity.cs using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; namespace Soccer.Web.Data.Entities { public class MatchEntity { public int Id { get; set; } public DateTime Date { get; set; } public DateTime DateLocal => Date.ToLocalTime(); public Team Local { get; set; } public Team Visitor { get; set; } [DisplayName("Goals Local")] public int GoalsLocal { get; set; } [DisplayName("Goals Visitor")] public int GoalsVisitor { get; set; } [DisplayName("Is Closed?")] public bool IsClosed { get; set; } public GroupEntity Group { get; set; } public ICollection<PredictionEntity> Predictions { get; set; } } } <file_sep>/Soccer.Web/Models/TeamViewModel.cs using Microsoft.AspNetCore.Http; using Soccer.Web.Data.Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace Soccer.Web.Models { public class TeamViewModel : Team { [DisplayName("Logo")] public IFormFile LogoFile { get; set; } } } <file_sep>/Soccer.Web/Data/DataContext.cs using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Soccer.Web.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Soccer.Web.Data { public class DataContext : IdentityDbContext<UserEntity> { public DataContext(DbContextOptions<DataContext>options) : base(options) { } public DbSet<GroupDetailEntity> GroupDetails { get; set; } public DbSet<GroupEntity> Groups { get; set; } public DbSet<MatchEntity> Matches { get; set; } public DbSet<PredictionEntity> Predictions { get; set; } public DbSet<Team> Teams { get; set; } internal object Include(Func<object, object> p) { throw new NotImplementedException(); } public DbSet<TournamentEntity> Tournaments { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Team>() .HasIndex(t => t.Name) .IsUnique(); } } } <file_sep>/Soccer.Web/Data/Entities/GroupEntity.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Soccer.Web.Data.Entities { public class GroupEntity { public int Id { get; set; } public string Name { get; set; } public TournamentEntity Tournament { get; set; } public ICollection<GroupDetailEntity> GroupDetails { get; set; } public ICollection<MatchEntity> Matches { get; set; } } } <file_sep>/Soccer.Web/Data/Entities/Team.cs using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Soccer.Web.Data.Entities { public class Team { public int Id { get; set; } //[MaxLength(100, ErrorMessage = "El campo {0} no puede tener mas de {1] caracteres")] //[Required(ErrorMessage = "El campo {0} es obligario")] public string Name { get; set; } [Display(Name = "Logo")] public string LogoPath { get; set; } public ICollection<UserEntity> Users { get; set; } } }
0a73492d1c6bcdc6e597b017f8e39ff9eb391fb0
[ "C#" ]
6
C#
javier206/AppSoccer_Xamarin_Forms_and_ASP_Core
45e77d394fbca605e67e02df7f52f1231590de53
83580c8b269df984e4afac2ca57f8cf84c2ad2bd
refs/heads/master
<file_sep>import { Body, Controller, Get, Patch, Post, Query, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { Context } from '../decorators/context.decorator'; import { User } from '../models/user'; import { CreateTrade, QueryTrade } from '../../../common/dto/trades.dto'; import { ITrade } from '../../../common/models/ITrade'; import { Trade } from '../models/trade'; import { TradePayment } from '../../../common/enums'; import moment = require('moment'); @Controller('trades') @UseGuards(AuthGuard()) export class TradesController { @Get('') async findTrades( @Context('user') user: User, @Query('filter') filter: QueryTrade, ): Promise<ITrade[]> { return []; } @Post('') async createTrade( @Context('user') user: User, @Body('trade') trade: CreateTrade, ): Promise<ITrade> { return Trade.query().insertGraph({ ...trade, userId: user.id, createdAt: moment(), paymentInd: TradePayment.Unattempted, }); } @Patch(':tradeId/:orderId') async cancelOrder(@Context('user') user: User): Promise<void> { return; } } <file_sep>import { Test, TestingModule } from '@nestjs/testing'; import { AppModule } from '../../src/app/app.module'; import { INestApplication } from '@nestjs/common'; import * as supertest from 'supertest'; import { MessageService } from '../../src/app/services/message.service'; import { SecretCode } from '../../src/app/models/secret_code'; import { MessagePurpose } from '../../common/enums'; describe('VericodeController (e2e)', () => { let app: INestApplication; let messageService: MessageService; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); messageService = app.get(MessageService); }); beforeEach(() => { jest.clearAllMocks(); }); it('/vericode (GET) return 400', async () => { // set up jest.spyOn(messageService, 'send').mockResolvedValue({ status: 'success', send_id: '093c0a7df143c087d6cba9cdf0cf3738', fee: 1, sms_credits: 14197, }); const response: supertest.Response = await supertest(app.getHttpServer()) .get( '/vericode?target=<EMAIL>&purpose=email_verification&code=715619', ) .set('Accept', 'application/json'); expect(response.badRequest).toBeTruthy(); }); it('/vericode (GET) return 200', async () => { // setup jest.spyOn(messageService, 'send').mockResolvedValue({ status: 'success', send_id: '093c0a7df143c087d6cba9cdf0cf3738', fee: 1, sms_credits: 14197, }); const email = '<EMAIL>'; const purpose = MessagePurpose.EmailVerification; await supertest(app.getHttpServer()) .post('/vericode') .set('Accept', 'application/json') .send({ target: email, purpose, channel: 'email', recipient: email, codeOptions: { expire: 5 }, }); const secretCode = await SecretCode.findUnexpiredByKey(email, purpose); console.log(secretCode); // action const response: supertest.Response = await supertest(app.getHttpServer()) .get( `/vericode?target=${email}&purpose=${purpose}&code=${secretCode.code}`, ) .set('Accept', 'application/json'); expect(response.ok).toBeTruthy(); // clean up await secretCode.$query().delete(); }); }); <file_sep>import { LoggerService as NestLoggerService, Injectable } from '@nestjs/common'; import * as winston from 'winston'; import { RuntimeService } from './runtime.service'; @Injectable() export class LoggerService implements NestLoggerService { private readonly winstonLogger: winston.Logger; constructor(private runtime: RuntimeService) { const { log } = this.runtime.getConfig(); const logLevel = log.level || 'info'; const logFormat = log.format || 'simple'; this.winstonLogger = winston.createLogger({ level: logLevel, transports: [ new winston.transports.Console(), // new winston.transports.File({ filename: 'app.log' }) ], format: this.getFormat(logFormat), }); } private getFormat(name: string) { const { combine, timestamp, label, json, padLevels, prettyPrint, colorize, splat, printf, } = winston.format; let format; if (name === 'simple') { format = combine( colorize(), splat(), timestamp({ format: 'YYYY/MM/DD HH:mm:ss.SSSSSS' }), padLevels(), prettyPrint(), printf( info => `[${this.runtime.getConfig().name}] ${info.level} ${ info.timestamp } ${(info.context || 'app:nest').padEnd(10, ' ')} | ${ info.message }`, ), ); } if (name === 'json') { format = combine( splat(), timestamp({ format: 'YYYY/MM/DD HH:mm:ss.SSSSSS' }), json(), ); if (this.runtime.getManifest().environment === 'development') { format = combine(format, prettyPrint()); } } return format; } get logger(): winston.Logger | null { if (!this.winstonLogger) { console.error('logger has not been intialised yet!'); return null; } return this.winstonLogger; } log(message: string) { this.winstonLogger.info(message); } error(message: string, trace: string) { this.winstonLogger.error(message + trace); } warn(message: string) { this.winstonLogger.warn(message); } } <file_sep>import { IProduct } from './IProduct'; import { Moment } from 'moment'; import { IShop } from './IShop'; import { ITrade } from './ITrade'; export interface IOrder { id: number; tradeId: number; shopId: number; productId: number; productionSnapshot: IProduct; quantity: number; price: number; bookDate: Moment; bookStart: Moment; bookEnd: Moment; processInd: string; processUpdatedAt: Moment; shop: IShop; trade: ITrade; product: IProduct; } <file_sep>CREATE DOMAIN dict_code AS CHARACTER VARYING (30) NOT NULL CHECK (value !~ '\s'); CREATE DOMAIN url AS CHARACTER VARYING (200); CREATE DOMAIN phone AS CHARACTER VARYING (20); CREATE DOMAIN email AS CHARACTER VARYING (30); CREATE DOMAIN id as bigint NOT NULL; -- -- Name: district; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.district_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.district ( id id DEFAULT nextval('district_id_seq'), name character varying(270), parent_id smallint, initial character(3), initials character varying(30), pinyin character varying(600), extra character varying(60), suffix character varying(15), code character(30), area_code character varying(30), "order" smallint, PRIMARY KEY (id) ); ALTER SEQUENCE public.district_id_seq OWNED BY public.district.id; -- -- Name: user; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.user_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public."user" ( id id DEFAULT nextval('public.user_id_seq'), name character varying(50) NOT NULL, password character varying(200) NOT NULL, phone phone NOT NULL, email email NOT NULL, is_phone_verified boolean NOT NULL, is_email_verified boolean NOT NULL, created_at timestamp(6) with time zone NOT NULL, updated_at timestamp(6) with time zone, PRIMARY KEY (id) ); ALTER SEQUENCE public.user_id_seq OWNED BY public."user".id; -- -- Name: role; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.role_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.role ( id id DEFAULT nextval('public.role_id_seq'), name dict_code, scope dict_code, scope_id id, user_id id, PRIMARY KEY (id) ); ALTER SEQUENCE public.role_id_seq OWNED BY public.role.id; -- -- Name: user_verification; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.user_verification_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.user_verification ( id id DEFAULT nextval('public.user_verification_id_seq'), user_id id, legal_name character varying, id_card_copy url, driver_license_copy url, photo_copy url, is_realname_verified boolean NOT NULL, PRIMARY KEY (id) ); ALTER SEQUENCE public.user_verification_id_seq OWNED BY public.user_verification.id; -- -- Name: shop; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.shop_id_seq START WITH 10001 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.shop ( id id DEFAULT nextval('public.shop_id_seq'), name character varying(50) NOT NULL, province character varying(50) NOT NULL, city character varying(50) NOT NULL, suburb character varying(50) NOT NULL, district_code character(6) NOT NULL, address character varying(70) NOT NULL, geolocation point, announcement character varying(50), brand_logo url NOT NULL, is_invoice_supported boolean NOT NULL, business_hours jsonb NOT NULL, phone phone NOT NULL, PRIMARY KEY (id) ); ALTER SEQUENCE public.shop_id_seq OWNED BY public.shop.id; -- -- Name: shop_qualification; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.shop_qualification_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.shop_qualification ( id id DEFAULT nextval('public.shop_qualification_id_seq'), shop_id id, business_license_copy url NOT NULL, business_certificate_copy url NOT NULL, business_name character varying(200), business_address character varying(200), statutory_representative character varying(50), certificate_no character varying(50), business_scope text, expire_date date, signed_agreement_doc url, PRIMARY KEY (id) ); ALTER SEQUENCE public.shop_qualification_id_seq OWNED BY public.shop_qualification.id; -- -- Name: product; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.product_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.product ( id id DEFAULT nextval('public.product_id_seq'), shop_id id, name character varying(100) NOT NULL, description text, image character varying(200), introduction character varying(100), gallery jsonb, unit character varying(20) NOT NULL, price numeric(8,2) NOT NULL, rrp numeric(8,2), is_online boolean NOT NULL, type dict_code, PRIMARY KEY (id) ); ALTER SEQUENCE public.product_id_seq OWNED BY public.product.id; -- -- Name: category; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.category_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.category ( id id DEFAULT nextval('category_id_seq'), shop_id id, name character varying(50) NOT NULL, "order" integer NOT NULL ); ALTER SEQUENCE public.category_id_seq OWNED BY public.category.id; -- -- Name: product_category; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.product_category_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.product_category ( id id DEFAULT nextval('public.product_category_id_seq'), product_id id, category_id id, PRIMARY KEY (id) ); ALTER SEQUENCE public.product_category_id_seq OWNED BY public.product_category.id; -- -- Name: trade; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.trade_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.trade ( id id DEFAULT nextval('public.trade_id_seq'), amount numeric(8,1) NOT NULL, payment_ind dict_code, user_id id, created_at timestamp(6) with time zone NOT NULL, payment_updated_at timestamp(6) with time zone, PRIMARY KEY (id) ); ALTER SEQUENCE public.trade_id_seq OWNED BY public.trade.id; -- -- Name: order; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.order_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public."order" ( id id DEFAULT nextval('public.order_id_seq'), trade_id id, shop_id id, product_id id, product_snapshot jsonb NOT NULL, quantity integer DEFAULT 1 NOT NULL, price integer NOT NULL, book_date date, book_start time(6) with time zone, book_end time(6) with time zone, process_ind dict_code, process_updated_at timestamp(6) with time zone, PRIMARY KEY (id) ); ALTER SEQUENCE public.order_id_seq OWNED BY public."order".id; -- -- cart -- CREATE SEQUENCE public.cart_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.cart ( id id DEFAULT nextval('public.cart_id_seq'), user_id id, product_id id, quantity int, PRIMARY KEY (id), UNIQUE (user_id) ); ALTER SEQUENCE public.cart_id_seq OWNED BY public.cart.id; -- -- Name: product_rating; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.product_rating_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.product_rating ( id id DEFAULT nextval('public.product_rating_id_seq'), order_id id, shop_id id, product_id id, rating numeric(2,1) NOT NULL, comment text, user_id id, created_at timestamp(6) with time zone NOT NULL, PRIMARY KEY (id) ); ALTER SEQUENCE public.product_rating_id_seq OWNED BY public.product_rating.id; -- -- Name: shop_rating; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.shop_rating_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.shop_rating ( id id DEFAULT nextval('public.shop_rating_id_seq'), shop_id id, trade_id id, rating numeric(2,1) NOT NULL, comment text, user_id id, created_at timestamp(6) with time zone NOT NULL, PRIMARY KEY (id) ); ALTER SEQUENCE public.shop_rating_id_seq OWNED BY public.shop_rating.id; -- -- Name: favorite; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.favorite_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.favorite ( id id DEFAULT nextval('favorite_id_seq'), user_id id, shop_id id, PRIMARY KEY (id) ); ALTER SEQUENCE public.favorite_id_seq OWNED BY public.favorite.id; -- -- Name: workflow_task; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.workflow_task_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.workflow_task ( id id DEFAULT nextval('public.workflow_task_id_seq'), workflow dict_code, data jsonb, process_ind dict_code, created_at timestamp(6) with time zone NOT NULL, updated_at timestamp(6) with time zone, PRIMARY KEY (id) ); ALTER SEQUENCE public.workflow_task_id_seq OWNED BY public.workflow_task.id; -- -- Name: workflow_step; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.workflow_step_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.workflow_step ( id id DEFAULT nextval('public.workflow_step_id_seq'), workflow_task_id id, last_step_id id DEFAULT -1, data jsonb, comment text, user_id id, created_at timestamp(6) with time zone NOT NULL, PRIMARY KEY (id) ); ALTER SEQUENCE public.workflow_step_id_seq OWNED BY public.workflow_step.id; -- -- Name: secret_code; Type: TABLE; Schema: public; Owner: - -- CREATE SEQUENCE public.secret_code_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.secret_code ( id id DEFAULT nextval('secret_code_id_seq'), target character varying NOT NULL, purpose dict_code, code character varying(50) NOT NULL, created_at timestamp(6) with time zone NOT NULL, expire_at timestamp(6) with time zone NOT NULL, PRIMARY KEY (id), UNIQUE (target, purpose) ); ALTER SEQUENCE public.secret_code_id_seq OWNED BY public.secret_code.id; -- -- PostgreSQL database dump complete -- <file_sep>import { IsArray, IsInt, IsString, Length, IsAlphanumeric, IsEmail, IsMobilePhone, IsNotEmpty, MaxLength, } from 'class-validator'; import { IRole } from '../models/IRole'; export class LoginInput { @IsString() @Length(5, 30) authname: string; @IsString() @Length(5, 30) password: string; } export class LoginOutput { @IsInt() id: number; @IsString() name: string; @IsString() token: string; @IsArray() roles: IRole[]; } export class SignupInput { @IsString() @IsNotEmpty() @MaxLength(30) name: string; @IsString() @IsNotEmpty() @MaxLength(50) @IsEmail() email: string; @IsString() @IsNotEmpty() @IsAlphanumeric() @MaxLength(6) emailVericode: string; @IsString() @IsNotEmpty() @IsMobilePhone('zh-CN') phone: string; @IsString() @IsNotEmpty() @IsAlphanumeric() @MaxLength(6) phoneVericode: string; @IsString() @IsNotEmpty() @Length(6, 30) password: string; } <file_sep>import { Injectable } from '@nestjs/common'; import * as pg from 'pg'; import * as knex from 'knex'; import * as objection from 'objection'; import { LoggerService } from './logger.service'; import * as moment from 'moment'; import { RuntimeService } from './runtime.service'; import knexTinyLogger from 'knex-tiny-logger'; @Injectable() export class KnexService { knex: knex; constructor(private runtime: RuntimeService, private logger: LoggerService) { this.initPostgres(); const { host, port, user, password, dbName: database, debug, } = this.runtime.getConfig().database; const kx = knex({ client: 'postgresql', connection: { host, port, user, password, database, debug, }, searchPath: ['public'], debug, pool: { min: 2, max: 20, }, // Merge `postProcessResponse` and `wrapIdentifier` mappers. // ...objection.knexSnakeCaseMappers(), }); this.knex = knexTinyLogger(kx, { // logger, }); // Give the connection to objection. objection.Model.knex(this.knex); this.checkDatabaseHealth(5000); } private checkDatabaseHealth(interval: number) { // quick check health this.knex .raw('SELECT 1') .then(res => { this.logger.logger.info('\x1b[35mDatabase service initialized\x1b[0m', { context: 'svc:knex', }); }) .catch(error => { this.logger.logger.error( '\x1b[35mDatabase service initialization failed\x1b[0m', { context: 'svc:knex' }, ); console.error(error); setTimeout(() => this.checkDatabaseHealth(interval), interval); }); } private initPostgres() { // select typname, oid, typarray from pg_type where typtype = 'b' order by oid const PG_NUMBERIC_OID = 1700; const PG_INT8_OID = 20; const PG_INT2_OID = 21; const PG_INT4_OID = 23; const PG_BOOL_OID = 16; const TIMESTAMPTZ_OID = 1184; const TIMESTAMP_OID = 1114; pg.types.setTypeParser(PG_INT8_OID, parseInt); pg.types.setTypeParser(PG_INT2_OID, parseInt); pg.types.setTypeParser(PG_INT4_OID, parseInt); pg.types.setTypeParser(PG_NUMBERIC_OID, parseFloat); pg.types.setTypeParser(PG_BOOL_OID, (val: any) => val === 'true'); pg.types.setTypeParser(TIMESTAMPTZ_OID, (val: any) => val ? moment(val) : null, ); pg.types.setTypeParser(TIMESTAMP_OID, (val: any) => val ? moment(val) : null, ); } } <file_sep>import { Moment } from 'moment'; import { IShop } from './IShop'; import { IProduct } from './IProduct'; import { IOrder } from './IOrder'; import { IUser } from './IUser'; export interface IProductRating { id: number; orderId: string; shopId: string; productId: string; rating: number; comment: string; userId: string; createdAt: Moment; shop: IShop; product: IProduct; order: IOrder; user: IUser; } <file_sep>CREATE TABLE public.payment ( id character varying(100) NOT NULL, bill_no id, purpose dict_code, html character varying(500), url character varying(500) NOT NULL, codeUrl character varying(500), req jsonb, res jsonb, is_success boolean NOT NULL, expire_at timestamp(6) with time zone NOT NULL, created_at timestamp(6) with time zone NOT NULL, PRIMARY KEY (id) ); CREATE SEQUENCE public.payment_webhook_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE TABLE public.payment_webhook ( id id DEFAULT nextval('public.payment_webhook_seq'), payment_id character varying(100) NOT NULL, total_fee bigint NOT NULL, is_success boolean NOT NULL, payload jsonb, created_at timestamp(6) with time zone NOT NULL, PRIMARY KEY (id) ); ALTER SEQUENCE public.payment_webhook_seq OWNED BY public."payment_webhook".id; <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { IPayment } from '../../../common/models/IPayment'; import { BillPurpose } from '../../../common/dto/payment.dto'; import { Moment } from 'moment'; import { IPaymentWebhook } from '../../../common/models/IPaymentWebhook'; export class PaymentWebhook extends Model implements IPaymentWebhook { id: number; paymentId: string; totalFee: number; createdAt: Moment; isSuccess: boolean; payload: any; // ---------------------------------- static tableName = 'payment_webhook'; static columnNameMappers = snakeCaseMappers(); } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import { ITrade } from '../../../common/models/ITrade'; import { TradePayment } from '../../../common/enums'; import { User } from './user'; import { Order } from './order'; export class Trade extends Model implements ITrade { id: number; amount: number; userId: number; createdAt: Moment; paymentInd: TradePayment; paymentUpdatedAt: Moment; order: Order[]; user: User; // ---------------------------------- static tableName = 'trade'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { return { orders: { relation: Model.HasManyRelation, modelClass: require('./order').Order, join: { from: 'trade.id', to: 'order.trade_id', }, }, user: { relation: Model.BelongsToOneRelation, modelClass: require('./user').User, join: { from: 'trade.user_id', to: 'user.id', }, }, }; } } <file_sep>import { IProduct } from './IProduct'; import { IShopQualification } from './IShopQualification'; import { ICategory } from './ICategory'; import { IShopRating } from './IShopRating'; import { Point } from '../Point'; import { BusinessHours } from '../BusinessHours'; export interface IShop { id: number; name: string; province: string; city: string; suburb: string; districtCode: string; address: string; geolocation: Point; announcement: string; brandLogo: string; isInvoiceSupported: boolean; businessHours: BusinessHours[]; phone: string; products: IProduct[]; qualification: IShopQualification; categories: ICategory[]; ratings: IShopRating[]; } <file_sep>import { Injectable, CanActivate, ExecutionContext, ForbiddenException, ReflectMetadata, UnauthorizedException, } from '@nestjs/common'; import { User } from '../models/user'; import { Shop } from '../models/shop'; import { Request } from 'express'; import { Reflector } from '@nestjs/core'; import { includes } from 'lodash'; import { RoleName, RoleScope } from '../../../common/enums'; @Injectable() export class RolesGuard implements CanActivate { constructor(private readonly reflector: Reflector) {} async canActivate(context: ExecutionContext): Promise<boolean> { const allowRoles = this.reflector.get<string[]>( 'roles', context.getHandler(), ); if (!allowRoles) { // no restrictions return true; } // double check authentications const req: Request = context.switchToHttp().getRequest(); const user: User = req.user; if (!user) { throw new UnauthorizedException({ error: '没有登录或token过期' }); } let roles = user.roles; if (!roles) { roles = await user.$relatedQuery('roles'); } console.debug('allow roles:', allowRoles); console.debug('actual roles', roles); let allow = false; roles.forEach(async role => { if (includes(allowRoles, role.name)) { allow = true; if (role.name === RoleName.ShopAdmin && role.scope === RoleScope.Shop) { req.shop = await Shop.query().findById(role.scopeId); } } }); if (!allow) { throw new ForbiddenException({ error: '未授权的操作' }); } return allow; } } export const Roles = (...roles: RoleName[]) => ReflectMetadata('roles', roles); <file_sep>import { Moment } from 'moment'; import { Workflow, WorkflowProcess } from '../enums'; import { WorkflowTaskData } from '../dto/workflow.dto'; import { IWorkflowStep } from './IWorkflowStep'; export interface IWorkflowTask { id: number; workflow: Workflow; data: WorkflowTaskData; processInd: WorkflowProcess; createdAt: Moment; updatedAt: Moment; steps: IWorkflowStep[]; } <file_sep>import { ValidationError } from 'class-validator'; import { HttpStatus } from '@nestjs/common'; // response structure the client side receives export interface IErrorResponse { statusCode: HttpStatus; message: string; error: IError; } export interface IError { code?: string; debug?: string; violations?: ValidationError[]; extra?: any; } <file_sep>import { Body, Controller, ForbiddenException, Param, Patch, Post, UseGuards, UseInterceptors, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { CreateTask, ReviewTask, WorkflowStepData, WorkflowTaskData, } from '../../../common/dto/workflow.dto'; import { Roles, RolesGuard } from '../guards/roles.guard'; import { RoleName, WorkflowProcess } from '../../../common/enums'; import { WorkflowTask } from '../models/workflow_task'; import { User } from '../models/user'; import { Context } from '../decorators/context.decorator'; import { WorkflowStep } from '../models/workflow_step'; import moment = require('moment'); import { TransactionInterceptor } from '../interceptors/transaction.interceptor'; import { Transaction } from 'objection'; import { WorkflowHandlerService } from '../services/workflow-handler.service'; @Controller('workflow') @UseGuards(AuthGuard(), RolesGuard) @UseInterceptors(TransactionInterceptor) export class WorkflowController { constructor(private workflowHandler: WorkflowHandlerService) {} @Post('tasks') async createTask( @Body() input: CreateTask, @Context('user') user: User, @Context('tx') tx: Transaction, ): Promise<WorkflowTask> { return await WorkflowTask.query(tx).insertGraph({ workflow: input.workflow, processInd: WorkflowProcess.Submitted, createdAt: moment(), steps: [ { data: input.data, userId: user.id, createdAt: moment(), }, ], }); } @Patch('tasks/:workflowTaskId/review') @Roles(RoleName.SystemAdmin) async reviewTask( @Body() input: ReviewTask, @Param('workflowTaskId') workflowTaskId: number, @Context('user') user: User, @Context('tx') tx: Transaction, ) { const step = await WorkflowStep.query(tx) .eager('task') .joinRelation<WorkflowStep>('task') .andWhere('workflow_task_id', workflowTaskId) .andWhere('task.process_ind', WorkflowProcess.Submitted) .orderBy('created_at', 'desc') .first(); if (!step) { throw new ForbiddenException('任务不存在或不能审阅'); } await WorkflowStep.query(tx).insert({ workflowTaskId, lastStepId: step.id, comment: input.comment, userId: user.id, createdAt: moment(), }); await step.task.$query().patch({ processInd: WorkflowProcess.Reviewed }); } @Patch('tasks/:workflowTaskId/update') async updateTask( @Body() input: WorkflowStepData, @Param('workflowTaskId') workflowTaskId: number, @Context('user') user: User, @Context('tx') tx: Transaction, ): Promise<void> { const step = await WorkflowStep.query(tx) .eager('task') .joinRelation<WorkflowStep>('task') .andWhere('workflow_task_id', workflowTaskId) .andWhere('task.process_ind', WorkflowProcess.Reviewed) .orderBy('created_at', 'desc') .first(); if (!step) { throw new ForbiddenException('任务不存在或不能修改'); } await WorkflowStep.query(tx).insert({ workflowTaskId, lastStepId: step.id, data: input, userId: user.id, createdAt: moment(), }); await step.task.$query(tx).patch({ processInd: WorkflowProcess.Submitted }); } @Patch('tasks/:workflowTaskId/approve') @Roles(RoleName.SystemAdmin) async approveTask( @Body() input: WorkflowTaskData, @Param('workflowTaskId') workflowTaskId: number, @Context('tx') tx: Transaction, ): Promise<void> { let task = await WorkflowTask.query(tx) .where('id', workflowTaskId) .andWhere('process_ind', WorkflowProcess.Submitted) .first(); if (!task) { throw new ForbiddenException(''); } const step = await WorkflowStep.query(tx) .eager('task') .joinRelation<WorkflowStep>('task') .andWhere('workflow_task_id', workflowTaskId) .orderBy('created_at', 'desc') .first(); // finish task = await WorkflowTask.query(tx).patchAndFetch({ data: input, processInd: WorkflowProcess.Finished, }); // trigger domain things await this.workflowHandler.handle(step, task, tx); } @Patch('tasks/:workflowTaskId/cancel') async cancelTask( @Param('workflowTaskId') workflowTaskId: number, @Context('user') user: User, @Context('tx') tx: Transaction, ): Promise<void> { const task = await WorkflowTask.query(tx) .where('id', workflowTaskId) .andWhere('user_id', user.id) .andWhere('process_ind', '!=', WorkflowProcess.Cancelled) .andWhere('process_ind', '!=', WorkflowProcess.Finished) .first(); if (!task) { throw new ForbiddenException(''); } await WorkflowTask.query(tx).patch({ processInd: WorkflowProcess.Cancelled, }); } } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import { IWorkflowStep } from '../../../common/models/IWorkflowStep'; import { WorkflowStepData } from '../../../common/dto/workflow.dto'; import { WorkflowTask } from './workflow_task'; import { User } from './user'; export class WorkflowStep extends Model implements IWorkflowStep { id: number; workflowTaskId: number; lastStepId: number; data: WorkflowStepData; comment: string; userId: number; createdAt: Moment; task: WorkflowTask; user: User; // ---------------------------------- static tableName = 'workflow_step'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { return { task: { relation: Model.BelongsToOneRelation, modelClass: require('./workflow_task').WorkflowTask, join: { from: 'workflow_step.workflow_task_id', to: 'workflow_task.id', }, }, lastStep: { relation: Model.BelongsToOneRelation, modelClass: WorkflowStep, join: { from: 'workflow_step.last_step_id', to: 'workflow_step.id', }, }, user: { relation: Model.BelongsToOneRelation, modelClass: require('./user').User, join: { from: 'workflow_step.user_id', to: 'user.id', }, }, }; } } <file_sep>import { Test, TestingModule } from '@nestjs/testing'; import { ShopController } from './shop.controller'; // import { AppService } from '../services/app.service'; describe('ShopController', () => { let app: TestingModule; beforeAll(async () => { app = await Test.createTestingModule({ controllers: [ShopController], providers: [], }).compile(); }); describe('loadShop', () => { it('should return "Hello World!"', () => { const shopController = app.get<ShopController>(ShopController); expect(true).toBe(true); }); }); }); <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import { IShopRating } from '../../../common/models/IShopRating'; import { IShop } from '../../../common/models/IShop'; import { ITrade } from '../../../common/models/ITrade'; import { IUser } from '../../../common/models/IUser'; import { User } from './user'; import { Trade } from './trade'; import { Shop } from './shop'; export class ShopRating extends Model implements IShopRating { id: number; shopId: number; tradeId: number; rating: number; comment: string; userId: number; createdAt: Moment; shop: Shop; trade: Trade; user: User; // ---------------------------------- static tableName = 'shop_rating'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { return { shop: { relation: Model.BelongsToOneRelation, modelClass: require('./shop').Shop, join: { from: 'shop_rating.shop_id', to: 'shop.id', }, }, trade: { relation: Model.BelongsToOneRelation, modelClass: require('./trade').Trade, join: { from: 'shop_rating.trade_id', to: 'trade.id', }, }, user: { relation: Model.HasOneRelation, modelClass: require('./user').User, join: { from: 'product_rating.user_id', to: 'user.id', }, }, }; } } <file_sep>import { IShop } from './IShop'; export interface ICategory { id: number; shopId: number; name: string; order: number; shop: IShop; } <file_sep>import { Moment } from 'moment'; import { Model, snakeCaseMappers } from 'objection'; import { ISecretCode } from '../../../common/models/ISecretCode'; import { MessagePurpose } from '../../../common/enums'; export class SecretCode extends Model implements ISecretCode { id: number; target: string; purpose: MessagePurpose; code: string; createdAt: Moment; expireAt: Moment; // ---------------------------------- static tableName = 'secret_code'; static columnNameMappers = snakeCaseMappers(); static async findUnexpiredByKey(target: string, purpose: MessagePurpose) { // clean expired vericode const numDeleted = await SecretCode.query() .delete() .where('target', target) .andWhere('purpose', purpose) .andWhereRaw('expire_at <= current_timestamp'); return await SecretCode.query() .where('target', target) .andWhere('purpose', purpose) .first(); } static async verifyCode( target: string, purpose: MessagePurpose, code: string, ): Promise<boolean> { const secretCode = await SecretCode.findUnexpiredByKey(target, purpose); return secretCode && secretCode.code === code; } } <file_sep>import 'source-map-support/register'; import { NestFactory, HTTP_SERVER_REF } from '@nestjs/core'; import { ValidationPipe } from '@nestjs/common'; import * as helmet from 'helmet'; import { AppModule } from './app/app.module'; import { LoggerService } from './app/services/logger.service'; import { AllExceptionsFilter } from './app/filters/allexceptions.filter'; import { RuntimeService } from './app/services/runtime.service'; async function bootstrap() { const app = await NestFactory.create(AppModule, { // logger: false }); const log = app.get(LoggerService); app.useLogger(log); app.use(helmet()); app.useGlobalFilters(new AllExceptionsFilter(app.get(HTTP_SERVER_REF))); app.useGlobalPipes( new ValidationPipe({ // whitelist: true, transform: true, }), ); // server settings const { server, cors } = app.get(RuntimeService).getConfig(); const { host, port } = server; // cors app.enableCors({ origin: cors.origin }); // start app await app.listen(port, host, () => { log.logger.info(`Server listening on 👉 http://${host}:${port} ${process.env.DEPLOY_ENV}`, { context: 'app:server', }); }); } bootstrap(); <file_sep>import { Moment } from 'moment'; import { MessagePurpose } from '../enums'; export interface ISecretCode { id: number; target: string; purpose: MessagePurpose; code: string; createdAt: Moment; expireAt: Moment; } <file_sep>import { Body, Controller, Get, NotFoundException, Param, Patch, Post, Query, UseGuards, } from '@nestjs/common'; import * as _ from 'lodash'; import { Roles, RolesGuard } from '../guards/roles.guard'; import { AuthGuard } from '@nestjs/passport'; import { Category } from '../models/category'; import { Product } from '../models/product'; import { Order } from '../models/order'; import { CreateCategory, CreateProduct, UpdateCategory, UpdateOrder, UpdateProduct, UpdateShop, } from '../../../common/dto/shop.dto'; import { Shop } from '../models/shop'; import { classToPlain } from 'class-transformer'; import { Context } from '../decorators/context.decorator'; import { ICategory } from '../../../common/models/ICategory'; import { IOrder } from '../../../common/models/IOrder'; import { IProduct } from '../../../common/models/IProduct'; import { OrderProcess, RoleName, TradePayment } from '../../../common/enums'; import moment = require('moment'); import { QueryTrade } from '../../../common/dto/trades.dto'; @Controller('shop') @UseGuards(AuthGuard(), RolesGuard) @Roles(RoleName.ShopAdmin) export class ShopController { @Get() findShop(@Context('shop') shop: Shop) { return shop; } @Patch() async updateShop( @Body() input: UpdateShop, @Context('shop') shop: Shop, ): Promise<Shop> { return await shop .$query() .patch(input) .returning('*'); } @Post('categories') async createCategory( @Context('shop') shop: Shop, @Body() payload: CreateCategory, ): Promise<ICategory> { const fields = ['name', 'order']; return await shop .$relatedQuery<Category, Category[]>('categories') .insert(_.pick(payload, fields)) .returning('*'); } @Patch('categories/:categoryId') async updateCategory( @Context('shop') shop: Shop, @Param('categoryId') categoryId: number, @Body() input: UpdateCategory, ): Promise<ICategory> { const category = await Category.query() .findById(categoryId) .andWhere('shop_id', shop.id); if (!category) { throw new NotFoundException('类别不存在'); } return await category .$query() .patch(input) .returning('*'); } @Post('products') async createProduct( @Context('shop') shop: Shop, @Body() input: CreateProduct, ): Promise<IProduct> { return await shop .$relatedQuery<Product, Product[]>('products') .insert(input) .returning('*'); } @Patch('products/:productId') async updateProduct( @Context('shop') shop: Shop, @Param('productId') productId: number, @Body() input: UpdateProduct, ): Promise<IProduct> { const product = await Product.query() .findById(productId) .andWhere('shop_id', shop.id); if (!product) { throw new NotFoundException('产品不存在'); } return await product .$query() .patch(input) .returning('*'); } @Get('orders') async findOrders( @Context('shop') shop: Shop, @Query('fetch') fetch: string = '', @Query('filter') filter: QueryTrade, ): Promise<IOrder[]> { if (!filter) { filter = new QueryTrade(); filter.paymentInd = TradePayment.Success; filter.processInd = OrderProcess.Submitted; } return await Order.query() .join('trade', 'order.trade_id', 'trade.id') .where('shop_id', shop.id) .andWhere('trade.payment_ind', filter.paymentInd) .andWhere('process_ind', filter.processInd); } @Patch('orders/:orderId') async processOrder( @Context('shop') shop: Shop, @Param('orderId') orderId: number, @Body() input: UpdateOrder, ): Promise<IOrder> { const order: Partial<Order> = classToPlain(input); order.processUpdatedAt = moment(); return await Order.query() .patch(order) .findById(orderId) .andWhere('shop_id', shop.id) .returning('*'); } } <file_sep>import { Controller, Get } from '@nestjs/common'; import { RuntimeService } from '../services/runtime.service'; @Controller() export class AppController { constructor(private runtime: RuntimeService) {} @Get('health') healthCheck() { return { status: 'UP', }; } @Get('manifest') manifest() { return this.runtime.getManifest(); } } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import { IProductRating } from '../../../common/models/IProductRating'; import { IOrder } from '../../../common/models/IOrder'; import { User } from './user'; import { Shop } from './shop'; import { Product } from './product'; import { Order } from './order'; export class ProductRating extends Model implements IProductRating { id: number; orderId: string; shopId: string; productId: string; rating: number; comment: string; userId: string; createdAt: Moment; order: Order; product: Product; shop: Shop; user: User; // ---------------------------------- static tableName = 'product_rating'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { return { shop: { relation: Model.BelongsToOneRelation, modelClass: require('./shop').Shop, join: { from: 'product_rating.shop_id', to: 'shop.id', }, }, product: { relation: Model.BelongsToOneRelation, modelClass: require('./product').Product, join: { from: 'product_rating.product_id', to: 'product.id', }, }, order: { relation: Model.BelongsToOneRelation, modelClass: require('./order').Order, join: { from: 'product_rating.order_id', to: 'order.id', }, }, user: { relation: Model.HasOneRelation, modelClass: require('./user').User, join: { from: 'product_rating.user_id', to: 'user.id', }, }, }; } } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { IUserVerification } from '../../../common/models/IUserVerifcation'; export class UserVerfication extends Model implements IUserVerification { id: number; userId: number; legalName: string; idCard: string; driverLicenseCopy: string; photoCopy: string; isRealnameVerified: boolean; // ---------------------------------- static tableName = 'user_verification'; static columnNameMappers = snakeCaseMappers(); } <file_sep>import { BadRequestException, Body, Controller, Get, Post, Query, } from '@nestjs/common'; import * as randomstring from 'randomstring'; import { SecretCode } from '../models/secret_code'; import { LoggerService } from '../services/logger.service'; import * as moment from 'moment'; import * as _ from 'lodash'; import { MessagePurpose } from '../../../common/enums'; import { CreateVericode } from '../../../common/dto/vericode.dto'; import { MessageService } from '../services/message.service'; @Controller('vericode') export class VericodeController { constructor( private messageService: MessageService, private logger: LoggerService, ) {} @Post('') async createVericode(@Body() input: CreateVericode): Promise<void> { const secretCode = await SecretCode.findUnexpiredByKey( input.target, input.purpose, ); if (secretCode) { throw new BadRequestException( `验证码已发送且仍在有效期,请${input.codeOptions.expire}分钟后再试`, ); } const defaultCodeOptions = { length: 6, charset: 'numeric', capitalization: 'uppercase', }; const code = randomstring.generate( _.defaults(input.codeOptions, defaultCodeOptions), ); await this.messageService.send( input.purpose, input.channel, input.recipient, { code, expire: input.codeOptions.expire }, ); const createdAt = moment(); const expireAt = moment(createdAt).add(input.codeOptions.expire, 'minutes'); await SecretCode.query().insert({ target: input.target, purpose: input.purpose, code, createdAt, expireAt, }); } @Get('') async verify( @Query('target') target: string, @Query('purpose') purpose: MessagePurpose, @Query('code') code: string, ): Promise<void> { const vericode = await SecretCode.findUnexpiredByKey(target, purpose); if (!vericode) { throw new BadRequestException('验证码不存在或已过期'); } if (vericode.code !== code) { throw new BadRequestException('验证码不正确'); } } } <file_sep>import { BadRequestException, Body, Controller, ForbiddenException, Post, } from '@nestjs/common'; import { pick } from 'lodash'; import { JwtService } from '@nestjs/jwt'; import { sh256 } from '../../utils/crypto'; import { User } from '../models/user'; import { SecretCode } from '../models/secret_code'; import { plainToClass } from 'class-transformer'; import { DeployEnv, RuntimeService } from '../services/runtime.service'; import { LoginInput, LoginOutput, SignupInput, } from '../../../common/dto/auth.dto'; import { JwtPayload } from '../services/jwt.strategy'; import { MessagePurpose } from '../../../common/enums'; import { IError } from '../../../common/response'; @Controller('auth') export class AuthController { constructor( private readonly jwt: JwtService, private readonly runtime: RuntimeService, ) {} @Post('login') async login(@Body() input: LoginInput): Promise<LoginOutput> { const user = await User.query() .whereRaw('password = ? and (email = ? or phone = ?)', [ sh256(input.password, this.runtime.getConfig().auth.passwordSecret), input.authname, input.authname, ]) .eager('[roles]') .first(); if (user) { const token = this.jwt.sign({ id: user.id, name: user.name, email: user.email, phone: user.phone, } as JwtPayload); return plainToClass(LoginOutput, { token, name: user.name, id: user.id, roles: user.roles, }); } else { throw new ForbiddenException({ message: '用户名或密码不正确', } as IError); } } @Post('signup') async signup(@Body() input: SignupInput): Promise<void> { let user = await User.query() .where('email', input.email) .first(); if (user) { throw new BadRequestException('邮箱已注册'); } user = await User.query() .where('phone', input.phone) .first(); if (user) { throw new BadRequestException('手机已注册'); } // skip verification in development if (this.runtime.getManifest().environment !== DeployEnv.development) { if ( !SecretCode.verifyCode( input.email, MessagePurpose.EmailVerification, input.emailVericode, ) ) { throw new BadRequestException('邮件验证码不正确'); } if ( !SecretCode.verifyCode( input.phone, MessagePurpose.PhoneVerification, input.phoneVericode, ) ) { throw new BadRequestException('手机验证码不正确'); } } input.password = <PASSWORD>( input.password, this.runtime.getConfig().auth.passwordSecret, ); user = plainToClass( User, pick(input, ['name', 'email', 'phone', 'password']), ); user.isEmailVerified = true; user.isPhoneVerified = true; await User.query().insert(user); } } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import moment = require('moment'); import { IUser } from '../../../common/models/IUser'; import { Role } from './role'; import { Product } from './product'; export type CartItem = Product & { quantity: number }; export class User extends Model implements IUser { id: number; name: string; // password: string; phone: string; email: string; isPhoneVerified: boolean; isEmailVerified: boolean; createdAt: Moment; updatedAt: Moment; roles: Role[]; cartItems: CartItem[]; // ---------------------------------- static tableName = 'user'; static columnNameMappers = snakeCaseMappers(); $formatJson(json: any) { // Remember to call the super class's implementation. json = super.$formatJson(json); // Do your conversion here. delete json.password; return json; } $beforeInsert() { this.createdAt = moment(); } $beforeUpdate() { this.updatedAt = moment(); } static get relationMappings() { return { roles: { relation: Model.HasManyRelation, modelClass: require('./role').Role, join: { from: 'user.id', to: 'role.user_id', }, }, cartItems: { relation: Model.ManyToManyRelation, modelClass: require('./product').Product, join: { from: 'user.id', through: { from: 'cart.user_id', to: 'cart.product_id', extra: ['quantity'], }, to: 'product.id', }, }, }; } } <file_sep>import { BadRequestException, Injectable } from '@nestjs/common'; import axios, { AxiosRequestConfig } from 'axios'; import * as qs from 'qs'; import { RuntimeService } from './runtime.service'; import { MessageChannel, MessagePurpose } from '../../../common/enums'; @Injectable() export class MessageService { constructor(private runtime: RuntimeService) {} async send( purpose: MessagePurpose, channel: MessageChannel, to: string, vars: Vars, ) { const requestConfig: AxiosRequestConfig = { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }; const { mail, sms } = this.runtime.getConfig(); const { appid, appkey } = channel === MessageChannel.Sms ? sms : mail; const response = await axios.post( mail.apiUri, qs.stringify({ appid, signature: appkey, to, project: findTemplate(purpose, channel), vars, }), requestConfig, ); if (response.data.status === 'success') { return response.data; } throw new BadRequestException('发送邮件失败', response.data); } } export interface Vars { code?: string; expire?: number; time?: number; } enum Template { MailVerification = 'BVmmE', PhoneVerification = 'En5tj', } interface DeliveryEntry { purpose: MessagePurpose; channel: MessageChannel; template: Template; } const deliveryConfigs: DeliveryEntry[] = [ { purpose: MessagePurpose.EmailVerification, channel: MessageChannel.Email, template: Template.MailVerification, }, { purpose: MessagePurpose.PhoneVerification, channel: MessageChannel.Sms, template: Template.PhoneVerification, }, ]; function findTemplate( purpose: MessagePurpose, channel: MessageChannel, ): Template { const deliveryEntry = deliveryConfigs.find( entry => entry.purpose === purpose && entry.channel === channel, ); if (!deliveryEntry) { throw new BadRequestException(`不支持的发送渠道: ${purpose} ${channel}`); } return deliveryEntry.template; } <file_sep>import { Controller, Get, NotFoundException, Query, Param, } from '@nestjs/common'; import { Shop } from '../models/shop'; import { Product } from '../models/product'; @Controller('shops') export class ShopsController { @Get() async listShops() { const shops = await Shop.query(); return shops; } // TODO @Get(':shopId') async findShop( @Param('shopId') shopId: number, @Query('fetch') fetch: string = '', ) { const shop = await Shop.query() .findById(shopId) .eager(fetch); if (!shop) { throw new NotFoundException({ error: '店面不存在' }); } return shop; } @Get(':shopId/ratings') async findShopRatingsWithPaging( @Param('shopId') shopId: number, @Query('fetch') fetch: string = '', @Query('page') page: number = 1, @Query('limit') limit: number = 50, ) { const shop = await Shop.query().findById(shopId); if (!shop) { throw new NotFoundException({ error: '店面不存在' }); } const ratings = await shop .$relatedQuery('ratings') .page(page - 1, limit) .eager(fetch); return ratings; } @Get(':shopId/products/:productId') async findProduct( @Param('productId') productId: number, @Param('shopId') shopId: number, @Query('fetch') fetch: string = '', ) { const product = await Product.query() .where('id', productId) .andWhere('shop_id', shopId) .eager(fetch) .first(); if (!product) { throw new NotFoundException({ error: '产品不存在' }); } return product; } @Get(':shopId/products/:productId/ratings') async findProductRatingsWithPaging( @Param('shopId') shopId: number, @Param('productId') productId: number, @Query('fetch') fetch: string = '', @Query('page') page: number = 1, @Query('limit') limit: number = 50, ) { const product = await Product.query() .where('id', productId) .andWhere('shop_id', shopId) .first(); if (!product) { throw new NotFoundException({ error: '产品不存在' }); } const ratings = await product .$relatedQuery('ratings') .page(page - 1, limit) .eager(fetch); return ratings; } } <file_sep>import * as crypto from 'crypto'; export function md5(data) { return crypto .createHash('md5') .update(data) .digest('hex'); } export function sh256(data, secret) { return crypto .createHmac('sha256', secret) .update(data) .digest('hex'); } <file_sep>export class AddCartItem { productId: number; quantity: number; } export class UpdateCartItem { quantity: number; } <file_sep>import { RoleName, RoleScope } from '../enums'; export interface IRole { id: number; name: RoleName; scope: RoleScope; scopeId: number; } <file_sep>export enum BillChannel { AlipayWeb = 'ALI_WEB', WechatWeb = 'WX_JSAPI', AlipayWap = 'ALI_WAP', AlipayCode = 'ALI_QRCODE', } export enum BillPurpose { Trade = 'trade', ShopFee = 'shop_fee', ShopBill = 'shop_bill', } export class WebBill { channel: BillChannel; totalFee: number; // total_fee(int 类型) 单位分 billNo: string; // 8到32位数字和/或字母组合,请自行确保在商户系统中唯一,同一订单号不可重复提交,否则会造成订单重复 title: string; // title UTF8编码格式,32个字节内,最长支持16个汉字 returnUrl?: string; showUrl?: string; openid?: string; purpose: BillPurpose; } export class WebBillRes { html?: string; url: string; codeUrl?: string; } export enum TransferChannel { AlipayTransfer = 'ALI_TRANSFER', WechatTransfer = 'WX_TRANSFER', } export class WebTransfer { channel: TransferChannel; totalFee: number; // total_fee(int 类型) 单位分 transferNo: string; // 8到32位数字和/或字母组合,请自行确保在商户系统中唯一,同一订单号不可重复提交,否则会造成订单重复 desc: string; // title UTF8编码格式,32个字节内,最长支持16个汉字 channelUserId: string; // 支付渠道方内收款人的标示, 微信为openid, 支付宝为支付宝账户 channelUserName: string; // 支付渠道内收款人账户名, 支付宝必填 } export class WebTransferRes { url: string; } export enum WebhookChannelType { Wechat = 'WX', Alipay = 'ALI', } export enum WebhookSubChannelType { AlipayWeb = 'ALI_WEB', AlipayCode = 'ALI_QRCODE', AlipayTransfer = 'ALI_TRANSFER', } export enum WebhookTransactionType { Pay = 'PAY', REFUND = 'REFUND', } export class Webhook { signature: string; timestamp: number; channel_type: WebhookChannelType; sub_channel_type: WebhookSubChannelType; transaction_type: WebhookTransactionType; transaction_id: string; // 对应支付请求的bill_no或者退款请求的refund_no transaction_fee: number; // 1 表示0.01元 bill_fee: number; // 1 表示0.01元 discount: number; // 1 表示0.01元 coupon_id: string; trade_success: boolean; message_detail: any; optional: { purpose: BillPurpose }; } // money unit in beecloud is cent export const MONEY_BY_CENTS = 100; export const WEB_HOOK_DONT_SEND = 'success'; export const WEB_HOOK_RESEND = 'resend'; <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { IRole } from '../../../common/models/IRole'; import { RoleName, RoleScope } from '../../../common/enums'; export class Role extends Model implements IRole { id: number; name: RoleName; scope: RoleScope; scopeId: number; userId: number; // ---------------------------------- static tableName = 'role'; static columnNameMappers = snakeCaseMappers(); } <file_sep>import { Injectable } from '@nestjs/common'; import { BillPurpose, MONEY_BY_CENTS, Webhook, } from '../../../common/dto/payment.dto'; import { User } from '../models/user'; import { Trade } from '../models/trade'; import { TradePayment } from '../../../common/enums'; import moment = require('moment'); @Injectable() export class PaymentHandlerService { async onBill( user: User, billNo: number, amount: number, purpose: BillPurpose, ): Promise<boolean> { // VALIDATE USER AND TRADE if (purpose === BillPurpose.ShopBill) { const trade = await Trade.query() .findById(billNo) .andWhere('user_id', user.id) .andWhere('amount', amount); if (trade) { trade.$query().update({ paymentInd: TradePayment.Attempted, paymentUpdatedAt: moment(), }); } } return false; } async onWebhook(hook: Webhook): Promise<boolean> { const { transaction_id, transaction_fee } = hook; if (hook.optional.purpose === BillPurpose.ShopBill) { const tradeId = parseInt(transaction_id, 10); const amount = (transaction_fee / MONEY_BY_CENTS).toFixed(2); const trade = await Trade.query() .findById(tradeId) .andWhere('amount', amount); if (trade) { trade.$query().update({ paymentInd: hook.trade_success ? TradePayment.Success : TradePayment.Failure, paymentUpdatedAt: moment(), }); return true; } } return false; } } <file_sep>import { Controller, Post } from '@nestjs/common'; @Controller('settings') export class SettingsController { @Post('/reset') async resetPassword() { return ''; } } <file_sep>import { Moment } from 'moment'; import { IWorkflowTask } from './IWorkflowTask'; import { IUser } from './IUser'; export interface IWorkflowStep { id: number; workflowTaskId: number; lastStepId: number; data: any; comment: string; userId: number; createdAt: Moment; task: IWorkflowTask; user: IUser; } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { IPayment } from '../../../common/models/IPayment'; import { BillPurpose } from '../../../common/dto/payment.dto'; import { Moment } from 'moment'; export class Payment extends Model implements IPayment { id: string; billNo: number; purpose: BillPurpose; html: string; url: string; codeUrl: string; req: any; res: any; isSuccess: boolean; expireAt: Moment; createdAt: Moment; // ---------------------------------- static tableName = 'payment'; static columnNameMappers = snakeCaseMappers(); } <file_sep>describe('Payment Controller', () => { // let controller: PaymentController; beforeEach(() => { // const module: TestingModule = await Test.createTestingModule({ // controllers: [PaymentController], // }).compile(); // // controller = module.get<PaymentController>(PaymentController); }); it('should be defined', () => { // expect(controller).toBeDefined(); expect(1).toEqual(1); }); }); <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { IShop } from '../../../common/models/IShop'; import { Point } from '../../../common/Point'; import { BusinessHours } from '../../../common/BusinessHours'; import { Product } from './product'; import { Category } from './category'; import { ShopQualification } from './shop_qualification'; import { ShopRating } from './shop_rating'; export class Shop extends Model implements IShop { id: number; name: string; province: string; city: string; suburb: string; districtCode: string; address: string; geolocation: Point; announcement: string; brandLogo: string; isInvoiceSupported: boolean; businessHours: BusinessHours[]; phone: string; categories: Category[]; products: Product[]; qualification: ShopQualification; ratings: ShopRating[]; // ---------------------------------- static tableName = 'shop'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { return { products: { relation: Model.HasManyRelation, modelClass: require('./product').default, join: { from: 'shop.id', to: 'product.shop_id', }, }, qualification: { relation: Model.HasOneRelation, modelClass: require('./shop_qualification').ShopQualification, join: { from: 'shop.id', to: 'shop_qualification.shop_id', }, }, categories: { relation: Model.HasManyRelation, modelClass: require('./category').Category, join: { from: 'shop.id', to: 'category.shop_id', }, }, ratings: { relation: Model.HasManyRelation, modelClass: require('./shop_rating').ShopRating, join: { from: 'shop.id', to: 'shop_rating.shop_id', }, }, }; } } <file_sep>import { ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'; import { Observable, throwError } from 'rxjs'; import { transaction } from 'objection'; import { catchError, tap } from 'rxjs/operators'; import { KnexService } from '../services/knex.service'; @Injectable() export class TransactionInterceptor implements NestInterceptor { constructor(private knexService: KnexService) {} async intercept( context: ExecutionContext, call$: Observable<any>, ): Promise<Observable<any>> { const tx = await transaction.start(this.knexService.knex); const req = context.switchToHttp().getRequest(); req.tx = tx; console.info('💜 Bill started'); return call$ .pipe( tap(async () => { await tx.commit(); console.info('💚 Bill committed'); }), ) .pipe( catchError(async err => { await tx.rollback(); console.warn('🧡 Bill rollbacked'); return throwError(err); }), ); } } <file_sep>import { Injectable } from '@nestjs/common'; import * as fs from 'fs'; import * as path from 'path'; export interface IConfig { name: string; server: { host: string; port: number; baseUrl: string; }; database: { host: string; port: number; dbName: string; user: string; password: string; debug: boolean; }; log: { level: string; format: string; }; auth: { jwtSecret: string; jwtExpire: string; passwordSecret: string; }; cors: { origin: string; }; sms: { apiUri: string; appid: string; appkey: string; }; mail: { apiUri: string; appid: string; appkey: string; }; beecloud: { appId: string; appSecret: string; masterSecret: string; testSecret: string; sandbox: boolean; webhook: { whitelist: string[]; }; bill: { timeout: number; }; }; } export enum DeployEnv { development = 'development', staging = 'staging', production = 'production', } export interface IManifest { environment: DeployEnv; version: string; } type EnvName = 'DEPLOY_ENV' | 'BUILD_VERSION'; declare const process: { env: { [key in EnvName]: string }; }; @Injectable() export class RuntimeService { defaultDeployEnv = DeployEnv.development; configJson: { [key: string]: IConfig; }; constructor() { let file = null; try { file = fs.readFileSync( path.resolve(__dirname, '../../config.json'), 'utf8', ); // ts-node src/main.ts } catch (err) { file = fs.readFileSync(path.resolve('./dist/config.json'), 'utf8'); // node dist/main.js } this.configJson = JSON.parse(file); console.log('config.json file loaded '); } getEnvVar(name: EnvName, defaultValue: string): string { return process.env[name] || defaultValue; } getConfig(): IConfig { return ( this.configJson[this.getEnvVar('DEPLOY_ENV', this.defaultDeployEnv)] || this.configJson[this.defaultDeployEnv] ); } getManifest(): IManifest { return { environment: DeployEnv[this.getEnvVar('DEPLOY_ENV', DeployEnv.development)], version: this.getEnvVar('BUILD_VERSION', 'no-ci'), }; } } <file_sep>import { Moment } from 'moment'; import { IShop } from './IShop'; export interface IShopQualification { id: number; shopId: number; businessLicenseCopy: string; businessCertificateCopy: string; businessName: string; businessAddress: string; statutoryRepresentative: string; certificateNo: string; businessScope: string; expireDate: Moment; signedAgreementDoc: string; shop: IShop; } <file_sep>import { IShop } from './IShop'; import { ICategory } from './ICategory'; import { IProductRating } from './IProductRating'; export interface IProduct { id: number; shopId: number; name: string; description: string; image: string; introduction: string; gallery: any; unit: string; price: number; rrp: number; isOnline: boolean; type: string; shop: IShop; categories: ICategory[]; ratings: IProductRating[]; } <file_sep>#!/bin/sh # gcloud auth export GOOGLE_APPLICATION_CREDENTIALS=/<KEY> # decrypt git-crypt config file if [ -z "$SKIP_GIT_CRYPT" ] || [ "$SKIP_GIT_CRYPT" -ne "0" ]; then cat /app/db/flyway.${DEPLOY_ENV}.conf | git-crypt smudge --key-file /git-crypt/key.asc > /tmp/conf mv /tmp/conf /app/db/flyway.${DEPLOY_ENV}.conf fi # db migration flyway -X -configFiles=/app/db/flyway.${DEPLOY_ENV}.conf migrate <file_sep>import { BeecloudService } from './beecloud.service'; describe('BeecloudService', () => { // let service: BeecloudService; beforeEach(async () => { // const module: TestingModule = await Test.createTestingModule({ // providers: [BeecloudService, RuntimeService], // }).compile(); // // service = module.get<BeecloudService>(BeecloudService); }); it('should be defined', () => { // expect(service).toBeDefined(); expect(1).toEqual(1); }); }); <file_sep>import { User } from '../models/user'; import { Shop } from '../models/shop'; import { createParamDecorator } from '@nestjs/common'; import { Request } from 'express'; declare global { namespace Express { export interface Request { // @ts-ignore user?: User; shop?: Shop; } } } export const Context = createParamDecorator( (name: 'user' | 'shop', req: Request) => req[name], ); <file_sep>import { Week } from './enums'; import { Range } from './Range'; export class BusinessHours { week: Week; hours: Array<Range<string>>; } <file_sep>import { IProduct } from './IProduct'; export type ICartItem = IProduct & { quantity: number }; <file_sep>import { Workflow } from '../enums'; import { BusinessHours } from '../BusinessHours'; import { Point } from '../Point'; import { Moment } from 'moment'; export class WorkflowStepData { shop: CreateShop; shopQualification: CreateShopQualification; } export class WorkflowTaskData { businessAddress: string; businessName: string; businessScope: string; certificateNo: string; expireDate: Moment; statutoryRepresentative: string; } export class CreateTask { workflow: Workflow; data: WorkflowStepData; } export class ReviewTask { comment: string; } export class CreateShop { address: string; announcement: string; brandLogo: string; businessHours: BusinessHours[]; city: string; districtCode: string; geolocation: Point; isInvoiceSupported: boolean; name: string; phone: string; province: string; suburb: string; } export class CreateShopQualification { businessCertificateCopy: string; businessLicenseCopy: string; signedAgreementDoc: string; } <file_sep>import { join } from 'path'; import * as nodeExternals from 'webpack-node-externals'; export default { entry: './src/main.ts', resolve: { extensions: ['.ts'] }, target: 'node', mode: 'none', node: { __filename: true, __dirname: true, }, // this makes sure we include node_modules and other 3rd party libraries externals: [nodeExternals()], devtool: 'source-map', output: { path: join(__dirname, 'dist'), filename: '[name].js', }, module: { rules: [{ test: /\.ts$/, loader: 'ts-loader' }], }, plugins: [], }; <file_sep>interface Dict { [key: string]: string; } export enum TradePayment { Unattempted = 'unattempted', Attempted = 'attempted', Success = 'success', Failure = 'failure', } export enum Gender { Male = 'male', Female = 'female', Unknow = 'unknown', } export enum OrderProcess { Submitted = 'submitted', Scheduled = 'scheduled', Cancelled = 'cancelled', } export enum MessageChannel { Sms = 'sms', Email = 'email', } export enum Workflow { CreateShop = 'create_shop', } export enum WorkflowProcess { Submitted = 'submitted', Reviewed = 'reviewed', Finished = 'finished', Cancelled = 'cancelled', } export enum MessagePurpose { EmailVerification = 'email_verification', PhoneVerification = 'phone_verification', } export enum RoleName { ShopAdmin = 'shop_admin', SystemAdmin = 'system_admin', } export enum RoleScope { Shop = 'shop', } export enum Week { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7, } <file_sep>export interface IUserVerification { id: number; userId: number; legalName: string; idCard: string; driverLicenseCopy: string; photoCopy: string; isRealnameVerified: boolean; } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { ICategory } from '../../../common/models/ICategory'; import { Shop } from './shop'; export class Category extends Model implements ICategory { id: number; name: string; order: number; shopId: number; shop: Shop; // ---------------------------------- static tableName = 'category'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { // solve loop require return { shop: { relation: Model.BelongsToOneRelation, modelClass: require('./shop').Shop, join: { from: 'category.shop_id', to: 'shop.id', }, }, }; } } <file_sep>import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { User } from '../models/user'; import { RuntimeService } from './runtime.service'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private runtime: RuntimeService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: runtime.getConfig().auth.jwtSecret, }); } async validate(payload: JwtPayload) { const user = await User.query() .findById(payload.id) .eager('roles'); if (!user) { throw new UnauthorizedException(); } return user; } } export class JwtPayload { id: number; email: string; name: string; phone: string; } <file_sep>import { BillPurpose } from '../dto/payment.dto'; import { Moment } from 'moment'; export interface IPayment { id: string; billNo: number; purpose: BillPurpose; html: string; url: string; codeUrl: string; req: any; res: any; isSuccess: boolean; expireAt: Moment; createdAt: Moment; } <file_sep>FROM node:11-alpine as build-stage WORKDIR /app COPY package*.json ./ RUN npm install --no-optional COPY tsconfig.json . COPY webpack.config.ts . COPY common ./common COPY src ./src RUN npm run test RUN npm run build FROM node:11-alpine as production-stage WORKDIR /app COPY package*.json ./ COPY --from=build-stage /app/dist dist RUN npm install --only=production --no-optional # install git-crypt RUN apk update && \ apk --no-cache add ca-certificates && \ wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://raw.githubusercontent.com/sgerrand/alpine-pkg-git-crypt/master/sgerrand.rsa.pub && \ wget https://github.com/sgerrand/alpine-pkg-git-crypt/releases/download/0.6.0-r1/git-crypt-0.6.0-r1.apk && \ apk add git-crypt-0.6.0-r1.apk && rm *.apk EXPOSE 8080 ARG BUILD_VERSION ENV BUILD_VERSION=${BUILD_VERSION} COPY docker-entrypoint.sh / ENTRYPOINT ["/docker-entrypoint.sh"] <file_sep>import { Moment } from 'moment'; import { OrderProcess, TradePayment } from '../enums'; export class CreateTrade { amount: number; orders: CreateOrder[]; } export class CreateOrder { shopId: number; productId: number; quantity: number; price: number; bookDate: Moment; bookStart: Moment; bookEnd: Moment; } export class QueryTrade { paymentInd: TradePayment; processInd: OrderProcess; } <file_sep>import { MessageChannel, MessagePurpose } from '../enums'; import { IsIn, IsNotEmpty, IsNumber, IsOptional, IsString, Max, MaxLength, Min, } from 'class-validator'; export class CodeOptions { @IsNumber() @Min(1) @Max(24 * 60) expire: number; // minutes @IsOptional() @IsNumber() @Min(4) @Max(8) length?: number; @IsOptional() @IsString() @IsIn(['alphanumeric', 'alphabetic', 'numeric', 'hex']) charset?: 'alphanumeric' | 'alphabetic' | 'numeric' | 'hex'; @IsOptional() @IsString() @IsIn(['lowercase', 'uppercase']) capitalization?: 'lowercase' | 'uppercase'; } export class CreateVericode { @IsString() @IsNotEmpty() @MaxLength(30) target: string; @IsString() @IsNotEmpty() @IsIn(Object.keys(MessagePurpose).map(key => MessagePurpose[key])) purpose: MessagePurpose; @IsString() @IsNotEmpty() @IsIn(Object.keys(MessageChannel).map(key => MessageChannel[key])) channel: MessageChannel; @IsString() @IsNotEmpty() @MaxLength(30) recipient: string; @IsNotEmpty() codeOptions: CodeOptions; } <file_sep>import { BadRequestException, Body, Controller, Post, Req, UnauthorizedException, UseGuards, } from '@nestjs/common'; import { Request } from 'express'; import { includes } from 'lodash'; import { AuthGuard } from '@nestjs/passport'; import { Roles, RolesGuard } from '../guards/roles.guard'; import { BeecloudService } from '../services/beecloud.service'; import { Context } from '../decorators/context.decorator'; import { User } from '../models/user'; import { BillChannel, MONEY_BY_CENTS, TransferChannel, WEB_HOOK_DONT_SEND, WEB_HOOK_RESEND, WebBill, WebBillRes, Webhook, WebTransfer, WebTransferRes, } from '../../../common/dto/payment.dto'; import { RuntimeService } from '../services/runtime.service'; import { IError } from '../../../common/response'; import { md5 } from '../../utils/crypto'; import { PaymentHandlerService } from '../services/payment-handler.service'; import { RoleName } from '../../../common/enums'; import moment = require('moment'); import { Payment } from '../models/payment'; import { PaymentWebhook } from '../models/payment_webhook'; @Controller('payment') export class PaymentController { constructor( private beecloud: BeecloudService, private runtime: RuntimeService, private paymentHandler: PaymentHandlerService, ) {} private populateBillData(bill: WebBill, timeout: number) { const data: any = { channel: bill.channel, timestamp: moment().valueOf(), total_fee: bill.totalFee, bill_no: bill.billNo, title: bill.title, optional: { purpose: bill.purpose }, bill_timeout: timeout, }; switch (data.channel) { case BillChannel.AlipayWeb: data.return_url = bill.returnUrl; // 当channel参数为 ALI_WEB 或 ALI_QRCODE 或 UN_WEB 或 JD_WAP 或 JD_WEB时为必填 data.show_url = bill.showUrl; // 商品展示地址以http://开头 break; case BillChannel.AlipayCode: data.return_url = bill.returnUrl; // 当channel参数为 ALI_WEB 或 ALI_QRCODE 或 UN_WEB 或 JD_WAP 或 JD_WEB时为必填 // 注: 二维码类型含义 // 0: 订单码-简约前置模式, 对应 iframe 宽度不能小于 600px, 高度不能小于 300px // 1: 订单码-前置模式, 对应 iframe 宽度不能小于 300px, 高度不能小于 600px // 3: 订单码-迷你前置模式, 对应 iframe 宽度不能小于 75px, 高度不能小于 75px data.qr_pay_mode = '0'; break; case BillChannel.AlipayWap: data.return_url = bill.returnUrl; // 当channel参数为 ALI_WEB 或 ALI_QRCODE 或 UN_WEB 或 JD_WAP 或 JD_WEB时为必填 data.use_app = true; break; case BillChannel.WechatWeb: data.openid = bill.openid; break; default: } return data; } @Post('bill') @UseGuards(AuthGuard()) async bill( @Context('user') user: User, @Body() bill: WebBill, ): Promise<WebBillRes> { const billNo = Number.parseInt(bill.billNo, 10); const next = await this.paymentHandler.onBill( user, billNo, bill.totalFee, bill.purpose, ); if (!next) { throw new BadRequestException('创建支付链接失败'); } // check if an unexpired and unattempted payment link const payment = await Payment.query() .where('bill_no', billNo) .andWhere('purpose', bill.purpose) .andWhere('is_success', 'false') .andWhereRaw('expire_at > current_timestamp') .orderBy('created_at', 'desc') .first(); if (payment) { return { url: payment.url, } as WebBillRes; } const { timeout } = this.runtime.getConfig().beecloud.bill; const data = this.populateBillData(bill, timeout); let res = null; try { res = await this.beecloud.api.bill(data); } catch (e) { // @ts-ignore throw new BadRequestException('创建支付链接失败', { extra: e, } as IError); } if (res.result_code === 0) { await Payment.query().insert({ id: res.id, billNo, purpose: bill.purpose, url: res.url, req: data, res, expireAt: moment().add(timeout, 'seconds'), createdAt: moment(), isSuccess: false, }); return { html: res.html, url: res.url, codeUrl: res.code_url, } as WebBillRes; } else { // @ts-ignore throw new BadRequestException('创建支付链接失败', { extra: { resultCode: res.result_code, resultMessage: res.result_msg, errorDetail: res.err_detail, }, } as IError); } } @Post('webhook') async webhook(@Body() webhook: Webhook, @Req() request: Request) { // whitelist filter const { whitelist } = this.runtime.getConfig().beecloud.webhook; const clientIp = request.headers['x-forwarded-for'] || request.connection.remoteAddress; console.log(clientIp); if (!includes(whitelist, clientIp)) { throw new UnauthorizedException('非法的访问'); } // verify signature const { appId, masterSecret } = this.runtime.getConfig().beecloud; const sign = md5( appId + webhook.transaction_id + webhook.transaction_type + webhook.channel_type + webhook.transaction_fee + masterSecret, ); console.log(sign); if (sign !== webhook.signature) { return 'resend-invalid-signature'; } await PaymentWebhook.query().insert({ paymentId: webhook.transaction_id, totalFee: webhook.transaction_fee, isSuccess: webhook.trade_success, payload: webhook, createdAt: moment(), }); const payment = await Payment.query().findById(webhook.transaction_id); if (!payment) { console.error('支付记录不存在'); return WEB_HOOK_RESEND; } // filter handled transaction if (payment.isSuccess) { return WEB_HOOK_DONT_SEND; } await Payment.query() .findById(webhook.transaction_id) .update({ isSuccess: webhook.trade_success }); const next = await this.paymentHandler.onWebhook(webhook); return next ? WEB_HOOK_DONT_SEND : WEB_HOOK_RESEND; } private populateTransferData(transfer: WebTransfer) { const data: any = { timestamp: moment().unix(), // 时间戳,毫秒数 channel: transfer.channel, transfer_no: transfer.transferNo, // 支付宝为11-32位数字字母组合, 微信企业打款为8-32位数字字母组合,微信红包为10位数字 total_fee: transfer.totalFee * MONEY_BY_CENTS, // 此次打款的金额,单位分,正整数(微信红包1.00-200元,微信打款>:1元) desc: transfer.desc, // 此次打款的说明 channel_user_id: transfer.channelUserId, // 支付渠道方内收款人的标示, 微信为openid, 支付宝为支付宝账户 }; switch (data.channel) { case TransferChannel.AlipayTransfer: data.channel_user_name = transfer.channelUserName; // 支付渠道内收款人账户名, 支付宝必填 data.account_name = '上海哈度信息技术有限公司'; // 打款方账号名称,支付宝必填 break; case TransferChannel.WechatTransfer: data.redpack_info = { send_name: '上海哈度<EMAIL>', // 红包发送者名称 32位 wishing: '问灸平台打款', // 红包祝福语 128 位 act_name: '问灸平台打款', // 红包活动名称 32位 }; break; default: } return data; } @Post('transfer') @UseGuards(AuthGuard(), RolesGuard) @Roles(RoleName.SystemAdmin) async transfer( @Context('user') user: User, @Body('transfer') transfer: WebTransfer, ) { const data = this.populateTransferData(transfer); try { const res = await this.beecloud.api.bill(data); return { url: res.url, } as WebTransferRes; } catch (e) { // @ts-ignore throw new BadRequestException('创建打款链接失败', { extra: e, } as IError); } } } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { IProduct } from '../../../common/models/IProduct'; import { ICategory } from '../../../common/models/ICategory'; import { IProductRating } from '../../../common/models/IProductRating'; import { Shop } from './shop'; import { ProductRating } from './product_rating'; import { Category } from './category'; export class Product extends Model implements IProduct { id: number; shopId: number; name: string; description: string; image: string; introduction: string; gallery: any; unit: string; price: number; rrp: number; isOnline: boolean; type: string; categories: Category[]; ratings: ProductRating[]; shop: Shop; // ---------------------------------- static tableName = 'product'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { // solve loop require return { shop: { relation: Model.BelongsToOneRelation, modelClass: require('./shop').Shop, join: { from: 'product.shop_id', to: 'shop.id', }, }, categories: { relation: Model.ManyToManyRelation, modelClass: require('./category').Category, join: { from: 'product.id', through: { from: 'product_category.product_id', to: 'product_category.category_id', }, to: 'category.id', }, }, ratings: { relation: Model.HasManyRelation, modelClass: require('./product_rating').ProductRating, join: { from: 'product.id', to: 'product_rating.product_id', }, }, }; } } <file_sep>import { Injectable } from '@nestjs/common'; import { RuntimeService } from './runtime.service'; import * as BCRESTApi from 'beecloud-node-sdk'; @Injectable() export class BeecloudService { api: BCRESTApi; constructor(private runtimeService: RuntimeService) { const API = new BCRESTApi(); const { appId, appSecret, masterSecret, testSecret, sandbox, } = runtimeService.getConfig().beecloud; API.registerApp(appId, appSecret, masterSecret, testSecret); API.setSandbox(sandbox); this.api = API; } } <file_sep>#!/bin/sh if [ -z "$SKIP_GIT_CRYPT" ] || [ "$SKIP_GIT_CRYPT" -ne "0" ]; then cat /app/dist/config.json | git-crypt smudge --key-file /git-crypt/key.asc > /tmp/json mv /tmp/json /app/dist/config.json fi node dist/main.js <file_sep>import { Moment } from 'moment'; export interface IPaymentWebhook { id: number; paymentId: string; totalFee: number; isSuccess: boolean; payload: any; createdAt: Moment; } <file_sep>import { IsNotEmpty, IsNumber } from 'class-validator'; export class Point { @IsNumber() @IsNotEmpty() x: number; @IsNumber() @IsNotEmpty() y: number; } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import { IShopQualification } from '../../../common/models/IShopQualification'; import { Shop } from './shop'; export class ShopQualification extends Model implements IShopQualification { id: number; shopId: number; businessLicenseCopy: string; businessCertificateCopy: string; businessName: string; businessAddress: string; statutoryRepresentative: string; certificateNo: string; businessScope: string; expireDate: Moment; signedAgreementDoc: string; shop: Shop; // ---------------------------------- static tableName = 'shop_qualification'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { // solve loop require return { shop: { relation: Model.BelongsToOneRelation, modelClass: require('./shop').Shop, join: { from: 'shop_qualification.shop_id', to: 'shop.id', }, }, }; } } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import { IWorkflowTask } from '../../../common/models/IWorkflowTask'; import { Workflow, WorkflowProcess } from '../../../common/enums'; import { WorkflowTaskData } from '../../../common/dto/workflow.dto'; import { WorkflowStep } from './workflow_step'; export class WorkflowTask extends Model implements IWorkflowTask { id: number; workflow: Workflow; data: WorkflowTaskData; processInd: WorkflowProcess; createdAt: Moment; updatedAt: Moment; steps: WorkflowStep[]; // ---------------------------------- static tableName = 'workflow_task'; static columnNameMappers = snakeCaseMappers(); static get relationMappings() { return { steps: { relation: Model.HasManyRelation, modelClass: require('./workflow_step').WorkflowStep, join: { from: 'workflow_task.id', to: 'workflow_step.workflow_task_id', }, }, }; } } <file_sep>import { Model, snakeCaseMappers } from 'objection'; import { Moment } from 'moment'; import { IOrder } from '../../../common/models/IOrder'; import { IProduct } from '../../../common/models/IProduct'; import { OrderProcess } from '../../../common/enums'; import { Product } from './product'; import { Shop } from './shop'; import { Trade } from './trade'; export class Order extends Model implements IOrder { id: number; tradeId: number; shopId: number; productId: number; productionSnapshot: Product; quantity: number; price: number; bookDate: Moment; bookStart: Moment; bookEnd: Moment; processInd: OrderProcess; processUpdatedAt: Moment; product: Product; shop: Shop; trade: Trade; // ---------------------------------- static tableName = 'order'; static columnNameMappers = snakeCaseMappers(); static jsonAttributes = ['productSnapshot']; // get snapshot() { // return JSON.parse(this.productSnapshot) // } static get relationMappings() { return { shop: { relation: Model.BelongsToOneRelation, modelClass: require('./shop').Shop, join: { from: 'order.shop_id', to: 'shop.id', }, }, trade: { relation: Model.BelongsToOneRelation, modelClass: require('./trade').Trade, join: { from: 'order.trade_id', to: 'trade.id', }, }, product: { relation: Model.BelongsToOneRelation, modelClass: require('./product').Product, join: { from: 'order.product_id', to: 'product.id', }, }, }; } } <file_sep>import { IShop } from '../models/IShop'; import { OrderProcess } from '../enums'; import { IProduct } from '../models/IProduct'; import { ICategory } from '../models/ICategory'; import { IOrder } from '../models/IOrder'; import { Point } from '../Point'; import { BusinessHours } from '../BusinessHours'; export class UpdateShop implements Pick< IShop, | 'name' | 'province' | 'city' | 'suburb' | 'districtCode' | 'address' | 'geolocation' | 'announcement' | 'brandLogo' | 'isInvoiceSupported' | 'businessHours' | 'phone' > { name: string; province: string; city: string; suburb: string; districtCode: string; address: string; geolocation: Point; announcement: string; brandLogo: string; isInvoiceSupported: boolean; businessHours: BusinessHours[]; phone: string; } export class CreateCategory implements Pick<ICategory, 'name' | 'order'> { name: string; order: number; } export class UpdateCategory implements Pick<ICategory, 'name' | 'order'> { name: string; order: number; } export class CreateProduct implements Pick< IProduct, | 'name' | 'description' | 'price' | 'unit' | 'rrp' | 'image' | 'introduction' | 'gallery' | 'isOnline' > { name: string; description: string; price: number; unit: string; rrp: number; image: string; introduction: string; gallery: any; isOnline: boolean; } export class UpdateProduct implements Pick< IProduct, | 'name' | 'description' | 'price' | 'unit' | 'rrp' | 'image' | 'introduction' | 'gallery' | 'isOnline' > { name: string; description: string; price: number; unit: string; rrp: number; image: string; introduction: string; gallery: any; isOnline: boolean; } export class UpdateOrder implements Pick<IOrder, 'processInd'> { processInd: OrderProcess; } <file_sep> <p align="center">Wenjiu API proudly powered by Nestjs and CI/CD with GitOps pattern.</p> ## Description Wenjiu API ## Development ```bash $ npm install $ npm run start $ npm run test $ npm run e2e $ npm run format $ npm run lint ``` ## Test ```bash # unit tests $ npm run test # e2e tests $ npm run e2e # test coverage $ npm run test -- --coverage ``` ## Build & Dockerise ```bash $ docker build . ``` <file_sep>import { Moment } from 'moment'; import { IShop } from './IShop'; import { ITrade } from './ITrade'; import { IUser } from './IUser'; export interface IShopRating { id: number; shopId: number; tradeId: number; rating: number; comment: string; userId: number; createdAt: Moment; shop: IShop; trade: ITrade; user: IUser; } <file_sep>import { Injectable } from '@nestjs/common'; import { Shop } from '../models/shop'; import { User } from '../models/user'; import { Role } from '../models/role'; import { RoleName, RoleScope, Workflow } from '../../../common/enums'; import { WorkflowStep } from '../models/workflow_step'; import { Transaction } from 'objection'; import { WorkflowTask } from '../models/workflow_task'; @Injectable() export class WorkflowHandlerService { async handle(step: WorkflowStep, task: WorkflowTask, tx: Transaction) { switch (task.workflow) { case Workflow.CreateShop: const shop = await Shop.query(tx).insertGraphAndFetch({ ...step.data.shop, // @ts-ignore qualification: { ...step.data.shopQualification, ...task.data, }, }); const user = await User.query(tx).findById(step.userId); await user.$relatedQuery<Role, Role[]>('roles').insert({ name: RoleName.ShopAdmin, scope: RoleScope.Shop, scopeId: shop.id, }); break; default: } } } <file_sep>export class Range<T> { lower: T; upper: T; bounds: Bounds = Bounds.BothInclusive; } export enum Bounds { BothInclusive = 'inclusive', // [] BothExclusive = 'exclusive', // () UpperExclusive = '', // (] LowerExclusive = '', // [) } <file_sep>import { Moment } from 'moment'; import { IOrder } from './IOrder'; import { IUser } from './IUser'; export interface ITrade { id: number; amount: number; userId: number; createdAt: Moment; paymentInd: string; paymentUpdatedAt: Moment; order: IOrder[]; user: IUser; } <file_sep>import { Moment } from 'moment'; import { IRole } from './IRole'; import { ICartItem } from './ICartItem'; export interface IUser { id: number; name: string; // password: string; phone: string; email: string; isPhoneVerified: boolean; isEmailVerified: boolean; createdAt: Moment; updatedAt: Moment; roles: IRole[]; cartItems: ICartItem[]; } <file_sep>import { BadRequestException, Body, Controller, Delete, Get, Param, Patch, Post, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { Context } from '../decorators/context.decorator'; import { CartItem, User } from '../models/user'; import { Product } from '../models/product'; import { ICartItem } from '../../../common/models/ICartItem'; import { AddCartItem, UpdateCartItem } from '../../../common/dto/cart.dto'; @Controller('cart') @UseGuards(AuthGuard()) export class CartController { @Get('') async loadCart(@Context('user') user: User): Promise<ICartItem[]> { return await user.$relatedQuery<CartItem, CartItem[]>('cartItems'); } @Post('items') async addItem( @Context('user') user: User, @Body('cartItem') cartItem: AddCartItem, ) { const { productId, quantity } = cartItem; const product = await Product.query().findById(productId); if (!product) { throw new BadRequestException('购物车物品不存在'); } await user.$relatedQuery<CartItem, CartItem[]>('cartItems').insert({ id: productId, quantity, }); } @Patch('items/:productId') async updateItem( @Context('user') user: User, @Param('productId') productId: number, @Body('cartItem') cartItem: UpdateCartItem, ) { const { quantity } = cartItem; const item = await user .$relatedQuery<CartItem, CartItem[]>('cartItems') .findById(productId); if (!item) { throw new BadRequestException('购物车物品不存在'); } await user .$relatedQuery<CartItem, CartItem[]>('cartItems') .where('product_id', productId) .patch({ quantity, }); } @Delete('items/:productId') async deleteItem( @Context('user') user: User, @Param('productId') productId: number, ) { const item = await user .$relatedQuery<CartItem, CartItem[]>('cartItems') .findById(productId); if (!item) { throw new BadRequestException('购物车物品不存在'); } await user .$relatedQuery<CartItem, CartItem[]>('cartItems') .where('product_id', productId) .delete(); } @Delete('items') async clearCart(@Context('user') user: User) { const items = await user.$relatedQuery<CartItem, CartItem[]>('cartItems'); if (items.length === 0) { console.warn('购物车已经为空'); } await user.$relatedQuery<CartItem, CartItem[]>('cartItems').delete(); } } <file_sep>import { Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { JwtModule } from '@nestjs/jwt'; import 'reflect-metadata'; import { JwtStrategy } from './services/jwt.strategy'; import { AuthController } from './controllers/auth.controller'; import { ShopController } from './controllers/shop.controller'; import { ShopsController } from './controllers/shops.controller'; import { AppController } from './controllers/app.controller'; import { VericodeController } from './controllers/vericode.controller'; import { MessageService } from './services/message.service'; import { RuntimeService } from './services/runtime.service'; import { LoggerService } from './services/logger.service'; import { KnexService } from './services/knex.service'; import { WorkflowController } from './controllers/workflow.controller'; import { CartController } from './controllers/cart.controller'; import { TradesController } from './controllers/trades.controller'; import { PaymentHandlerService } from './services/payment-handler.service'; import { WorkflowHandlerService } from './services/workflow-handler.service'; import { BeecloudService } from './services/beecloud.service'; import { PaymentController } from './controllers/payment.controller'; @Module({ imports: [ PassportModule.register({ defaultStrategy: 'jwt', // @AuthGuard don't need pass strategy name property: 'user', // inject to req.user session: true, // enable session }), JwtModule.registerAsync({ imports: [AppModule], useFactory: async (runtime: RuntimeService) => ({ secretOrPrivateKey: runtime.getConfig().auth.jwtSecret, signOptions: { expiresIn: runtime.getConfig().auth.jwtExpire, }, }), inject: [RuntimeService], }), ], controllers: [ AppController, AuthController, VericodeController, ShopController, ShopsController, WorkflowController, CartController, TradesController, PaymentController, ], providers: [ RuntimeService, LoggerService, KnexService, JwtStrategy, MessageService, PaymentHandlerService, WorkflowHandlerService, BeecloudService, ], exports: [RuntimeService], }) export class AppModule {}
507a3aa8a8cf4f18e207c6b7565e21a4de04b576
[ "SQL", "Markdown", "TypeScript", "Dockerfile", "Shell" ]
80
TypeScript
chaoyangnz/wenjiu-api
1d5a409a385598ceb153845667671dc70f1765eb
4eff3884063d17fd3f107aee1841805b1dd9c517
refs/heads/master
<file_sep>import argparse def a(FILE): f=open(FILE,'r') n,m,A=4,4,[] B=list(map(float,f.readline().strip().split())) for i in range(0,n): A.append(list(map(float,f.readline().strip().split()))) A[i].append(B[i]) M=list(map(float,f.readline().strip().split())) solver(A,M,n,m,'output_problem1_part1.txt') f.close() def b(FILE): f=open(FILE,'r') n,m=map(int,f.readline().strip().split()) B=list(map(float,f.readline().strip().split())) A=[] for i in range(0,n): A.append(list(map(float,f.readline().strip().split()))) A[i].append(B[i]) M=list(map(float,f.readline().strip().split())) solver(A,M,n,m,'output_problem1_part2.txt') f.close() def solver(A,M,n,m,FILE):#A is augmented Matrix, can simply make m=m+1 #Step1:- Reduce to Upper Triangler matrix <echolen form> Also memorizing each operation Operations,K,I,free,basic,pivot,flag=[],-1,-1,[],[],[],0 while(K<m and I<(n-1)):#here k<m is correct as k==m is B matrix so it's good. I+=1#row for pivot... K+=1#Column at which pivot will occur ...worst case k==m #if(I==n): either I< n-1 in while loop or use this and make I<n # break flag=0 while(A[I][K]==0): flag=0 for i in range(I+1,n): if(A[i][K]!=0):#checking for non-zero column for pivot possibility Operations.append(['SWITCH',I,i]) flag=1 A[I],A[i]=A[i],A[I]#perform switch break #end of for loop... if(flag==0):#add free variable and move on. free.append(K) K+=1 if(K>m or I>=n):#I>=n is redundant here. But leave it for now. #Ops... No more pivot left. flag=2#since I dont know how to add label so better use flag to get out. break pass#end of while loop. if(flag==2): break#CRAP! need to exit the loop... #We now have a non-zero column entry so add a basic variable to our list basic.append(K) pivot.append((I,K)) #Converting the row below the pivot K to 0. scale=1/float(A[I][K]) Operations.append(['MULTIPLY',scale,I])#adding to operations list. A[I]=SCALE(A,I,scale)#scaling done...returns a row #print(A) A,ops=ConvertRowsToZero(A,I,K,n) if(len(ops)!=0):#sometimes zero operations can occur Operations.append(ops) pass#end of outer while loop #Add those free variables which were unreachable in step1 and couldnt get added. for i in range(basic[-1]+1,m): free.append(i)# add i to free list... #Step2:-Convert into identity matrix if possible..simply reduced echolen form... #to do so make each column zero which has a basic variable(pivot) in it and obviously except the pivot. for i,k in pivot: A,ops=MakeItReduced(A,i,k) if(len(ops)!=0):#sometimes zero operations can occur Operations.append(ops) #Step3:-Get Free variables:THis task is required to be done for question 1. isIn=isInconsistent(basic,m)#returns true if inconsistent else false maxLimitCrossed=False free=list(set(free)) f=open(FILE,'w') if(not(isIn)): equations=CreateX(A,free,pivot,n,m) X=[1 for i in range(0,m)] maxfree=1 #print(free) if m in free: free.remove(m) #print(free) for i in free: if i!=m: #print M[i] maxfree*=M[i] xf=len(free)-1#current incrementer. maxfree=int(maxfree) #print(maxfree) for _ in range(0,int(maxfree)): #print(_,xf,free[xf],m, free ,"previous X: ", X) maxLimitCrossed=False for i in equations: #print(i) exec(i) for i in range(0,m): if( X[i]>M[i] or X[i]<=0): maxLimitCrossed=True break if isinstance(X[i],int): X[i]=round(X[i]) if isinstance(X[i],float): X[i]=round(X[i],3) if(maxLimitCrossed==False): break '''for xf in free: #print(xf) if xf<m and X[xf]<=M[xf]: X[xf]+=1''' if X[free[xf]]<M[free[xf]]: X[free[xf]]+=1 else: xk=xf-1 X[free[xf]]=1 while xk>=0: if X[free[xk]]<=M[free[xk]]: X[free[xk]]+=1 break else: X[free[xk]]=1 xk=xk-1 if(not(maxLimitCrossed)): if(len(free)==0): print('EXACTLY ONE!') sx=' '.join(map(str,X[0:m])) print(sx) f.writelines(['EXACTLY ONE!\n',sx,'\n']) else:#inf soln... print('MORE THAN ONE!') sx=' '.join(map(str,X[0:m])) print(sx) sf='free Variables={' for fr in free: sf+=' X['+str(fr)+'],' sf+='}' sb=sf+' Equations={' sb+=' ; '.join(map(str,equations[::-1])) sb+='}' print(sb) f.writelines(['MORE THAN ONE!\n',sx,'\n',sb,'\n']) if(isIn or maxLimitCrossed):#no solution. print 'NOT POSSIBLE, SNAPE IS WICKED!' f.write('NOT POSSIBLE, SNAPE IS WICKED!\n') f.close()#end of COdE solver def SCALE(A,I,scale): return [i*round(scale,10) for i in A[I]] def ConvertRowsToZero(A,I,K,n): ops=[] for i in range(I+1,n): scale=-1*float(A[i][K]) if(scale==0): continue ops.append(['MULTIPLY&ADD',scale,I,i]) tmpI=SCALE(A,I,scale)#getting scaled value in tmpI. A[i]=[round(x+y,10) for x,y in zip(tmpI,A[i])]#element-wise addition. Thanks Python! return A,ops def MakeItReduced(A,I,K): ops=[] for i in range(0,I): #print(A[i]) scale=-1*float(A[i][K]) if(scale==0): continue ops.append(['MULTIPLY&ADD',scale,I,i]) tmpI=SCALE(A,I,scale)#getting scaled value in tmpI. tmpAdd=[round(x+y,10) for x,y in zip(tmpI,A[i])]#element-wise addition. Thanks Python! A[i]=tmpAdd#update the ith row. return A,ops def CreateX(A,free,pivot,n,m): equations=[] revpivot=pivot[::-1] X=[1 for i in range(0,m)] for i in free: if(i<m): X[i]='X['+str(i)+']' for i,k in revpivot: equation='X['+str(k)+']'+'='+str(A[i][-1]) for j in range(k+1,m): if(A[i][j]==0): continue equation+='-'+str(A[i][j])+'*'+str(X[j]) equations.append(equation) return equations def isInconsistent(basic,m): for i in basic: if(i==m): return True return False #parser starts parser = argparse.ArgumentParser(description='Problem 1.') parser.add_argument('filename', metavar='<FILENAME.TXT>', type=str, help='file name.txt for the problem1') parser.add_argument('-part=one', dest='func', action='store_const', const=a, help='execution of part one') parser.add_argument('-part=two', dest='func', action='store_const', const=b, help='execution of part two') args = parser.parse_args() args.func(args.filename) #parser ends '''0.1 0.3 0.2 0.4 27 0.3 0.3 0.2 0.1 21 0.4 0.1 0.4 0.1 22 0.1 0.2 0.1 0.2 16''' ''' 0.1 0.3 0.2 0.4 0.3 0.3 0.2 0.1 0.4 0.1 0.4 0.1 0.1 0.2 0.1 0.2 ''' ''' 27 21 22 16 0.1 0.3 0.2 0.4 0.3 0.3 0.2 0.1 0.4 0.1 0.4 0.1 0.1 0.2 0.1 0.2 33 35 46 57 ''' ''' 3 2 10 20 30 0.1 0.2 0.3 0.4 0.2 0.2 100 100 '''
bfd448c2f48eed90754fa174596b0028cbf2c32f
[ "Python" ]
1
Python
mohitgupta07/LINEAR-ALGEBRA-ASSIGNMENT-1
3696d71d64a447ac9a36c599830f4aa59063bc6e
bc125085f63fb2b5fd4c07f62ae3df9b0f05b62e
refs/heads/master
<repo_name>snowbozh/NumberOnly4And7<file_sep>/README.md # NumberOnly4And7 Solve problem : number have only 4 and 7 with JavaScript Long time ago, a king who interesting in number 4 and 7. He told everybody to use only 4 and 7 for number system. #### Let's create program to parse number from decimal to 4_7 number system !! **Input** > Receive N by 1 <= N <= 10^9 **Output** > parsed number **Example** |Input |Output | |:---: |:---: | |1 |4 | |2 |7 | |3 |44 | |4 |47 | |5 |74 | |6 |77 | |7 |444 | |8 |447 | |10524 |4744744477747 | **How to** I try to parse value to binary. and then check the last bit of binary. If it equal to "1" then I will parse it to "4" and recursive this with value divide by 2 (same as shift right 1 time) If it equal to "0", I will parse it to "7" but I will subtract it by 1 before recursive same as above. Ps. this is a one solution, you can use loop to solve that but it will take a lot time to calculate this. <file_sep>/solve.js function parseTo_4_7(value) { if (value === 0) return ""; var tempStr = (value >>> 0).toString(2); if (tempStr[tempStr.length - 1] === "1") { return parseTo_4_7(value >> 1) + "4"; } if (tempStr[tempStr.length - 1] === "0") { return parseTo_4_7(value - 1 >> 1) + "7"; } } console.log(parseTo_4_7(1)); console.log(parseTo_4_7(2)); console.log(parseTo_4_7(3)); console.log(parseTo_4_7(4)); console.log(parseTo_4_7(5)); console.log(parseTo_4_7(6)); console.log(parseTo_4_7(7)); console.log(parseTo_4_7(8)); console.log(parseTo_4_7(10524));
336dd10d3cf4c165e45c6874d95fc747edab36bd
[ "Markdown", "JavaScript" ]
2
Markdown
snowbozh/NumberOnly4And7
0368e1c282f8a6f3911d4626f8cf429ca5a39b3e
96bcd684632d1d38d2c825ddb355830430988fe0
refs/heads/master
<repo_name>CaoRuiming/biangbiang<file_sep>/src/App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import OutputDisplay from './components/display/OutputDisplay.js'; class App extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSelection = this.handleSelection.bind(this); this.state = ({ input: '', selectedText: [], }); } handleChange(e) { this.setState({ input: e.target.value }); } handleSelection(index, character) { let updatedSelectedText = [...this.state.selectedText, {index: index, character: character}]; updatedSelectedText.sort((a,b) => {return a.index >= b.index;}); if(updatedSelectedText.filter((element) => {return element.index === index;}).length > 1) { updatedSelectedText = updatedSelectedText.filter((element) => {return element.index !== index;}); } this.setState({ selectedText: updatedSelectedText }); } render() { const processedSelectedText = this.state.selectedText.map((object) => object.character).join(''); return ( <div className='App'> <h1> <img src = { logo } style = {{ 'width': '75pt', 'height': '75pt', 'viewBox': '0 0 550.000000 135.000000' }} className='App-logo' alt='logo' /> ⇋ BiángBiáng </h1> <textarea style = {{ 'marginBottom': '30px' }} placeholder = 'Paste input here!' onChange = { this.handleChange }> </textarea> <OutputDisplay input = { this.state.input } selectedText = { processedSelectedText } handleSelection = { this.handleSelection } /> </div> ); } } export default App; <file_sep>/src/components/display/EnglishDisplay.js import React, { Component } from 'react'; export default class EnglishDisplay extends Component { render() { const style = { 'borderTop': '2px solid black', 'position': 'fixed', 'bottom': '0', 'width': '100%', 'background': 'white' }; const outputText = (this.props.selectedText.length < 1) ? 'Click on or drag over output to select text to translate!' : (this.props.selectedText + ' → ' + this.props.englishTranslation); return ( <div style = { style }> <p> { outputText } </p> </div> ); } } <file_sep>/README.md This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). BiangBiang is an offline, user-friendly tool for Chinese learners (who are English speakers). Users can input strings of Chinese and use BiangBiang to read through and translate phrases within the text. To run for the first time: ``` npm install npm start ``` To run afterwards: ``` npm start ``` To build for Production: ``` npm run build ``` For more details on running, building, and testing, refer to the documentation for Create React App. <file_sep>/src/utils/Dictionary.js import Cedict from './Cedict.js'; export default class Dictionary { //input must be a string that can be found in the dictionary static getEnglishTranslation(input) { input = ' '+input+' '; const dictionary = Cedict.getDictionaryText(); const indexNeeded = dictionary.indexOf(input); if (indexNeeded !== -1) { const startIndex = dictionary.substr(indexNeeded).indexOf('/')+indexNeeded+1; const endIndex = dictionary.substr(startIndex).indexOf('/\n')+startIndex; return dictionary.substring(startIndex, endIndex); } else { return 'No translation to show...'; } } //input must be a string that can be found in the dictionary static getPinyin(input) { input = ' '+input+' '; const dictionary = Cedict.getDictionaryText(); const indexNeeded = dictionary.indexOf(input); if (indexNeeded !== -1 && !this.isInvalidChar(input.substring(1,input.length-1))) { const startIndex = dictionary.substr(indexNeeded).indexOf('[')+indexNeeded+1; const endIndex = dictionary.substr(startIndex).indexOf(']')+startIndex; return dictionary.substring(startIndex, endIndex); } else { return ' '; } } static isInvalidChar(input) { return ',.!\'"-–—[]{}()'.indexOf(input) !== -1; } }
b1d6926a9c70019cf8ae1ab9c4f3d5d1aa5eec26
[ "JavaScript", "Markdown" ]
4
JavaScript
CaoRuiming/biangbiang
c7adc2fb13b8650128c16ce67e56aaf957675cf9
e34ece5025b7d17a94ff3e101fe575f7496693c1
refs/heads/master
<repo_name>cmanallen/rserver<file_sep>/src/lib.rs use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc; use std::thread; type Job = Box<dyn FnOnce() + Send + 'static>; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } impl ThreadPool { pub fn new(size: usize) -> ThreadPool { assert!(size > 0); // Message passing components. let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); // Worker processes. let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } struct Worker { id: usize, thread: thread::JoinHandle<()>, } impl Worker { // Arc (atomic reference counting). Arc let's multiple workers own // the receiver. // Mutex (mutual exclusion) locks request processing to a single // worker. Since all workers own the same receiver some locking // mechanism is needed to prevent all of the workers from // processing the same request. // mpsc (multi-producer; single-consumer) is used for sending // messages between threads (channels). fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let job = receiver.lock().unwrap().recv().unwrap(); println!("Worker {} got a job; executing.", id); job(); }); Worker { id, thread } } }
ab41f7f2a0a708924cb40a3a927e7a58207a1ee2
[ "Rust" ]
1
Rust
cmanallen/rserver
1934863cc92511f0db4179b8d1202be0b89e9ae1
5908c2253341904d671cf6f723be26b655f404b8
refs/heads/master
<file_sep> /* To search for YouTube videos, you'll use the API's Search:list endpoint. To help keep your code organized, write a helper function that is solely responsible for interacting with this endpoint. In lib/searchYouTube.js fill out the searchYouTube function. It should: Use $.ajax to send a GET request to the search endpoint. This is the only time you should use jQuery in this sprint Accept a callback function that is invoked with the videos array that is returned from hitting the endpoint Accept an options object with the following properties: query - the string to search for max - the maximum number of videos to get, which should default to 5 key - an authorized YouTube Browser API key Only GET embeddable videos */ var searchYouTube = (options, callback) => { var cb = callback; $.ajax({ url: 'https://www.googleapis.com/youtube/v3/search', type: 'GET', data: { q: options.q, part: 'snippet', maxResults: 8, type: 'video', videoEmbeddable: 'true', key: YOUTUBE_API_KEY}, success: function(videos) { console.log('IN ONSUCCESS'); cb(videos); }, error: function(data) { console.log('IN ONERROR'); } }); }; window.searchYouTube = searchYouTube; // url: GET https://www.googleapis.com/youtube/v3/search // params: // q: query string aka search string // parts: snippet <file_sep>class App extends React.Component { constructor(props) { super(props); this.state = { currentVideo: null, videos: null }; } componentDidMount() { this.searchYouTubeForVideos('cute cats'); } render() { return ( <div> <Nav handleSearchClickEvent={this.handleSearchClickEvent.bind(this)}/> <div className="col-md-7"> <VideoPlayer video={this.state.currentVideo}/> </div> <div className="col-md-5"> <VideoList videoList={this.state.videos} onUserInput={this.handleUserInput.bind(this)}/> </div> </div> ); } handleUserInput(videoList, currentVideo) { this.setState( { currentVideo: currentVideo, videos: videoList } ); } handleSearchClickEvent(searchString) { this.searchYouTubeForVideos(searchString); } searchYouTubeForVideos(searchString) { var options = { q: searchString }; searchYouTube(options, function (videos) { this.setState( { currentVideo: videos.items[0], videos: videos.items } ); }.bind(this)); } } ReactDOM.render(<App videoList={window.exampleVideoData}/>, document.getElementById('app'));
2f2bb809678bf3887b83f656aafde89bfdc615fe
[ "JavaScript" ]
2
JavaScript
brnewby602/recast.ly
4221f2865ae515cfc1ce99ea50b387fef3ae8d69
b0133756d75c034550378b5995ec3135bac6476e
refs/heads/master
<file_sep>#!/usr/bin/env bash # Set term to 256color mode, if 256color is not supported, colors won't work properly if [[ $COLORTERM = gnome-* && $TERM = xterm ]] && infocmp gnome-256color >/dev/null 2>&1; then export TERM=gnome-256color elif infocmp xterm-256color >/dev/null 2>&1; then export TERM=xterm-256color fi # Detect whether a rebbot is required function show_reboot_required() { if [ ! -z "$_bf_prompt_reboot_info" ]; then if [ -f /var/run/reboot-required ]; then printf "Reboot required!\n" fi fi } # Set different host color for local and remote sessions function set_host_color() { # Detect if connection is through SSH if [[ ! -z $SSH_CLIENT ]]; then printf "${powder_blue}" else printf "${hot_pink}" fi } # Set different username color for users and root function set_user_color() { case $(id -u) in 0) printf "${red}" ;; *) printf "${gold}" ;; esac } scm_prompt() { CHAR=$(scm_char) if [ $CHAR = $SCM_NONE_CHAR ] then return else echo "$CHAR$(scm_prompt_info)" fi } # Define custom colors we need # non-printable bytes in PS1 need to be contained within \[ \]. # Otherwise, bash will count them in the length of the prompt function set_custom_colors() { dark_grey="\[$(tput setaf 8)\]" light_grey="\[$(tput setaf 248)\]" powder_blue="\[$(tput setaf 153)\]" bright_yellow="\[$(tput setaf 226)\]" hot_pink="\[$(tput setaf 205)\]" dark_olive="\[$(tput setaf 107)\]" slate="\[$(tput setaf 105)\]" gold="\[$(tput setaf 220)\]" steel="\[$(tput setaf 189)\]" } __ps_time() { echo "$(clock_prompt)${normal}" } # Define the prompt marker # macOS does fine with the high voltage sign # It may cause spacing issues in other OSes function prompt_marker() { if [[ "$OSTYPE" == "darwin"* ]] then echo "⚡︎" else echo "\$ " fi } function prompt_command() { ps_reboot="${bright_yellow}$(show_reboot_required)\n${normal}" ps_username="$(set_user_color)\u${normal}" ps_uh_separator="${steel}@${normal}" ps_hostname="$(set_host_color)\h${normal}" ps_path="${dark_olive}\w${normal}" ps_scm_prompt="${light_grey}$(scm_prompt)${normal}" ps_user_mark="${steel}\n $(prompt_marker) ${normal}" ps_user_input="${normal}" # Set prompt PS1="$ps_reboot$(__ps_time) $ps_scm_prompt\n$ps_username$ps_uh_separator$ps_hostname $ps_path $ps_user_mark$ps_user_input" ## 01 February 23:45 ±<branch> ↑1 ↓4 U:1 ✗ ## <user>@<machine> ~ ## ⚡︎ } # Initialize custom colors set_custom_colors # Clock theming THEME_CLOCK_COLOR=${THEME_CLOCK_COLOR:-"$dark_grey"} THEME_CLOCK_FORMAT="%d %B %H:%M" # scm theming SCM_THEME_PROMPT_PREFIX="" SCM_THEME_PROMPT_SUFFIX="" SCM_THEME_PROMPT_DIRTY=" ${bold_red}✗${light_grey}" SCM_THEME_PROMPT_CLEAN=" ${green}✓${light_grey}" SCM_GIT_CHAR="${green}±${light_grey}" SCM_SVN_CHAR="${bold_cyan}⑆${light_grey}" SCM_HG_CHAR="${bold_red}☿${light_grey}" safe_append_prompt_command prompt_command <file_sep>Driftless is a theme for Oh My Posh and Bash-It ## Oh My Posh 1. Install [Oh My Posh](https://ohmyposh.dev/) 2. Clone this repo 3. Update your [OMP settings](https://ohmyposh.dev/docs/installation/prompt) to point to the location of `driftless.omp.json` ## Bash-It (Deprecated) 1. Install [Bash-It](https://github.com/Bash-it/bash-it) 2. Run the following lines of code ``` $ mkdir ~/.bash_it/custom/themes && cd $_ $ git clone https://github.com/theodinspire/driftless.git ``` 3. Edit your `~/.bashrc` file, setting Bash-It's theme to `driftless`
f13e953e3fd7b57c70e8eacb20e708beed8feb2d
[ "Markdown", "Shell" ]
2
Shell
theodinspire/driftless
74d097202d2261b2a82cf31036a130e3fa41f9fa
f24cf2cf17a947a1e3ef61f4762ffb6cf68409df
refs/heads/master
<file_sep>export interface ICard { image?: string, fontSize?: string, paddingTop?: string, bgColor?: string, width?: string, bShadow?: boolean, border?: string, main?: boolean }<file_sep>import styled from 'styled-components'; import { IModalStyled } from './Modal.interface'; export const ModalFade = styled.div` align-items: center; background-color: rgba(0, 0, 0, .5); bottom: 0; display: flex; height: 100%; justify-content: center; left: 0; position: fixed; right: 0; top: 0; width: 100%; z-index: 5; `; export const ModalContainer = styled.div` background: #121212; box-shadow: 1px 2px 8px 2px #1e1e1e; display: flex; flex-direction: column; height: 95vh; position: absolute; top: 5vh; width: 40%; z-index: 6; `; export const ModalWalppaper = styled.div<IModalStyled>` background: ${props => `url(${props.image})`} no-repeat center; background-size: cover; box-shadow: inset 0px -42px 36px -8px #121212, 0 42px 36px 8px #121212; display: block; height: 55%; width: 100%; `; export const ModalDescription = styled.div<IModalStyled>` color: #fff; font-family: Arial, Helvetica, sans-serif; display: flex; flex-direction: column; overflow-y: auto; padding: 10px 20px; width: 100%; p { margin-bottom: 5px; } > p:last-of-type { color: #29d429; font-weight: bold; margin-bottom: 5vh; } .flex:first-child { margin: 5vh 0; } .flex:not(:first-child) { margin-bottom: 5px; } .description { line-height: 1.40; margin-bottom: 30px; width: 90%; } .flex { align-items: center; display: flex; p:last-child:not(:only-child) { margin-left: 20px; span { color: #222; font-size: 1.1em; font-weight: bolder; background-color: #e4e40c; margin-left: 5px; padding: 2px 8px; } } .link { &:hover { color: #cecece; cursor: pointer; transform: scale(1.1); transition: .2s ease-in; } } } @media (max-width: 768px) { width: -webkit-fill-available !important; .flex { flex-direction: column; p:last-child:not(:only-child) { margin: 20px 0 !important; } span { display: inline-block; } } } `;<file_sep>export interface IModal { show: boolean, type: string, image: string, name?: String, gender?: String, created?: String, films?: Number, starships?: Number characters?: Object, director?: String, edited?: String, episode_id?: Number, opening_crawl?: string, planets?: Object, producer?: String, release_date?: String species?: Object, title?: String, url?: string, vehicles?: Object, } export interface IModalStyled { image?: string }<file_sep>import styled from 'styled-components'; import { INavbar } from './Navbar.interface'; export const Navbar = styled.nav<INavbar>` font-family: sans-serif; align-items: center; background: ${props => props.scrolled ? '#141414' : '#1c1e2280' }; display: flex; height: 8vh; margin-bottom: 7vw; padding-left: 2vw; position: fixed; transition: .5s ease-in; width: -webkit-fill-available; z-index: 2; a { text-decoration: initial; margin: auto 10px; } a, a:visited { color: #fff; } a:hover:not(.scrolled) { color: #686868; transform: scale(1.1); transition: .2s ease-in-out; } a.scrolled:hover { color: #cecece; } a:first-child { background: ${props => `url(${props.image})`} no-repeat center; background-size: contain; width: 6vw; height: 4vh; margin-right: 3vw; } `;<file_sep>import React, { useEffect, useState } from 'react'; import { Router, Switch, Link, Route, Redirect } from 'react-router-dom'; import { Navbar } from './components/styled/Navbar/Navbar'; import Main from './views/Main/Main'; import Characters from './views/Characters/Characters.tsx'; import Films from './views/Films/Films.tsx'; import NotFound from './views/NotFound/NotFound.tsx'; import history from './history'; import starWarsLogo from './assets/img/Star_Wars_logo.png'; const Routes = () => { const [scroll, setScroll] = useState(window.scrollY); useEffect(() => { window.addEventListener("scroll", () => setScroll(window.scrollY)); }, []); return <> <Router history={history} forceRefresh={true}> <Navbar image={starWarsLogo} scrolled={scroll > 0 ? true : false} > <Link to="/" className={!scroll > 0 ? 'scrolled' : ''}></Link> <Link to="/films" className={!scroll > 0 ? 'scrolled' : ''}>Films</Link> <Link to="/characters" className={!scroll > 0 ? 'scrolled' : ''}>Characters</Link> </Navbar> <Switch> <Route exact path='/' render={() => <Main />} /> <Route exact path='/films' render={() => <Films />} /> <Route exact path='/characters' render={() => <Characters />} /> <Route path='/404' render={() => <NotFound />} /> <Redirect to="/404" /> </Switch> </Router> </> } export default Routes;<file_sep>export interface IFilms { characters: Object, created: String, director: String, edited: String, episode_id: Number, opening_crawl: string, planets: Object, producer: String, release_date: String species: Object, starships: Object, title: String, url: string, vehicles: Object, showDescription: Boolean }<file_sep>export interface INavbar { image: String, scrolled: Boolean }<file_sep>import styled from 'styled-components'; import { ICard } from './Card.interface'; export const CardWallpapper = styled.div<ICard>` overflow: visible; background: ${props => `url(${props.image})`} no-repeat center; background-size: cover; box-shadow: inset 0px -42px 36px -8px #1b1b1b, 0 42px 36px 8px #1b1b1b; height: 55vh; position: absolute; top: 0; width: -webkit-fill-available; `; export const CardContainer = styled.div<ICard>` align-items: center; display: flex; flex-direction: column; padding-top: ${props => props.paddingTop}; `; export const CardBoxContainer = styled.div<ICard>` align-items: center; display: flex; flex-wrap: wrap; justify-content: center; margin-top: ${props => !props.main ? '45vh' : 0}; width: -webkit-fill-available; `; export const CardTitle = styled.h1<ICard>` color: #fff; font-family: Arial, Helvetica, sans-serif; font-size: ${props => `${props.fontSize}em`}; margin-bottom: 5vh; `; export const CardBox = styled.div<ICard>` align-items: center; display: flex; flex-direction: column; margin: 2vh 1vw; opacity: ${props => props.main ? 0.5 : 1}; width: ${props => `${props.width}`}; &:hover { opacity: ${props => props.main ? 1 : 1}; transform: ${props => !props.bShadow ? 'scale(1.2, 1.5)' : ''}; transition: .2s ease-in; } @media (max-width: 768px) { width: 40vw; } `; export const Card = styled.div<ICard>` background: ${props => `${props.bgColor ? props.bgColor : ''} url(${props.image})`} no-repeat center; background-size: cover; border-radius: ${props => props.border === 'full' ? '5px' : '0'}; border-top-left-radius: ${props => props.border === 'top' ? '5px' : '0'}; border-top-right-radius: ${props => props.border === 'top' ? '5px' : '0'}; cursor: pointer; display: flex; flex-direction: column-reverse; height: 22vh; width: ${props => `${props.width}`}; &:hover { box-shadow: ${props => props.bShadow ? 'inset 0px 0px 0px 3px #fff' : ''}; + .title { color: #fff; } } + .title { color: grey; font-family: Arial, Helvetica, sans-serif; font-size: 1.2em; margin-top: 10px; } @media (max-width: 768px) { width: 40vw; } `; export const CardDescription = styled.div<ICard>` color: #fff; font-family: Arial, Helvetica, sans-serif; font-size: .7em; font-weight: bold; background: #171717; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; box-shadow: 0px 3px 6px -1px #333; display: flex; flex-direction: column; padding: 10px; width: -webkit-fill-available; .area-button, .area-info, .area-tags{ align-items: center; display: flex; &:not(:last-child) { margin-bottom: 10px; } .button, .info, .tag { margin: 5px 10px; } } .area-button { justify-content: flex-start; .button { align-items: center; border-radius: 15px; box-shadow: 0px 0px 3px 1px #ccc6; cursor: pointer; display: flex; height: 30px; justify-content: center; width: 33px; :last-child { margin-left: auto; } img { height: 10px; width: 10px; } } } .area-info { flex-wrap: wrap; .info { &:first-child { color: #29d429; } span { color: #222; font-size: 1.1em; font-weight: bolder; background-color: #e4e40c; margin-left: 5px; padding: 2px 8px; } } } .area-tags { align-items: center; display: flex; flex-wrap: wrap; .tag:not(:first-child)::before { background: #4d4d4d; border-radius: 2px; content: ''; display: inline-block; height: 4px; margin-right: 10px; width: 4px; } } `;
8c4728eaaed9bc7cd916185f4d289d9e9a9e7668
[ "JavaScript", "TypeScript" ]
8
TypeScript
jpcanto/prova_NTConsult
a9c68837f14f350616cb98f348344a7fd2c31880
95d1191b2411cf958afa14c7ce745160efc777a7