<commit_before>/* logs.cc
   Eric Robert, 9 October 2013
   Copyright (c) 2013 Datacratic.  All rights reserved.

   Basic logs
*/

#include "soa/service/logs.h"
#include "jml/utils/exc_check.h"

#include <iostream>
#include <mutex>
#include <unordered_map>
#include <vector>

namespace Datacratic {

void Logging::ConsoleWriter::head(char const * timestamp,
                                  char const * name,
                                  char const * function,
                                  char const * file,
                                  int line) {
    if(color) {
        stream << timestamp << " " << "\033[1;32m" << name << " ";
    }
    else {
        stream << timestamp << " " << name << " ";
    }
}

void Logging::ConsoleWriter::body(std::string const & content) {
    if(color) {
        stream << "\033[1;34m";
        stream.write(content.c_str(), content.size() - 1);
        stream << "\033[0m\n";
    }
    else {
        stream << content;
    }

    std::cerr << stream.str();
    stream.str("");
}

void Logging::FileWriter::head(char const * timestamp,
                               char const * name,
                               char const * function,
                               char const * file,
                               int line) {
    stream << timestamp << " " << name << " ";
}

void Logging::FileWriter::body(std::string const & content) {
    file << stream.str() << content;
    stream.str("");
}

void Logging::FileWriter::open(char const * filename, char const mode) {
    if(mode == 'a')
        file.open(filename, std::ofstream::app);
    else if (mode == 'w')
        file.open(filename);
    else
        throw ML::Exception("File mode not recognized");

    if(!file) {
        std::cerr << "unable to open log file '" << filename << "'" << std::endl;
    }
}

void Logging::JsonWriter::head(char const * timestamp,
                               char const * name,
                               char const * function,
                               char const * file,
                               int line) {
    stream << "{\"time\":\"" << timestamp
           << "\",\"name\":\"" << name
           << "\",\"call\":\"" << function
           << "\",\"file\":\"" << file
           << "\",\"line\":" << line
           << ",\"text\":\"";
}

void Logging::JsonWriter::body(std::string const & content) {
    stream.write(content.c_str(), content.size() - 1);
    stream << "\"}\n";
    if(!writer) {
        std::cerr << stream.str();
    }
    else {
        writer->body(stream.str());
    }

    stream.str("");
}

namespace {

struct Registry {
    std::mutex lock;
    std::unordered_map<std::string, std::unique_ptr<Logging::CategoryData> > categories;
};

Registry& getRegistry() {
    // Will leak but that's on program exit so who cares.
    static Registry* registry = new Registry;

    return *registry;
}

} // namespace anonymous

struct Logging::CategoryData {
    bool initialized;
    bool enabled;
    char const * name;
    std::shared_ptr<Writer> writer;
    std::stringstream stream;

    CategoryData * parent;
    std::vector<CategoryData *> children;

    static CategoryData * getRoot();
    static CategoryData * get(char const * name);

    static CategoryData * create(char const * name, char const * super, bool enabled);
    static void destroy(CategoryData * name);

    void activate(bool recurse = true);
    void deactivate(bool recurse = true);
    void writeTo(std::shared_ptr<Writer> output, bool recurse = true);

private:

    CategoryData(char const * name, bool enabled) :
        initialized(false),
        enabled(enabled),
        name(name),
        parent(nullptr) {
    }

};

Logging::CategoryData * Logging::CategoryData::get(char const * name) {
    Registry& registry = getRegistry();

    auto it = registry.categories.find(name);
    return it != registry.categories.end() ? it->second.get() : nullptr;
}

Logging::CategoryData * Logging::CategoryData::getRoot() {
    CategoryData * root = get("*");
    if (root) return root;

    getRegistry().categories["*"].reset(root = new CategoryData("*", true /* enabled */));
    root->parent = root;
    root->writer = std::make_shared<ConsoleWriter>();

    return root;
}

Logging::CategoryData * Logging::CategoryData::create(char const * name, char const * super, bool enabled) {
    Registry& registry = getRegistry();
    std::lock_guard<std::mutex> guard(registry.lock);

    CategoryData * root = getRoot();
    CategoryData * data = get(name);

    if (!data) {
        registry.categories[name].reset(data = new CategoryData(name, enabled));
    }
    else {
        ExcCheck(!data->initialized,
                "making duplicate category: " + std::string(name));
    }

    data->initialized = true;

    data->parent = get(super);
    if (!data->parent) {
        registry.categories[super].reset(data->parent = new CategoryData(super, enabled));
    }

    data->parent->children.push_back(data);

    if (data->parent->initialized) {
        data->writer = data->parent->writer;
    }
    else {
        data->writer = root->writer;
    }

    return data;
}

void Logging::CategoryData::destroy(CategoryData * data) {
    if (data->parent == data) return;

    Registry& registry = getRegistry();
    std::string name = data->name;

    std::lock_guard<std::mutex> guard(registry.lock);

    auto dataIt = registry.categories.find(name);
    ExcCheck(dataIt != registry.categories.end(),
            "double destroy of a category: " + name);

    auto& children = data->parent->children;

    auto childIt = std::find(children.begin(), children.end(), data);
    if (childIt != children.end()) {
        children.erase(childIt);
    }

    CategoryData* root = getRoot();
    for (auto& child : data->children) {
        child->parent = root;
    }

    registry.categories.erase(dataIt);
}

void Logging::CategoryData::activate(bool recurse) {
    enabled = true;
    if(recurse) {
        for(auto item : children) {
            item->activate(recurse);
        }
    }
}

void Logging::CategoryData::deactivate(bool recurse) {
    enabled = false;
    if(recurse) {
        for(auto item : children) {
            item->deactivate(recurse);
        }
    }
}

void Logging::CategoryData::writeTo(std::shared_ptr<Writer> output, bool recurse) {
    writer = output;
    if(recurse) {
        for(auto item : children) {
            item->writeTo(output, recurse);
        }
    }
}

Logging::Category& Logging::Category::root() {
    static Category root(CategoryData::getRoot());
    return root;
}

Logging::Category::Category(CategoryData * data) :
    data(data) {
}

Logging::Category::Category(char const * name, Category & super, bool enabled) :
    data(CategoryData::create(name, super.name(), enabled)) {
}

Logging::Category::Category(char const * name, char const * super, bool enabled) :
    data(CategoryData::create(name, super, enabled)) {
}

Logging::Category::Category(char const * name, bool enabled) :
    data(CategoryData::create(name, "*", enabled)) {
}

Logging::Category::~Category()
{
    CategoryData::destroy(data);
}

char const * Logging::Category::name() const {
    return data->name;
}

bool Logging::Category::isEnabled() const {
    return data->enabled;
}

bool Logging::Category::isDisabled() const {
    return !data->enabled;
}

auto Logging::Category::getWriter() const -> std::shared_ptr<Writer> const &
{
    return data->writer;
}

void Logging::Category::activate(bool recurse) {
    data->activate(recurse);
}

void Logging::Category::deactivate(bool recurse) {
    data->deactivate(recurse);
}

void Logging::Category::writeTo(std::shared_ptr<Writer> output, bool recurse) {
    data->writeTo(output, recurse);
}

std::ostream & Logging::Category::beginWrite(char const * fct, char const * file, int line) {
    timeval now;
    gettimeofday(&now, 0);
    char text[64];
    auto count = strftime(text, sizeof(text), "%Y-%m-%d %H:%M:%S", localtime(&now.tv_sec));
    int ms = now.tv_usec / 1000;
    sprintf(text + count, ".%03d", ms);
    data->writer->head(text, data->name, fct, file, line);
    return data->stream;
}

void Logging::Printer::operator&(std::ostream & stream) {
    std::stringstream & text = (std::stringstream &) stream;
    category.getWriter()->body(text.str());
    text.str("");
}

void Logging::Thrower::operator&(std::ostream & stream) {
    std::stringstream & text = (std::stringstream &) stream;
    std::string message(text.str());
    text.str("");
    throw ML::Exception(message);
}

} // namespace Datacratic
<commit_msg>hotfix for memory corruption caused by using a logging category from multiple threads.<commit_after>/* logs.cc
   Eric Robert, 9 October 2013
   Copyright (c) 2013 Datacratic.  All rights reserved.

   Basic logs
*/

#include "soa/service/logs.h"
#include "jml/utils/exc_check.h"

#include <iostream>
#include <mutex>
#include <unordered_map>
#include <vector>

namespace Datacratic {

void Logging::ConsoleWriter::head(char const * timestamp,
                                  char const * name,
                                  char const * function,
                                  char const * file,
                                  int line) {
    if(color) {
        stream << timestamp << " " << "\033[1;32m" << name << " ";
    }
    else {
        stream << timestamp << " " << name << " ";
    }
}

void Logging::ConsoleWriter::body(std::string const & content) {
    if(color) {
        stream << "\033[1;34m";
        stream.write(content.c_str(), content.size() - 1);
        stream << "\033[0m\n";
    }
    else {
        stream << content;
    }

    std::cerr << stream.str();
    stream.str("");
}

void Logging::FileWriter::head(char const * timestamp,
                               char const * name,
                               char const * function,
                               char const * file,
                               int line) {
    stream << timestamp << " " << name << " ";
}

void Logging::FileWriter::body(std::string const & content) {
    file << stream.str() << content;
    stream.str("");
}

void Logging::FileWriter::open(char const * filename, char const mode) {
    if(mode == 'a')
        file.open(filename, std::ofstream::app);
    else if (mode == 'w')
        file.open(filename);
    else
        throw ML::Exception("File mode not recognized");

    if(!file) {
        std::cerr << "unable to open log file '" << filename << "'" << std::endl;
    }
}

void Logging::JsonWriter::head(char const * timestamp,
                               char const * name,
                               char const * function,
                               char const * file,
                               int line) {
    stream << "{\"time\":\"" << timestamp
           << "\",\"name\":\"" << name
           << "\",\"call\":\"" << function
           << "\",\"file\":\"" << file
           << "\",\"line\":" << line
           << ",\"text\":\"";
}

void Logging::JsonWriter::body(std::string const & content) {
    stream.write(content.c_str(), content.size() - 1);
    stream << "\"}\n";
    if(!writer) {
        std::cerr << stream.str();
    }
    else {
        writer->body(stream.str());
    }

    stream.str("");
}

namespace {

struct Registry {
    std::mutex lock;
    std::unordered_map<std::string, std::unique_ptr<Logging::CategoryData> > categories;
};

Registry& getRegistry() {
    // Will leak but that's on program exit so who cares.
    static Registry* registry = new Registry;

    return *registry;
}

} // namespace anonymous

struct Logging::CategoryData {
    bool initialized;
    bool enabled;
    char const * name;
    std::shared_ptr<Writer> writer;
    std::stringstream stream;

    CategoryData * parent;
    std::vector<CategoryData *> children;

    static CategoryData * getRoot();
    static CategoryData * get(char const * name);

    static CategoryData * create(char const * name, char const * super, bool enabled);
    static void destroy(CategoryData * name);

    void activate(bool recurse = true);
    void deactivate(bool recurse = true);
    void writeTo(std::shared_ptr<Writer> output, bool recurse = true);

private:

    CategoryData(char const * name, bool enabled) :
        initialized(false),
        enabled(enabled),
        name(name),
        parent(nullptr) {
    }

};

Logging::CategoryData * Logging::CategoryData::get(char const * name) {
    Registry& registry = getRegistry();

    auto it = registry.categories.find(name);
    return it != registry.categories.end() ? it->second.get() : nullptr;
}

Logging::CategoryData * Logging::CategoryData::getRoot() {
    CategoryData * root = get("*");
    if (root) return root;

    getRegistry().categories["*"].reset(root = new CategoryData("*", true /* enabled */));
    root->parent = root;
    root->writer = std::make_shared<ConsoleWriter>();

    return root;
}

Logging::CategoryData * Logging::CategoryData::create(char const * name, char const * super, bool enabled) {
    Registry& registry = getRegistry();
    std::lock_guard<std::mutex> guard(registry.lock);

    CategoryData * root = getRoot();
    CategoryData * data = get(name);

    if (!data) {
        registry.categories[name].reset(data = new CategoryData(name, enabled));
    }
    else {
        ExcCheck(!data->initialized,
                "making duplicate category: " + std::string(name));
    }

    data->initialized = true;

    data->parent = get(super);
    if (!data->parent) {
        registry.categories[super].reset(data->parent = new CategoryData(super, enabled));
    }

    data->parent->children.push_back(data);

    if (data->parent->initialized) {
        data->writer = data->parent->writer;
    }
    else {
        data->writer = root->writer;
    }

    return data;
}

void Logging::CategoryData::destroy(CategoryData * data) {
    if (data->parent == data) return;

    Registry& registry = getRegistry();
    std::string name = data->name;

    std::lock_guard<std::mutex> guard(registry.lock);

    auto dataIt = registry.categories.find(name);
    ExcCheck(dataIt != registry.categories.end(),
            "double destroy of a category: " + name);

    auto& children = data->parent->children;

    auto childIt = std::find(children.begin(), children.end(), data);
    if (childIt != children.end()) {
        children.erase(childIt);
    }

    CategoryData* root = getRoot();
    for (auto& child : data->children) {
        child->parent = root;
    }

    registry.categories.erase(dataIt);
}

void Logging::CategoryData::activate(bool recurse) {
    enabled = true;
    if(recurse) {
        for(auto item : children) {
            item->activate(recurse);
        }
    }
}

void Logging::CategoryData::deactivate(bool recurse) {
    enabled = false;
    if(recurse) {
        for(auto item : children) {
            item->deactivate(recurse);
        }
    }
}

void Logging::CategoryData::writeTo(std::shared_ptr<Writer> output, bool recurse) {
    writer = output;
    if(recurse) {
        for(auto item : children) {
            item->writeTo(output, recurse);
        }
    }
}

Logging::Category& Logging::Category::root() {
    static Category root(CategoryData::getRoot());
    return root;
}

Logging::Category::Category(CategoryData * data) :
    data(data) {
}

Logging::Category::Category(char const * name, Category & super, bool enabled) :
    data(CategoryData::create(name, super.name(), enabled)) {
}

Logging::Category::Category(char const * name, char const * super, bool enabled) :
    data(CategoryData::create(name, super, enabled)) {
}

Logging::Category::Category(char const * name, bool enabled) :
    data(CategoryData::create(name, "*", enabled)) {
}

Logging::Category::~Category()
{
    CategoryData::destroy(data);
}

char const * Logging::Category::name() const {
    return data->name;
}

bool Logging::Category::isEnabled() const {
    return data->enabled;
}

bool Logging::Category::isDisabled() const {
    return !data->enabled;
}

auto Logging::Category::getWriter() const -> std::shared_ptr<Writer> const &
{
    return data->writer;
}

void Logging::Category::activate(bool recurse) {
    data->activate(recurse);
}

void Logging::Category::deactivate(bool recurse) {
    data->deactivate(recurse);
}

void Logging::Category::writeTo(std::shared_ptr<Writer> output, bool recurse) {
    data->writeTo(output, recurse);
}

// This lock is a quick-fix for the case where a category is used by multiple
// threads. Note that this lock should either eventually be removed or replaced
// by a per category lock. Unfortunately the current setup makes it very
// difficult to pass the header information to the operator& so that everything
// can be dumped in the stream in one go.
namespace { std::mutex loggingMutex; }

std::ostream & Logging::Category::beginWrite(char const * fct, char const * file, int line) {
    loggingMutex.lock();

    timeval now;
    gettimeofday(&now, 0);
    char text[64];
    auto count = strftime(text, sizeof(text), "%Y-%m-%d %H:%M:%S", localtime(&now.tv_sec));
    int ms = now.tv_usec / 1000;
    sprintf(text + count, ".%03d", ms);
    data->writer->head(text, data->name, fct, file, line);
    return data->stream;
}

void Logging::Printer::operator&(std::ostream & stream) {
    std::stringstream & text = (std::stringstream &) stream;
    category.getWriter()->body(text.str());
    text.str("");

    loggingMutex.unlock();
}

void Logging::Thrower::operator&(std::ostream & stream) {
    std::stringstream & text = (std::stringstream &) stream;
    std::string message(text.str());
    text.str("");
    loggingMutex.unlock();

    throw ML::Exception(message);
}

} // namespace Datacratic
<|endoftext|>


<commit_before>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <iostream>
#include <sstream>
#include <iomanip>
#include <thread>

#include "Runtime.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>

using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

using namespace  ::bm_runtime;

class RuntimeHandler : virtual public RuntimeIf {
 public:
  RuntimeHandler() {
    // Your initialization goes here
  }

  std::string ToHex(const std::string& s, bool upper_case = false) {
    std::ostringstream ret;

    for (std::string::size_type i = 0; i < s.length(); i++) {
      ret << std::setw(2) << std::setfill('0') << std::hex
	  << (upper_case ? std::uppercase : std::nouppercase)
	  << (int) static_cast<unsigned char>(s[i]);
    }

    return ret.str();
  }

  void print_spec(const std::vector<std::string> &v) {
    for(const auto &e : v)
      std::cout << ToHex(e) << " ";
    std::cout << std::endl;
  }

  void print_match_param(const BmMatchParam &param) {
    switch(param.type) {
    case BmMatchParamType::type::EXACT:
      std::cout << "EXACT: "
		<< ToHex(param.exact.key);
      break;
    case BmMatchParamType::type::LPM:
      std::cout << "LPM: "
		<< ToHex(param.lpm.key) << "/" << param.lpm.prefix_length;
      break;
    case BmMatchParamType::type::TERNARY:
      std::cout << "TERNARY: "
		<<ToHex(param.ternary.key) << "&&&" << ToHex(param.ternary.mask);
      break;
    case BmMatchParamType::type::VALID:
      std::cout << "VALID: "
		<<std::boolalpha << param.valid.key << std::noboolalpha;
      break;
    default:
      assert(0 && "invalid match type");
      break;
    }
    std::cout << std::endl;
  }

  BmEntryHandle bm_mt_add_entry(const std::string& table_name, const BmMatchParams& match_key, const std::string& action_name, const BmActionData& action_data, const BmAddEntryOptions& options) {
    std::cout << "bm_table_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << action_name << std::endl;
    print_spec(action_data);
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_set_default_action(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_set_default_action" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  void bm_mt_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_table_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const std::string &action_name, const BmActionData& action_data) {
    std::cout << "bm_table_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  BmMemberHandle bm_mt_indirect_add_member(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_add_member" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
    return 0;
  }

  void bm_mt_indirect_delete_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_delete_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_modify_member(const std::string& table_name, const BmMemberHandle mbr_handle, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_modify_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  BmEntryHandle bm_mt_indirect_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmMemberHandle mbr_handle, const BmAddEntryOptions& options) {
    std::cout << "bm_mt_indirect_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << mbr_handle << std::endl;
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_indirect_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_indirect_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_indirect_set_default_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_set_default_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  BmGroupHandle bm_mt_indirect_ws_create_group(const std::string& table_name) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_create_group\n");
    return 0;
  }

  void bm_mt_indirect_ws_delete_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_delete_group\n");
  }

  void bm_mt_indirect_ws_add_member_to_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_member_to_group\n");
  }

  void bm_mt_indirect_ws_remove_member_from_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_remove_member_from_group\n");
  }

  BmEntryHandle bm_mt_indirect_ws_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmGroupHandle grp_handle, const BmAddEntryOptions& options) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_entry\n");
    return 0;
  }

  void bm_mt_indirect_ws_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_modify_entry\n");
  }

  void bm_mt_indirect_ws_set_default_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_set_default_group\n");
  }

  void bm_table_read_counter(BmCounterValue& _return, const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_table_read_counter" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_table_reset_counters(const std::string& table_name) {
    std::cout << "bm_table_reset_counters" << std::endl
	      << table_name << std::endl;
  }

  void bm_learning_ack(const BmLearningListId list_id, const BmLearningBufferId buffer_id, const std::vector<BmLearningSampleId> & sample_ids) {
    // Your implementation goes here
    printf("bm_learning_ack\n");
  }

  void bm_learning_ack_buffer(const BmLearningListId list_id, const BmLearningBufferId buffer_id) {
    // Your implementation goes here
    printf("bm_learning_ack_buffer\n");
  }

  void bm_load_new_config(const std::string& config_str) {
    // Your implementation goes here
    printf("bm_load_new_config\n");
  }

  void bm_swap_configs() {
    // Your implementation goes here
    printf("bm_swap_configs\n");
  }

  BmMcMgrpHandle bm_mc_mgrp_create(const BmMcMgrp mgrp) {
    // Your implementation goes here
    printf("bm_mc_mgrp_create\n");
    return 0;
  }

  void bm_mc_mgrp_destroy(const BmMcMgrpHandle mgrp_handle) {
    // Your implementation goes here
    printf("bm_mc_mgrp_destroy\n");
  }

  BmMcL1Handle bm_mc_l1_node_create(const BmMcRid rid) {
    // Your implementation goes here
    printf("bm_mc_l1_node_create\n");
    return 0;
  }

  void bm_mc_l1_node_associate(const BmMcMgrpHandle mgrp_handle, const BmMcL1Handle l1_handle) {
    // Your implementation goes here
    printf("bm_mc_l1_node_associate\n");
  }

  void bm_mc_l1_node_destroy(const BmMcL1Handle l1_handle) {
    // Your implementation goes here
    printf("bm_mc_l1_node_destroy\n");
  }

  BmMcL2Handle bm_mc_l2_node_create(const BmMcL1Handle l1_handle, const BmMcPortMap& port_map) {
    std::cout << "bm_mc_l2_node_create" << std::endl
	      << l1_handle << std::endl
	      << port_map.substr(0, 16) << std::endl;
    return 0;
  }

  void bm_mc_l2_node_update(const BmMcL2Handle l2_handle, const BmMcPortMap& port_map) {
    // Your implementation goes here
    printf("bm_mc_l2_node_update\n");
  }

  void bm_mc_l2_node_destroy(const BmMcL2Handle l2_handle) {
    // Your implementation goes here
    printf("bm_mc_l2_node_destroy\n");
  }

  void bm_meter_array_set_rates(const std::string& meter_array_name, const std::vector<BmMeterRateConfig> & rates) {
    // Your implementation goes here
    printf("bm_meter_array_set_rates\n");
  }

  void bm_meter_set_rates(const std::string& meter_array_name, const int32_t index, const std::vector<BmMeterRateConfig> & rates) {
    std::cout << "bm_meter_set_rates" << std::endl
	      << meter_array_name << std::endl
	      << index << std::endl;
    for(const auto &rate : rates) {
      std::cout << rate.units_per_micros << " " << rate.burst_size << std::endl;
    }
  }

  void bm_dev_mgr_add_port(const std::string& iface_name, const int32_t port_num, const std::string& pcap_path) {
    // Your implementation goes here
    printf("bm_dev_mgr_add_port\n");
  }

  void bm_dev_mgr_remove_port(const int32_t port_num) {
    // Your implementation goes here
    printf("bm_dev_mgr_remove_port\n");
  }

  void bm_dump_table(std::string& _return, const std::string& table_name) {
    // Your implementation goes here
    printf("bm_dump_table\n");
  }

};

void run_server(int port) {
  shared_ptr<RuntimeHandler> handler(new RuntimeHandler());
  shared_ptr<TProcessor> processor(new RuntimeProcessor(handler));
  shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

  TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
  server.serve();
}

int start_server(void) {
  int port = 9090;
  std::thread t(run_server, port);
  t.detach();
  return 0;
}
<commit_msg>fixed bug in how port map was printed (for pd sanity check)<commit_after>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <iostream>
#include <sstream>
#include <iomanip>
#include <thread>

#include "Runtime.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>

using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

using namespace  ::bm_runtime;

class RuntimeHandler : virtual public RuntimeIf {
 public:
  RuntimeHandler() {
    // Your initialization goes here
  }

  std::string ToHex(const std::string& s, bool upper_case = false) {
    std::ostringstream ret;

    for (std::string::size_type i = 0; i < s.length(); i++) {
      ret << std::setw(2) << std::setfill('0') << std::hex
	  << (upper_case ? std::uppercase : std::nouppercase)
	  << (int) static_cast<unsigned char>(s[i]);
    }

    return ret.str();
  }

  void print_spec(const std::vector<std::string> &v) {
    for(const auto &e : v)
      std::cout << ToHex(e) << " ";
    std::cout << std::endl;
  }

  void print_match_param(const BmMatchParam &param) {
    switch(param.type) {
    case BmMatchParamType::type::EXACT:
      std::cout << "EXACT: "
		<< ToHex(param.exact.key);
      break;
    case BmMatchParamType::type::LPM:
      std::cout << "LPM: "
		<< ToHex(param.lpm.key) << "/" << param.lpm.prefix_length;
      break;
    case BmMatchParamType::type::TERNARY:
      std::cout << "TERNARY: "
		<<ToHex(param.ternary.key) << "&&&" << ToHex(param.ternary.mask);
      break;
    case BmMatchParamType::type::VALID:
      std::cout << "VALID: "
		<<std::boolalpha << param.valid.key << std::noboolalpha;
      break;
    default:
      assert(0 && "invalid match type");
      break;
    }
    std::cout << std::endl;
  }

  BmEntryHandle bm_mt_add_entry(const std::string& table_name, const BmMatchParams& match_key, const std::string& action_name, const BmActionData& action_data, const BmAddEntryOptions& options) {
    std::cout << "bm_table_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << action_name << std::endl;
    print_spec(action_data);
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_set_default_action(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_set_default_action" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  void bm_mt_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_table_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const std::string &action_name, const BmActionData& action_data) {
    std::cout << "bm_table_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  BmMemberHandle bm_mt_indirect_add_member(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_add_member" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
    return 0;
  }

  void bm_mt_indirect_delete_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_delete_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_modify_member(const std::string& table_name, const BmMemberHandle mbr_handle, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_modify_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  BmEntryHandle bm_mt_indirect_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmMemberHandle mbr_handle, const BmAddEntryOptions& options) {
    std::cout << "bm_mt_indirect_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << mbr_handle << std::endl;
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_indirect_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_indirect_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_indirect_set_default_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_set_default_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  BmGroupHandle bm_mt_indirect_ws_create_group(const std::string& table_name) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_create_group\n");
    return 0;
  }

  void bm_mt_indirect_ws_delete_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_delete_group\n");
  }

  void bm_mt_indirect_ws_add_member_to_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_member_to_group\n");
  }

  void bm_mt_indirect_ws_remove_member_from_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_remove_member_from_group\n");
  }

  BmEntryHandle bm_mt_indirect_ws_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmGroupHandle grp_handle, const BmAddEntryOptions& options) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_entry\n");
    return 0;
  }

  void bm_mt_indirect_ws_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_modify_entry\n");
  }

  void bm_mt_indirect_ws_set_default_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_set_default_group\n");
  }

  void bm_table_read_counter(BmCounterValue& _return, const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_table_read_counter" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_table_reset_counters(const std::string& table_name) {
    std::cout << "bm_table_reset_counters" << std::endl
	      << table_name << std::endl;
  }

  void bm_learning_ack(const BmLearningListId list_id, const BmLearningBufferId buffer_id, const std::vector<BmLearningSampleId> & sample_ids) {
    // Your implementation goes here
    printf("bm_learning_ack\n");
  }

  void bm_learning_ack_buffer(const BmLearningListId list_id, const BmLearningBufferId buffer_id) {
    // Your implementation goes here
    printf("bm_learning_ack_buffer\n");
  }

  void bm_load_new_config(const std::string& config_str) {
    // Your implementation goes here
    printf("bm_load_new_config\n");
  }

  void bm_swap_configs() {
    // Your implementation goes here
    printf("bm_swap_configs\n");
  }

  BmMcMgrpHandle bm_mc_mgrp_create(const BmMcMgrp mgrp) {
    // Your implementation goes here
    printf("bm_mc_mgrp_create\n");
    return 0;
  }

  void bm_mc_mgrp_destroy(const BmMcMgrpHandle mgrp_handle) {
    // Your implementation goes here
    printf("bm_mc_mgrp_destroy\n");
  }

  BmMcL1Handle bm_mc_l1_node_create(const BmMcRid rid) {
    // Your implementation goes here
    printf("bm_mc_l1_node_create\n");
    return 0;
  }

  void bm_mc_l1_node_associate(const BmMcMgrpHandle mgrp_handle, const BmMcL1Handle l1_handle) {
    // Your implementation goes here
    printf("bm_mc_l1_node_associate\n");
  }

  void bm_mc_l1_node_destroy(const BmMcL1Handle l1_handle) {
    // Your implementation goes here
    printf("bm_mc_l1_node_destroy\n");
  }

  BmMcL2Handle bm_mc_l2_node_create(const BmMcL1Handle l1_handle, const BmMcPortMap& port_map) {
    std::string str(port_map.rbegin(), port_map.rbegin() + 16);
    std::cout << "bm_mc_l2_node_create" << std::endl
	      << l1_handle << std::endl
	      << str << std::endl;
    return 0;
  }

  void bm_mc_l2_node_update(const BmMcL2Handle l2_handle, const BmMcPortMap& port_map) {
    // Your implementation goes here
    printf("bm_mc_l2_node_update\n");
  }

  void bm_mc_l2_node_destroy(const BmMcL2Handle l2_handle) {
    // Your implementation goes here
    printf("bm_mc_l2_node_destroy\n");
  }

  void bm_meter_array_set_rates(const std::string& meter_array_name, const std::vector<BmMeterRateConfig> & rates) {
    // Your implementation goes here
    printf("bm_meter_array_set_rates\n");
  }

  void bm_meter_set_rates(const std::string& meter_array_name, const int32_t index, const std::vector<BmMeterRateConfig> & rates) {
    std::cout << "bm_meter_set_rates" << std::endl
	      << meter_array_name << std::endl
	      << index << std::endl;
    for(const auto &rate : rates) {
      std::cout << rate.units_per_micros << " " << rate.burst_size << std::endl;
    }
  }

  void bm_dev_mgr_add_port(const std::string& iface_name, const int32_t port_num, const std::string& pcap_path) {
    // Your implementation goes here
    printf("bm_dev_mgr_add_port\n");
  }

  void bm_dev_mgr_remove_port(const int32_t port_num) {
    // Your implementation goes here
    printf("bm_dev_mgr_remove_port\n");
  }

  void bm_dump_table(std::string& _return, const std::string& table_name) {
    // Your implementation goes here
    printf("bm_dump_table\n");
  }

};

void run_server(int port) {
  shared_ptr<RuntimeHandler> handler(new RuntimeHandler());
  shared_ptr<TProcessor> processor(new RuntimeProcessor(handler));
  shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

  TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
  server.serve();
}

int start_server(void) {
  int port = 9090;
  std::thread t(run_server, port);
  t.detach();
  return 0;
}
<|endoftext|>


<commit_before>#ifndef BUW_SDFLOADER_HPP
#define BUW_SDFLOADER_HPP

#include <string>
#include <scene.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <regex>

void sdf_splitString(std::string const& input, std::vector<std::string>& output) {
	std::istringstream tmp{input};
	do {
		std::string sub{""};
		tmp >> sub;
		output.push_back(sub);
	} while(tmp);
}

bool sdf_isMaterial(std::string const& input) {
	std::regex rgx_material{"define[\\s\\t]material[\\s\\t]\\S+[\\s\\t]([0-9][\\s\\t]){9}[0-9].*"};
	if(std::regex_match(input,rgx_material)) {
		return true;
	}
	return false;
}

void sdf_parseMaterial(std::string const& input, std::map<std::string,Material>& materials) {
	std::vector<std::string> parsed;
	sdf_splitString(input,parsed);
	Color ka = {std::stof(parsed[3]),std::stof(parsed[4]),std::stof(parsed[5])};
	Color kd = {std::stof(parsed[6]),std::stof(parsed[7]),std::stof(parsed[8])};
	Color ks = {std::stof(parsed[9]),std::stof(parsed[10]),std::stof(parsed[11])};
	materials.insert(materials.end(),
		std::pair<std:string,Material>{parsed[2],{parsed[2],ka,kd,ks,std::stof(parsed[12]});
}

bool sdf_isComment(std::string const& input) {
	std::regex rgx_comment{"^#.*"};
	if(std::regex_match(input, rgx_comment)) {
		return true;
	}
	return false;
}

void sdf_loadScene(std::ifstream& file, Scene& scene) {
	std::string line{""};
	while(std::getline(file,line)) {
		//Comment
		if(sdf_isComment(line)) {
			continue;
		}
		// Material
		//Material* tmp_material{nullptr};
		if(sdf_isMaterial(line)) {
			sdf_parseMaterial(line,scene.materials);
			//scene.materials.push_back(tmp_material);
			continue;
		}
	}
}

#endif
<commit_msg>try fix sdfloader the fourth<commit_after>#ifndef BUW_SDFLOADER_HPP
#define BUW_SDFLOADER_HPP

#include <string>
#include <scene.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <regex>

void sdf_splitString(std::string const& input, std::vector<std::string>& output) {
	std::istringstream tmp{input};
	do {
		std::string sub{""};
		tmp >> sub;
		output.push_back(sub);
	} while(tmp);
}

bool sdf_isMaterial(std::string const& input) {
	std::regex rgx_material{"define[\\s\\t]material[\\s\\t]\\S+[\\s\\t]([0-9][\\s\\t]){9}[0-9].*"};
	if(std::regex_match(input,rgx_material)) {
		return true;
	}
	return false;
}

void sdf_parseMaterial(std::string const& input, std::map<std::string,Material>& materials) {
	std::vector<std::string> parsed;
	sdf_splitString(input,parsed);
	Color ka = {std::stof(parsed[3]),std::stof(parsed[4]),std::stof(parsed[5])};
	Color kd = {std::stof(parsed[6]),std::stof(parsed[7]),std::stof(parsed[8])};
	Color ks = {std::stof(parsed[9]),std::stof(parsed[10]),std::stof(parsed[11])};
	materials.insert(materials.end(),
		std::pair<std:string,Material>(parsed[2],{parsed[2],ka,kd,ks,std::stof(parsed[12])});
}

bool sdf_isComment(std::string const& input) {
	std::regex rgx_comment{"^#.*"};
	if(std::regex_match(input, rgx_comment)) {
		return true;
	}
	return false;
}

void sdf_loadScene(std::ifstream& file, Scene& scene) {
	std::string line{""};
	while(std::getline(file,line)) {
		//Comment
		if(sdf_isComment(line)) {
			continue;
		}
		// Material
		//Material* tmp_material{nullptr};
		if(sdf_isMaterial(line)) {
			sdf_parseMaterial(line,scene.materials);
			//scene.materials.push_back(tmp_material);
			continue;
		}
	}
}

#endif
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////

#include "handler.h"
#include "being.h"
#include "disease.h"
#include "combat.h"
#include "disc_deikhan.h"

extern void startChargeTask(TBeing *, const char *);

int synostodweomer(TBeing *caster, TBeing *v, int level, short bKnown)
{
  int hitp = 0;
  affectedData aff;

  if (!caster->isImmortal() && caster->checkForSkillAttempt(SPELL_SYNOSTODWEOMER)) {
    act("You are not prepared to try to Snyostodweomer again so soon.",
         FALSE, caster, NULL, NULL, TO_CHAR);
    return FALSE;
  }

  if (v->affectedBySpell(SPELL_SYNOSTODWEOMER)) {
    caster->sendTo(COLOR_MOBS, format("%s is already affected by Snyostodweomer.\n\r") % v->getName());
    return FALSE;
  }

  if (caster->bSuccess(bKnown, caster->getPerc(), SPELL_SYNOSTODWEOMER)) {
    act("Power rushes through your fingers as you bless $N.", FALSE, caster, NULL, v, TO_CHAR);
    act("Power rushes through $n's fingers as $e blesses $N.", TRUE, caster, NULL, v, TO_NOTVICT);
    act("Power surges through $n's fingers as $e blesses you.", TRUE, caster, NULL, v, TO_VICT);

    if (!caster->isImmortal()) {
      aff.type = AFFECT_SKILL_ATTEMPT;
      aff.location = APPLY_NONE;
      aff.duration = max(min(level/12, 5), 1) * Pulse::UPDATES_PER_MUDHOUR;
      aff.bitvector = 0;
      aff.modifier = SPELL_SYNOSTODWEOMER;
      caster->affectTo(&aff, -1);
    }

    // hps to add to the vict
    int learnedness = caster->getDiscipline(DISC_DEIKHAN_AEGIS)->getLearnedness();
    // max of 60
    hitp = 10 + (caster->GetMaxLevel() * learnedness / 100);

    if (critSuccess(caster, SPELL_SYNOSTODWEOMER)) {
      CS(SPELL_SYNOSTODWEOMER);
      hitp += 10;
    }

    aff.type = SPELL_SYNOSTODWEOMER;
    aff.level = level;
    aff.duration  = max(min(level/12, 5), 1) * Pulse::UPDATES_PER_MUDHOUR;
    aff.modifier = hitp;
    aff.location = APPLY_HIT;
    aff.bitvector = 0;
    v->affectTo(&aff, -1);
    aff.location = APPLY_CURRENT_HIT;
    v->affectTo(&aff, -1);

    v->updatePos();
    caster->updatePos();
    caster->reconcileHelp(v, 0.11);
    return SPELL_SUCCESS;
  } else {
    caster->sendTo("Nothing seems to happen.\n\r");
    act("Nothing seems to happen.", TRUE, caster, 0, 0, TO_ROOM);
    return SPELL_FAIL;
  }
}

int synostodweomer(TBeing *caster, TBeing *v)
{
  int level, ret;
  int rc = 0;

  // caster->sendTo("The synostodweomer prayer has been disabled due to a crash bug.\n\r");
  // return FALSE;

  if (!bPassClericChecks(caster,SPELL_SYNOSTODWEOMER))
     return FALSE;

  if (!caster->isImmortal() &&
          caster->checkForSkillAttempt(SPELL_SYNOSTODWEOMER)) {
    act("You are not prepared to try to Snyostodweomer again so soon.",
        FALSE, caster, NULL, NULL, TO_CHAR);
    return FALSE;
  }

  if (v->affectedBySpell(SPELL_SYNOSTODWEOMER)) {
    caster->sendTo(COLOR_MOBS, format("%s is already affected by Snyostodweomer.\n\r") % v->getName());
    return FALSE;
  }

  level = caster->getSkillLevel(SPELL_SYNOSTODWEOMER);

  ret = synostodweomer(caster,v,level,caster->getSkillValue(SPELL_SYNOSTODWEOMER));

  if (IS_SET(ret, VICTIM_DEAD))
    ADD_DELETE(rc, DELETE_VICT);
  if (IS_SET(ret, CASTER_DEAD))
    ADD_DELETE(rc, DELETE_THIS);
  return rc;
}

int TBeing::doLayHands(const char *arg)
{
  int amt;
  affectedData aff;
  char name_buf[MAX_INPUT_LENGTH + 1];
  TBeing *vict;

  if (!doesKnowSkill(SKILL_LAY_HANDS)) {
    sendTo("You know nothing about laying on of hands.\n\r");
    return FALSE;
  }
  if (checkForSkillAttempt(SKILL_LAY_HANDS)) {
    sendTo("You are unprepared to attempt to lay hands again.\n\r");
    return FALSE;
  }
  if (affectedBySpell(SKILL_LAY_HANDS)) {
    sendTo("You are unable to lay hands again at this time.\n\r");
    return FALSE;
  }
  one_argument(arg, name_buf, cElements(name_buf));

  if (!(vict = get_char_room_vis(this, name_buf))) {
    sendTo("No one here by that name.\n\r");
    return FALSE;
  }

  // Prevent back-to-back attempts
  aff.type = AFFECT_SKILL_ATTEMPT;
  aff.duration = 1.5 * Pulse::UPDATES_PER_MUDHOUR;
  aff.modifier = SKILL_LAY_HANDS;
  aff.location = APPLY_NONE;
  aff.bitvector = 0;
  affectTo(&aff, -1);

  if (vict == this) {
    sendTo("You attempt to lay hands on yourself.\n\r");
    act("$n tries to lay hands on $mself.", FALSE, this, NULL, NULL, TO_ROOM);
  } else {
    act("You attempt to lay hands on $N.", FALSE, this, NULL, vict, TO_CHAR);
    act("$n attempts to lay hands on you.", FALSE, this, NULL, vict, TO_VICT);
    act("$n attempts to lay hands on $N.", FALSE, this, NULL, vict, TO_NOTVICT);
  }
  amt = ::number(1,100) + (4 * getClassLevel(CLASS_DEIKHAN));

  if (bSuccess(getSkillValue(SKILL_LAY_HANDS), getPerc(), SKILL_LAY_HANDS)) {
    LogDam(this, SKILL_LAY_HANDS, amt);

    if (this != vict) {
      act("A soft yellow light surrounds your hands as you touch $N.",
          FALSE, this, 0, vict, TO_CHAR);
      act("A soft yellow light surrounds $n's hands as $e touches you.",
          FALSE, this, 0, vict, TO_VICT);
      act("A soft yellow light surrounds $n's hands as $e touches $N.",
          FALSE, this, 0, vict, TO_NOTVICT);
    } else {
      act("A soft yellow light surrounds your hands as you touch yourself.",
          FALSE, this, 0, vict, TO_CHAR);
      act("A soft yellow light surrounds $n's hands as $e touches $mself.",
          FALSE, this, 0, vict, TO_ROOM);
    }
    vict->addToHit(amt);
    vict->setHit(std::min(vict->getHit(), (int) vict->hitLimit()));

    // success prevents from working for longer
    aff.type = SKILL_LAY_HANDS;
    aff.duration = 10 * Pulse::UPDATES_PER_MUDHOUR;
    aff.location = APPLY_NONE;
    aff.modifier = 0;
    aff.bitvector = 0;
    affectTo(&aff, -1);
  }
  reconcileHelp(vict, discArray[SKILL_LAY_HANDS]->alignMod);
  return TRUE;
}

int TBeing::doSmite(const char *arg, TBeing *victim)
{
  TBeing *vict;
  char tmp[80];
  int rc;

  if (checkBusy()) {
    return FALSE;
  }
  if (!doesKnowSkill(SKILL_SMITE)) {
    sendTo("You know nothing about smiting.\n\r");
    return FALSE;
  }
  strcpy(tmp, arg);
  if (!(vict = victim)) {
    if (!(vict = get_char_room_vis(this,tmp))) {
      if (!(vict = fight())) {
        sendTo("Smite whom?\n\r");
        return FALSE;
      }
    }
  }

  if (!sameRoom(*vict)) {
    sendTo("That person isn't around.\n\r");
    return FALSE;
  }
  if (noHarmCheck(vict))
    return FALSE;
  rc = smite(this, vict);
  if (rc)
    addSkillLag(SKILL_SMITE, rc);
  if (IS_SET_DELETE(rc, DELETE_VICT)) {
    if (victim)
      return rc;
    delete vict;
    vict = NULL;
    REM_DELETE(rc, DELETE_VICT);
  }
  return rc;
}

int smite(TBeing *ch, TBeing *v)
{
  TThing *weap;

  if (ch->getPosition() < POSITION_STANDING) {
    ch->sendTo("It is undignified to smite someone while not on your own two feet.\n\r");
    return FALSE;
  }
  if (ch == v) {
    ch->sendTo("You contemplate smiting yourself.\n\rYou realize there are better ways to punish yourself.\n\r");
    return FALSE;
  }
  if (ch->checkPeaceful("This room is too peaceful to contemplate violence in.\n\r"))
    return FALSE;

  if (!(weap = ch->heldInPrimHand())) {
    ch->sendTo("Perhaps you'd like to smite with something next time...?\n\r");
    return FALSE;
  }
  return weap->smiteWithMe(ch, v);
}

int TThing::smiteWithMe(TBeing *ch, TBeing *)
{
  ch->sendTo("Perhaps you'd like to smite with a weapon next time...?\n\r");
  return FALSE;
}
<commit_msg>remove comment<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////

#include "handler.h"
#include "being.h"
#include "disease.h"
#include "combat.h"
#include "disc_deikhan.h"

extern void startChargeTask(TBeing *, const char *);

int synostodweomer(TBeing *caster, TBeing *v, int level, short bKnown)
{
  int hitp = 0;
  affectedData aff;

  if (!caster->isImmortal() && caster->checkForSkillAttempt(SPELL_SYNOSTODWEOMER)) {
    act("You are not prepared to try to Snyostodweomer again so soon.",
         FALSE, caster, NULL, NULL, TO_CHAR);
    return FALSE;
  }

  if (v->affectedBySpell(SPELL_SYNOSTODWEOMER)) {
    caster->sendTo(COLOR_MOBS, format("%s is already affected by Snyostodweomer.\n\r") % v->getName());
    return FALSE;
  }

  if (caster->bSuccess(bKnown, caster->getPerc(), SPELL_SYNOSTODWEOMER)) {
    act("Power rushes through your fingers as you bless $N.", FALSE, caster, NULL, v, TO_CHAR);
    act("Power rushes through $n's fingers as $e blesses $N.", TRUE, caster, NULL, v, TO_NOTVICT);
    act("Power surges through $n's fingers as $e blesses you.", TRUE, caster, NULL, v, TO_VICT);

    if (!caster->isImmortal()) {
      aff.type = AFFECT_SKILL_ATTEMPT;
      aff.location = APPLY_NONE;
      aff.duration = max(min(level/12, 5), 1) * Pulse::UPDATES_PER_MUDHOUR;
      aff.bitvector = 0;
      aff.modifier = SPELL_SYNOSTODWEOMER;
      caster->affectTo(&aff, -1);
    }

    // hps to add to the vict
    int learnedness = caster->getDiscipline(DISC_DEIKHAN_AEGIS)->getLearnedness();
    // max of 60
    hitp = 10 + (caster->GetMaxLevel() * learnedness / 100);

    if (critSuccess(caster, SPELL_SYNOSTODWEOMER)) {
      CS(SPELL_SYNOSTODWEOMER);
      hitp += 10;
    }

    aff.type = SPELL_SYNOSTODWEOMER;
    aff.level = level;
    aff.duration  = max(min(level/12, 5), 1) * Pulse::UPDATES_PER_MUDHOUR;
    aff.modifier = hitp;
    aff.location = APPLY_HIT;
    aff.bitvector = 0;
    v->affectTo(&aff, -1);
    aff.location = APPLY_CURRENT_HIT;
    v->affectTo(&aff, -1);

    v->updatePos();
    caster->updatePos();
    caster->reconcileHelp(v, 0.11);
    return SPELL_SUCCESS;
  } else {
    caster->sendTo("Nothing seems to happen.\n\r");
    act("Nothing seems to happen.", TRUE, caster, 0, 0, TO_ROOM);
    return SPELL_FAIL;
  }
}

int synostodweomer(TBeing *caster, TBeing *v)
{
  int level, ret;
  int rc = 0;

  if (!bPassClericChecks(caster,SPELL_SYNOSTODWEOMER))
     return FALSE;

  if (!caster->isImmortal() &&
          caster->checkForSkillAttempt(SPELL_SYNOSTODWEOMER)) {
    act("You are not prepared to try to Snyostodweomer again so soon.",
        FALSE, caster, NULL, NULL, TO_CHAR);
    return FALSE;
  }

  if (v->affectedBySpell(SPELL_SYNOSTODWEOMER)) {
    caster->sendTo(COLOR_MOBS, format("%s is already affected by Snyostodweomer.\n\r") % v->getName());
    return FALSE;
  }

  level = caster->getSkillLevel(SPELL_SYNOSTODWEOMER);

  ret = synostodweomer(caster,v,level,caster->getSkillValue(SPELL_SYNOSTODWEOMER));

  if (IS_SET(ret, VICTIM_DEAD))
    ADD_DELETE(rc, DELETE_VICT);
  if (IS_SET(ret, CASTER_DEAD))
    ADD_DELETE(rc, DELETE_THIS);
  return rc;
}

int TBeing::doLayHands(const char *arg)
{
  int amt;
  affectedData aff;
  char name_buf[MAX_INPUT_LENGTH + 1];
  TBeing *vict;

  if (!doesKnowSkill(SKILL_LAY_HANDS)) {
    sendTo("You know nothing about laying on of hands.\n\r");
    return FALSE;
  }
  if (checkForSkillAttempt(SKILL_LAY_HANDS)) {
    sendTo("You are unprepared to attempt to lay hands again.\n\r");
    return FALSE;
  }
  if (affectedBySpell(SKILL_LAY_HANDS)) {
    sendTo("You are unable to lay hands again at this time.\n\r");
    return FALSE;
  }
  one_argument(arg, name_buf, cElements(name_buf));

  if (!(vict = get_char_room_vis(this, name_buf))) {
    sendTo("No one here by that name.\n\r");
    return FALSE;
  }

  // Prevent back-to-back attempts
  aff.type = AFFECT_SKILL_ATTEMPT;
  aff.duration = 1.5 * Pulse::UPDATES_PER_MUDHOUR;
  aff.modifier = SKILL_LAY_HANDS;
  aff.location = APPLY_NONE;
  aff.bitvector = 0;
  affectTo(&aff, -1);

  if (vict == this) {
    sendTo("You attempt to lay hands on yourself.\n\r");
    act("$n tries to lay hands on $mself.", FALSE, this, NULL, NULL, TO_ROOM);
  } else {
    act("You attempt to lay hands on $N.", FALSE, this, NULL, vict, TO_CHAR);
    act("$n attempts to lay hands on you.", FALSE, this, NULL, vict, TO_VICT);
    act("$n attempts to lay hands on $N.", FALSE, this, NULL, vict, TO_NOTVICT);
  }
  amt = ::number(1,100) + (4 * getClassLevel(CLASS_DEIKHAN));

  if (bSuccess(getSkillValue(SKILL_LAY_HANDS), getPerc(), SKILL_LAY_HANDS)) {
    LogDam(this, SKILL_LAY_HANDS, amt);

    if (this != vict) {
      act("A soft yellow light surrounds your hands as you touch $N.",
          FALSE, this, 0, vict, TO_CHAR);
      act("A soft yellow light surrounds $n's hands as $e touches you.",
          FALSE, this, 0, vict, TO_VICT);
      act("A soft yellow light surrounds $n's hands as $e touches $N.",
          FALSE, this, 0, vict, TO_NOTVICT);
    } else {
      act("A soft yellow light surrounds your hands as you touch yourself.",
          FALSE, this, 0, vict, TO_CHAR);
      act("A soft yellow light surrounds $n's hands as $e touches $mself.",
          FALSE, this, 0, vict, TO_ROOM);
    }
    vict->addToHit(amt);
    vict->setHit(std::min(vict->getHit(), (int) vict->hitLimit()));

    // success prevents from working for longer
    aff.type = SKILL_LAY_HANDS;
    aff.duration = 10 * Pulse::UPDATES_PER_MUDHOUR;
    aff.location = APPLY_NONE;
    aff.modifier = 0;
    aff.bitvector = 0;
    affectTo(&aff, -1);
  }
  reconcileHelp(vict, discArray[SKILL_LAY_HANDS]->alignMod);
  return TRUE;
}

int TBeing::doSmite(const char *arg, TBeing *victim)
{
  TBeing *vict;
  char tmp[80];
  int rc;

  if (checkBusy()) {
    return FALSE;
  }
  if (!doesKnowSkill(SKILL_SMITE)) {
    sendTo("You know nothing about smiting.\n\r");
    return FALSE;
  }
  strcpy(tmp, arg);
  if (!(vict = victim)) {
    if (!(vict = get_char_room_vis(this,tmp))) {
      if (!(vict = fight())) {
        sendTo("Smite whom?\n\r");
        return FALSE;
      }
    }
  }

  if (!sameRoom(*vict)) {
    sendTo("That person isn't around.\n\r");
    return FALSE;
  }
  if (noHarmCheck(vict))
    return FALSE;
  rc = smite(this, vict);
  if (rc)
    addSkillLag(SKILL_SMITE, rc);
  if (IS_SET_DELETE(rc, DELETE_VICT)) {
    if (victim)
      return rc;
    delete vict;
    vict = NULL;
    REM_DELETE(rc, DELETE_VICT);
  }
  return rc;
}

int smite(TBeing *ch, TBeing *v)
{
  TThing *weap;

  if (ch->getPosition() < POSITION_STANDING) {
    ch->sendTo("It is undignified to smite someone while not on your own two feet.\n\r");
    return FALSE;
  }
  if (ch == v) {
    ch->sendTo("You contemplate smiting yourself.\n\rYou realize there are better ways to punish yourself.\n\r");
    return FALSE;
  }
  if (ch->checkPeaceful("This room is too peaceful to contemplate violence in.\n\r"))
    return FALSE;

  if (!(weap = ch->heldInPrimHand())) {
    ch->sendTo("Perhaps you'd like to smite with something next time...?\n\r");
    return FALSE;
  }
  return weap->smiteWithMe(ch, v);
}

int TThing::smiteWithMe(TBeing *ch, TBeing *)
{
  ch->sendTo("Perhaps you'd like to smite with a weapon next time...?\n\r");
  return FALSE;
}
<|endoftext|>


<commit_before>/*
 *  RBCamera.cpp
 *  golf
 *
 *  Created by Robert Rose on 9/13/08.
 *  Copyright 2008 __MyCompanyName__. All rights reserved.
 *
 */

#include "RBCamera.h"
#include "RudeGL.h"

RBCamera::RBCamera()
: m_pos(0,0,0)
, m_lookAt(0,0,1)
, m_up(0,1,0)
, m_halffov((16.0f / 180.0f) * 3.1415926f)
{
}

void RBCamera::SetView(float aspect)
{
	float near = 2.0f;
	float far = 2000.0f;

	float hw = 2.0f * tan(m_halffov) * near;
	float w = hw * 2.0f;

	//printf("fov=%f w=%f aspect=%f\n", halffov, w, aspect);

	RGL.Frustum(0.0f, 0.0f, w * aspect, w, near, far);

	RGL.LookAt(m_pos.x(), m_pos.y(), m_pos.z(), m_lookAt.x(), m_lookAt.y(), m_lookAt.z(), m_up.x(), m_up.y(), m_up.z());
}

<commit_msg>push near plane out to 4, improves some z fighting<commit_after>/*
 *  RBCamera.cpp
 *  golf
 *
 *  Created by Robert Rose on 9/13/08.
 *  Copyright 2008 __MyCompanyName__. All rights reserved.
 *
 */

#include "RBCamera.h"
#include "RudeGL.h"

RBCamera::RBCamera()
: m_pos(0,0,0)
, m_lookAt(0,0,1)
, m_up(0,1,0)
, m_halffov((16.0f / 180.0f) * 3.1415926f)
{
}

void RBCamera::SetView(float aspect)
{
	float near = 4.0f;
	float far = 2000.0f;

	float hw = 2.0f * tan(m_halffov) * near;
	float w = hw * 2.0f;

	//printf("fov=%f w=%f aspect=%f\n", halffov, w, aspect);

	RGL.Frustum(0.0f, 0.0f, w * aspect, w, near, far);

	RGL.LookAt(m_pos.x(), m_pos.y(), m_pos.z(), m_lookAt.x(), m_lookAt.y(), m_lookAt.z(), m_up.x(), m_up.y(), m_up.z());
}

<|endoftext|>


<commit_before>#include "Core.h"
#include <SDL2/SDL.h>
#include <stdio.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#define SUCCESS 0

//app initialization
Core::Core()
{
	if (!appInitialization())
		printf("App Initialization not successful\n");
}

//app destruction
Core::~Core()
{
	appCleanUp();
}

Uint64 Core::getTargetFPS()
{
	return targetFPS;
}

float Core::getTargetDeltaTime()
{
	return targetDeltaTime;
}

SDL_Renderer * Core::getRenderer()
{
	return mainRenderer;
}

SDL_Window * Core::getWindow()
{
	return mainWindow;
}

bool Core::appInitialization()
{
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER);

	if (SDL_GetNumVideoDisplays() <= 0)
	{
		printf("No display monitors attached to current device: %s\n", SDL_GetError());
		return false;
	}

	//obtain target fps based on monitor's refresh rate (hz).
	SDL_DisplayMode displayMode;
	//get the first monitor attached to device display mode settings.
	if (SDL_GetDisplayMode(0, 0, &displayMode) != SUCCESS)
	{
		printf("Unable to get display mode settings : %s\n", SDL_GetError());
		return false;
	}

	targetFPS = displayMode.refresh_rate;
	targetDeltaTime = 1000.0f / targetFPS;

	mainWindow = SDL_CreateWindow("Beat Em Left", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (mainWindow == NULL)
	{
		printf("Main window creation failed : %s\n", SDL_GetError());
		return false;
	}

	mainRenderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (mainRenderer == NULL)
	{
		printf("Main renderer creation failed : %s\n", SDL_GetError());
		return false;
	}

	//load external sdl libraries
	if (IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF | IMG_INIT_WEBP) == 0)
	{
		printf("Failed to initialize SDL IMG Library: %s\n", IMG_GetError());
		return false;
	}

	if (TTF_Init() == -1)
	{
		printf("Failed to initialize SDL TTF Library: %s\n", TTF_GetError());
		return false;
	}

	return true;
}

void Core::appCleanUp()
{
	IMG_Quit();
	if (TTF_WasInit())
		TTF_Quit();
	if (mainRenderer != NULL)
	{
		SDL_DestroyRenderer(mainRenderer);
		mainRenderer = NULL;
	}
	if (mainWindow != NULL)
	{
		SDL_DestroyWindow(mainWindow);
		mainWindow = NULL;
	}
	SDL_Quit();
}

<commit_msg>Maintain max fps to 60 if a monitor's refresh rate exceeds 60hz<commit_after>#include "Core.h"
#include <SDL2/SDL.h>
#include <stdio.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#define SUCCESS 0

//app initialization
Core::Core()
{
	if (!appInitialization())
		printf("App Initialization not successful\n");
}

//app destruction
Core::~Core()
{
	appCleanUp();
}

Uint64 Core::getTargetFPS()
{
	return targetFPS;
}

float Core::getTargetDeltaTime()
{
	return targetDeltaTime;
}

SDL_Renderer * Core::getRenderer()
{
	return mainRenderer;
}

SDL_Window * Core::getWindow()
{
	return mainWindow;
}

bool Core::appInitialization()
{
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER);

	if (SDL_GetNumVideoDisplays() <= 0)
	{
		printf("No display monitors attached to current device: %s\n", SDL_GetError());
		return false;
	}

	//obtain target fps based on monitor's refresh rate (hz).
	SDL_DisplayMode displayMode;
	//get the first monitor attached to device display mode settings.
	if (SDL_GetDisplayMode(0, 0, &displayMode) != SUCCESS)
	{
		printf("Unable to get display mode settings : %s\n", SDL_GetError());
		return false;
	}

	//cap targetFPS to 60
	targetFPS = displayMode.refresh_rate > 60 ? 60 : displayMode.refresh_rate;
	targetDeltaTime = 1000.0f / targetFPS;

	mainWindow = SDL_CreateWindow("Beat Em Left", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (mainWindow == NULL)
	{
		printf("Main window creation failed : %s\n", SDL_GetError());
		return false;
	}

	mainRenderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (mainRenderer == NULL)
	{
		printf("Main renderer creation failed : %s\n", SDL_GetError());
		return false;
	}

	//load external sdl libraries
	if (IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF | IMG_INIT_WEBP) == 0)
	{
		printf("Failed to initialize SDL IMG Library: %s\n", IMG_GetError());
		return false;
	}

	if (TTF_Init() == -1)
	{
		printf("Failed to initialize SDL TTF Library: %s\n", TTF_GetError());
		return false;
	}

	return true;
}

void Core::appCleanUp()
{
	IMG_Quit();
	if (TTF_WasInit())
		TTF_Quit();
	if (mainRenderer != NULL)
	{
		SDL_DestroyRenderer(mainRenderer);
		mainRenderer = NULL;
	}
	if (mainWindow != NULL)
	{
		SDL_DestroyWindow(mainWindow);
		mainWindow = NULL;
	}
	SDL_Quit();
}

<|endoftext|>


<commit_before>#include <iostream>
#include "userlayer.h"
//
#include <iterator>
#include <sstream>
//

using namespace std;

void UserLayer::addPerson()
{
    string gender, comment, birthYear,deathYear, input;
    string name = "";
    char userInput;
    int error_counter = 0;
    bool validity = false;
    // A list of all computers the scientist might have had something to do with
    vector<Computer> list = _service.getComputerList();

    // If user inputs no input an error message occurs
    do
    {
        cout << "Enter name: ";
        cin.ignore();
        getline(cin, name);
        if(name == constants::EMPTY_STRING)
        {
            invalidInput();
        }
    }while(name == constants::EMPTY_STRING);

    do
    {
        input = "";
        if(error_counter > 0)
        {
            cout << endl;
            invalidInput();
            cout << endl;
        }

        printGenderMenu();

        cin >> input;
        if(input == constants::GENDER_MALE)
        {
            gender = "Male";
            break;
        }
        else if(input == constants::GENDER_FEMALE)
        {
            gender = "Female";
            break;
        }
        else if(input == constants::GENDER_OTHER)
        {
            gender = "Other";
            break;
        }
        error_counter++;
    }while(input != constants::GENDER_MALE || input != constants::GENDER_FEMALE || input != constants::GENDER_OTHER);

    // Birth year validation
    cout << "Enter the year of birth: ";
    cin >> birthYear;
    birthYear = birthYearValidation(birthYear);
    cout << "Enter the year this person died, (0 if this person is still alive): ";
    cin >> deathYear;

    // No need to validate if person is still alive.
    if(deathYear != constants::ALIVE)
    {
        deathYear = deathYearValidation(birthYear, deathYear);
    }
    cout << "What is this person's greatest achievement: ";
    cin.ignore();
    getline(cin, comment);
    cout << endl;

    error_counter = 0;
    do
    {
        if(error_counter == 0)
        {
            cout << "Did this person contribute to designing or creating a computer?" << endl;
            cout << "Enter y for yes, n for no." << endl;
        }
        else
        {
            invalidInput();
            cout << "Enter y for yes, n for no." << endl;
        }
        cin >> userInput;

        switch(userInput)
        {
            case 'y':
            case 'Y':
                userInput = 'y';
                validity = true;
                break;
            case 'n':
            case 'N':
                validity = true;
                break;
            default:
                invalidInput();
                break;
        }

    }while(validity != true);

    // Prints the options of computers the user can associate with a scientist
    if(userInput == 'y')
    {
        /*if(list.size() == 0)
        {
            cout << "List of computers is empty." << endl;
        }
        else
        {*/
            for(unsigned int i=0; i<list.size(); i++)
            {
                  cout << i << "  " << list.at(i).getName() << endl;
            }

            vector<int> vectorOfInts;
            validity = false;
            int sizeOfList = list.size();

            do
            {
                cout << "Enter one or more numbers with spaces between them: " << endl;

                //while()

            }while(validity == false);

            //}
        //}
    }

    if(_service.addNewPersonToList(name, gender, birthYear, deathYear, comment))
    {
        cout << "The person has been added successfully." << endl;
        cout << endl;

    }
    else
    {
        cout << "Something went wrong." << endl;
    }

}

void UserLayer::addComputer()
{
    string name, type;
    string designYear, buildYear;
    int intDesignYear, intBuildYear;
    bool created = false;
    bool validity = false;
    char yesOrNo;

    cout << "What is the name of the computer: ";
    do
    {
        cin.ignore();
        getline(cin, name);
        if(name == "")
        {
            invalidInput();
        }
    }while(name == "");

    do
    {
        cout << "When was the computer designed? Enter a year: ";
        cin >> designYear;

        if(!checkNumberValidity(designYear))
        {
            intDesignYear = stoi(designYear);
            validity = true;
            break;
        }
        else
        {
            invalidInput();
        }
    }while(validity != true);

    cout << "What is the computer type: ";
    cin.ignore();
    getline(cin, designYear);

    cout << "What is the computer type: ";
    // TODO DISPLAY A LIST OF POSSIBLE TYPES!!!
    type = "mammathin";
    cout << endl;

    validity = false;

    do
    {
        cout << "Was this computer created?" << endl;
        cout << "Enter y for yes, n for no." << endl;
        cin >> yesOrNo;

        switch(yesOrNo)
        {
            case 'y':
            case 'Y':
                created = true;
                validity = true;
                break;
            case 'n':
            case 'N':
                created = false;
                validity = true;
                break;
            default:
                invalidInput();
                break;
        }

    }while(validity != true);

    if(created == true)
    {

        validity = false;
        do
        {
            cout << "When was the computer created? Enter a year: ";
            cin >> buildYear;

            if(!checkNumberValidity(buildYear))
            {
                intBuildYear = stoi(buildYear);
                validity = true;
            }
            else
            {
                invalidInput();
            }
        }while(validity != true);
    }
    else
    {
        intBuildYear = 0;
    }

    if(!(_service.addNewComputerToList(name, intDesignYear, intBuildYear, type, created)))
    {
        cout << "Computer added successfully." << endl;
        cout << endl;
    }
    else
    {
        cout << "Something went wrong." << endl;
    }
}

void UserLayer::removePersonFromList()
{
    printCompleteList();
    string personToRemove;
    cout << "Enter the number of the person that is to be removed or 0 to go back: ";
    cin >> personToRemove;
    if(personToRemove == constants::GO_BACK)
    {
        return;
    }
    _service.removePersonFromList(personToRemove);
}

void UserLayer::printGenderMenu()
{
    cout << "Select gender: " << endl << endl;
    cout << "| 1 | Male" << endl;
    cout << "| 2 | Female" << endl;
    cout << "| 3 | Other" << endl;
    cout << "Enter your choice here: ";
}

bool UserLayer::checkNumberValidity(string userInput)
{
    // numberTest becomes zero if the user input is invalid.
    int numberTest = 0;
    try
    {
        numberTest = atoi(userInput.c_str());
    }
    catch(int e)
    {
        return false;
    }
    if(numberTest <= 0  || numberTest >= 3000)//If number is beetween 1 - 2999
    {
        return true;
    }

    return false;
}

string UserLayer::birthYearValidation(string birthYear)
{
    bool birthYearValidation = true;
    int error_counter = 0;
    while(birthYearValidation)
    {
        if(error_counter > 0)
        {
            cout << "Enter the year of birth: ";
            cin >> birthYear;
        }
        if(checkNumberValidity(birthYear))
        {
            invalidInput();
        }
        else
        {
            birthYearValidation = false;
            return birthYear;
        }
        error_counter++;
    }
    return "ERROR";
}

string UserLayer::deathYearValidation(string birthYear, string deathYear)
{
    bool deathYearValidation = true;
    int error_counter = 0;
    while(deathYearValidation)
    {
        if(error_counter > 0)
        {
            cout << "Enter the year of death: ";
            cin >> deathYear;
        }
        if(checkNumberValidity(deathYear) || birthYear >= deathYear)
        {
            invalidInput();
        }

        else
        {
            deathYearValidation = false;
            return deathYear;
        }
        error_counter++;
    }
    return "ERROR";
}

void UserLayer::printListOfComputers(vector<Computer> list)
{
    // TODO gera svipað og fyrir neðan   :D
}

void UserLayer::printListOfScientists(vector<CSPerson> list)
{
    int sizeOfList = list.size();
    if(sizeOfList == 0)
    {
        cout << "List is empty." << endl;
        cout << endl;
        return;
    }

    cout <<   "#     NAME                            GENDER     YOB     YOD      AGE" << endl;
    cout <<   "------------------------------------------------------------------------------"<< endl;
    for(int i=0;i<sizeOfList;i++)
    {
        string name = list.at(i).getName();
        string gender = list.at(i).getGender();
        string stringBirthYear = to_string(list.at(i).getBirthYear());
        string stringPassedAway = to_string(list.at(i).getPassedAwayYear());
        int age = list.at(i).getAge();

        // adjustForSpaces adjusts the spaces between the
        // number and name of the scientist according to the size of the value i in the for loop
        adjustForSpaces(i);

        cout << name.append(32 - name.length(), constants::SPACE);
        cout << gender.append(11 - gender.length(), constants::SPACE);
        cout << stringBirthYear.append(8 - stringBirthYear.length(), constants::SPACE);

        if(stringPassedAway != constants::ALIVE)
        {
            cout << stringPassedAway.append(9 - stringPassedAway.length(), constants::SPACE);
            cout << age;
        }
        else
        {
            cout << "Alive";
            cout << "    " << age;

        }
        cout << endl;
    }
    cout <<   "------------------------------------------------------------------------" << endl;
    cout <<   "Year of birth = YOB , Year of death = YOD" << endl << endl;

}

void UserLayer::printListMoreInfo(vector<CSPerson> list)
{
    int sizeOfList = list.size();

    if(sizeOfList == 0)
    {
        cout << "List is empty." << endl;
        return; //á að hætta í forritinu hér?
    }

    cout <<   "#     NAME                            GENDER     YOB     YOD      AGE" << endl;
    cout <<   "------------------------------------------------------------------------------"<< endl;
    for(int i=0;i<sizeOfList;i++)
    {
        string name = list.at(i).getName();
        string gender = list.at(i).getGender();
        string stringBirthYear = to_string(list.at(i).getBirthYear());
        string stringPassedAway = to_string(list.at(i).getPassedAwayYear());
        string info = list.at(i).getComments();
        int age = list.at(i).getAge();

        // adjustForSpaces adjusts the spaces according to the size of the value i in the for loop
        adjustForSpaces(i);

        cout << name.append(32 - name.length(), constants::SPACE);
        cout << gender.append(11 - gender.length(), constants::SPACE);
        cout << stringBirthYear.append(8 - stringBirthYear.length(), constants::SPACE);

        if(stringPassedAway != constants::ALIVE)
        {
            cout << stringPassedAway.append(9 - stringPassedAway.length(), constants::SPACE);
            cout << age;
        }
        else
        {
            cout << "Alive";
            cout << "    " << age;

        }
        cout << endl;
        cout << endl;
        cout << info << endl;
    }
    cout <<   "------------------------------------------------------------------------" << endl << endl;
    cout <<   "Year of birth = YOB , Year of death = YOD" << endl;
}

void UserLayer::printCompleteList()
{
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListAlphabetically()
{
    _service.sortListAlphabetically();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListAlphabeticallyASC()
{
    _service.sortListAlphabeticallyASC();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByGender()
{
    _service.sortListByGender();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByDeathYear()
{
    _service.sortListByDeathYear();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByBirthYear()
{
    _service.sortListByBirthYear();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByBirthYearASC()
{
    _service.sortListByBirthYearASC();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByAge()
{
    _service.sortListByAge();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::searchForAPerson()
{
    string userInput, searchString;

    do
    {
        cout << "| 1 | Search by name" << endl;
        cout << "| 2 | Search by year of year of birth" << endl;
        cout << "| 3 | Search by year of year of death" << endl;
        cout << "| 0 | Go back" << endl;
        cout << "Enter your choice here: ";
        //viljum við hafa Go Back option hérna til að hætta við leit?

        cin >> userInput;
        if(userInput == constants::GO_BACKSTRING)
        {
            return;
        }
        if(userInput == constants::SEARCH_BY_NAME || userInput == constants::SEARCH_BY_YEAR_OF_BIRTH || userInput == constants::SEARCH_BY_YEAR_OF_DEATH)
        {
            break;
        }
        invalidInput();

    }while(userInput != constants::SEARCH_BY_NAME || userInput != constants::SEARCH_BY_YEAR_OF_BIRTH || userInput != constants::SEARCH_BY_YEAR_OF_DEATH);

    cout << "Who are we searching for : ";
    cin.ignore();
    getline(cin, searchString);

    if(userInput == constants::SEARCH_BY_NAME)
    {
        printListMoreInfo(_service.searchByName(searchString));
    }
    else if(userInput == constants::SEARCH_BY_YEAR_OF_BIRTH)
    {
        printListMoreInfo(_service.searchByYearOfBirth(searchString));
    }
    else if(userInput == constants::SEARCH_BY_YEAR_OF_DEATH)
    {
        printListMoreInfo(_service.searchByYearOfDeath(searchString));
    }
}

//Gefur villuskilaboð ef notandi slær inn rangan valkost
void UserLayer::invalidInput()
{
    cout << "Your input was invalid, please try again." << endl;
}

void UserLayer::adjustForSpaces(int i)
{
    i = i+1;
    if(i < 10)
    {
        cout << i << ".    ";
    }
    else if(i>= 10 && i <100)
    {
        cout << i << ".   ";
    }
    else if(i>= 100 && i <1000)
    {
        cout << i << ".  ";
    }
    else if(i>= 1000 && i <10000)
    {
        cout << i << ". ";
    }
}
<commit_msg>still working on addPerson   :/<commit_after>#include <iostream>
#include "userlayer.h"
//
#include <iterator>
#include <sstream>
//

using namespace std;

void UserLayer::addPerson()
{
    string gender, comment, birthYear,deathYear, input;
    string name = "";
    char userInput;
    int error_counter = 0;
    bool validity = false;
    // A list of all computers the scientist might have had something to do with
    vector <Computer> computerList = _service.getComputerList();
    vector <string> userSelection;
    vector <int> realComputerID;

    // If user inputs no input an error message occurs
    do
    {
        cout << "Enter name: ";
        cin.ignore();
        getline(cin, name);
        if(name == constants::EMPTY_STRING)
        {
            invalidInput();
        }
    }while(name == constants::EMPTY_STRING);

    do
    {
        input = "";
        if(error_counter > 0)
        {
            cout << endl;
            invalidInput();
            cout << endl;
        }

        printGenderMenu();

        cin >> input;
        if(input == constants::GENDER_MALE)
        {
            gender = "Male";
            break;
        }
        else if(input == constants::GENDER_FEMALE)
        {
            gender = "Female";
            break;
        }
        else if(input == constants::GENDER_OTHER)
        {
            gender = "Other";
            break;
        }
        error_counter++;
    }while(input != constants::GENDER_MALE || input != constants::GENDER_FEMALE || input != constants::GENDER_OTHER);

    // Birth year validation
    cout << "Enter the year of birth: ";
    cin >> birthYear;
    birthYear = birthYearValidation(birthYear);
    cout << "Enter the year this person died, (0 if this person is still alive): ";
    cin >> deathYear;

    // No need to validate if person is still alive.
    if(deathYear != constants::ALIVE)
    {
        deathYear = deathYearValidation(birthYear, deathYear);
    }
    cout << "What is this person's greatest achievement: ";
    cin.ignore();
    getline(cin, comment);
    cout << endl;

    error_counter = 0;
    do
    {
        if(error_counter == 0)
        {
            cout << "Did this person contribute to designing or creating a computer?" << endl;
            cout << "Enter y for yes, n for no." << endl;
        }
        else
        {
            invalidInput();
            cout << "Enter y for yes, n for no." << endl;
        }
        cin >> userInput;

        switch(userInput)
        {
            case 'y':
            case 'Y':
                userInput = 'y';
                validity = true;
                break;
            case 'n':
            case 'N':
                validity = true;
                break;
            default:
                invalidInput();
                break;
        }

    }while(validity != true);

    // Prints the options of computers the user can associate with a scientist
    if(userInput == 'y')
    {
        if(computerList.size() == 0)
        {
            cout << "List of computers is empty." << endl;
        }
        else
        {
            cout << endl;
            cout << "Choose one or more computers" << endl;
            cout << endl;

            for(unsigned int i=0; i<computerList.size(); i++)
            {
                  cout << i+1 << "  " << computerList.at(i).getName() << endl;
            }

            int number = 1;
            validity = false;
            int sizeOfList = computerList.size();
            error_counter = 0;

            do
            {
                cout << "Enter one or more numbers with spaces between them: " << endl;
                cout << "End with a zero." << endl;
                while(number != 0)
                {
                    try
                    {
                        cin >> number;
                    }
                    catch(int e)
                    {
                        invalidInput();
                    }

                    if(number < 0 || number >= sizeOfList)
                    {
                        invalidInput();
                        error_counter = 1;
                    }
                    else if(number == 0)
                    {
                        validity = true;
                    }
                    else if(!isdigit(number))
                    {

                        string selection = computerList.at(number -1).getName();
                        cout << "PB selection--->" << selection << endl;
                        userSelection.push_back(selection);
                    }

                }
            }while(validity == false);
        }
    }

    /*string computerName;
    int realID;
    for(unsigned i = 0; i< computerList.size();i++)
    {
        computerName = computerList.at(i).getName();
        if(computerName == userSelection.at(i))
        {
            realID = computerList.at(i).getID();
            cout << "REALID   ----------> " << realID << endl;
        }
    }*/

    //for(unsigned int j = 0; j<)

   /* if(_service.addNewPersonToList(name, gender, birthYear, deathYear, comment))
    {
        cout << "The person has been added successfully." << endl;
        cout << endl;
    }
    else
    {
        cout << "Something went wrong." << endl;
    }*/

}

void UserLayer::addComputer()
{
    string name, type;
    string designYear, buildYear;
    int intDesignYear, intBuildYear;
    bool created = false;
    bool validity = false;
    char yesOrNo;

    cout << "What is the name of the computer: ";
    do
    {
        cin.ignore();
        getline(cin, name);
        if(name == "")
        {
            invalidInput();
        }
    }while(name == "");

    do
    {
        cout << "When was the computer designed? Enter a year: ";
        cin >> designYear;

        if(!checkNumberValidity(designYear))
        {
            intDesignYear = stoi(designYear);
            validity = true;
            break;
        }
        else
        {
            invalidInput();
        }
    }while(validity != true);

    cout << "What is the computer type: ";
    cin.ignore();
    getline(cin, designYear);

    cout << "What is the computer type: ";
    // TODO DISPLAY A LIST OF POSSIBLE TYPES!!!
    type = "mammathin";
    cout << endl;

    validity = false;

    do
    {
        cout << "Was this computer created?" << endl;
        cout << "Enter y for yes, n for no." << endl;
        cin >> yesOrNo;

        switch(yesOrNo)
        {
            case 'y':
            case 'Y':
                created = true;
                validity = true;
                break;
            case 'n':
            case 'N':
                created = false;
                validity = true;
                break;
            default:
                invalidInput();
                break;
        }

    }while(validity != true);

    if(created == true)
    {

        validity = false;
        do
        {
            cout << "When was the computer created? Enter a year: ";
            cin >> buildYear;

            if(!checkNumberValidity(buildYear))
            {
                intBuildYear = stoi(buildYear);
                validity = true;
            }
            else
            {
                invalidInput();
            }
        }while(validity != true);
    }
    else
    {
        intBuildYear = 0;
    }

    if(!(_service.addNewComputerToList(name, intDesignYear, intBuildYear, type, created)))
    {
        cout << "Computer added successfully." << endl;
        cout << endl;
    }
    else
    {
        cout << "Something went wrong." << endl;
    }
}

void UserLayer::removePersonFromList()
{
    printCompleteList();
    string personToRemove;
    cout << "Enter the number of the person that is to be removed or 0 to go back: ";
    cin >> personToRemove;
    if(personToRemove == constants::GO_BACK)
    {
        return;
    }
    _service.removePersonFromList(personToRemove);
}

void UserLayer::printGenderMenu()
{
    cout << "Select gender: " << endl << endl;
    cout << "| 1 | Male" << endl;
    cout << "| 2 | Female" << endl;
    cout << "| 3 | Other" << endl;
    cout << "Enter your choice here: ";
}

bool UserLayer::checkNumberValidity(string userInput)
{
    // numberTest becomes zero if the user input is invalid.
    int numberTest = 0;
    try
    {
        numberTest = atoi(userInput.c_str());
    }
    catch(int e)
    {
        return false;
    }
    if(numberTest <= 0  || numberTest >= 3000)//If number is beetween 1 - 2999
    {
        return true;
    }

    return false;
}

string UserLayer::birthYearValidation(string birthYear)
{
    bool birthYearValidation = true;
    int error_counter = 0;
    while(birthYearValidation)
    {
        if(error_counter > 0)
        {
            cout << "Enter the year of birth: ";
            cin >> birthYear;
        }
        if(checkNumberValidity(birthYear))
        {
            invalidInput();
        }
        else
        {
            birthYearValidation = false;
            return birthYear;
        }
        error_counter++;
    }
    return "ERROR";
}

string UserLayer::deathYearValidation(string birthYear, string deathYear)
{
    bool deathYearValidation = true;
    int error_counter = 0;
    while(deathYearValidation)
    {
        if(error_counter > 0)
        {
            cout << "Enter the year of death: ";
            cin >> deathYear;
        }
        if(checkNumberValidity(deathYear) || birthYear >= deathYear)
        {
            invalidInput();
        }

        else
        {
            deathYearValidation = false;
            return deathYear;
        }
        error_counter++;
    }
    return "ERROR";
}

void UserLayer::printListOfComputers(vector<Computer> list)
{
    // TODO gera svipað og fyrir neðan   :D
}

void UserLayer::printListOfScientists(vector<CSPerson> list)
{
    int sizeOfList = list.size();
    if(sizeOfList == 0)
    {
        cout << "List is empty." << endl;
        cout << endl;
        return;
    }

    cout <<   "#     NAME                            GENDER     YOB     YOD      AGE" << endl;
    cout <<   "------------------------------------------------------------------------------"<< endl;
    for(int i=0;i<sizeOfList;i++)
    {
        string name = list.at(i).getName();
        string gender = list.at(i).getGender();
        string stringBirthYear = to_string(list.at(i).getBirthYear());
        string stringPassedAway = to_string(list.at(i).getPassedAwayYear());
        int age = list.at(i).getAge();

        // adjustForSpaces adjusts the spaces between the
        // number and name of the scientist according to the size of the value i in the for loop
        adjustForSpaces(i);

        cout << name.append(32 - name.length(), constants::SPACE);
        cout << gender.append(11 - gender.length(), constants::SPACE);
        cout << stringBirthYear.append(8 - stringBirthYear.length(), constants::SPACE);

        if(stringPassedAway != constants::ALIVE)
        {
            cout << stringPassedAway.append(9 - stringPassedAway.length(), constants::SPACE);
            cout << age;
        }
        else
        {
            cout << "Alive";
            cout << "    " << age;

        }
        cout << endl;
    }
    cout <<   "------------------------------------------------------------------------" << endl;
    cout <<   "Year of birth = YOB , Year of death = YOD" << endl << endl;

}

void UserLayer::printListMoreInfo(vector<CSPerson> list)
{
    int sizeOfList = list.size();

    if(sizeOfList == 0)
    {
        cout << "List is empty." << endl;
        return; //á að hætta í forritinu hér?
    }

    cout <<   "#     NAME                            GENDER     YOB     YOD      AGE" << endl;
    cout <<   "------------------------------------------------------------------------------"<< endl;
    for(int i=0;i<sizeOfList;i++)
    {
        string name = list.at(i).getName();
        string gender = list.at(i).getGender();
        string stringBirthYear = to_string(list.at(i).getBirthYear());
        string stringPassedAway = to_string(list.at(i).getPassedAwayYear());
        string info = list.at(i).getComments();
        int age = list.at(i).getAge();

        // adjustForSpaces adjusts the spaces according to the size of the value i in the for loop
        adjustForSpaces(i);

        cout << name.append(32 - name.length(), constants::SPACE);
        cout << gender.append(11 - gender.length(), constants::SPACE);
        cout << stringBirthYear.append(8 - stringBirthYear.length(), constants::SPACE);

        if(stringPassedAway != constants::ALIVE)
        {
            cout << stringPassedAway.append(9 - stringPassedAway.length(), constants::SPACE);
            cout << age;
        }
        else
        {
            cout << "Alive";
            cout << "    " << age;

        }
        cout << endl;
        cout << endl;
        cout << info << endl;
    }
    cout <<   "------------------------------------------------------------------------" << endl << endl;
    cout <<   "Year of birth = YOB , Year of death = YOD" << endl;
}

void UserLayer::printCompleteList()
{
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListAlphabetically()
{
    _service.sortListAlphabetically();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListAlphabeticallyASC()
{
    _service.sortListAlphabeticallyASC();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByGender()
{
    _service.sortListByGender();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByDeathYear()
{
    _service.sortListByDeathYear();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByBirthYear()
{
    _service.sortListByBirthYear();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByBirthYearASC()
{
    _service.sortListByBirthYearASC();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::sortListByAge()
{
    _service.sortListByAge();
    printListOfScientists(_service.getComputerScientistList());
}

void UserLayer::searchForAPerson()
{
    string userInput, searchString;

    do
    {
        cout << "| 1 | Search by name" << endl;
        cout << "| 2 | Search by year of year of birth" << endl;
        cout << "| 3 | Search by year of year of death" << endl;
        cout << "| 0 | Go back" << endl;
        cout << "Enter your choice here: ";
        //viljum við hafa Go Back option hérna til að hætta við leit?

        cin >> userInput;
        if(userInput == constants::GO_BACKSTRING)
        {
            return;
        }
        if(userInput == constants::SEARCH_BY_NAME || userInput == constants::SEARCH_BY_YEAR_OF_BIRTH || userInput == constants::SEARCH_BY_YEAR_OF_DEATH)
        {
            break;
        }
        invalidInput();

    }while(userInput != constants::SEARCH_BY_NAME || userInput != constants::SEARCH_BY_YEAR_OF_BIRTH || userInput != constants::SEARCH_BY_YEAR_OF_DEATH);

    cout << "Who are we searching for : ";
    cin.ignore();
    getline(cin, searchString);

    if(userInput == constants::SEARCH_BY_NAME)
    {
        printListMoreInfo(_service.searchByName(searchString));
    }
    else if(userInput == constants::SEARCH_BY_YEAR_OF_BIRTH)
    {
        printListMoreInfo(_service.searchByYearOfBirth(searchString));
    }
    else if(userInput == constants::SEARCH_BY_YEAR_OF_DEATH)
    {
        printListMoreInfo(_service.searchByYearOfDeath(searchString));
    }
}

//Gefur villuskilaboð ef notandi slær inn rangan valkost
void UserLayer::invalidInput()
{
    cout << "Your input was invalid, please try again." << endl;
}

void UserLayer::adjustForSpaces(int i)
{
    i = i+1;
    if(i < 10)
    {
        cout << i << ".    ";
    }
    else if(i>= 10 && i <100)
    {
        cout << i << ".   ";
    }
    else if(i>= 100 && i <1000)
    {
        cout << i << ".  ";
    }
    else if(i>= 1000 && i <10000)
    {
        cout << i << ". ";
    }
}
<|endoftext|>