text:
<file_sep>#ifndef sector_class
#define sector_class

#include "./spaceship.h"
#include "./trading_station.h"
#include "./planet.h"

class Sector {
    private:
        int sector_width;
        bool journey;
    public:
        Sector(SpaceShip*);
        bool journey_ended();
        void spaceship_encountered(SpaceShip*, SpaceShip*);
        void planet_encountered(Planet*, SpaceShip*);
        void trading_station_encountered(TradingStation*, SpaceShip*);
        void abandoned_spaceship_encountered(SpaceShip*, SpaceShip*);
};

#endif

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/species_attributes.h"

SpeciesAttributes::SpeciesAttributes() {
    this->diplomacy = rand() % 100 + 1;
    this->trading = rand() % 100 + 1;
}

int SpeciesAttributes::get_diplomacy_score() {
    return this->diplomacy;
}

int SpeciesAttributes::get_trading_score() {
    return this->trading;
}
<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/planet.h"

Planet::Planet() {
    this->name = planet_names[rand() % planet_names.size()];
    this->resources = new Resource(2);
    this->civilization = new Species();
}

string Planet::get_name() {
    return this->name;
}

int Planet::diplomacy() {
    return this->civilization->diplomacy();
}

void Planet::mining(SpaceShip *spaceship) {
    int mining_ability = spaceship->mining_ability();
    int food_needed = spaceship->food_needed();
    int fuel_needed = spaceship->fuel_needed();
    int gold_needed = spaceship->gold_needed();
    int scrap_needed = spaceship->scrap_needed();

    int food;
    int fuel;
    int gold;
    int scrap;

    if(food_needed < mining_ability) {
        food = food_needed;
    } else {
        food = (food_needed * mining_ability)/100;
    }

    if(fuel_needed < mining_ability) {
        fuel = fuel_needed;
    } else {
        fuel = (fuel_needed * mining_ability)/100;
    }

    if(gold_needed < mining_ability) {
        gold = gold_needed;
    } else {
        gold = (gold_needed * mining_ability) / 100;
    }

    if(scrap_needed < mining_ability) {
        scrap = scrap_needed;
    } else {
        scrap = (scrap_needed * mining_ability) / 100;
    }

    output_file << "            Resources mined : " << endl;
    output_file << "                Food collected : " << food << endl;
    output_file << "                Fuel mined : " << fuel << endl;
    output_file << "                Gold mined : " << gold << endl;
    output_file << "                Scrap Metal mined : " << scrap << endl;

    Resource *mined = new Resource(food, fuel, gold, scrap);
    spaceship->resources = spaceship->resources->operator+(mined);
    delete mined;
}

void Planet::trading(SpaceShip *spaceship) {
    this->civilization->trade(spaceship);
}

void Planet::conflict(SpaceShip *spaceship) {
    spaceship->combat(this->civilization->get_spaceship());
}

<file_sep>compile:
	g++ main.cpp ./src/components/*.cpp -o JSE

run:
	./JSE 20
<file_sep>#ifndef species_attributes_class
#define species_attributes_class

class SpeciesAttributes {
    protected:
        int diplomacy;
        int trading;

    public:
        SpeciesAttributes();

        int get_diplomacy_score();
        int get_trading_score();
};

#endif

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/species.h"

Species::Species() {
    this->name = species_names[rand() % species_names.size()];
    this->attributes = new SpeciesAttributes();
    this->resources = new Resource(1);
    this->spaceship = new SpaceShip(true, this->attributes->get_diplomacy_score(), this->attributes->get_trading_score());
}

string Species::get_species_name() {
    return this->name;
}

int Species::diplomacy() {
    return this->attributes->get_diplomacy_score();
}

void Species::trade(SpaceShip *another_spaceship) {
    int trade_multiplier;
    bool traveler_trade = (rand() % 100 + 1) <= another_spaceship->trading();
    bool species_trade = (rand() % 100 + 1) <= this->attributes->get_trading_score();

    if(traveler_trade && species_trade) {
        trade_multiplier = 4;
        this->do_trading(another_spaceship, trade_multiplier);
    } else if(traveler_trade && !species_trade) {
        trade_multiplier = 3; // If they are bad at trading, they end up paying more
        this->do_trading(another_spaceship, trade_multiplier);
    } else if (!traveler_trade && species_trade) {
        trade_multiplier = 5; // If travelers are bad at trading, they end up paying more
        this->do_trading(another_spaceship, trade_multiplier);
    }
}

void Species::do_trading(SpaceShip *another_spaceship, int multiplier) {
    if(another_spaceship->resources->get_fuel() > 1000) {
        if((this->resources->get_food()-5000) > another_spaceship->resources->get_food()) {
            // FOOD
            int needed = another_spaceship->food_needed();
            if(another_spaceship->resources->get_gold() < (needed*multiplier)/4) {
                needed = (another_spaceship->resources->get_gold() * 4) / multiplier;
            }
            int cost = (needed*multiplier)/4;
            output_file << "                Got " << needed << " food for " << cost << " gold." << endl;
            Resource *res = new Resource(needed, 0, -cost, 0);
                another_spaceship->resources = another_spaceship->resources->operator+(res);
                this->resources = this->resources->operator-(res);
            delete res;
        }
    }

    if((this->resources->get_fuel()-5000) > another_spaceship->resources->get_fuel()) {
        // FUEL
        int needed = another_spaceship->fuel_needed();
        if(another_spaceship->resources->get_gold() < (needed*multiplier)/4) {
            needed = (another_spaceship->resources->get_gold() * 4) / multiplier;
        }
        int cost = (needed * multiplier) / 4;
        output_file << "                Got " << needed << " fuel for " << cost << " gold." << endl;
        Resource *res = new Resource(0, needed, -cost, 0);
            another_spaceship->resources = another_spaceship->resources->operator+(res);
            this->resources = this->resources->operator-(res);
        delete res;
    }

    if((this->resources->get_scrap_metal()-5000) > another_spaceship->resources->get_scrap_metal()) {
        // METAL
        int needed = another_spaceship->scrap_needed();
        if(another_spaceship->resources->get_gold() < (needed*multiplier)/4) {
            needed = (another_spaceship->resources->get_gold() * 4) / multiplier;
        }
        int cost = (needed*multiplier)/4;
        Resource *res = new Resource(0, 0, -cost, needed);
            output_file << "                Got " << needed << " scrap metal for " << cost << " gold." << endl;
            another_spaceship->resources = another_spaceship->resources->operator+(res);
            this->resources = this->resources->operator-(res);
        delete res;
    }

}

SpaceShip* Species::get_spaceship() {
    return this->spaceship;
}

<file_sep>-------------------------------------------------------------------------------------------------------------------------------------

Project Title - A Journey Of Space Exploration

Name - <NAME>

-------------------------------------------------------------------------------------------------------------------------------------

Instructions :
    Compile :
        cd <Directory>
        CC -std=c++11 -o JSE ./main.cpp ./src/components/*.cpp

    Run :
        ./JSE <number of sectors>

-------------------------------------------------------------------------------------------------------------------------------------

Project Structure :
    Folder Name :
        - File Name

-------------------------------------------------------------------------------------------------------------------------------------

Project Structure :
    - main.cpp - *Application Logic*
    headers :
        - all_imports.h - Contains all the imports from libraries and global variables
        classes : *All the class declaration*
            - crew_member_attributes.h
            - crew_member.h
            - dead_crew_member.h
            - planet.h
            - resource.h
            - setor.h
            - spaceship.h
            - species_attributes.h
            - species.h
            - trading_station.h
    src :
        assets : *text files*
            - planet_names.txt
            - spaceship_names.txt
            - species_names.txt
            - trading_station_names.txt
            crew : *text files for crew member names*
                - first_names.txt
                - last_names.txt
        components : *All the class definitions*
            - crew_member_attributes.cpp
            - crew_member.cpp
            - dead_crew_member.cpp
            - planet.cpp
            - resource.cpp
            - setor.cpp
            - spaceship.cpp
            - species_attributes.cpp
            - species.cpp
            - trading_station.

-------------------------------------------------------------------------------------------------------------------------------------

Simulation Logic :

1. The simulation takes the number of sectors as input from the command line at the beginning. The program terminates if the
number is less than 1 or greater than 50.

2. 5 objects of the class Species are created out of which one is chosen randomly using rand() function. Every Species have their
own spaceship, so that spaceship is chosen as our traveler for our journey.

3. A loop is run between 0 and the input value(-1) and for every iteration an object of class Sector is created.

4. At the beginning of the journey, the resources consumed are calculated for the distance traveled in that sector. If the resources
have been depleted enough for the journey to get over, then the loop will be terminated. Otherwise the journey will continue. In
case if the spaceship has been in a battle in previous sector and their spaceship health has depleted to 0 or crew members have all
died, then the journey will be terminated.

5. A random number is generate between 1 and 100. If the number is between 1 and 35, a spaceship is encountered. If the number
is between 36 and 60, a planet is encountered. If the number is between 61 and 75, a Trading Station is encountered. If the number
is between 76 and 90, an empty sector is encountered. If the number is between 91 and 100, an abandoned spaceship is encountered.

6. In case of a spaceship encounter, if the diplomacies of both the captains match, then they will trade. If not, then they will
have a combat. In case of trading, if either of the captains have better trading skills than the other, then that spaceship will be
benefited (by giving less gold for goods) and vice versa. In case of combat, The spaceship will try to run away if the number of
crew is less or if the spaceship health is low. Depending on the skills of the crew, the spaceship can evade attacks and reduce
the damage taken by the spaceship from a missile, launched by the enemy. A number of crew members and the officers die when damage
is taken.

7. In case of a planet encounter, the travelers will meet any species residing on that planet. If the diplomacy levels match,
the species may allow the traveler to do mining on their planet. In case if only either of them are happy with this encounter,
then they will agree on trade. Otherwise there will be a conflict and the species will launch a spaceship for battle.

8. In case of a trading station encounter, the travelers will come in contact with another alien species. Depending on their trading
skills, either of them will be benefited or both will have a fair trade if their trading skills are good.

9. In case of an empty sector, the traveler will not come in contact with anyone and will just end up using resources while traveling.

10. In case the travelers come in contact with an abandoned spaceship, the traveler will take the resources they have left and also
accommodate the remaining crew members of that spaceship on theirs.

11. At the end of the simulation the remaining resources, crew information, officers information and dead crew member information
will be displayed in the output file. In case the journey ends because of some other reason, then the reason will be stated as well.

-------------------------------------------------------------------------------------------------------------------------------------
<file_sep>#include "./headers/all_imports.h"
#include "./headers/classes/sector.h"
#include "./headers/classes/spaceship.h"
#include "./headers/classes/species.h"

vector<string> crew_first_names;
vector<string> crew_last_names;

vector<string> spaceship_names;
vector<string> planet_names;
vector<string> species_names;
vector<string> trading_stations_names;

ofstream output_file;
string output_file_name;

int current_sector;
int day;

void load_text_files();

int main(int inputs, char **args) {
    if(inputs != 2) {
        /* The number of parameters inserted in the command line */
        cerr << "The number of expected parameters do not match..." << endl;
        return 0;
    }
    else {
        srand(time(0));
        load_text_files();
        output_file_name = "output";
        output_file.open(output_file_name, ios::trunc);
        output_file.close();

        day = 1;

        output_file.open(output_file_name, ios::app);
        output_file << "Choosing a spaceship among : " << endl;

        vector<Species> species;
        for(int i=0;i<5; i++) {
            output_file << "    Spaceship " << i+1 << " : " << endl;
            Species ss;
            output_file << "        Name of the Species : " << ss.get_species_name() << endl;
            output_file << "        Name of the Spaceship : " << ss.get_spaceship()->getName() << endl;
            output_file << endl;
            species.push_back(ss);
            // delete ss;
        }

        int random = rand() % 5;

        /* Checking the value for the number of sectors*/
        int sector_number = stoi(args[1]);
        if (sector_number > 50 || sector_number < 1){
            cerr << "Please Enter a number between 1 and 50" << endl;
            return 0;
        }

        output_file << "Spaceship chosen : " << endl;
        output_file << "    Species : " << species[random].get_species_name() << endl;
        species[random].get_spaceship()->getInfo();

        output_file << "        Captain :" << endl;
        species[random].get_spaceship()->get_captain_info();

        output_file << "        Pilot :" << endl;
        species[random].get_spaceship()->get_pilot_info();

        output_file << "        Engineer :" << endl;
        species[random].get_spaceship()->get_engineer_info();

        output_file << "        Mining Officer :" << endl;
        species[random].get_spaceship()->get_mining_officer_info();

        output_file << "        Weapon Officer :" << endl;
        species[random].get_spaceship()->get_weapon_officer_info();

        output_file << "\nThe Journey Begins...\n" << endl;

        output_file << "========================= Sector Beginning ===========================" << endl;
        output_file << "    DAY : " << day << endl;

        cout << "Journey starting..." << endl;
        for (int i = 0; i < sector_number; i++) {
            current_sector = i+1;
            cout << "Sector Number : " << current_sector << endl;

            output_file << "    Sector Number : " << i + 1 << endl;
            Sector *sector = new Sector(species[random].get_spaceship());
            if(sector->journey_ended()) {
                delete sector;
                break;
            } else {
                delete sector;
            }
            output_file << "    Resources left at the end of the sector :" << endl;
            species[random].get_spaceship()->resources->getInfo();
            output_file << endl;
            output_file << "======================== Sector End ===========================" << endl;
            output_file << endl;
        }
        cout << "Journey Finished." << endl;

        output_file << "JOURNEY FINISHED.\n" << endl;

        output_file << "Spaceship status :" << endl;
        species[random].get_spaceship()->getInfo();
        species[random].get_spaceship()->resources->getInfo();

        output_file << "    Captain :" << endl;
        species[random].get_spaceship()->get_captain_info();

        output_file << "    Pilot :" << endl;
        species[random].get_spaceship()->get_pilot_info();

        output_file << "    Engineer :" << endl;
        species[random].get_spaceship()->get_engineer_info();

        output_file << "    Mining Officer :" << endl;
        species[random].get_spaceship()->get_mining_officer_info();

        output_file << "    Weapon Officer :" << endl;
        species[random].get_spaceship()->get_weapon_officer_info();

        output_file << "    Crew Members :" << endl;
        species[random].get_spaceship()->get_crew_info();

        output_file << "    Dead Crew Members :" << endl;
        species[random].get_spaceship()->get_dead_crew_info();

        output_file.close();
        return 0;
    }
}

void load_text_files() {
    ifstream crew_first_names_file, crew_last_names_file, spaceship_names_file, planet_names_file, species_names_file, trading_stations_names_file;

    // FIRST NAMES FOR CREW MEMBERS
    crew_first_names_file.open("./src/assets/crew/first_names.txt");
    if(!crew_first_names_file) {
        cerr << "Error Loading file." << endl;
    } else {
        while(!crew_first_names_file.eof()) {
            string x;
            crew_first_names_file >> x;
            crew_first_names.push_back(x);
        }
    }
    crew_first_names_file.close();

    // LAST NAMES FOR CREW MEMBERS
    crew_last_names_file.open("./src/assets/crew/last_names.txt");
    if(!crew_last_names_file) {
        cerr << "Error Loading file." << endl;
    } else {
        while(!crew_last_names_file.eof()) {
            string x;
            crew_last_names_file >> x;
            crew_last_names.push_back(x);
        }
    }
    crew_first_names_file.close();

    // NAMES FOR SPACESHIP
    spaceship_names_file.open("./src/assets/spaceship_names.txt");
    if(!spaceship_names_file) {
        cerr << "Error Loading file." << endl;
    } else {
        while(!spaceship_names_file.eof()) {
            string x;
            spaceship_names_file >> x;
            spaceship_names.push_back(x);
        }
    }
    crew_first_names_file.close();

    // NAMES FOR PLANETS
    planet_names_file.open("./src/assets/planet_names.txt");
    if(!planet_names_file) {
        cerr << "Error Loading file." << endl;
    } else {
        while(!planet_names_file.eof()) {
            string x;
            planet_names_file >> x;
            planet_names.push_back(x);
        }
    }
    crew_first_names_file.close();

    // NAMES FOR SPECIES
    species_names_file.open("./src/assets/species_names.txt");
    if(!species_names_file) {
        cerr << "Error Loading file." << endl;
    } else {
        while(!species_names_file.eof()) {
            string x;
            species_names_file >> x;
            species_names.push_back(x);
        }
    }
    crew_first_names_file.close();

    // NAMES FOR TRADING STATIONS
    trading_stations_names_file.open("./src/assets/trading_station_names.txt");
    if(!trading_stations_names_file) {
        cerr << "Error Loading file." << endl;
    } else {
        while(!trading_stations_names_file.eof()) {
            string x;
            trading_stations_names_file >> x;
            trading_stations_names.push_back(x);
        }
    }
    crew_first_names_file.close();

}
<file_sep>#ifndef crew_member_attributes_class
#define crew_member_attribites_class

#include "./species_attributes.h"

class CrewMemberAttributes: public SpeciesAttributes {
    protected:
        int travel_efficiency;
        int combat_maneuvers;
        int conflict_evasion;
        int system_recovery;

        int mining_ability;
        int offensive_performance;
        int defensive_performance;

    public:
        CrewMemberAttributes();
        CrewMemberAttributes(int, int);

        void getInfo();

        int captain_score();
        int pilot_score();
        int engineer_score();
        int mining_score();
        int weapon_score();
};

#endif

<file_sep>#ifndef dead_crew_member_class
#define dead_crew_member_class

#include "./crew_member.h"

class DeadCrewMember: public CrewMember {
    private:
        int place_of_death;
        int time_of_death;
    public:
        DeadCrewMember();
        DeadCrewMember(CrewMember);
        void set_death();
        void getInfo();

};

#endif

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/dead_crew_member.h"

DeadCrewMember::DeadCrewMember() {
    this->place_of_death = current_sector;
    this->time_of_death = day;
}

void DeadCrewMember::set_death() {
    this->place_of_death = current_sector;
    this->time_of_death = day;
}

DeadCrewMember::DeadCrewMember(CrewMember crew_member) {
    this->name = crew_member.get_name();
    this->role = crew_member.get_designation();
    this->age = crew_member.get_age();
    this->is_officer = crew_member.is_officer;

    this->place_of_death = current_sector;
    this->time_of_death = day;
}

void DeadCrewMember::getInfo() {
    output_file << "                Name : " << this->name << endl;
    output_file << "                Age : " << this->age << endl;
    output_file << "                Role : " << this->role << endl;
    output_file << "                Place of Death : Sector " << this->place_of_death << endl;
    output_file << "                Day of Death : " << this->time_of_death << endl;

    output_file << endl;
}
<file_sep>#ifndef crew_member_class
#define crew_member_class

#include "./crew_member_attributes.h"

class CrewMember {
    protected:
        string name;
        string role;
        int age;

        CrewMemberAttributes *attributes;

    public:
        bool is_officer;

        string get_name();
        string get_designation();
        int get_age();

        int captain_score();
        int pilot_score();
        int engineer_score();
        int mining_score();
        int weapon_score();

        CrewMember();
        CrewMember(int, int);
        void getInfo();
        void change_officer_status(string);

};

#endif

<file_sep>#ifndef species_class
#define species_class

#include "./species_attributes.h"
#include "./resource.h"
#include "./spaceship.h"

class Species {
    private:
        string name;
        SpeciesAttributes *attributes;
        Resource *resources;
        SpaceShip *spaceship;
        void do_trading(SpaceShip*, int);

    public:
        Species();
        string get_species_name();
        int diplomacy();
        void trade(SpaceShip*);
        SpaceShip* get_spaceship();
};

#endif

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/spaceship.h"
#include "../../headers/classes/crew_member.h"

SpaceShip::SpaceShip(bool active) {
    this->name = spaceship_names[rand() % spaceship_names.size()];

    /*  Cargo Distribution  */
    this->fuel_capacity = rand() % 1500 + 7000;
    this->food_capacity = rand() % 1500 + 5000;
    this->crew_capacity = rand() % 50 + 25;
    this->scrap_capacity = rand() % 1000 + 1500;
    this->gold_capacity = rand() % 1000 + 3000;
    this->resources = new Resource(0);

    if(active) {
        int crew_number = rand() % 20 + (this->crew_capacity - 20);
        for(int i = 0; i < crew_number; i++) {
            CrewMember crew_member;
            this->crew.push_back(crew_member);
        }
        this->find_officers();
    } else {
        int crew_number = rand() % 20 + 5;
        for(int i = 0; i < crew_number; i++) {
            CrewMember crew_member;
            this->crew.push_back(crew_member);
        }
    }
    this->speed = rand() % 40 + 60;
    this->spaceship_health = rand() % 30 + 70;
}

SpaceShip::SpaceShip(bool active, int species_diplomacy, int species_trading) {
    this->name = spaceship_names[rand() % spaceship_names.size()];

    /*  Cargo Distribution  */
    this->fuel_capacity = rand() % 1500 + 7000;
    this->food_capacity = rand() % 1500 + 5000;
    this->crew_capacity = rand() % 50 + 25;
    this->scrap_capacity = rand() % 1000 + 1500;
    this->gold_capacity = rand() % 1000 + 5000;
    this->resources = new Resource(0);

    if(active) {
        int crew_number = rand() % 20 + (this->crew_capacity - 20);
        for(int i = 0; i < crew_number; i++) {
            CrewMember crew_member(species_diplomacy, species_trading);
            this->crew.push_back(crew_member);
        }
        this->find_officers();
    } else {
        int crew_number = rand() % 20 + 5;
        for(int i = 0; i < crew_number; i++) {
            CrewMember crew_member;
            this->crew.push_back(crew_member);
        }
    }
    this->speed = rand() % 40 + 60;
    this->spaceship_health = rand() % 30 + 70;
}

void SpaceShip::find_officers() {
    this->find_captain();
    this->find_pilot();
    this->find_engineer();
    this->find_mining_officer();
    this->find_weapon_officer();
}

string SpaceShip::getName() {
    return this->name;
}

void SpaceShip::getInfo() {
    output_file << "    Spaceship : " << this->name << endl;
    output_file << "    Fuel Capacity : " << this->fuel_capacity << endl;
    output_file << "    Food Capacity : " << this->food_capacity << endl;
    output_file << "    Crew Capacity : " << this->crew_capacity << endl;
    output_file << "    Defensive Performance : " << this->defensive_performance() << endl;
    output_file << "    Offensive Performance : " << this->offensive_performance() << endl;
    output_file << "    Mining Potential : " << this->mining_ability() << endl;
    output_file << "    Travel Effeciency : " << this->travel_efficiency() << endl;
    output_file << "    Spaceship Speed : " << this->speed << endl;
    output_file << "    Spaceship Health : " << this->spaceship_health << endl;
}

void SpaceShip::operator+(SpaceShip *spaceship) {
    output_file << "            Crew Members added : " << spaceship->crew.size() << endl;
    for(int i=0; i<spaceship->crew.size(); i++) {
        if(this->crew.size() < this->crew_capacity) {
            this->crew.push_back(spaceship->crew[i]);
        }
    }
    output_file << "            Resources added : " << endl;
    output_file << "                Food : " << spaceship->resources->get_food() << endl;
    output_file << "                Fuel : " << spaceship->resources->get_fuel() << endl;
    output_file << "                Gold : " << spaceship->resources->get_gold() << endl;
    output_file << "                Metal : " << spaceship->resources->get_scrap_metal() << endl;

    this->resources = this->resources->operator+(spaceship->resources);

    int extra_food = 0;
    int extra_fuel = 0;
    int extra_gold = 0;
    int extra_scrap = 0;

    if(this->resources->get_food() > this->food_capacity) {
        extra_food = this->resources->get_food() - this->food_capacity;
    }

    if(this->resources->get_fuel() > this->food_capacity) {
        extra_fuel = this->resources->get_fuel() - this->fuel_capacity;
    }

    if(this->resources->get_gold() > this->food_capacity) {
        extra_gold = this->resources->get_gold() - this->gold_capacity;
    }

    if(this->resources->get_scrap_metal() > this->food_capacity) {
        extra_scrap = this->resources->get_scrap_metal() - this->scrap_capacity;
    }

    output_file << "            Extra Resources removed : " << endl;
    output_file << "                Food : " << extra_food << endl;
    output_file << "                Fuel : " << extra_fuel << endl;
    output_file << "                Gold : " << extra_gold << endl;
    output_file << "                Metal : " << extra_scrap << endl;

    Resource *res = new Resource(extra_food, extra_fuel, extra_gold, extra_scrap);
    this->resources = this->resources->operator-(res);
    delete res;

}

bool SpaceShip::operator==(SpaceShip *spaceship) {
    if(
        this->name == spaceship->name &&
        this->fuel_capacity == spaceship->fuel_capacity &&
        this->food_capacity == spaceship->food_capacity &&
        this->crew_capacity == spaceship->crew_capacity &&
        this->scrap_capacity == spaceship->scrap_capacity &&
        this->gold_capacity == spaceship->gold_capacity &&
        this->speed == spaceship->speed &&
        this->spaceship_health == spaceship->spaceship_health
    ) {
        return true;
    } else {
        return false;
    }
}

void SpaceShip::fuel_consume(int amount) {
    Resource *res = new Resource(0, amount, 0, 0);
    this->resources = this->resources->operator-(res);
    delete res;
}

bool SpaceShip::travel(int distance) {

    output_file << "    Travel : " << endl;

    // FOOD CONSUMPTION
    int food_consumed = (this->crew.size() + 5)*distance/10;
    int food_available = this->resources->get_food();
    if(food_available < food_consumed) {
        output_file << "---LOW ON FOOD---" << endl;
        return true;
    }

    // FUEL CONSUMPTION
    int fuel_consumed = distance*7;
    fuel_consumed = (fuel_consumed * travel_efficiency()) / 100;
    int fuel_available = this->resources->get_fuel();
    if(fuel_available < fuel_consumed) {
        // Journey over if no fuel
        output_file << "---LOW ON FUEL---" << endl;
        return true;
    }

    // SYSTEM RECOVERY
    int health_recoverable = 100 - this->spaceship_health;
    int can_be_recovered = distance/10;

    if(can_be_recovered < health_recoverable) {
        health_recoverable = can_be_recovered;
    }

    int metal_required = health_recoverable*100; // 100 metal scrap for 1 health of spaceship
    if(metal_required > this->resources->get_scrap_metal()) {
        metal_required = this->resources->get_scrap_metal();
    }

    health_recoverable = metal_required/100;
    this->spaceship_health = this->spaceship_health + health_recoverable;

    output_file << "        Food Consumed : " << food_consumed << endl;
    output_file << "        Fuel Consumed : " << fuel_consumed << endl;
    output_file << "        Ship Health : " << this->spaceship_health << endl;
    output_file << "        Material Consumed : " << metal_required << endl;

    Resource *res = new Resource(food_consumed, fuel_consumed, 0, metal_required);
    this->resources = this->resources->operator-(res);
    delete res;
    return false;
}

void SpaceShip::combat(SpaceShip *spaceship) {
    bool fighting = true;
    int *spaceship_health1 = new int(this->spaceship_health);
    int *spaceship_health2 = new int(spaceship->spaceship_health);

    SpaceShip *current_spaceship = this;
    SpaceShip *other_spaceship = spaceship;
    int *current_health = spaceship_health1;
    int *other_health = spaceship_health2;

    while(fighting) {
        int original_health = current_spaceship->spaceship_health;
        original_health = (original_health * 70) / 100;

        if(current_spaceship->crew.size() < 1) {
            output_file << "                ------- " << current_spaceship->getName() << " have no crew left! -------" << endl;
            fighting = false;
            break;
        }

        if(current_spaceship->spaceship_health < 1) {
            output_file << "                ------- " << current_spaceship->getName() << " is destroyed! -------" << endl;
            fighting = false;
            break;
        }

        if(*current_health < original_health || current_spaceship->crew.size() < 10) {
            //try to run if health below 30%
            int evasion = current_spaceship->conflict_evasaion();
            if((rand() % 100 + 1) <= evasion){
                output_file << "                " << current_spaceship->getName() << " ran away!" << endl;
                fighting = false;
                break;
            }
        } else {
            try {
                output_file << "                " << current_spaceship->getName() << " launched a missile!" << endl;
                if((rand() % 100 + 1) <= other_spaceship->combat_maneuvers() && other_spaceship->resources->get_fuel() > 55) {
                    // damage evaded
                    other_spaceship->fuel_consume(rand()%5 + 1); // Fuel gets consumed to dodge attack
                    output_file << "                " << other_spaceship->getName() << " evaded the attack!" << endl;
                } else {
                    int damage = current_spaceship->offensive_performance() - (current_spaceship->offensive_performance()*other_spaceship->defensive_performance())/100;
                    output_file << "                " << current_spaceship->getName() << " dealt " << damage << " damage to " << other_spaceship->getName() << endl;
                    *other_health = *other_health - damage;
                    other_spaceship->damage_dealt(damage);
                }

                // Changing conditions before next loop
                if(current_spaceship == this) {
                    current_spaceship = spaceship;
                    other_spaceship = this;
                } else {
                    current_spaceship = this;
                    other_spaceship = spaceship;
                }

                if(current_health == spaceship_health1) {
                    current_health = spaceship_health2;
                    other_health = spaceship_health1;
                } else {
                    current_health = spaceship_health1;
                    other_health = spaceship_health2;
                }
            } catch (exception e) {
                fighting = false;
                break;
            }
        }
    }
}

void SpaceShip::damage_dealt(int damage) {
    if(damage > 10) {
        int officer_dead = rand() % 5;
        if(officer_dead == 0) {
            DeadCrewMember dead_officer(this->captain);
            output_file << "                    Captain Dead!" << endl;
            output_file << "                        Time Of Death : " << "asdasd" << endl;
            output_file << "                        Place of Death : Sector " << current_sector << endl;
            this->dead_crew.push_back(dead_officer);
            this->find_captain();
            output_file << "                    New Captain Chosen!" << endl;
            this->captain.getInfo();
        } else if(officer_dead == 1) {
            DeadCrewMember dead_officer(this->pilot);
            output_file << "                    Pilot Dead!" << endl;
            output_file << "                        Time Of Death : " << "asdasd" << endl;
            output_file << "                        Place of Death : Sector " << current_sector << endl;
            this->dead_crew.push_back(dead_officer);
            this->find_pilot();
            output_file << "                    New Pilot Chosen!" << endl;
            this->pilot.getInfo();
        } else if(officer_dead == 2) {
            DeadCrewMember dead_officer(this->engineer);
            output_file << "                    Engineer Dead!" << endl;
            output_file << "                        Time Of Death : " << "asdasd" << endl;
            output_file << "                        Place of Death : Sector " << current_sector << endl;
            this->dead_crew.push_back(dead_officer);
            this->find_engineer();
            output_file << "                    New Engineer Chosen!" << endl;
            this->engineer.getInfo();
        } else if(officer_dead == 3) {
            DeadCrewMember dead_officer(this->mining_officer);
            output_file << "                    Mining Officer Dead!" << endl;
            output_file << "                        Time Of Death : " << "asdasd" << endl;
            output_file << "                        Place of Death : Sector " << current_sector << endl;
            this->dead_crew.push_back(dead_officer);
            this->find_mining_officer();
            output_file << "                    New Mining Officer Chosen!" << endl;
            this->mining_officer.getInfo();
        } else if(officer_dead == 4) {
            DeadCrewMember dead_officer(this->weapon_officer);
            output_file << "                    Weapon Officer Dead!" << endl;
            output_file << "                        Time Of Death : " << "asdasd" << endl;
            output_file << "                        Place of Death : Sector " << current_sector << endl;
            this->dead_crew.push_back(dead_officer);
            this->find_weapon_officer();
            output_file << "                    New Weapon Officer Chosen!" << endl;
            this->weapon_officer.getInfo();
        }
        damage = 7; // Keeping maximum number of deaths per kill to be 9
    }
    int number_of_dead = rand() % damage + 1;
    if(number_of_dead > this->crew.size()) {
        number_of_dead = this->crew.size();
    }
    output_file << "                    " << number_of_dead <<" crew members dead!" << endl;
    for(int i=0; i<number_of_dead; i++) {
        int dead = rand() % this->crew.size();
        DeadCrewMember dead_member(this->crew[dead]);
        this->dead_crew.push_back(dead_member);
        this->crew.erase(this->crew.begin() + dead);
    }
}

void SpaceShip::trade(SpaceShip *spaceship) {
    int trade_multiplier;
    bool traveler_trade = (rand() % 100 + 1) <= this->trading();
    bool spaceship_trade = (rand() % 100 + 1) <= spaceship->trading();

    if(traveler_trade && spaceship_trade) {
        trade_multiplier = 4;
        this->do_trading(spaceship, trade_multiplier);
    } else if(traveler_trade && !spaceship_trade) {
        trade_multiplier = 2; // If they are bad at trading, they end up paying more
        this->do_trading(spaceship, trade_multiplier);
    } else if (!traveler_trade && spaceship_trade) {
        trade_multiplier = 6; // If travelers are bad at trading, they end up paying more
        this->do_trading(spaceship, trade_multiplier);
    }
}

void SpaceShip::do_trading(SpaceShip *spaceship, int multiplier) {
    if(this->resources->get_fuel() > 800) {
        if (this->resources->get_food() < this->food_capacity) {
            // Needs food
            if(spaceship->resources->get_food() > (spaceship->food_capacity - 500)) {
                // Spaceship has excess of food resource
                int available_to_give = (spaceship->resources->get_food()) - (spaceship->food_capacity - 500);
                int needed = this->food_capacity - this->resources->get_food();
                if(needed < available_to_give) {
                    available_to_give = needed;
                }
                int cost = (available_to_give * multiplier)/4;
                if(cost > this->resources->get_gold()) {
                    cost = this->resources->get_gold();
                }
                available_to_give = (cost * 4) / multiplier;
                Resource *res = new Resource(available_to_give, 0, -cost, 0);
                this->resources = this->resources->operator+(res);
                spaceship->resources = spaceship->resources->operator-(res);
                delete res;
                output_file << "                Took " << available_to_give << " food for " << cost << " gold." << endl;
            }
        } else {
            if(spaceship->resources->get_food() < (spaceship->food_capacity - 500)) {
                // Traveler has excess of food resource
                int available_to_give = (this->resources->get_food()) - (this->food_capacity - 500);
                int needed = spaceship->food_capacity - spaceship->resources->get_food();
                if(needed < available_to_give) {
                    available_to_give = needed;
                }
                // cout << "available_to_give : " << available_to_give << endl;
                int cost = (available_to_give * multiplier)/4;
                if(cost > spaceship->resources->get_gold()) {
                    cost = spaceship->resources->get_gold();
                }
                available_to_give = (cost * 4)/multiplier;
                Resource *res = new Resource(available_to_give, 0, -cost, 0);
                spaceship->resources = spaceship->resources->operator+(res);
                this->resources = this->resources->operator-(res);
                delete res;
                output_file << "                Gave " << available_to_give << " food for " << cost << " gold." << endl;
            }
        }
    }

    if (this->resources->get_fuel() < this->fuel_capacity) {
        // cout << "1....." << endl;
        // Needs fuel
        if(spaceship->resources->get_fuel() > (spaceship->fuel_capacity - 500)) {
            // Spaceship has excess of fuel resource
            int available_to_give = (spaceship->resources->get_fuel()) - (spaceship->fuel_capacity - 500);
            int needed = this->fuel_capacity - this->resources->get_fuel();
            if(needed < available_to_give) {
                available_to_give = needed;
            }
            int cost = (available_to_give * multiplier)/4;
            if(cost > this->resources->get_gold()) {
                cost = this->resources->get_gold();
            }
            available_to_give = (cost * 4)/multiplier;
            Resource *res = new Resource(0, available_to_give, -cost, 0);
            this->resources = this->resources->operator+(res);
            spaceship->resources = spaceship->resources->operator-(res);
            delete res;
            output_file << "                Took " << available_to_give << " fuel for " << cost << " gold." << endl;
        }
    } else {
        if(this->resources->get_fuel() > (this->fuel_capacity - 500)) {
            // Traveler has excess of fuel resource
            int available_to_give = (this->resources->get_fuel()) - (this->fuel_capacity - 500);
            int needed = spaceship->fuel_capacity - spaceship->resources->get_fuel();
            if(needed < available_to_give) {
                available_to_give = needed;
            }
            int cost = (available_to_give * multiplier)/4;
            if(cost > spaceship->resources->get_gold()) {
                cost = spaceship->resources->get_gold();
            }
            available_to_give = (cost * 4) / multiplier;
            Resource *res = new Resource(0, available_to_give, -cost, 0);
            spaceship->resources = spaceship->resources->operator+(res);
            this->resources = this->resources->operator-(res);
            delete res;
            output_file << "                Gave " << available_to_give << " fuel for " << cost << " gold." << endl;
        }
    }

    if (this->resources->get_scrap_metal() < this->scrap_capacity) {
        // Needs Metal
        if(spaceship->resources->get_scrap_metal() > (spaceship->scrap_capacity - 500)) {
            // Spaceship has excess of metal resource
            int available_to_give = (spaceship->resources->get_scrap_metal()) - (spaceship->scrap_capacity - 500);
            int needed = this->scrap_capacity - this->resources->get_scrap_metal();
            if(needed < available_to_give) {
                available_to_give = needed;
            }
            int cost = (available_to_give * multiplier)/4;
            if(cost > this->resources->get_gold()) {
                cost = this->resources->get_gold();
            }
            available_to_give = (cost * 4) / multiplier;
            Resource *res = new Resource(0, 0, -cost, available_to_give);
            this->resources = this->resources->operator+(res);
            spaceship->resources = spaceship->resources->operator-(res);
            delete res;
            output_file << "                Took " << available_to_give << " metal for " << cost << " gold." << endl;
        }
    } else {
        if(this->resources->get_scrap_metal() > (this->scrap_capacity - 500)) {
            // Traveler has excess of metal resource
            int available_to_give = (this->resources->get_scrap_metal()) - (this->scrap_capacity - 500);
            int needed = spaceship->scrap_capacity - spaceship->resources->get_scrap_metal();
            if(needed < available_to_give) {
                available_to_give = needed;
            }
            int cost = (available_to_give * multiplier)/4;
            if(cost > spaceship->resources->get_gold()) {
                cost = spaceship->resources->get_gold();
            }
            available_to_give = (cost * 4) / multiplier;
            Resource *res = new Resource(0, 0, -cost, available_to_give);
            spaceship->resources = spaceship->resources->operator+(res);
            this->resources = this->resources->operator-(res);
            delete res;
            output_file << "                Gave " << available_to_give << " metal for " << cost << " gold." << endl;
        }
    }
}

/*   FINDING OFFICERS   */

void SpaceShip::find_captain() {
    int capt_id = 0;
    for(int i = 1; i < this->crew.size(); i++) {
        if(this->crew[capt_id].captain_score() < this->crew[i].captain_score() && !this->crew[i].is_officer) {
            capt_id = i;
        }
    }
    this->captain = this->crew[capt_id];
    this->crew.erase(this->crew.begin() + capt_id);
    this->captain.change_officer_status("Captain");
}

void SpaceShip::find_pilot() {
    int pilot_id = 0;
    for(int i = 1; i < this->crew.size(); i++) {
        if(this->crew[pilot_id].pilot_score() < this->crew[i].pilot_score() && !this->crew[i].is_officer) {
            pilot_id = i;
        }
    }
    this->pilot = this->crew[pilot_id];
    this->crew.erase(this->crew.begin() + pilot_id);
    this->pilot.change_officer_status("Pilot");
}

void SpaceShip::find_engineer() {
    int engineer_id = 0;
    for(int i = 1; i < this->crew.size(); i++) {
        if(this->crew[engineer_id].engineer_score() < this->crew[i].engineer_score() && !this->crew[i].is_officer) {
            engineer_id = i;
        }
    }
    this->engineer = this->crew[engineer_id];
    this->crew.erase(this->crew.begin() + engineer_id);
    this->engineer.change_officer_status("Engineer");
}

void SpaceShip::find_mining_officer() {
    int mining_officer_id = 0;
    for(int i = 1; i < this->crew.size(); i++) {
        if(this->crew[mining_officer_id].mining_score() < this->crew[i].mining_score() && !this->crew[i].is_officer) {
            mining_officer_id = i;
        }
    }
    this->mining_officer = this->crew[mining_officer_id];
    this->crew.erase(this->crew.begin() + mining_officer_id);
    this->mining_officer.change_officer_status("Mining Officer");
}

void SpaceShip::find_weapon_officer() {
    int weapon_officer_id = 0;
    for(int i = 1; i < this->crew.size(); i++) {
        if(this->crew[weapon_officer_id].weapon_score() < this->crew[i].weapon_score() && !this->crew[i].is_officer) {
            weapon_officer_id = i;
        }
    }
    this->weapon_officer = this->crew[weapon_officer_id];
    this->crew.erase(this->crew.begin() + weapon_officer_id);
    this->weapon_officer.change_officer_status("Weapon Officer");
}

/*  ACTIVITIES CARRIED OUT BY THE SPACESHIP  */

int SpaceShip::diplomacy() {
    return this->captain.captain_score();
}

int SpaceShip::trading() {
    return this->captain.captain_score();
}

int SpaceShip::travel_efficiency() {
    int travel_score = (this->pilot.pilot_score() + this->engineer.engineer_score()) / 2;
    return travel_score;
}

int SpaceShip::combat_maneuvers() {
    int combat_score;
        int officer_score = (this->pilot.pilot_score() + this->engineer.engineer_score()) / 2;
        int crew_combat_score = 0;
        for(int i=0; i < this->crew.size(); i++) {
            crew_combat_score += (this->crew[i].pilot_score() + this->crew[i].engineer_score()) / 2;
        }
        if(this->crew.size() > 0) {
            crew_combat_score = crew_combat_score / (this->crew.size());
        } else {
            crew_combat_score = 0;
        }
        crew_combat_score = (crew_combat_score + this->crew.size()) / 2;
        // The more number of crew members, the better the score and vice versa.
        combat_score = (crew_combat_score + 2 * officer_score) / 3;
        // Multiplier of 2 for officer score because his abilities should affect the overall performance of combat.
        combat_score = combat_score*2/3; // better to have less evasion
        return combat_score;
}

int SpaceShip::conflict_evasaion() {
    int evasion_score = (this->pilot.pilot_score() + this->engineer.engineer_score()) / 2;
    return evasion_score;
}

int SpaceShip::system_recovery() {
    int recovery_score;
        int engineer_score = this->engineer.engineer_score();
        int crew_engineer_score = 0;
        for(int i=0; i < this->crew.size(); i++) {
            crew_engineer_score += this->crew[i].engineer_score();
        }
        if(this->crew.size() > 0) {
            crew_engineer_score = crew_engineer_score / (this->crew.size());
        } else {
            crew_engineer_score = 0;
        }
        crew_engineer_score = (crew_engineer_score + this->crew.size()) / 2;
        // The more number of crew members, the better the score and vice versa.
        recovery_score = (crew_engineer_score + 2*engineer_score)/3;
        // Multiplier of 2 for officer score because his abilities should affect the overall performance of system recovery.
    return recovery_score;
}

int SpaceShip::mining_ability() {
    int mining_score;
        int officer_score = this->mining_officer.mining_score();
        int crew_mining_score = 0;
        for(int i=0; i < this->crew.size(); i++) {
            crew_mining_score += this->crew[i].mining_score();
        }
        crew_mining_score = crew_mining_score/(this->crew.size());
        crew_mining_score = (crew_mining_score + this->crew.size()) / 2;
        // The more number of crew members, the better the score and vice versa.
        mining_score = (crew_mining_score + 2*officer_score)/3;
        // Multiplier of 2 for officer score because his abilities should affect the overall performance of mining.
    return mining_score;
}

int SpaceShip::defensive_performance() {
    int defensive_score = (this->engineer.engineer_score() + this->weapon_officer.weapon_score())/2;
    return defensive_score;
}

int SpaceShip::offensive_performance() {
    int offensive_score = this->weapon_officer.weapon_score();
    return offensive_score;
}

int SpaceShip::food_needed() {
    int capacity = this->food_capacity;
    int food = this->resources->get_food();
    return (capacity - food);
}

int SpaceShip::fuel_needed() {
    int capacity = this->fuel_capacity;
    int fuel = this->resources->get_fuel();
    return (capacity - fuel);
}

int SpaceShip::gold_needed() {
    int capacity = this->gold_capacity;
    int gold = this->resources->get_gold();
    return (capacity - gold);
}

int SpaceShip::scrap_needed() {
    int capacity = this->scrap_capacity;
    int scrap = this->resources->get_scrap_metal();
    return (capacity - scrap);
}

int SpaceShip::total_crew() {
    return this->crew.size();
}

bool SpaceShip::check_if_alive() {
    output_file << "    Spaceship Health : " << this->spaceship_health << endl;
    output_file << "    Crew Members Left : " << this->crew.size() << endl;
    if(this->spaceship_health <= 0) {
        return true;
    } else if(this->crew.size() == 0) {
        return true;
    } else {
        return false;
    }
}

void SpaceShip::get_captain_info() {
    this->captain.getInfo();
}

void SpaceShip::get_pilot_info() {
    this->pilot.getInfo();
}

void SpaceShip::get_engineer_info() {
    this->engineer.getInfo();
}

void SpaceShip::get_mining_officer_info() {
    this->mining_officer.getInfo();
}

void SpaceShip::get_weapon_officer_info() {
    this->weapon_officer.getInfo();
}

void SpaceShip::get_crew_info() {
    for(int i=0;i<this->crew.size(); i++) {
        this->crew[i].getInfo();
    }
}

void SpaceShip::get_dead_crew_info() {
    for(int i=0;i<this->dead_crew.size(); i++) {
        this->dead_crew[i].getInfo();
    }
}

int SpaceShip::get_speed() {
    return this->speed;
}

<file_sep>#ifndef spaceship_class
#define spaceship_class

#include "./resource.h"
#include "./crew_member.h"
#include "./dead_crew_member.h"
// #include  "./species.h"

class SpaceShip {
    private:
        string name;

        int fuel_capacity;
        int food_capacity;
        int crew_capacity;
        int scrap_capacity;
        int gold_capacity;

        int speed;
        int spaceship_health;

        void do_trading(SpaceShip*, int);
        // void starved_to_death(int);

        vector<CrewMember> crew;
        vector<DeadCrewMember> dead_crew;

        CrewMember captain;
        CrewMember pilot;
        CrewMember engineer;
        CrewMember mining_officer;
        CrewMember weapon_officer;

        void find_officers();

        void find_captain();
        void find_pilot();
        void find_engineer();
        void find_mining_officer();
        void find_weapon_officer();

        void damage_dealt(int);
        void fuel_consume(int);

    public:
        SpaceShip(bool);
        SpaceShip(bool, int, int);

        int total_crew();
        Resource *resources;

        string getName();
        void getInfo();

        bool check_if_alive();

        void operator+(SpaceShip *);
        bool operator==(SpaceShip *);

        bool travel(int);
        void combat(SpaceShip*);

        void trade(SpaceShip*);

        void get_captain_info();
        void get_pilot_info();
        void get_engineer_info();
        void get_mining_officer_info();
        void get_weapon_officer_info();

        void get_crew_info();
        void get_dead_crew_info();

        int get_speed();

        int diplomacy();
        int trading();
        int travel_efficiency();
        int combat_maneuvers();
        int conflict_evasaion();
        int system_recovery();

        int mining_ability();
        int defensive_performance();
        int offensive_performance();

        int food_needed();
        int fuel_needed();
        int scrap_needed();
        int gold_needed();
};

#endif

<file_sep>#ifndef resource_class
#define resource_class

class Resource {
    private:
        int food;
        int fuel;
        int gold;
        int scrap_metal;

    public:
        Resource(int); // 0 -> SpaceShip,   1 -> Species,   2 -> Planet
        Resource(int, int, int, int);

        int get_food();
        int get_fuel();
        int get_gold();
        int get_scrap_metal();

        void getInfo();

        Resource* operator+(Resource*);
        Resource* operator-(Resource*);
};

#endif

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/crew_member_attributes.h"

CrewMemberAttributes::CrewMemberAttributes() {
    this->travel_efficiency = rand() % 100 + 1;
    this->combat_maneuvers = rand() % 100 + 1;
    this->conflict_evasion = rand() % 100 + 1;
    this->system_recovery = rand() % 100 + 1;
    this->mining_ability = rand() % 100 + 1;
    this->offensive_performance = rand() % 100 + 1;
    this->defensive_performance = rand() % 100 + 1;
}

CrewMemberAttributes::CrewMemberAttributes(int species_diplomacy, int species_trading) {
    this->diplomacy = rand() % species_diplomacy + 1;
    this->trading = rand() % species_trading + 1;

    this->travel_efficiency = rand() % 100 + 1;
    this->combat_maneuvers = rand() % 100 + 1;
    this->conflict_evasion = rand() % 100 + 1;
    this->system_recovery = rand() % 100 + 1;
    this->mining_ability = rand() % 100 + 1;
    this->offensive_performance = rand() % 100 + 1;
    this->defensive_performance = rand() % 100 + 1;
}

void CrewMemberAttributes::getInfo() {
    cout << "   travel_efficiency : " << this->travel_efficiency << endl;
    cout << "   combat_maneuvers : " << this->combat_maneuvers << endl;
    cout << "   conflict_evasion : " << this->conflict_evasion << endl;
    cout << "   system_recovery : " << this->system_recovery << endl;
    cout << "   mining_ability : " << this->mining_ability << endl;
    cout << "   offensive_performance : " << this->offensive_performance << endl;
    cout << "   defensive_performance : " << this->defensive_performance << endl;
    cout << "   diplomacy : " << this->diplomacy << endl;
    cout << "   trading : " << this->trading << endl;

    cout << "       Captain Score : " << this->captain_score() << endl;
    cout << "       Pilot Score : " << this->pilot_score() << endl;
    cout << "       Engineer Score : " << this->engineer_score() << endl;
    cout << "       Mining Score : " << this->mining_score() << endl;
    cout << "       Weapon Score : " << this->weapon_score() << endl;
}

int CrewMemberAttributes::captain_score() {
    int score = (this->diplomacy + this->trading) / 2;
    return score;
}

int CrewMemberAttributes::pilot_score() {
    int score = (this->travel_efficiency + this->combat_maneuvers + this->conflict_evasion)/3;
    return score;
}
int CrewMemberAttributes::engineer_score() {
    int score = (this->travel_efficiency + this->combat_maneuvers + this->conflict_evasion + this->defensive_performance + this->system_recovery) / 5;
    return score;
}
int CrewMemberAttributes::mining_score() {
    int score = this->mining_ability;
    return score;
}
int CrewMemberAttributes::weapon_score() {
    int score = (this->offensive_performance + this->defensive_performance) / 2;
    return score;
}

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/resource.h"

Resource::Resource(int val) {
    if(val ==0){
        /* SPACESHIP */
        this->food = rand() % 1800 + 3100;
        this->fuel = rand() % 800 + 6200;
        this->gold = rand() % 2000 + 3500;
        this->scrap_metal = rand() % 200 + 400;
    } else if(val == 1) {
        /* SPECIES */
        this->food = rand() % 50000 + 5000;
        this->fuel = rand() % 50000 + 5000;
        this->gold = rand() % 50000 + 5000;
        this->scrap_metal = rand() % 50000 + 5000;
    } else if(val == 2) {
        /* PLANET */
        this->food = rand() % 200000 + 15000;
        this->fuel = rand() % 200000 + 15000;
        this->gold = rand() % 200000 + 15000;
        this->scrap_metal = rand() % 200000 + 15000;
    }
}

Resource::Resource(int new_food, int new_fuel, int new_gold, int new_scrap_metal) {
    this->food = new_food;
    this->fuel = new_fuel;
    this->gold = new_gold;
    this->scrap_metal = new_scrap_metal;
}

int Resource::get_food() {
    return this->food;
}

int Resource::get_fuel() {
    return this->fuel;
}

int Resource::get_gold() {
    return this->gold;
}

int Resource::get_scrap_metal() {
    return this->scrap_metal;
}

Resource* Resource::operator+(Resource *a) {
    this->food = this->food + a->food;
    this->fuel = this->fuel + a->fuel;
    this->gold = this->gold + a->gold;
    this->scrap_metal = this->scrap_metal + a->scrap_metal;
    return this;
}

Resource* Resource::operator-(Resource *a) {
    this->food = this->food - a->food;
    this->fuel = this->fuel - a->fuel;
    this->gold = this->gold - a->gold;
    this->scrap_metal = this->scrap_metal - a->scrap_metal;
    return this;
}

void Resource::getInfo() {
    output_file << "        Food : " << this->food << endl;
    output_file << "        Fuel : " << this->fuel << endl;
    output_file << "        Gold : " << this->gold << endl;
    output_file << "        Scrap Metal : " << this->scrap_metal << endl;
}

<file_sep>#ifndef tradingstation_class
#define tradingstation_class

#include "./spaceship.h"
#include "./resource.h"
#include "./species.h"

class TradingStation {
    private:
        string name;
        Species *species;

    public:
        TradingStation();
        int trading_score();
        void trade(SpaceShip*);

        string get_species_name();
};

#endif

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/crew_member.h"

// vector<string> crew_first_names;
// vector<string> crew_last_names;

CrewMember::CrewMember() {
    this->name = crew_first_names[rand() % crew_first_names.size()] + " " + crew_last_names[rand() % crew_last_names.size()];
    this->role = "Crew Member";
    this->age = rand() % 80 + 20;
    this->is_officer = false;
    this->attributes = new CrewMemberAttributes();
}

CrewMember::CrewMember(int species_diplomacy, int species_trading) {
    this->name = crew_first_names[rand() % crew_first_names.size()] + " " + crew_last_names[rand() % crew_last_names.size()];
    this->role = "Crew Member";
    this->age = rand() % 80 + 20;
    this->is_officer = false;
    this->attributes = new CrewMemberAttributes(species_diplomacy, species_trading);
}

int CrewMember::captain_score() {
    return this->attributes->captain_score();
}

int CrewMember::pilot_score() {
    return this->attributes->pilot_score();
}

int CrewMember::engineer_score() {
    return this->attributes->engineer_score();
}

int CrewMember::mining_score() {
    return this->attributes->mining_score();
}

int CrewMember::weapon_score() {
    return this->attributes->weapon_score();
}

void CrewMember::getInfo() {
    output_file << "                Name : " << this->name << endl;
    output_file << "                Age : " << this->age << endl;
    output_file << endl;
}

void CrewMember::change_officer_status(string designation) {
    this->role = designation;
    this->is_officer = !this->is_officer;
}

string CrewMember::get_name() {
    return this->name;
}

string CrewMember::get_designation() {
    return this->role;
}

int CrewMember::get_age() {
    return this->age;
}
<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/sector.h"
#include "../../headers/classes/spaceship.h"
#include "../../headers/classes/species.h"
#include "../../headers/classes/planet.h"
#include "../../headers/classes/trading_station.h"

Sector::Sector(SpaceShip *traveler){
    this->journey = false;
    this->sector_width = rand() % 80 + 20;
    int random = rand() % 100 + 1;

    day = day + (this->sector_width*traveler->get_speed())/100;

    output_file << "DAY : " << day << endl;

    output_file << "    Distance Covered : " << this->sector_width << endl;

    if(traveler->travel(this->sector_width) || traveler->check_if_alive()) {
        this->journey = true;
    } else {
        /*  Probability of being encountered by a Spaceship  */
        if(random <= 35) {
            output_file << "        Spaceship Encountered" << endl;
            SpaceShip *spaceship = new SpaceShip(true);
                this->spaceship_encountered(traveler, spaceship);
            delete spaceship;
        }
        /*  Probability of being encountered by a Planet  */
        else if(random > 35 && random <=60) {
            output_file << "        Planet Encountered" << endl;
            Planet *planet = new Planet();
                this->planet_encountered(planet, traveler);
            delete planet;
        }
        /*  Probability of being encountered by a Trading Station  */
        else if(random > 60 && random <=75) {
            output_file << "        Trading Station Encountered" << endl;
            TradingStation *trading_station = new TradingStation();
                this->trading_station_encountered(trading_station, traveler);
            delete trading_station;
        }
        /*  Probability of finding an Empty Sector  */
        else if(random > 75 && random <=90) {
            output_file << "        Empty Sector" << endl;
            // do nothing
        }
        /*  Probability of being encountered by an Abandoned Spaceship  */
        else if(random > 90) {
            output_file << "        Abandoned Spaceship Encountered" << endl;
            SpaceShip *abandoned_spaceship = new SpaceShip(false);
                this->abandoned_spaceship_encountered(abandoned_spaceship, traveler);
            delete abandoned_spaceship;
        }

    }
}

void Sector::spaceship_encountered(SpaceShip *spaceship, SpaceShip *spaceship_encountered) {
    int diplomacy1 = spaceship->diplomacy();
    int diplomacy2 = spaceship_encountered->diplomacy();
    if(diplomacy1 > 70) {
        diplomacy1 = 70;
    }
    if(diplomacy2 > 70) {
        diplomacy2 = 70;
    }

    output_file << "            Captains of both the spaceships are negotiating..." << endl;

    bool condition1 = (rand() % 100 + 1) <= diplomacy1;
    bool condition2 = (rand() % 100 + 1) <= diplomacy2;
    if (condition1 && condition2) {
        output_file << "            Negotiation Successful. Trading..." << endl;
        spaceship->trade(spaceship_encountered);
        output_file << "            Trading Completed." << endl;
    } else {
        output_file << "            Negotiation Unsuccessful. Preparing for combat..." << endl;
        output_file << "            COMBAT BEGINS!" << endl;
        spaceship->combat(spaceship_encountered);
        output_file << "            COMBAT OVER" << endl;
    }
}

void Sector::planet_encountered(Planet *planet, SpaceShip *spaceship) {
    output_file << "            Negotiation with the species found on planet " << planet->get_name() << " to either allow to mine or trade." << endl;
    int diplomacy1 = spaceship->diplomacy();
    int diplomacy2 = planet->diplomacy();
    if(diplomacy1 > 70) {
        diplomacy1 = 70;
    }
    if(diplomacy2 > 70) {
        diplomacy2 = 70;
    }

    bool condition1 = (rand() % 100 + 1) <= diplomacy1;
    bool condition2 = (rand() % 100 + 1) <= diplomacy2;
    if(condition1 && condition2) {
        output_file << "            Agreed for Mining." << endl;
        planet->mining(spaceship);
    } else if(condition1 || condition2) {
        output_file << "            Agreed for Trade." << endl;
        planet->trading(spaceship);
    } else {
        output_file << "            Negotiation Unsuccessful. Species launched a spaceship for battle..." << endl;
        output_file << "            COMBAT BEGINS!" << endl;
        planet->conflict(spaceship);
        output_file << "            COMBAT OVER!" << endl;
    }
}

void Sector::trading_station_encountered(TradingStation *trading_station, SpaceShip *spaceship) {
    output_file << "            Trading with species - " << trading_station->get_species_name() << endl;
    trading_station->trade(spaceship);
}

void Sector::abandoned_spaceship_encountered(SpaceShip *abandoned_spaceship, SpaceShip *spaceship) {
    spaceship->operator+(abandoned_spaceship);
}

bool Sector::journey_ended() {
    return this->journey;
}

<file_sep>#include "../../headers/all_imports.h"
#include "../../headers/classes/trading_station.h"

TradingStation::TradingStation() {
    this->name = trading_stations_names[rand() % trading_stations_names.size()];
    this->species = new Species();
}

int TradingStation::trading_score() {
    return this->species->diplomacy();
}

void TradingStation::trade(SpaceShip *spaceship) {
    this->species->trade(spaceship);
}

string TradingStation::get_species_name() {
    return this->species->get_species_name();
}

<file_sep>#ifndef planet_class
#define planet_class

#include "./resource.h"
#include "./species.h"
#include "./spaceship.h"

class Planet {
    private:
        string name;
        Resource *resources;
        Species *civilization;

    public:
        Planet();
        string get_name();
        void mining(SpaceShip*);
        int diplomacy();
        void trading(SpaceShip*);
        void conflict(SpaceShip*);
};

#endif

<file_sep>#ifndef all_imports
#define all_imports

#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <fstream>

using namespace std;

extern vector<string> crew_first_names;
extern vector<string> crew_last_names;
extern vector<string> spaceship_names;
extern vector<string> planet_names;
extern vector<string> species_names;
extern vector<string> trading_stations_names;

extern ofstream output_file;
extern string output_file_name;

extern int current_sector;
extern int day;

#endif

languages: Makefile C++ Text

repo_language: Makefile


text:
<repo_name>myszunimpossibru/shapes<file_sep>/main1.py
# coding: utf8
import rectangles
import circle
import triangle
import parallelogram
import numpy as np
import pygame

#Defining the shapes
par1 = parallelogram.Parallelogram((24, 500), 2, 4, 45)
rect1 = rectangles.Rectangle((20, 10), 2, 3)
cir1 = circle.Circle((400, 50), 1)
tr1 = triangle.Triangle((300, 500), np.array([0, 2]), np.array([2, 0]))

#Initalization of PyGame
pygame.init()
running = True
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Shape drawing")
clock = pygame.time.Clock()

#PyGame's main loop
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    par1.draw(screen)
    rect1.draw(screen)
    cir1.draw(screen)
    tr1.draw(screen)
    pygame.display.update()
    clock.tick(60)
<file_sep>/parallelogram.py
from shape import Shape
import numpy as np
import pygame

class Parallelogram(Shape):
    """
    Class for creating the Parallelogram

    Parameters:
        pos: tuple
            Tuple of form (x, y) describing the position of the circle on the screen.
            Reminder: PyGame sets point (0, 0) as the upper left corner and the point with highest value of coordinates
                      as the  lower right corner.
        a: integer
            Length of the first side.
        b: integer
            Length of the second side.
        alpha: degrees
            Angle between two sides.
    """

    a = None
    b = None
    alpha = None
    __deg = None

    def __init__(self, pos, a, b, alpha, scale=50):
        super().__init__(pos, scale)
        self.a = a
        self.b = b

        if alpha >= 90 or alpha <= 0:
            raise ValueError("The angle has to be between 0° and 90° degrees")

        self.__deg = alpha
        self.alpha = np.pi * alpha / 180

    def area(self):
        return self.a * self.b * np.sin(self.alpha)

    def perimeter(self):
        return 2 * (self.a + self.b)

    def __str__(self):
        return "Parallelogram with dimensions of {} x {} and angle {} between sides.".format(self.a, self.b, self.__deg)

    def __repr__(self):
        return "Parallelogram({}, {}, {}, {})".format(self.pos, self.a, self.b, self.__deg)

    def draw(self, screen):
        h = np.ceil(self.b * np.sin(self.alpha)) * self.scale
        dx = np.ceil(self.b * np.cos(self.alpha)) * self.scale
        points = [self.pos, (self.pos[0] + self.a * self.scale, self.pos[1]), (self.pos[0] + self.a * self.scale + dx,
                  self.pos[1] - h), (self.pos[0] + dx, self.pos[1] - h)]
        return pygame.draw.polygon(screen, (255, 255, 255), points)

class CrazyDiamond(Parallelogram):
    """
    Parallelogram with even sides

    See help of Parallelogram class for more information.
    """

    def __init__(self, a, alpha):
        super().__init__(a, a, alpha)

    def __repr__(self):
        return "Rhombus({}, {}, {})".format(self.pos, self.a, self.alpha)
<file_sep>/triangle.py
from shape import Shape
import numpy as np
import pygame

class Triangle(Shape):
    """
    Class for creating the triangular shape

    Parameters:
        pos: tuple
            Tuple of form (x, y) describing the position of the triangle on the screen.
            Reminder: PyGame sets point (0, 0) as the upper left corner and the point with highest value of coordinates
                      as the  lower right corner.
        a: array
            Components of the first triangle vector
        b: array
            Components of the second triangle vector
        scale: integer (default scale=50)
            Value used for scaling the shape while drawing. In default case 1 unit is equal to 50 pixels.
    """

    a = None
    b = None
    c = None

    def __init__(self, pos, a, b, scale=50):
        super().__init__(pos, scale)
        self.a = a
        self.b = b

        if np.linalg.norm(self.a) == 0 or np.linalg.norm(self.b) == 0:
            raise ValueError("Vectors cannot have zero length.")
        elif np.linalg.norm(np.cross(a, b)) == 0:
            raise ValueError("Vectors cannot have the same direction")

        self.c = a - b

    def area(self):
        return 0.5 * np.linalg.norm(self.a[0] * self.b[1] - self.a[1] * self.b[0])

    def perimeter(self):
        return np.linalg.norm(self.a) + np.linalg.norm(self.b) + np.linalg.norm(self.c)

    def __str__(self):
        return "Triangle with sides a:{}, b:{}, c:{})".format(self.a, self.b, self.c)

    def __repr__(self):
        return "Triangle({}, {}, {})".format(self.pos, self.a, self.b)

    def draw(self, screen):
        points = [self.pos, (self.pos + self.a * self.scale), (self.pos + self.b * self.scale)]
        return pygame.draw.polygon(screen, (255, 255, 255), points)
<file_sep>/rectangles.py
# coding: utf8
from shape import Shape
import pygame

class Rectangle(Shape):
    """
    Class for creating the rectangular shape

    Parameters:
        pos: tuple
            Tuple of form (x, y) describing the position of the rectangle on the screen.
            Reminder: PyGame sets point (0, 0) as the upper left corner and the point with highest value of coordinates
                      as the  lower right corner.
        a: integer
            Length of the first side
        b: integer
            Length of the second side
        scale: integer (default scale=50)
            Value used for scaling the shape while drawing. In default case 1 unit is equal to 50 pixels.
    """

    a = None
    b = None

    def __init__(self, pos, a, b, scale=50):
        super().__init__(pos, scale)
        self.a = a
        self.b = b

        if self.a <= 0 or self.b <= 0:
            raise ValueError("Size cannot be negative or zero")

    def area(self):
        return self.a * self.b

    def perimeter(self):
        return 2 * (self.a + self.b)

    def __str__(self):
        return "Rectangle of dimensions {} x {}".format(self.a, self.b)

    def __repr__(self):
        return "Rectangle({}, {}, {})".format(self.pos, self.a, self.b)

    def draw(self, screen):
        points = [self.pos, (self.pos[0] + self.a * self.scale, self.pos[1]), (self.pos[0] + self.a * self.scale, self.pos[1] + self.b * self.scale), \
                  (self.pos[0], self.pos[1] + self.b * self.scale)]
        return pygame.draw.polygon(screen, (255, 255, 255), points)

class Square(Rectangle):
    """
    Rectangle with even sides.

    See help of Rectangle class for more information.
    """

    def __init__(self, a):
        super().__init__(a, a)

    def __repr__(self):
        return "Square({}, {})".format(self.pos, self.a)
<file_sep>/circle.py
from shape import Shape
import numpy as np
import pygame

class Circle(Shape):
    """
    Class for creating the circle

    Parameters:
        pos: tuple
            Tuple of form (x, y) describing the position of the circle on the screen.
            Reminder: PyGame sets point (0, 0) as the upper left corner and the point with highest value of coordinates
                      as the  lower right corner.
        r: integer
            Radius of the circle.
        scale: integer (default scale=50)
            Value used for scaling the shape while drawing. In default case 1 unit is equal to 50 pixels.
    """

    r = None

    def __init__(self, pos, r, scale=50):
        super().__init__(pos, scale)
        self.r = r

        if r <= 0:
            raise ValueError("Radius cannot be zero or negative.")

    def area(self):
        return self.r * np.pi ** 2

    def perimeter(self):
        return 2 * np.pi * self.r

    def __str__(self):
        return "Circle with radius {}".format(self.r)

    def __repr__(self):
        return "Circle({}, {})".format(self.pos, self.r)

    def draw(self, screen):
        return pygame.draw.circle(screen, (255, 255, 255), self.pos, self.r * self.scale)
<file_sep>/shape.py
# coding: utf8

class Shape(object):
    """
    Base class for all shapes.
    """

    pos = None
    scale = None

    def __init__(self, pos, scale):
        self.pos = pos
        self.scale = scale

    def area(self):
        """
        Abstract method returning area of a shape.
        """

    def perimeter(self):
        """
        Abstract method returning shape perimeter.
        """

    def summary(self):
        """
        Return summary of a shape.
        """
        return {
            'area': self.area(),
            'perimeter': self.perimeter()
        }

    def draw(self, screen):
        """
        Draws the given shape
        """

branch_name: refs/heads/master

repo_language: Python

repo_name: myszunimpossibru/shapes


text:
<repo_name>felizami/OnlineShopping<file_sep>/src/java/com/leapfrog/onlineshopping/entity/Login.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 com.leapfrog.onlineshopping.entity;

import java.util.Date;

/**
 *
 * @author Anuz
 */
public class Login {
    private int loginId;
    private String loginEmail;
    private String password;
    private String token;
    private Date date;

    public Login() {
    }

    public int getLoginId() {
        return loginId;
    }

    public void setLoginId(int loginId) {
        this.loginId = loginId;
    }

    public String getLoginEmail() {
        return loginEmail;
    }

    public void setLoginEmail(String loginEmail) {
        this.loginEmail = loginEmail;
    }

    public String getPassword() {
        return <PASSWORD>;
    }

    public void setPassword(String password) {
        this.password = <PASSWORD>;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "Login{" + "loginId=" + loginId + ", loginEmail=" + loginEmail + ", password=" + <PASSWORD> + ", token=" + token + ", date=" + date + '}';
    }

}
<file_sep>/src/java/com/leapfrog/onlineshopping/entity/Purchase.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 com.leapfrog.onlineshopping.entity;

import java.util.Date;

/**
 *
 * @author Anuz
 */
public class Purchase {
    private int purchaseId;
    private Date purchaseDate;
    private int purchaseQuantity;
    private int unit;
    private int productId;

    public Purchase() {
    }

    public int getPurchaseId() {
        return purchaseId;
    }

    public void setPurchaseId(int purchaseId) {
        this.purchaseId = purchaseId;
    }

    public Date getPurchaseDate() {
        return purchaseDate;
    }

    public void setPurchaseDate(Date purchaseDate) {
        this.purchaseDate = purchaseDate;
    }

    public int getPurchaseQuantity() {
        return purchaseQuantity;
    }

    public void setPurchaseQuantity(int purchaseQuantity) {
        this.purchaseQuantity = purchaseQuantity;
    }

    public int getUnit() {
        return unit;
    }

    public void setUnit(int unit) {
        this.unit = unit;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    @Override
    public String toString() {
        return "Purchase{" + "purchaseId=" + purchaseId + ", purchaseDate=" + purchaseDate + ", purchaseQuantity=" + purchaseQuantity + ", unit=" + unit + ", productId=" + productId + '}';
    }

}
<file_sep>/src/java/com/leapfrog/onlineshopping/entity/Cart.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 com.leapfrog.onlineshopping.entity;

/**
 *
 * @author Anuz
 */
public class Cart {
    private int userId;
    private int productId;
    private int categoryId;
    private int quantity;
    private String unit;

    public Cart() {
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public String getUnit() {
        return unit;
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }

    @Override
    public String toString() {
        return "Cart{" + "userId=" + userId + ", productId=" + productId + ", categoryId=" + categoryId + ", quantity=" + quantity + ", unit=" + unit + '}';
    }

}
<file_sep>/src/java/com/leapfrog/onlineshopping/entity/Product.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 com.leapfrog.onlineshopping.entity;

/**
 *
 * @author Anuz
 */
public class Product {
    private int productId;
    private String productName;
    private int CategoryId;
    private int productDescription;
    private int productCostPrice;
    private int productSellPrice;
    private String productManufacturer;
    private int productPhotoId;
    private int productViewCount;
    private int coverPhotoId;
    private int productQuantity;

}
<file_sep>/src/java/com/leapfrog/onlineshopping/entity/Subscriber.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 com.leapfrog.onlineshopping.entity;

import java.util.Date;

/**
 *
 * @author Anuz
 */
public class Subscriber {
    private int subscriberId;
    private String subscriberEmail;
    private Boolean unsubscribe;
    private Date subscribedDate;

    public Subscriber() {
    }

    public int getSubscriberId() {
        return subscriberId;
    }

    public void setSubscriberId(int subscriberId) {
        this.subscriberId = subscriberId;
    }

    public String getSubscriberEmail() {
        return subscriberEmail;
    }

    public void setSubscriberEmail(String subscriberEmail) {
        this.subscriberEmail = subscriberEmail;
    }

    public Boolean getUnsubscribe() {
        return unsubscribe;
    }

    public void setUnsubscribe(Boolean unsubscribe) {
        this.unsubscribe = unsubscribe;
    }

    public Date getSubscribedDate() {
        return subscribedDate;
    }

    public void setSubscribedDate(Date subscribedDate) {
        this.subscribedDate = subscribedDate;
    }

    @Override
    public String toString() {
        return "Subscriber{" + "subscriberId=" + subscriberId + ", subscriberEmail=" + subscriberEmail + ", unsubscribe=" + unsubscribe + ", subscribedDate=" + subscribedDate + '}';
    }

}
<file_sep>/src/java/com/leapfrog/onlineshopping/entity/CategoryPhotos.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 com.leapfrog.onlineshopping.entity;

/**
 *
 * @author Anuz
 */
public class CategoryPhotos {
    private int categoryPhotoId;
    private int categoryId;
    private String categoryPhonePath;

    public CategoryPhotos() {
    }

    public int getCategoryPhotoId() {
        return categoryPhotoId;
    }

    public void setCategoryPhotoId(int categoryPhotoId) {
        this.categoryPhotoId = categoryPhotoId;
    }

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryPhonePath() {
        return categoryPhonePath;
    }

    public void setCategoryPhonePath(String categoryPhonePath) {
        this.categoryPhonePath = categoryPhonePath;
    }

    @Override
    public String toString() {
        return "CategoryPhotos{" + "categoryPhotoId=" + categoryPhotoId + ", categoryId=" + categoryId + ", categoryPhonePath=" + categoryPhonePath + '}';
    }

}
<file_sep>/src/java/com/leapfrog/onlineshopping/entity/View.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 com.leapfrog.onlineshopping.entity;

import java.util.Date;

/**
 *
 * @author Anuz
 */
public class View {
    private int viewId;
    private Date time;
    private String ipAddress;
    private int productId;

    public View() {
    }

    public int getViewId() {
        return viewId;
    }

    public void setViewId(int viewId) {
        this.viewId = viewId;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    @Override
    public String toString() {
        return "View{" + "viewId=" + viewId + ", time=" + time + ", ipAddress=" + ipAddress + ", productId=" + productId + '}';
    }

}
<file_sep>/src/java/com/leapfrog/onlineshopping/entity/Unit.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 com.leapfrog.onlineshopping.entity;

/**
 *
 * @author Anuz
 */
public class Unit {
    private int unitId;
    private String unitName;

    public Unit() {
    }

    public int getUnitId() {
        return unitId;
    }

    public void setUnitId(int unitId) {
        this.unitId = unitId;
    }

    public String getUnitName() {
        return unitName;
    }

    public void setUnitName(String unitName) {
        this.unitName = unitName;
    }

    @Override
    public String toString() {
        return "Unit{" + "unitId=" + unitId + ", unitName=" + unitName + '}';
    }

}

repo_language: Java

repo_name: felizami/OnlineShopping


text:
<repo_name>PossumLab/test-new<file_sep>/README.md
Welcome to the Possum Lab repository for test-new

repo_language: Markdown

repo_name: PossumLab/test-new


text:
<repo_name>mathetes/React_Redux_Roman<file_sep>/src/containers/Articles/Article.js
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'

class Article extends Component {

/*
  Article

*/

  render() {
    var details = this.props.details,
        styles = {
          backgroundColor: '#' + details.color
        }

    return (

{details.category}

{details.title}

{details.excerpt}

    )
  }

}

export default Article<file_sep>/src/containers/Articles/index.js
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import Article from './Article'

require('./article.css')

class AppArticle extends Component {
    renderArticle = (key) => {
      return (

      )
    }
    render() {
        const articles = this.props.articles
      return (

            {Object.keys(articles).map(this.renderArticle)}

      )
    }
}

export default connect(state => {
  const { articles } = state
  return { articles }
})(AppArticle)

repo_language: JavaScript


text:
<repo_name>ntoll/nhsdtraining<file_sep>/README.md
To run the slides: `./show.sh`.

# Virtualenv

```
$ python3 -m venv my_virtualenv
```

Also use `system-site-packages` if needed.

Then

```
$ source my_virtualenv/bin/activate
```

(Unix)

or

```
> \path\to\env\Scripts\activate
```

See: https://virtualenv.pypa.io/en/stable/userguide/

You're in your virtualenv.

```
$ deactivate
```

# Python Packaging

Once in a virtualenv use `pip` to install a package.

Try:

```
$ pip install requests
```

See: pypi.python.org and https://pypi.org/

* `requirements.txt` (recommend pinned version numbers)
* Source packages
* Wheels for binary packaging
* Don't use `setup.py`
* It's a mess but getting fixed

For more information see:

https://packaging.python.org/key_projects/
https://pythonwheels.com/

Common commands and use cases for `pip`:

```
$ pip install -r requirements.txt

$ pip list

$ pip freeze

$ pip install --upgrade

$ pip uninstall

$ pip search "pgzero"
```

Various pip related behaviours can be overridden and configured by the `pip`
configuration file.

Do you want to package..?

See: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/

# Python Core / Basics

* Use Python 3
* Indentation and conventions (4 spaces, PEP8)
* Objects not variables (how naming works in Python)
* Basic types: `str`, `int`, `float`, `bool`, `byte`.
* Basic arithmetic operators.
* Using the REPL (`help` / `dir`)
* Zen of Python (`import this`)
* The community (and where to find it: https://python.org)

Learner task:

* Create a script that emits "Hello World".

I should be able to see something like this:

```
$ python hello.py
Hello, World!
```

## Control Flow:

* User input with `input`
* Conditionals (`if`, `elif`, `else`)
* Loops (`while` and `for`)
* `break`
* Exception handling (`try`, `except`, `finally`)

Learner task:

* Number guessing game (demonstrate `random.randint`)

I should see something like this:

```
$ python guess.py
Try to guess my number (between 1-100) within 1 goes.
Guess 1: 50
Too low. Try again.
Guess 2: 75
Too high. Try again.
Guess 3: 63
Correct. You win!
```

## Data Structures

* Lists - bound by square brackets: `[1, 2, "a", "b", ]`
* Tuples - think of them as immutable lists (bound by parenthesis): `(1, 2, "a", "b")`
* Sets - each item is unique: `{1, 2, 3}`
* Dictionaries - key value pairs: `{"a": 1, "b": 2}` (keys must be immutable)
* Iterables (an object capable of returning its members one at a time).
* Indexing and slicing via square brackets!

Learner task:

* In the REPL, make some lists, sets and dicts (as we go along explaining the
  above).

##Functions:

* Basic syntax
* Docstrings
* Default values for args (don't use mutables!)
* `*args` and  `**kwargs`
* `return` a result.

```
def hello(name="World!"):
    """
    Returns a friendly greeting.
    """
    return "Hello, " + name

print(hello("Nicholas"))
print(hello())
```

Learner task:

* Create a pig latin function (see example app for solution).
* How could you make it more flexible? (Default args etc)

# Modules

* Using import to get other modules
* Batteries included - popular modules for certain tasks

Zen of Python:
-------------

```
import this
```

Tools to help write idiomatic Python:

* `pycodestyle`
* `flake8`
* `pyflakes`
* `black`
* Wrap these in a `Makefile` to automate the process of code quality cheking.

# LUNCH

Lunchtime task: Make a `piglatin` module.

# Documenting Python projects with Sphinx

```
$ pip install sphinx
$ mkdir doc
$ cd doc
$ sphinx-quickstart
$ make html
```

You have basic docs..!

In order to "autodoc" from your commentary in code try this with your PigLatin
module:

Update `conf.py` to include path for code (uncomment imports and extensions
from line 13 to look like this):

```
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
```

Ensure the autodoc extensions are enabled:

```
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode'
]
```

Add:

```
.. automodule:: app
    :members:
```

To your `index.rst` then `make` again.

Markdown support: http://www.sphinx-doc.org/en/stable/markdown.html

Go visit https://readthedocs.org/ and then https://writethedocs.org/ for more
advanced help on documenting in Python.

# Testing with PyTest

```
$ pip install pytest
$ mkdir tests
$ cd tests
$ touch __init__.py
```

Add following function to `test_piglatin.py`:

```
def test_translate():
    assert True
```

Then, to run your new test try:

```
$ cd ..
$ pytest
```

Fill in some proper unit tests with assert. Further documentation at
https://pytest.org/

Mocking objects and spying on interactions via the `unittest.mock` module.

See PigLatin module for examples.

We'll cover the xUnit style `unittest` framework with the Django API work
that's coming later.

# Debugging with PDB

```
import pdb; pdb.set_trace()
```

or in Python3.7 +

```
breakpoint()
```

Use `help` to discover the commands available to you.

* Step over lines
* Step into callables
* Step out of blocks
* Finish loops
* Evaluate objects
* Change things on-the-fly.

It's an interactive REPL for a running program.

You should probably use a visual debugger if that's what you're used to from
Java. But it's important to know you can debug scripts like this.

# DJANGO and Django Rest Framework

We're going to build a simple API for musicians and albums. See the example
code for a working example.

New virtualenv.

```
$ pip install djangorestframework
$ pip install markdown
$ pip install django-filter
```

Use Django admin commands (explain) to start a new project:

```
$ django-admin startproject myapi
$ cd myapi
$ ./manage.py migrate
$ ./manage.py createsuperuser
$ ./manage.py runserver
```

It works. Play with the `admin` application to demonstrate CRUD (add a new
user).

Add the Django Rest Framework into this "vanilla" website.

```
$ cd myapi/myapi
```

In settings.py (explain the concept of "apps" in Django):

```
INSTALLED_APPS = [
    ...
    'rest_framework',
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}
```

In urls.py (explain routes, serializers, viewsets):

```
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'is_staff']

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
```

Now browse the API in the website.

We need to add musicians and albums now we have a working API.

## Customizing things:

Create and configure a `musicians` app:

```
$ ./manage.py startapp musicians
$ cd myapi
```

Add "musicians" to installed apps in `settings.py`.

```
$ cd ..
$ cd musicians
```

Make models that look like this in `models.py`:

```
from django.db import models

# Create your models here.

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()
```

Explain migrations and make some for the musicians:

```
$ ./manage.py makemigrations
$ ./manage.py migrate
```

Add industry standard swagger docs to your API:

```
$ pip install -U drf-yasg
```

Update `settings.py` to have "drf_yasg" as an installed app.

Update `urls.py` to:

```
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

... serializers, views and routes for musicians and albums...

schema_view = get_schema_view(
   openapi.Info(
      title="Snippets API",
      default_version='v1',
      description="Test description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="<EMAIL>"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

   url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
   url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
   url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
```

It should just work (tm):

```
$ ./manage.py runserver
```

Visit: http://127.0.0.1:8000/redoc/

## Adding Tests

In `musician/tests.py`:

```
from django.test import TestCase
from .models import Musician, Album

# Create your tests here.

class MusicianModelTests(TestCase):

    def test_create_musician(self):
        m = Musician(first_name="Nicholas", last_name="Tollervey", instrument="Tuba")
        m.save()
        result = Musician.objects.filter(first_name="Nicholas").first()
        assert result.last_name == "Tollervey"
```

This uses the familiar xUnit class based testing practice.

To run the test suite:

```
$ ./manage.py test
```

Use of client and REPL with Django to also demonstrate client based tests.

```
$ ./manage.py shell
```

This is a REPL for your web application.

```
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client = Client()
>>> response = client.get('/')
>>> response.status_code
>>> dir(response)
>>> response.json()
```

Turned into a class based test:

```
from django.test import TestCase, Client

class ViewTests(TestCase):

    def setUp(self):
        """
        Run before all other tests.
        """
        self.client = Client()

    def test_root_path(self):
        result = self.client.get("/")
        assert result.status_code == 200
        data = result.json()
        assert "users" in data
        assert "musicians" in data
        assert "albums" in data
```

Then:

$ ./manage.py test

Mocking. See:

https://github.com/nhsd-ddce/dos-capacity-status-api/blob/master/application/api/capacityauth/tests/test_authorise.py

See the example app for a working API.

# Questions..?

repo_name: ntoll/nhsdtraining