<commit_before>/*
 * Copyright (c) 2015, 2016, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <hwloc.h>

#include "geopm_message.h"
#include "geopm_plugin.h"
#include "GoverningDecider.hpp"
#include "Exception.hpp"

int geopm_plugin_register(int plugin_type, struct geopm_factory_c *factory)
{
    int err = 0;

    try {
        if (plugin_type == GEOPM_PLUGIN_TYPE_DECIDER) {
            geopm::Decider *decider = new geopm::GoverningDecider;
            geopm_factory_register(factory, decider);
        }
    }
    catch(...) {
        err = geopm::exception_handler(std::current_exception());
    }

    return err;
}

namespace geopm
{
    GoverningDecider::GoverningDecider()
        : m_name("governing")
        , m_guard_band(0.05)
        , m_min_num_converged(5)
        , m_last_power_budget(DBL_MIN)
    {

    }

    GoverningDecider::~GoverningDecider()
    {

    }

    bool GoverningDecider::decider_supported(const std::string &description)
    {
        return (description == m_name);
    }

    const std::string& GoverningDecider::name(void) const
    {
        return m_name;
    }

    bool GoverningDecider::update_policy(const struct geopm_policy_message_s &policy_msg, Policy &curr_policy)
    {
        bool result = false;
        if (policy_msg.power_budget != m_last_power_budget) {
            int num_domain = curr_policy.num_domain();
            double split_budget = policy_msg.power_budget / num_domain;
            std::vector<double> domain_budget(num_domain);
            std::fill(domain_budget.begin(), domain_budget.end(), split_budget);
            std::vector<uint64_t> region_id;
            curr_policy.region_id(region_id);
            for (auto it = region_id.begin(); it != region_id.end(); ++it) {
                curr_policy.update(*it, domain_budget);
            }
            m_last_power_budget = policy_msg.power_budget;
            result = true;
        }
        return result;
    }

    bool GoverningDecider::update_policy(Region &curr_region, Policy &curr_policy)
    {
        const int num_domain = curr_policy.num_domain();
        const uint64_t region_id = curr_region.identifier();
        bool is_updated = false;

        std::vector<double> target(num_domain);
        curr_policy.target(region_id, target);
        for (int domain_idx = 0; domain_idx < num_domain; ++domain_idx) {
            double pkg_power = curr_region.derivative(domain_idx, GEOPM_TELEMETRY_TYPE_PKG_ENERGY);
            double dram_power = curr_region.derivative(domain_idx, GEOPM_TELEMETRY_TYPE_DRAM_ENERGY);
            double total_power = pkg_power + dram_power;
            if (total_power > target[domain_idx] * (1 + m_guard_band) ||
                total_power < target[domain_idx] * (1 - m_guard_band)) {
                target[domain_idx] -= dram_power;
                is_updated = true;
            }
        }
        if (is_updated) {
            curr_policy.update(region_id, target);
            auto it = m_num_converged.find(region_id);
            if (it == m_num_converged.end()) {
                it = m_num_converged.insert(m_num_converged.begin(), std::pair<uint64_t, unsigned>(region_id, 0));
            }
            else {
                (*it).second = 0;
            }
            curr_policy.is_converged(region_id, false);

        }
        else {
            auto it = m_num_converged.find(region_id);
            if (it == m_num_converged.end()) {
                it = m_num_converged.insert(m_num_converged.begin(), std::pair<uint64_t, unsigned>(region_id, 1));
            }
            else {
                ++(*it).second;
            }
            if ((*it).second >= m_min_num_converged) {
                curr_policy.is_converged(region_id, true);
            }
        }
        return is_updated;
    }
}
<commit_msg>Improve speed of map insertion in GoverningDecider.<commit_after>/*
 * Copyright (c) 2015, 2016, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <hwloc.h>

#include "geopm_message.h"
#include "geopm_plugin.h"
#include "GoverningDecider.hpp"
#include "Exception.hpp"

int geopm_plugin_register(int plugin_type, struct geopm_factory_c *factory)
{
    int err = 0;

    try {
        if (plugin_type == GEOPM_PLUGIN_TYPE_DECIDER) {
            geopm::Decider *decider = new geopm::GoverningDecider;
            geopm_factory_register(factory, decider);
        }
    }
    catch(...) {
        err = geopm::exception_handler(std::current_exception());
    }

    return err;
}

namespace geopm
{
    GoverningDecider::GoverningDecider()
        : m_name("governing")
        , m_guard_band(0.05)
        , m_min_num_converged(5)
        , m_last_power_budget(DBL_MIN)
    {

    }

    GoverningDecider::~GoverningDecider()
    {

    }

    bool GoverningDecider::decider_supported(const std::string &description)
    {
        return (description == m_name);
    }

    const std::string& GoverningDecider::name(void) const
    {
        return m_name;
    }

    bool GoverningDecider::update_policy(const struct geopm_policy_message_s &policy_msg, Policy &curr_policy)
    {
        bool result = false;
        if (policy_msg.power_budget != m_last_power_budget) {
            int num_domain = curr_policy.num_domain();
            double split_budget = policy_msg.power_budget / num_domain;
            std::vector<double> domain_budget(num_domain);
            std::fill(domain_budget.begin(), domain_budget.end(), split_budget);
            std::vector<uint64_t> region_id;
            curr_policy.region_id(region_id);
            for (auto it = region_id.begin(); it != region_id.end(); ++it) {
                curr_policy.update(*it, domain_budget);
            }
            m_last_power_budget = policy_msg.power_budget;
            result = true;
        }
        return result;
    }

    bool GoverningDecider::update_policy(Region &curr_region, Policy &curr_policy)
    {
        const int num_domain = curr_policy.num_domain();
        const uint64_t region_id = curr_region.identifier();
        bool is_updated = false;

        std::vector<double> target(num_domain);
        curr_policy.target(region_id, target);
        for (int domain_idx = 0; domain_idx < num_domain; ++domain_idx) {
            double pkg_power = curr_region.derivative(domain_idx, GEOPM_TELEMETRY_TYPE_PKG_ENERGY);
            double dram_power = curr_region.derivative(domain_idx, GEOPM_TELEMETRY_TYPE_DRAM_ENERGY);
            double total_power = pkg_power + dram_power;
            if (total_power > target[domain_idx] * (1 + m_guard_band) ||
                total_power < target[domain_idx] * (1 - m_guard_band)) {
                target[domain_idx] -= dram_power;
                is_updated = true;
            }
        }
        if (is_updated) {
            curr_policy.update(region_id, target);
            auto it = m_num_converged.lower_bound(region_id);
            if (it != m_num_converged.end() && (*it).first == region_id) {
                (*it).second = 0;
            }
            else {
                it = m_num_converged.insert(it, std::pair<uint64_t, unsigned>(region_id, 0));
            }
            curr_policy.is_converged(region_id, false);
        }
        else {
            auto it = m_num_converged.lower_bound(region_id);
            if (it != m_num_converged.end() && (*it).first == region_id) {
                ++(*it).second;
            }
            else {
                it = m_num_converged.insert(it, std::pair<uint64_t, unsigned>(region_id, 1));
            }
            if ((*it).second >= m_min_num_converged) {
                curr_policy.is_converged(region_id, true);
            }
        }
        return is_updated;
    }
}
<|endoftext|>


<commit_before>#include "config.h"

Config::Config(const bfs::path& config_path) {
  if(config_path.is_absolute()) {
    path = config_path;
  }
  else if(BuildVars::sysconfdir.is_absolute()) {
    path = BuildVars::sysconfdir / config_path;
  }
  else {
    path = BuildVars::install_prefix / BuildVars::sysconfdir / config_path;
  }

  read_ini(path.string(), vars);
  return;
}

Config::Config(const std::string& config_path) : Config::Config(bfs::path(config_path)) {
}

std::string Config::get(const std::string& key) const {
  return vars.get<std::string>(key);
}
<commit_msg>What did I change?<commit_after>#include "config.h"

Config::Config(const bfs::path& config_path) {
  if(config_path.is_absolute()) {
    path = config_path;
  }
  else if(BuildVars::sysconfdir.is_absolute()) {
    path = BuildVars::sysconfdir / config_path;
  }
  else {
    path = BuildVars::install_prefix / BuildVars::sysconfdir / config_path;
  }

  bpt::read_ini(path.string(), vars);
  return;
}

Config::Config(const std::string& config_path) : Config::Config(bfs::path(config_path)) {
}

std::string Config::get(const std::string& key) const {
  return vars.get<std::string>(key);
}
<|endoftext|>


<commit_before>#include "System.h"
#include "Display.h"

#include "interface.h"
#include "Signals.h"

Console c(USART2, 115200);
Screen mainScreen = Screen();
Screen settingsScreen = Screen();

extern "C" void TIM3_IRQHandler(void) {
	if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) {
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
		int val = ecg.read();
		c.print(val);
		c.print("\n");
	}
}

void MainScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  mainScreen.initialDraw();
}

void SettingsScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  settingsScreen.initialDraw();
}

void systemInit() {
	adcInit();
  	tft.startup();
    composeMainScreen(mainScreen);
    composeSettingsScreen(settingsScreen);
    connectSignalsToScreen(mainScreen);
    enableSignalAcquisition();
}

int main(void)
{
	c.configure();
	c.print("\n");
	c.print("Starting FreePulse...\n");
	systemInit();
	c.print("Welcome!\n");
	while (1) {
		MainScreenInit();
		delay(1000);
		tft.read_touch();
		tft.reset_touch();
		while (currentMode == home) {
			while (digitalRead(tft.interrupt)){
                mainScreen.update();
				delay(100);
			}
			tft.read_touch();
            mainScreen.listenForTouch();
			tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
		}
		if (currentMode == settings) {
			SettingsScreenInit();
			delay(1000);
			tft.read_touch();
			tft.reset_touch();
			while (currentMode == settings) {
				while (digitalRead(tft.interrupt)){}
				tft.read_touch();
                settingsScreen.listenForTouch();
				tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
			}
		}
    }
    return 0;
}
<commit_msg>Add print calls to debug touch screen<commit_after>#include "System.h"
#include "Display.h"

#include "interface.h"
#include "Signals.h"

Console c(USART2, 115200);
Screen mainScreen = Screen();
Screen settingsScreen = Screen();

extern "C" void TIM3_IRQHandler(void) {
	if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) {
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
		int val = ecg.read();
		/* c.print(val); */
		/* c.print("\n"); */
	}
}

void MainScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  mainScreen.initialDraw();
}

void SettingsScreenInit(void){
  tft.fillScreen(RA8875_BLACK);
  tft.showGrid();
  settingsScreen.initialDraw();
}

void systemInit() {
	adcInit();
  	tft.startup();
    composeMainScreen(mainScreen);
    composeSettingsScreen(settingsScreen);
    connectSignalsToScreen(mainScreen);
    enableSignalAcquisition();
}

int main(void)
{
	c.configure();
	c.print("\n");
	c.print("Starting FreePulse...\n");
	systemInit();
	c.print("Welcome!\n");
	while (1) {
		MainScreenInit();
		delay(1000);
		tft.read_touch();
		tft.reset_touch();
		while (currentMode == home) {
			while (digitalRead(tft.interrupt)){
                mainScreen.update();
				delay(1000);
			}
            delay(1000);
			tft.read_touch();
            c.print("x: ");
            c.print(tft.touch_points[0]);
            c.print(", y: ");
            c.print(tft.touch_points[1]);
            c.print("\n");
            mainScreen.listenForTouch();
			tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
		}
		if (currentMode == settings) {
			SettingsScreenInit();
			delay(1000);
			tft.read_touch();
			tft.reset_touch();
			while (currentMode == settings) {
				while (digitalRead(tft.interrupt)){}
				tft.read_touch();
                settingsScreen.listenForTouch();
				tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE);
			}
		}
    }
    return 0;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file function.hpp
 * \brief Activation functions for neural networks
 */

#pragma once

namespace dll {

/*!
 * \brief An activation function
 */
enum class function {
    IDENTITY, ///< Identity activation function
    SIGMOID,  ///< Sigmoid activation function
    TANH,     ///< Hyperbolic tangent
    RELU,     ///< Rectified Linear Unit
    SOFTMAX   ///< Softmax
};

inline std::string to_string(function f) {
    switch (f) {
        case function::IDENTITY:
            return "IDENTITY";
        case function::SIGMOID:
            return "SIGMOID";
        case function::TANH:
            return "TANH";
        case function::RELU:
            return "RELU";
        case function::SOFTMAX:
            return "SOFTMAX";
    }

    cpp_unreachable("Unreachable code");

    return "UNDEFINED";
}

template <function F, typename E, cpp_enable_if(F == function::IDENTITY)>
decltype(auto) f_activate(E&& expr) {
    return etl::identity(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::SIGMOID)>
decltype(auto) f_activate(E&& expr) {
    return etl::sigmoid(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::TANH)>
decltype(auto) f_activate(E&& expr) {
    return etl::tanh(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::RELU)>
decltype(auto) f_activate(E&& expr) {
    return etl::relu(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::SOFTMAX)>
decltype(auto) f_activate(E&& expr) {
    return etl::softmax(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::IDENTITY)>
decltype(auto) f_derivative(E&& expr) {
    return etl::identity_derivative(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::SIGMOID)>
decltype(auto) f_derivative(E&& expr) {
    return etl::sigmoid_derivative(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::TANH)>
decltype(auto) f_derivative(E&& expr) {
    return etl::tanh_derivative(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::RELU)>
decltype(auto) f_derivative(E&& expr) {
    return etl::relu_derivative(std::forward<E>(expr));
}

template <function F, typename E, cpp_enable_if(F == function::SOFTMAX)>
decltype(auto) f_derivative(E&& expr) {
    return etl::softmax_derivative(std::forward<E>(expr));
}

} //end of dll namespace
<commit_msg>Some doc<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file function.hpp
 * \brief Activation functions for neural networks
 */

#pragma once

namespace dll {

/*!
 * \brief An activation function
 */
enum class function {
    IDENTITY, ///< Identity activation function
    SIGMOID,  ///< Sigmoid activation function
    TANH,     ///< Hyperbolic tangent
    RELU,     ///< Rectified Linear Unit
    SOFTMAX   ///< Softmax
};

/*!
 * \brief Returns a string representation of an activation function
 * \param f The function to transform to string
 * \return a string representation of an activation function
 */
inline std::string to_string(function f) {
    switch (f) {
        case function::IDENTITY:
            return "IDENTITY";
        case function::SIGMOID:
            return "SIGMOID";
        case function::TANH:
            return "TANH";
        case function::RELU:
            return "RELU";
        case function::SOFTMAX:
            return "SOFTMAX";
    }

    cpp_unreachable("Unreachable code");

    return "UNDEFINED";
}

/*!
 * \brief Computes the activations from the given input using the specified activation function
 * \param expr The input expression
 * \tparam F The activation function to use
 * \return The result of the activation function
 */
template <function F, typename E, cpp_enable_if(F == function::IDENTITY)>
decltype(auto) f_activate(E&& expr) {
    return etl::identity(std::forward<E>(expr));
}

/*!
 * \copydoc f_activate
 */
template <function F, typename E, cpp_enable_if(F == function::SIGMOID)>
decltype(auto) f_activate(E&& expr) {
    return etl::sigmoid(std::forward<E>(expr));
}

/*!
 * \copydoc f_activate
 */
template <function F, typename E, cpp_enable_if(F == function::TANH)>
decltype(auto) f_activate(E&& expr) {
    return etl::tanh(std::forward<E>(expr));
}

/*!
 * \copydoc f_activate
 */
template <function F, typename E, cpp_enable_if(F == function::RELU)>
decltype(auto) f_activate(E&& expr) {
    return etl::relu(std::forward<E>(expr));
}

/*!
 * \copydoc f_activate
 */
template <function F, typename E, cpp_enable_if(F == function::SOFTMAX)>
decltype(auto) f_activate(E&& expr) {
    return etl::softmax(std::forward<E>(expr));
}

/*!
 * \brief Computes the derivatives from the given output using the specified activation function
 * \param expr The input expression
 * \tparam F The activation function to use
 * \return The derivative of the activation function
 */
template <function F, typename E, cpp_enable_if(F == function::IDENTITY)>
decltype(auto) f_derivative(E&& expr) {
    return etl::identity_derivative(std::forward<E>(expr));
}

/*!
 * \copydoc f_derivative
 */
template <function F, typename E, cpp_enable_if(F == function::SIGMOID)>
decltype(auto) f_derivative(E&& expr) {
    return etl::sigmoid_derivative(std::forward<E>(expr));
}

/*!
 * \copydoc f_derivative
 */
template <function F, typename E, cpp_enable_if(F == function::TANH)>
decltype(auto) f_derivative(E&& expr) {
    return etl::tanh_derivative(std::forward<E>(expr));
}

/*!
 * \copydoc f_derivative
 */
template <function F, typename E, cpp_enable_if(F == function::RELU)>
decltype(auto) f_derivative(E&& expr) {
    return etl::relu_derivative(std::forward<E>(expr));
}

/*!
 * \copydoc f_derivative
 */
template <function F, typename E, cpp_enable_if(F == function::SOFTMAX)>
decltype(auto) f_derivative(E&& expr) {
    return etl::softmax_derivative(std::forward<E>(expr));
}

} //end of dll namespace
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <iostream>
#include "parser.h"
#include "scanner.h"
#include "exp.h"
#include <sstream>

using namespace std;

string& checkcomanndcc123456(string &s) {
int i = 0, index = 0;
string ss = "";

  if (s.empty()) {
    return s;
  }
    for(i=0 ; i<s.size() ; i++){
      if(s[i] != ' '){
          index = i;
          ss = ss + s[i];
      }
    }
    s = ss;
    return s;
  }

int main( int argc , char **argv ) {
  string input;

	do {
		cout << "?-";
		getline(cin, input);
		if (checkcomanndcc123456(input) == "halt."){
      break;
    }
		if (checkcomanndcc123456(input) == ""){
      continue;
    }
		Scanner s(input);
		Parser p(s);
		try{
			p.buildExpression();
			string result = p.getExpressionTree()->getExpressionResult() + '.';
			cout << result << endl;
		} catch (std::string & msg) {
			cout << msg << endl;
		}
	} while(true);
  return 0;
}
<commit_msg>HW8<commit_after>#include <gtest/gtest.h>
#include <iostream>
#include "parser.h"
#include "scanner.h"
#include "exp.h"
#include <sstream>

using namespace std;

string& checkcomanndcc123456(string &s) {
int i = 0, index = 0;
string ss = "";

  if (s.empty()) {
    return s;
  }
    for(i=0 ; i<s.size() ; i++){
      if(s[i] != ' '){
          index = i;
          ss = ss + s[i];
      }
    }
    s = ss;
    return s;
  }

int main( int argc , char **argv ) {
  string input, part, code = "";
  stringstream inputStream;

	do {
    while ( input == "" || input.back() != '.') {
      if(input ==""){
        cout << "?-";
      }else{
        cout << "|  ";
      }
      getline(cin, input);
      inputStream << input;
      while ( inputStream >> part)
        code += part ;

      inputStream.str("");  // must have
      inputStream.clear();  // for reuse inputStream
    }

		// getline(cin, input);
		// if (checkcomanndcc123456(input) == "halt."){
    //   break;
    // }
		// if (checkcomanndcc123456(input) == ""){
    //   continue;
    // }
    // if (checkcomanndcc123456(input) != "."){
    //
    // }
		Scanner s(input);
		Parser p(s);
		try{
			p.buildExpression();
			string result = p.getExpressionTree()->getExpressionResult() + '.';
			cout << result << endl;
		} catch (std::string & msg) {
			cout << msg << endl;
		}
	} while(true);
  return 0;
}
<|endoftext|>


<commit_before>#include <boost/interprocess/sync/named_upgradable_mutex.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <string>
#include <map>
#include <util/izene_serialization.h>
#include <iostream>
#include <glog/logging.h>
#include <signal.h>

using namespace std;
using namespace boost;

#define SF1R_PROCESS_MUTEX_NAME "sf1r_named_mutex_for_process"
#define SF1R_PROCESS_SHARED_MEM_NAME "sf1r_shared_mem_for_process"
#define MAX_SHARED_SIZE 1024*32
#define SLOW_THRESHOLD 10
typedef std::map<std::string, size_t> Sf1rSharedSlowCounterT;

static volatile bool s_stop = false;
static sigset_t maskset;
static void* sig_thread(void *arg)
{
    sigset_t *set = (sigset_t *)arg;
    int s,sig;
    for(;;){
        s = sigwait(set, &sig);
        if(s != 0)
        {
            exit(1);
        }
        switch(sig)
        {
        case SIGINT:
        case SIGHUP:
        case SIGQUIT:
        case SIGABRT:
        case SIGTERM:
            std::cout << "got interrupt signal, begin quit" << std::endl;
            s_stop = true;
            break;
        default:
            break;
        }
    }
}

void init_sig_env()
{
    sigemptyset(&maskset);
    sigaddset(&maskset, SIGINT);
    sigaddset(&maskset, SIGHUP);
    sigaddset(&maskset, SIGQUIT);
    sigaddset(&maskset, SIGABRT);
    sigaddset(&maskset, SIGTERM);

    int ret;
    ret = pthread_sigmask(SIG_BLOCK, &maskset, NULL);
    if(ret != 0)
    {
        perror("failed to block signal");
        exit(1);
    }

    pthread_t thread;
    ret = pthread_create(&thread, NULL, &sig_thread, (void*)&maskset);
    if(ret != 0)
    {
        perror("failed to create signal handle thread");
        exit(1);
    }
}

void decreSlowCounterForAll()
{
    // decrease the slow counter period.
    using namespace boost::interprocess;
    try
    {
        shared_memory_object shm_obj(open_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
        mapped_region region(shm_obj, read_write);
        named_upgradable_mutex mutex(open_only, SF1R_PROCESS_MUTEX_NAME);
        LOG(INFO) << "write lock begin : ";
        scoped_lock<named_upgradable_mutex> lock(mutex);

        LOG(INFO) << "write lock success.";
        Sf1rSharedSlowCounterT cur_shared_data;
        void *addr = region.get_address();
        size_t data_size = (*(int*)addr);
        if (data_size == 0)
            return;
        izenelib::util::izene_deserialization<Sf1rSharedSlowCounterT> izdeserial((char*)addr + sizeof(int), data_size);
        izdeserial.read_image(cur_shared_data);
        Sf1rSharedSlowCounterT::iterator it;
        it = cur_shared_data.begin();
        while(it != cur_shared_data.end())
        {
            if (it->second > 0)
                (it->second)--;
            ++it;
        }
        LOG(INFO) << "current slow counter size :" << cur_shared_data.size();

        char* buf;
        izenelib::util::izene_serialization<Sf1rSharedSlowCounterT> izs(cur_shared_data);
        izs.write_image(buf, data_size);
        if (data_size > MAX_SHARED_SIZE)
        {
            LOG(ERROR) << "shared data is too large to write." << std::endl;
            return;
        }
        (*(int*)addr) = (int)data_size;
        memcpy((char*)addr + sizeof(int), buf, data_size);
        region.flush(0, region.get_size());
    }
    catch(const std::exception& e)
    {
        LOG(ERROR) << "write shared memory failed : " << e.what() << std::endl;
        return;
    }
}

void checking_func()
{
    while(!s_stop)
    {
        struct timespec req, rem;
        req.tv_sec = 20;
        req.tv_nsec = 0;

        while(0 != nanosleep(&req, &rem))
        {
            if (errno == EINTR)
                req = rem;
            else
            {
                perror("sleep error.");
                break;
            }
        }
        LOG(INFO) << "decreasing slow counter period." << std::endl;
        decreSlowCounterForAll();
    }
}

int
main(int argc, char *argv[])
{
    init_sig_env();
    using namespace boost::interprocess;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);

    shared_memory_object shm_obj(create_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
    shm_obj.truncate(MAX_SHARED_SIZE);

    named_upgradable_mutex mutex(create_only, SF1R_PROCESS_MUTEX_NAME);

    LOG(INFO) << "shared memory master started. ";
    boost::thread checking_thread(boost::bind(&checking_func));
    checking_thread.join();
    LOG(INFO) << "shared data master quiting." << std::endl;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);
    return 0;
}
<commit_msg>reset shared memory data if data size is out of range.<commit_after>#include <boost/interprocess/sync/named_upgradable_mutex.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <string>
#include <map>
#include <util/izene_serialization.h>
#include <iostream>
#include <glog/logging.h>
#include <signal.h>

using namespace std;
using namespace boost;

#define SF1R_PROCESS_MUTEX_NAME "sf1r_named_mutex_for_process"
#define SF1R_PROCESS_SHARED_MEM_NAME "sf1r_shared_mem_for_process"
#define MAX_SHARED_SIZE 1024*32
#define SLOW_THRESHOLD 10
typedef std::map<std::string, size_t> Sf1rSharedSlowCounterT;

static volatile bool s_stop = false;
static sigset_t maskset;
static void* sig_thread(void *arg)
{
    sigset_t *set = (sigset_t *)arg;
    int s,sig;
    for(;;){
        s = sigwait(set, &sig);
        if(s != 0)
        {
            exit(1);
        }
        switch(sig)
        {
        case SIGINT:
        case SIGHUP:
        case SIGQUIT:
        case SIGABRT:
        case SIGTERM:
            std::cout << "got interrupt signal, begin quit" << std::endl;
            s_stop = true;
            break;
        default:
            break;
        }
    }
}

void init_sig_env()
{
    sigemptyset(&maskset);
    sigaddset(&maskset, SIGINT);
    sigaddset(&maskset, SIGHUP);
    sigaddset(&maskset, SIGQUIT);
    sigaddset(&maskset, SIGABRT);
    sigaddset(&maskset, SIGTERM);

    int ret;
    ret = pthread_sigmask(SIG_BLOCK, &maskset, NULL);
    if(ret != 0)
    {
        perror("failed to block signal");
        exit(1);
    }

    pthread_t thread;
    ret = pthread_create(&thread, NULL, &sig_thread, (void*)&maskset);
    if(ret != 0)
    {
        perror("failed to create signal handle thread");
        exit(1);
    }
}

void decreSlowCounterForAll()
{
    // decrease the slow counter period.
    using namespace boost::interprocess;
    try
    {
        named_upgradable_mutex mutex(open_only, SF1R_PROCESS_MUTEX_NAME);
        LOG(INFO) << "write lock begin : ";
        scoped_lock<named_upgradable_mutex> lock(mutex);

        LOG(INFO) << "write lock success.";
        shared_memory_object shm_obj(open_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
        mapped_region region(shm_obj, read_write);

        Sf1rSharedSlowCounterT cur_shared_data;
        void *addr = region.get_address();
        size_t data_size = (*(int*)addr);
        if (data_size == 0)
            return;
        if (data_size >= MAX_SHARED_SIZE - sizeof(int))
        {
            LOG(ERROR) << "the data_size is larger than shared memory size :" << data_size;
            (*(int*)addr) = 0;
            std::memset((char*)addr + sizeof(int), 0, region.get_size() - sizeof(int));
            region.flush(0, region.get_size());
            return;
        }
        izenelib::util::izene_deserialization<Sf1rSharedSlowCounterT> izdeserial((const char*)addr + sizeof(int), data_size);
        izdeserial.read_image(cur_shared_data);
        Sf1rSharedSlowCounterT::iterator it;
        it = cur_shared_data.begin();
        while(it != cur_shared_data.end())
        {
            if (it->second > 0)
                (it->second)--;
            ++it;
        }
        LOG(INFO) << "current slow counter size :" << cur_shared_data.size();

        char* buf;
        izenelib::util::izene_serialization<Sf1rSharedSlowCounterT> izs(cur_shared_data);
        izs.write_image(buf, data_size);
        if (data_size >= MAX_SHARED_SIZE - sizeof(int))
        {
            LOG(ERROR) << "shared data is too large to write." << std::endl;
            return;
        }
        (*(int*)addr) = (int)data_size;
        memcpy((char*)addr + sizeof(int), buf, data_size);
        region.flush(0, region.get_size());
    }
    catch(const std::exception& e)
    {
        LOG(ERROR) << "write shared memory failed : " << e.what() << std::endl;
        return;
    }
}

void checking_func()
{
    while(!s_stop)
    {
        struct timespec req, rem;
        req.tv_sec = 20;
        req.tv_nsec = 0;

        while(0 != nanosleep(&req, &rem))
        {
            if (errno == EINTR)
                req = rem;
            else
            {
                perror("sleep error.");
                break;
            }
        }
        LOG(INFO) << "decreasing slow counter period." << std::endl;
        decreSlowCounterForAll();
    }
}

int
main(int argc, char *argv[])
{
    init_sig_env();
    using namespace boost::interprocess;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);

    shared_memory_object shm_obj(create_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
    shm_obj.truncate(MAX_SHARED_SIZE);

    {
        mapped_region region(shm_obj, read_write);
        LOG(INFO) << "init shared memory size : " << region.get_size();
    }
    named_upgradable_mutex mutex(create_only, SF1R_PROCESS_MUTEX_NAME);

    LOG(INFO) << "shared memory master started. ";
    boost::thread checking_thread(boost::bind(&checking_func));
    checking_thread.join();
    LOG(INFO) << "shared data master quiting." << std::endl;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);
    return 0;
}
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////
// This file is part of EasyRPG.
//
// EasyRPG is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// EasyRPG is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
/////////////////////////////////////////////////////////////////////////////

#include <algorithm>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

#include "ldb_reader.h"
#include "lmt_reader.h"
#include "lmu_reader.h"
#include "lsd_reader.h"

enum FileTypes
{
	FileType_LCF_MapUnit,
	FileType_LCF_SaveData,
	FileType_LCF_Database,
	FileType_LCF_MapTree,
	FileType_XML_MapUnit,
	FileType_XML_SaveData,
	FileType_XML_Database,
	FileType_XML_MapTree,
	FileType_Invalid
};

std::string GetFilename(const std::string& str);
FileTypes GetFiletype(const std::string& in_file, std::string& out_extension);
void PrintReaderError(const std::string data);
int ReaderWriteToFile(const std::string& in, const std::string& out, FileTypes in_type);

int main(int argc, char** argv)
{
	if (argc <= 1)
	{
		std::cerr << "Lcf2Xml - Converts RPG Maker 2k/2k3 Files to XML and vice versa" << std::endl;
		std::cerr << "Usage: lcf2xml [FILE] [OUTFILE]" << std::endl;
		//std::cerr << "If OUTFILE is missing the resulting file is named FILE with the extension replaced" << std::endl;
		return 1;
	}

	std::string infile;
	std::string outfile;

	infile = argv[1];

	FileTypes type;
	std::string extension;

	if (argc >= 3)
	{
		// OUTFILE
		outfile = argv[2];
		type = GetFiletype(infile, extension);
	}
	else
	{
		// No OUTFILE, add extension based on detected filetype
		outfile = GetFilename(infile);
		type = GetFiletype(infile, extension);
		outfile += extension;
	}

	return ReaderWriteToFile(infile, outfile, type);
}

/// Returns the filename (without extension)
std::string GetFilename(const std::string& str)
{
	std::string s = str;
#ifdef _WIN32
	std::replace(s.begin(), s.end(), '\\', '/');
#endif
	// Extension
	size_t found = s.find_last_of(".");
	if (found != std::string::npos)
	{
		s = s.substr(0, found);
	}

	// Filename
	found = s.find_last_of("/");
	if (found == std::string::npos)
	{
		return s;
	}

	s = s.substr(found + 1);
	return s;
}

/// Uses heuristics to detect the file type
FileTypes GetFiletype(const std::string& in_file, std::string& out_extension)
{
	std::ifstream in(in_file);

	char buf[128];
	memset(buf, '\0', 128);

	in.seekg(1, std::ios::beg);
	in.read(buf, 10);
	std::string input(buf);

	out_extension = ".xml";
	if (input == "LcfDataBas") {
		return FileType_LCF_Database;
	} else if (input == "LcfMapTree") {
		return FileType_LCF_MapTree;
	} else if (input == "LcfSaveDat") {
		return FileType_LCF_SaveData;
	} else if (input == "LcfMapUnit") {
		return FileType_LCF_MapUnit;
	} else if (input == "?xml versi") {
		in.read(buf, 128);
		std::string in(buf);

		size_t pos = in.find('<');
		if (pos != std::string::npos)
		{
			in = in.substr(pos + 1, 3);
			if (in == "LDB") {
				out_extension = ".ldb";
				return FileType_XML_Database;
			} else if (in == "LMT") {
				out_extension = ".lmt";
				return FileType_XML_MapTree;
			} else if (in == "LSD") {
				out_extension = ".lsd";
				return FileType_XML_SaveData;
			} else if (in == "LMU") {
				out_extension = ".lmu";
				return FileType_XML_MapUnit;
			}
		}
	}

	out_extension = "";
	return FileType_Invalid;
}

/// Utility func for errors
void PrintReaderError(const std::string data)
{
	std::cerr << data << " error: " << LcfReader::GetError() << std::endl;
}

#define LCFXML_ERROR(cond, text) \
	if (cond) {\
		PrintReaderError(text);\
		return 2;\
	}

/// Takes data from in and writes converted data into out using libreaders
int ReaderWriteToFile(const std::string& in, const std::string& out, FileTypes in_type)
{
	switch (in_type)
	{
		case FileType_LCF_MapUnit:
		{
			std::auto_ptr<RPG::Map> file = LMU_Reader::Load(in);
			LCFXML_ERROR(file.get() == NULL, "LMU load");
			LCFXML_ERROR(!LMU_Reader::SaveXml(out, *file), "LMU XML save");
			break;
		}
		case FileType_LCF_SaveData:
		{
			std::auto_ptr<RPG::Save> file = LSD_Reader::Load(in);
			LCFXML_ERROR(file.get() == NULL, "LSD load");
			LCFXML_ERROR(!LSD_Reader::SaveXml(out, *file), "LSD XML save");
			break;
		}
		case FileType_LCF_Database:
		{
			LCFXML_ERROR(!LDB_Reader::Load(in), "LDB load");
			LCFXML_ERROR(!LDB_Reader::SaveXml(out), "LDB XML save");
			break;
		}
		case FileType_LCF_MapTree:
		{
			LCFXML_ERROR(!LMT_Reader::Load(in), "LMT load");
			LCFXML_ERROR(!LMT_Reader::SaveXml(out), "LMT XML save");
			break;
		}
		case FileType_XML_MapUnit:
		{
			std::auto_ptr<RPG::Map> file = LMU_Reader::LoadXml(in);
			LCFXML_ERROR(file.get() == NULL, "LMU XML load");
			LCFXML_ERROR(!LMU_Reader::Save(out, *file), "LMU save");
			break;
		}
		case FileType_XML_SaveData:
		{
			std::auto_ptr<RPG::Save> file = LSD_Reader::LoadXml(in);
			LCFXML_ERROR(file.get() == NULL, "LSD XML load");
			LCFXML_ERROR(!LSD_Reader::Save(out, *file), "LSD save");
			break;
		}
		case FileType_XML_Database:
		{
			LCFXML_ERROR(!LDB_Reader::LoadXml(in), "LDB XML load");
			LCFXML_ERROR(!LDB_Reader::Save(out), "LDB save");
			break;
		}
		case FileType_XML_MapTree:
		{
			LCFXML_ERROR(!LMT_Reader::LoadXml(in), "LMT XML load");
			LCFXML_ERROR(!LMT_Reader::Save(out), "LMT save");
			break;
		}
		case FileType_Invalid:
		{
			std::cerr << in << " unsupported" << std::endl;
			return 2;
		}
	}

	return 0;
}
<commit_msg>Fix compile error in mingw-w64-g++ 4.6<commit_after>/////////////////////////////////////////////////////////////////////////////
// This file is part of EasyRPG.
//
// EasyRPG is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// EasyRPG is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
/////////////////////////////////////////////////////////////////////////////

#include <algorithm>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

#include "ldb_reader.h"
#include "lmt_reader.h"
#include "lmu_reader.h"
#include "lsd_reader.h"

enum FileTypes
{
	FileType_LCF_MapUnit,
	FileType_LCF_SaveData,
	FileType_LCF_Database,
	FileType_LCF_MapTree,
	FileType_XML_MapUnit,
	FileType_XML_SaveData,
	FileType_XML_Database,
	FileType_XML_MapTree,
	FileType_Invalid
};

std::string GetFilename(const std::string& str);
FileTypes GetFiletype(const std::string& in_file, std::string& out_extension);
void PrintReaderError(const std::string data);
int ReaderWriteToFile(const std::string& in, const std::string& out, FileTypes in_type);

int main(int argc, char** argv)
{
	if (argc <= 1)
	{
		std::cerr << "Lcf2Xml - Converts RPG Maker 2k/2k3 Files to XML and vice versa" << std::endl;
		std::cerr << "Usage: lcf2xml [FILE] [OUTFILE]" << std::endl;
		//std::cerr << "If OUTFILE is missing the resulting file is named FILE with the extension replaced" << std::endl;
		return 1;
	}

	std::string infile;
	std::string outfile;

	infile = argv[1];

	FileTypes type;
	std::string extension;

	if (argc >= 3)
	{
		// OUTFILE
		outfile = argv[2];
		type = GetFiletype(infile, extension);
	}
	else
	{
		// No OUTFILE, add extension based on detected filetype
		outfile = GetFilename(infile);
		type = GetFiletype(infile, extension);
		outfile += extension;
	}

	return ReaderWriteToFile(infile, outfile, type);
}

/// Returns the filename (without extension)
std::string GetFilename(const std::string& str)
{
	std::string s = str;
#ifdef _WIN32
	std::replace(s.begin(), s.end(), '\\', '/');
#endif
	// Extension
	size_t found = s.find_last_of(".");
	if (found != std::string::npos)
	{
		s = s.substr(0, found);
	}

	// Filename
	found = s.find_last_of("/");
	if (found == std::string::npos)
	{
		return s;
	}

	s = s.substr(found + 1);
	return s;
}

/// Uses heuristics to detect the file type
FileTypes GetFiletype(const std::string& in_file, std::string& out_extension)
{
	std::ifstream in(in_file.c_str());

	char buf[128];
	memset(buf, '\0', 128);

	in.seekg(1, std::ios::beg);
	in.read(buf, 10);
	std::string input(buf);

	out_extension = ".xml";
	if (input == "LcfDataBas") {
		return FileType_LCF_Database;
	} else if (input == "LcfMapTree") {
		return FileType_LCF_MapTree;
	} else if (input == "LcfSaveDat") {
		return FileType_LCF_SaveData;
	} else if (input == "LcfMapUnit") {
		return FileType_LCF_MapUnit;
	} else if (input == "?xml versi") {
		in.read(buf, 128);
		std::string in(buf);

		size_t pos = in.find('<');
		if (pos != std::string::npos)
		{
			in = in.substr(pos + 1, 3);
			if (in == "LDB") {
				out_extension = ".ldb";
				return FileType_XML_Database;
			} else if (in == "LMT") {
				out_extension = ".lmt";
				return FileType_XML_MapTree;
			} else if (in == "LSD") {
				out_extension = ".lsd";
				return FileType_XML_SaveData;
			} else if (in == "LMU") {
				out_extension = ".lmu";
				return FileType_XML_MapUnit;
			}
		}
	}

	out_extension = "";
	return FileType_Invalid;
}

/// Utility func for errors
void PrintReaderError(const std::string data)
{
	std::cerr << data << " error: " << LcfReader::GetError() << std::endl;
}

#define LCFXML_ERROR(cond, text) \
	if (cond) {\
		PrintReaderError(text);\
		return 2;\
	}

/// Takes data from in and writes converted data into out using libreaders
int ReaderWriteToFile(const std::string& in, const std::string& out, FileTypes in_type)
{
	switch (in_type)
	{
		case FileType_LCF_MapUnit:
		{
			std::auto_ptr<RPG::Map> file = LMU_Reader::Load(in);
			LCFXML_ERROR(file.get() == NULL, "LMU load");
			LCFXML_ERROR(!LMU_Reader::SaveXml(out, *file), "LMU XML save");
			break;
		}
		case FileType_LCF_SaveData:
		{
			std::auto_ptr<RPG::Save> file = LSD_Reader::Load(in);
			LCFXML_ERROR(file.get() == NULL, "LSD load");
			LCFXML_ERROR(!LSD_Reader::SaveXml(out, *file), "LSD XML save");
			break;
		}
		case FileType_LCF_Database:
		{
			LCFXML_ERROR(!LDB_Reader::Load(in), "LDB load");
			LCFXML_ERROR(!LDB_Reader::SaveXml(out), "LDB XML save");
			break;
		}
		case FileType_LCF_MapTree:
		{
			LCFXML_ERROR(!LMT_Reader::Load(in), "LMT load");
			LCFXML_ERROR(!LMT_Reader::SaveXml(out), "LMT XML save");
			break;
		}
		case FileType_XML_MapUnit:
		{
			std::auto_ptr<RPG::Map> file = LMU_Reader::LoadXml(in);
			LCFXML_ERROR(file.get() == NULL, "LMU XML load");
			LCFXML_ERROR(!LMU_Reader::Save(out, *file), "LMU save");
			break;
		}
		case FileType_XML_SaveData:
		{
			std::auto_ptr<RPG::Save> file = LSD_Reader::LoadXml(in);
			LCFXML_ERROR(file.get() == NULL, "LSD XML load");
			LCFXML_ERROR(!LSD_Reader::Save(out, *file), "LSD save");
			break;
		}
		case FileType_XML_Database:
		{
			LCFXML_ERROR(!LDB_Reader::LoadXml(in), "LDB XML load");
			LCFXML_ERROR(!LDB_Reader::Save(out), "LDB save");
			break;
		}
		case FileType_XML_MapTree:
		{
			LCFXML_ERROR(!LMT_Reader::LoadXml(in), "LMT XML load");
			LCFXML_ERROR(!LMT_Reader::Save(out), "LMT save");
			break;
		}
		case FileType_Invalid:
		{
			std::cerr << in << " unsupported" << std::endl;
			return 2;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <stdlib.h>

using namespace std;

//adds space before and after all instances of op in text to text
void addSpaces(string &text, const string &op) {
	size_t length = op.length();
	size_t pos;
	pos = text.find(op, 0);	//some inspiration from stackoverflow.com/questions/4034750

	while(pos != string::npos) {
		//pos+1 to go to thing pos was pointing at, but want to move AFTER that
		text.insert(pos, " ");	//one space before
		text.insert(pos+1+length, " "); //and one space after
		pos = text.find(op, pos+1+length);
	}
}

//adds space before and after all instances of op in text to text
void addNumbers(string &text, const string &op) {
	size_t length = op.length();
	size_t pos;
	pos = text.find(op, 0);	//some inspiration from stackoverflow.com/questions/4034750

	while(pos != string::npos) {
		//pos+1 to go to thing pos was pointing at, but want to move AFTER that
		text.insert(pos, " ");	//one space before
		text.insert(pos+1+length, " "); //and one space after
		pos = text.find(op, pos+1+length);
	}
}

/*
//takes in string and deliminator and tokenizes that string into vector<char*>
vector<char*> parser(string text, const char *delim) {
	char *line = new char[text.length()+1];	//strtok requires char*
						//got this from cplusplus.com/reference/string/string/c_str
	strcpy(line, text.c_str());

	char *token = strtok(line, delim);	//can be any character
	vector<char*> words;

	while(token != NULL) {
		words.push_back(token);
		token = strtok(NULL, delim);
	}

	delete[] token;

	return words;
}
*/

bool redirectionstuff(vector<char*> &onecommand) {
	for(unsigned int i = 0; i < onecommand.size(); i++) {
		if(strcmp
		//let's do input < first
		int save = dup(0);
		if(-1 == close(0)) {
			perror("close");
		}
		int fd = open(blah, O_RDONLY);
		if(-1 == fd) {
			perror("error with open");
			exit(1);
		}
		//run some execvp shti

		close(0);		//closing what i oepened
		dup2(0, save);		//have to restore stdin to 0
		close(save);		//gotta close the backup

bool execvpstuff(vector<char*> &onecommand) {
	bool returnval = true;
	int pipearr[2];
	char **command = &onecommand[0]; //stackoverflow.com/questions/5846934/
		//EXECVP STUFF HERE
	//http://github.com/mikeizbicki/ucr-cs100/blob/2015spring/textbook/assignment-help/syscalls/exec.md
	if(onecommand.size() < 2) {
		returnval = true;
	} else {

		if(strcmp(command[0], "exit") == 0) {
			onecommand.clear();
			exit(0);
		} else {
			pipe(pipearr);		//some pipe bs.
			int pid = fork();
			if(pid == -1) {
				perror("Error with fork");
				exit(1);
			} else if(pid == 0) {	//child process
				close(pipearr[0]);
				if(-1 == execvp(command[0], command)) {
					returnval = false;
					write(pipearr[1], &returnval, sizeof(returnval));
					close(pipearr[1]);
					perror("Error wit execvp");
				}
				onecommand.clear();		//clear vector so it can hold next command.
				exit(0);
			}
			if(-1 == wait(0)) {
				perror("error with wait");
			}
			close(pipearr[1]);
			read(pipearr[0], &returnval, sizeof(returnval));
			close(pipearr[0]);
			//parent here
			onecommand.clear();
			return returnval;
		}
	}
	return returnval;
}

void terminal() {
	//~~~~~~~~~~~~print username, hostnam, and prompte~~~~~~~~
	char host[32];//add to readme: 32 cuz max is 64 and i dont want long printing
	int pid;

	string input;

	pid = gethostname(host, 32);
	if(pid == -1) {				//error
		perror("gethostname");
	} else {
		 cout << getlogin() << "§" << host << ':' << ' ';
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//shit starts here
	//we will begin tonight's program by taking in
	getline(cin, input);

	//add spaces before and after all operators in input
	addSpaces(input, ";");
	addSpaces(input, "&&");
	addSpaces(input, "||");
	addSpaces(input, "#");

	//vector<char*> words;
	//words = parser(arg, " "); //take out all spaces from arg

//~~~~~~~~~~~~~~~~~~~~~~~~~~PARSER~~~~~~~~~~~~~~~~~~~~~~~~~~
	char *line = new char[input.length()+1];	//strtok requires char*
						//got this from cplusplus.com/reference/string/string/c_str
	strcpy(line, input.c_str());

	char *token = strtok(line, " \t\n");	//can be any character
	vector<char*> words;

	while(token != NULL) {
		words.push_back(token);
		token = strtok(NULL, " \t\n");
	}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`

	char cmenot[] = ";";
	words.push_back(cmenot);

	vector<char*> onecommand;
	onecommand.clear();

	bool success = true;	//status of previous command. used for operators

	bool issemi;
	bool isand;
	bool isor;
	bool ispound;
	bool isoperator;

	size_t i = 0;

	while(i < words.size()) {
		issemi = strcmp(words.at(i), ";") == 0;
		isand = strcmp(words.at(i), "&&") == 0;
		isor = strcmp(words.at(i), "||") == 0;
		ispound = strcmp(words.at(i), "#") == 0;
		isoperator = issemi || isand || isor || ispound;

		if(!isoperator) {
			onecommand.push_back(words.at(i));
		//	for(int j = 0; j < onecommand.size(); j++) cout << "oc " << j << onecommand.at(j) << endl;
		} else {
			onecommand.push_back(NULL);	//needs to end in null for exec
			success = execvpstuff(onecommand);
			if(issemi) {
				onecommand.clear();
				//moveon
			} else if(isand && success) {
				//moveon
				onecommand.clear();
			} else if(isor && !success) {
				onecommand.clear();
				//moveon
			} else {
				break;
			}
		}
		i++;
	}

	delete[] line;

	//TESTING DELETE THIS LATER
//	for(int i = 0; i < words.size(); i++) cout << "words" << i << words.at(i) << endl;

}

int main(int argc, char* argv[]) {

	cout << "¤¤¡¡¡¡¡Bienvenidos a la terminál rshell de Chirag!!!!!¤¤" << endl;

	while(1)
	terminal();

	return 0;
}
<commit_msg>input< seems to work<commit_after>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

//adds space before and after all instances of op in text to text
void addSpaces(string &text, const string &op) {
	size_t length = op.length();
	size_t pos;
	pos = text.find(op, 0);	//some inspiration from stackoverflow.com/questions/4034750

	while(pos != string::npos) {
		//pos+1 to go to thing pos was pointing at, but want to move AFTER that
		text.insert(pos, " ");	//one space before
		text.insert(pos+1+length, " "); //and one space after
		pos = text.find(op, pos+1+length);
	}
}

//adds space before and after all instances of op in text to text
void addNumbers(string &text, const string &op) {
	size_t length = op.length();
	size_t pos;
	pos = text.find(op, 0);	//some inspiration from stackoverflow.com/questions/4034750

	while(pos != string::npos) {
		//pos+1 to go to thing pos was pointing at, but want to move AFTER that
		text.insert(pos, " ");	//one space before
		text.insert(pos+1+length, " "); //and one space after
		pos = text.find(op, pos+1+length);
	}
}

/*
//takes in string and deliminator and tokenizes that string into vector<char*>
vector<char*> parser(string text, const char *delim) {
	char *line = new char[text.length()+1];	//strtok requires char*
						//got this from cplusplus.com/reference/string/string/c_str
	strcpy(line, text.c_str());

	char *token = strtok(line, delim);	//can be any character
	vector<char*> words;

	while(token != NULL) {
		words.push_back(token);
		token = strtok(NULL, delim);
	}

	delete[] token;

	return words;
}
*/

bool redirectors(vector<char*> &onecommand) {
	size_t i = 0;
	//find the first redirector
	//putting everything before it into char* vector along the way
	int redirector = -1;
	vector<char*> newcommand;
	for(i = 0; (i < onecommand.size() - 1) && (redirector < 0); i++) {
		if(strcmp(onecommand.at(i), "<") == 0) {
			redirector = 0;		//input
		} else if(strcmp(onecommand.at(i), ">") == 0) {
			redirector = 1;		//single output
		} else if(strcmp(onecommand.at(i), ">>") == 0) {
			redirector = 2;		//double output
		} else if(strcmp(onecommand.at(i), "|") == 0) {
			redirector = 3;		//pipe
		} else {
			newcommand.push_back(onecommand.at(i));
			cout << "theo" << onecommand.at(i) << endl;
		}
	}
	newcommand.push_back(NULL);

	//it's an input
	if(redirector == 0) {
		if(i < onecommand.size()) {		//check if file is in the vector
			//close stdin
			int backup = dup(0);
			if(-1 == backup) {
				perror("error with dup");
			}
			if(-1 == close(0)) {
				perror("error with close");
			}

			int fd = open(onecommand.at(i), O_RDONLY);	//open to lowest file desc
			if(-1 == fd) {
				perror("error with open");
				exit(1);
			}

			int forkid = fork();
			if(-1 == forkid) {
				perror("error with fork");
				exit(1);
			} else if(0 == forkid) {
				//the child
				if(-1 == execvp(newcommand.at(0), &newcommand[0])) {
					perror("erro with execvp");
				}
				cout << "before exit execvp" << endl;
				exit(0);
			}
			cout << "in parent" << endl;
			if(-1 == wait(0)) {
				perror("error with wait");
			}
			//parent here i guess
			if(-1 == dup2(backup, 0)) {
				perror("error with dup2");
			}
			if(-1 == close(backup)) {
				perror("error with close backup");
			}
		}
	}

	return true;
}

/*
vector<char*> redirectionstuff(vector<char*> &onecommand) {
	vector<char*> newcommand;
	for(unsigned int i = 0; i < onecommand.size(); i++) {
		if(strcmp(onecommand.at(i), "<") == 0) {
			if(i > 0 && i+1 > onecommand.size()) {
				//let's do input < first
				if(-1 == close(0)) {
					perror("close");
				}
				int fd = open(blah, O_RDONLY);	//opened to 0 since we closed 0
				if(-1 == fd) {
					perror("error with open");
					exit(1);
				}
				//run some execvp shti
				newcommand.push_back(onecommand.at(i-1));
				while(i < )

				//close(0);		//closing what i oepened
			} else {
				cout << "Invalid use of redirection" << endl;
				exit(1);
			}
		}
	}
	return newcommand;
}
*/

bool execvpstuff(vector<char*> &onecommand) {
	bool returnval = true;
	int pipearr[2];

	char** command = &onecommand[0]; //stackoverflow.com/questions/5846934/

		//EXECVP STUFF HERE
	//http://github.com/mikeizbicki/ucr-cs100/blob/2015spring/textbook/assignment-help/syscalls/exec.md
	if(onecommand.size() < 2) {
		returnval = true;
	} else {

		if(strcmp(command[0], "exit") == 0) {
			onecommand.clear();
			exit(0);
		} else {
			pipe(pipearr);		//some pipe bs.
			int pid = fork();
			if(pid == -1) {
				perror("Error with fork");
				exit(1);
			} else if(pid == 0) {	//child process
				close(pipearr[0]);
				if(-1 == execvp(command[0], command)) {
					returnval = false;
					write(pipearr[1], &returnval, sizeof(returnval));
					close(pipearr[1]);
					perror("Error wit execvp");
				}
				onecommand.clear();		//clear vector so it can hold next command.
				exit(0);
			}
			if(-1 == wait(0)) {
				perror("error with wait");
			}
			close(pipearr[1]);
			read(pipearr[0], &returnval, sizeof(returnval));
			close(pipearr[0]);
			//parent here
			onecommand.clear();
			return returnval;
		}
	}
	return returnval;
}

void terminal() {
	//~~~~~~~~~~~~print username, hostnam, and prompte~~~~~~~~
	char host[32];//add to readme: 32 cuz max is 64 and i dont want long printing
	int pid;

	string input;

	pid = gethostname(host, 32);
	if(pid == -1) {				//error
		perror("gethostname");
	} else {
		 cout << getlogin() << "§" << host << ':' << ' ';
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//shit starts here
	//we will begin tonight's program by taking in
	getline(cin, input);

	//add spaces before and after all operators in input
	addSpaces(input, ";");
	addSpaces(input, "&&");
	addSpaces(input, "||");
	addSpaces(input, "#");

	//vector<char*> words;
	//words = parser(arg, " "); //take out all spaces from arg

//~~~~~~~~~~~~~~~~~~~~~~~~~~PARSER~~~~~~~~~~~~~~~~~~~~~~~~~~
	char *line = new char[input.length()+1];	//strtok requires char*
						//got this from cplusplus.com/reference/string/string/c_str
	strcpy(line, input.c_str());

	char *token = strtok(line, " \t\n");	//can be any character
	vector<char*> words;

	while(token != NULL) {
		words.push_back(token);
		token = strtok(NULL, " \t\n");
	}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`

	char cmenot[] = ";";
	words.push_back(cmenot);

	vector<char*> onecommand;
	onecommand.clear();

	bool success = true;	//status of previous command. used for operators

	bool issemi;
	bool isand;
	bool isor;
	bool ispound;
	bool isoperator;

	size_t i = 0;

	while(i < words.size()) {
		issemi = strcmp(words.at(i), ";") == 0;
		isand = strcmp(words.at(i), "&&") == 0;
		isor = strcmp(words.at(i), "||") == 0;
		ispound = strcmp(words.at(i), "#") == 0;
		isoperator = issemi || isand || isor || ispound;

		if(!isoperator) {
			onecommand.push_back(words.at(i));
		//	for(int j = 0; j < onecommand.size(); j++) cout << "oc " << j << onecommand.at(j) << endl;
		} else {
			onecommand.push_back(NULL);	//needs to end in null for exec
			success = redirectors(onecommand);
			cout << success << endl;
	//		success = execvpstuff(onecommand);
			if(issemi) {
				onecommand.clear();
				//moveon
			} else if(isand && success) {
				//moveon
				onecommand.clear();
			} else if(isor && !success) {
				onecommand.clear();
				//moveon
			} else {
				break;
			}
		}
		i++;
	}

	delete[] line;

	//TESTING DELETE THIS LATER
//	for(int i = 0; i < words.size(); i++) cout << "words" << i << words.at(i) << endl;

}

int main(int argc, char* argv[]) {

	cout << "¤¤¡¡¡¡¡Bienvenidos a la terminál rshell de Chirag!!!!!¤¤" << endl;

	while(1)
	terminal();

	return 0;
}
<|endoftext|>


<commit_before>// Lesson 13.cpp : Defines the entry point for the console application.

#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )

using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;

#define OBJECTS 1

// Global scope box
shared_ptr<mesh> object[1];
shared_ptr<chase_camera> cam;
shared_ptr<mesh> plane;

/*
 * userTranslation
 *
 * Moves the object around inside the window using the keyboard arrow keys.
 */
void userTranslation(float deltaTime)
{
	// Move the quad when arrow keys are pressed
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
		object[0]->trans.translate(vec3(10.0, 0.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
		object[0]->trans.translate(vec3(-10.0, 0.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
		object[0]->trans.translate(vec3(0.0, 0.0, -10.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
		object[0]->trans.translate(vec3(0.0, 0.0, 10.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
		object[0]->trans.translate(vec3(0.0, 10.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
		object[0]->trans.translate(vec3(0.0, -10.0, 0.0) * deltaTime);
	}

} // userTranslation()

/*
 * Update routine
 *
 * Updates the application state
 */
void update(float deltaTime) {

	userTranslation(deltaTime);

	cam->move(object[0]->trans.position, eulerAngles(object[0]->trans.orientation));

	cam->rotate(vec3(0.0, half_pi<float>() * deltaTime, 0.0));

	cam->update(deltaTime);

} // update()

bool load_content() {

	int i = 0;
	for (i=0;i<OBJECTS;i++) {
		// Create box
		object[i] = make_shared<mesh>();
		object[i]->geom = geometry_builder::create_box();

		// Load in effect.  Start with shaders
		auto eff = make_shared<effect>();
		eff->add_shader("shader.vert", GL_VERTEX_SHADER);
		eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
		if (!effect_loader::build_effect(eff)) {
			return false;
		}

		// Create material for box
		object[i]->mat = make_shared<material>();
		object[i]->mat->effect = eff;

		// Set texture for shader
		object[i]->mat->set_texture("tex", texture_loader::load("Checkered.png"));

		// Create plane
		plane = make_shared<mesh>();
		plane->geom = geometry_builder::create_plane();
		plane->trans.translate(vec3(0.0, -0.5, 0.0));

		// Reuse the material from the box
		plane->mat = object[i]->mat;
	}

	return true;

} // load_content()

bool load_camera() {
	// Initialize the camera
	cam = make_shared<chase_camera>();

	/* Set the projection matrix */
	// First get the aspect ratio (width/height)
	float aspect = (float)renderer::get_instance().get_screen_width() /
					(float)renderer::get_instance().get_screen_width();
	// Use this to set the camera projection matrix
	cam->set_projection(
						quarter_pi<float>(),			// FOV
						aspect,							// Aspect ratio
						2.414f,							// Near plane
						10000.0f);						// Far plane
	// Set the camera properties
	cam->set_position(vec3(0.0, 0.0, 20.0));
	cam->set_springiness(0.001);
	cam->set_position_offset(vec3(0.0, 5.0, 10.0));

	// Attach camera to renderer
	renderer::get_instance().set_camera(cam);

	// Set the view matrix
	auto view = lookAt(
					vec3(20.0f, 20.0f, 20.0f),	// Camera position
					vec3(0.0f, 0.0f, 0.0f),		// Target
					vec3(0.0f, 1.0f, 0.0f));	// Up vector
	renderer::get_instance().set_view(view);

	return true;
} // load_camera

int main()
{
	// Initialize the renderer
	if (!renderer::get_instance().initialise()) return -1;

	// Set the clear colour to cyan
	glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

	if (!load_content()) {
		return -1;
	}

	if (!load_camera()) {
		return -1;
	}

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	// Main render loop
	while (renderer::get_instance().is_running())
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
		// Convert to fractions of a second
		auto seconds = float(elapsed.count()) / 1000.0;

		// Update Scene
		update(seconds);

		// Check if running
		if (renderer::get_instance().begin_render())
		{
			// Render Cube
			int i = 0;
			for (i = 0; i <OBJECTS; i++) {
				renderer::get_instance().render(object[i]);
			}

			// Render plane
			renderer::get_instance().render(plane);

			// End the render
			renderer::get_instance().end_render();
		}

		prevTimeStamp = currentTimeStamp;

	} // Main render loop
}
<commit_msg>Changed camera to arc ball<commit_after>// Lesson 13.cpp : Defines the entry point for the console application.

#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )

using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;

#define OBJECTS 1

// Global scope box
shared_ptr<mesh> object[1];
shared_ptr<arc_ball_camera> cam;
shared_ptr<mesh> plane;

/*
 * userTranslation
 *
 * Moves the object around inside the window using the keyboard arrow keys.
 */
void userTranslation(float deltaTime)
{
	// Move the quad when arrow keys are pressed
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
		cam->rotate(0.0, half_pi<float>() * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
		cam->rotate(0.0, -half_pi<float>() * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
		cam->move(-5.0f * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
		cam->move(5.0f * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
		cam->rotate(half_pi<float>() * deltaTime, 0.0);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
		cam->rotate(-half_pi<float>() * deltaTime, 0.0);
	}

} // userTranslation()

/*
 * Update routine
 *
 * Updates the application state
 */
void update(float deltaTime) {

	userTranslation(deltaTime);

	cam->update(deltaTime);

} // update()

bool load_content() {

	int i = 0;
	for (i=0;i<OBJECTS;i++) {
		// Create box
		object[i] = make_shared<mesh>();
		object[i]->geom = geometry_builder::create_box();

		// Load in effect.  Start with shaders
		auto eff = make_shared<effect>();
		eff->add_shader("shader.vert", GL_VERTEX_SHADER);
		eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
		if (!effect_loader::build_effect(eff)) {
			return false;
		}

		// Create material for box
		object[i]->mat = make_shared<material>();
		object[i]->mat->effect = eff;

		// Set texture for shader
		object[i]->mat->set_texture("tex", texture_loader::load("Checkered.png"));

		// Create plane
		plane = make_shared<mesh>();
		plane->geom = geometry_builder::create_plane();
		plane->trans.translate(vec3(0.0, -0.5, 0.0));

		// Reuse the material from the box
		plane->mat = object[i]->mat;
	}

	return true;

} // load_content()

bool load_camera() {
	// Initialize the camera
	cam = make_shared<arc_ball_camera>();

	/* Set the projection matrix */
	// First get the aspect ratio (width/height)
	float aspect = (float)renderer::get_instance().get_screen_width() /
					(float)renderer::get_instance().get_screen_width();
	// Use this to set the camera projection matrix
	cam->set_projection(
						quarter_pi<float>(),			// FOV
						aspect,							// Aspect ratio
						2.414f,							// Near plane
						10000.0f);						// Far plane
	// Set the camera properties
	cam->set_position(vec3(0.0, 0.0, 0.0));
	cam->set_distance(20.0f);

	// Attach camera to renderer
	renderer::get_instance().set_camera(cam);

	// Set the view matrix
	auto view = lookAt(
					vec3(20.0f, 20.0f, 20.0f),	// Camera position
					vec3(0.0f, 0.0f, 0.0f),		// Target
					vec3(0.0f, 1.0f, 0.0f));	// Up vector
	renderer::get_instance().set_view(view);

	return true;
} // load_camera

int main()
{
	// Initialize the renderer
	if (!renderer::get_instance().initialise()) return -1;

	// Set the clear colour to cyan
	glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

	if (!load_content()) {
		return -1;
	}

	if (!load_camera()) {
		return -1;
	}

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	// Main render loop
	while (renderer::get_instance().is_running())
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
		// Convert to fractions of a second
		auto seconds = float(elapsed.count()) / 1000.0;

		// Update Scene
		update(seconds);

		// Check if running
		if (renderer::get_instance().begin_render())
		{
			// Render Cube
			int i = 0;
			for (i = 0; i <OBJECTS; i++) {
				renderer::get_instance().render(object[i]);
			}

			// Render plane
			renderer::get_instance().render(plane);

			// End the render
			renderer::get_instance().end_render();
		}

		prevTimeStamp = currentTimeStamp;

	} // Main render loop
}
<|endoftext|>


<commit_before>#ifndef LIBICS3_ICS3_VERSION_H_
#define LIBICS3_ICS3_VERSION_H_

namespace ics {
  class MinorVersion {
  public:
    enum struct Versions {
      DEFAULT,
      V0,
      V5,
      V6
    };

    static const Versions getVersion();
    static void setVersion(const Versions);
  private:
    static Versions version;
    MinorVersion();
  };
}

#endif // LIBICS3_ICS3_VERSION_H_
<commit_msg>Update version class for add noexception<commit_after>#ifndef LIBICS3_ICS3_VERSION_H_
#define LIBICS3_ICS3_VERSION_H_

namespace ics {
  class MinorVersion {
  public:
    enum struct Versions {
      DEFAULT,
      V0,
      V5,
      V6
    };

    static const Versions getVersion() noexcept;
    static void setVersion(const Versions) noexcept;
  private:
    static Versions version;
    MinorVersion();
  };
}

#endif // LIBICS3_ICS3_VERSION_H_
<|endoftext|>


<commit_before>/*
 * Copyright 2010, Nikhil Marathe <nsm.nikhil@gmail.com> All rights reserved.
 * See LICENSE for details.
*/
#include "sasljs.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

using namespace v8;
using namespace node;

/*
 * Macro from the sqlite3 bindings
 * http://github.com/grumdrig/node-sqlite/blob/master/sqlite3_bindings.cc
 * by Eric Fredricksen
 */
#define REQ_STR_ARG(I, VAR)                                             \
      if (args.Length() <= (I) || !args[I]->IsString())                     \
    return ThrowException(Exception::TypeError(                         \
                                  String::New("Argument " #I " must be a string"))); \
  String::Utf8Value VAR(args[I]->ToString());

namespace sasljs {
void ServerSession::Initialize ( Handle<Object> target )
{
  v8::HandleScope scope;

  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);

  t->InstanceTemplate()->SetInternalFieldCount(1);

  NODE_DEFINE_CONSTANT( target, GSASL_OK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE  );
  NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES  );
  NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN  );

  NODE_SET_PROTOTYPE_METHOD( t, "_mechanisms", GetMechanisms );
  NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
  NODE_SET_PROTOTYPE_METHOD( t, "step", Step );

  target->Set( v8::String::NewSymbol( "ServerSession"), t->GetFunction() );
}

/*
 * Call in JS
 * new ServerSession( "service name" );
 * All other options default to NULL for now
 */
v8::Handle<v8::Value>
ServerSession::New (const v8::Arguments& args)
{
  HandleScope scope;

  REQ_STR_ARG( 0, realm );

  if( args.Length() <= 1 || !args[1]->IsFunction() ) {
    return ThrowException(Exception::TypeError(
                                  String::New("Argument 1 must be a callback")));
  }

  ServerSession *server = new ServerSession( *realm, cb_persist( args[1] ) );
  server->Wrap( args.This() );
  return args.This();
}

ServerSession::ServerSession( const char *realm, Persistent<Function> *cb )
  : ObjectWrap()
  , m_session( NULL )
  , m_callback( cb )
{
}

ServerSession::~ServerSession()
{
}

Handle<Value>
ServerSession::GetMechanisms( const v8::Arguments &args )
{
  ServerSession *sc = Unwrap<ServerSession>( args.This() );

  char *result;

  int mechres = gsasl_server_mechlist( ctx, &result );
  if( mechres != GSASL_OK ) {
    return String::New( "" );
  }

  Handle<String> ret = String::New( result, strlen( result ) );
  free( result );
  return ret;
}

int
ServerSession::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )
{
  ServerSession *sc = static_cast<ServerSession*>(gsasl_session_hook_get( sctx ));
  assert( sc );

  Local<Value> argv[] = { Integer::New( prop ) };
  Local<Value> ret = (*sc->m_callback)->Call( Context::GetCurrent()->Global(), 1, argv );
  std::cerr << "Array " << ret->IsArray();
  std::cerr << "Obj " << ret->IsObject();
  std::cerr << "Integer " << ret->IsInt32();
  std::cerr << "String " << ret->IsString();
  std::cerr << "Null " << ret->IsNull();
  std::cerr << "Undefined " << ret->IsUndefined();
  std::cerr << "True " << ret->IsTrue();
  std::cerr << "False " << ret->IsFalse();
  std::cerr << "Function " << ret->IsFunction();
  std::cerr << "Number " << ret->IsNumber();
  std::cerr << "External " << ret->IsExternal();
  if( ret->IsString() ) {
    std::cerr << "--- Returned " << *String::Utf8Value(ret->ToString());
    gsasl_property_set( sctx, prop, *String::Utf8Value(ret->ToString()) );
    return GSASL_OK;
  }
  return GSASL_NO_CALLBACK;
}

/**
 * Returns a map
 * { status: integer_error_code,
 *   data : data to send to client if error == GSASL_OK }
 */
v8::Handle<v8::Value>
ServerSession::Start( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, mechanismString );

  int res;

  ServerSession *sc = Unwrap<ServerSession>( args.This() );
  if( sc->m_session != NULL ) {
    return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
  }

  res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );
  gsasl_session_hook_set( sc->m_session, sc );
  gsasl_callback_set( ctx, sc->Callback );

  return Integer::New( res );
}

v8::Handle<v8::Value>
ServerSession::Step( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, clientinString );

  ServerSession *sc = Unwrap<ServerSession>( args.This() );

  char *reply;
  size_t len;

  char *b64;
  size_t crap;
  gsasl_base64_from( *clientinString, strlen( *clientinString ), &b64, &crap );
  std::cerr << std::endl << "sasljs: step: " << b64 << std::endl;

  gsasl_base64_from( *clientinString, strlen(*clientinString), &reply, &len );
  int res = gsasl_step64( sc->m_session, *clientinString, &reply );

  Handle<Object> obj = Object::New();
  Local<String> status = String::New( "status" );

  char *d64;
  gsasl_base64_from( reply, strlen(reply), &d64, &len );
  std::cerr << std::endl << "sasljs: step OUT: " << d64 << std::endl;

  if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {
    obj->Set( status, Integer::New( res ) );
    obj->Set( String::New( "data" ), String::New( reply, strlen( reply ) ) );

    return obj;
  }
  else {
    obj->Set( status, Integer::New( res ) );
    obj->Set( String::New( "data" ), String::New( gsasl_strerror( res ) ) );
    return obj;
  }
}
}

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;

  sasljs::ctx = NULL;
  int initres = gsasl_init( &sasljs::ctx );

  if( initres != GSASL_OK ) {
      fprintf( stderr, "Could not initialize gsasl: %s\n", gsasl_strerror( initres ) );
      abort();
  }

  sasljs::ServerSession::Initialize(target);
}
<commit_msg>Added property/callback constants<commit_after>/*
 * Copyright 2010, Nikhil Marathe <nsm.nikhil@gmail.com> All rights reserved.
 * See LICENSE for details.
*/
#include "sasljs.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

using namespace v8;
using namespace node;

/*
 * Macro from the sqlite3 bindings
 * http://github.com/grumdrig/node-sqlite/blob/master/sqlite3_bindings.cc
 * by Eric Fredricksen
 */
#define REQ_STR_ARG(I, VAR)                                             \
      if (args.Length() <= (I) || !args[I]->IsString())                     \
    return ThrowException(Exception::TypeError(                         \
                                  String::New("Argument " #I " must be a string"))); \
  String::Utf8Value VAR(args[I]->ToString());

namespace sasljs {
void ServerSession::Initialize ( Handle<Object> target )
{
  v8::HandleScope scope;

  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);

  t->InstanceTemplate()->SetInternalFieldCount(1);

  // error codes
  NODE_DEFINE_CONSTANT( target, GSASL_OK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE  );
  NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES  );
  NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN  );

  // property constants
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHID );
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHZID );
  NODE_DEFINE_CONSTANT( target, GSASL_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_ANONYMOUS_TOKEN );
  NODE_DEFINE_CONSTANT( target, GSASL_SERVICE );
  NODE_DEFINE_CONSTANT( target, GSASL_HOSTNAME );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME );
  NODE_DEFINE_CONSTANT( target, GSASL_PASSCODE );
  NODE_DEFINE_CONSTANT( target, GSASL_SUGGESTED_PIN );
  NODE_DEFINE_CONSTANT( target, GSASL_PIN );
  NODE_DEFINE_CONSTANT( target, GSASL_REALM );
  NODE_DEFINE_CONSTANT( target, GSASL_DIGEST_MD5_HASHED_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_QOPS );
  NODE_DEFINE_CONSTANT( target, GSASL_QOP );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_ITER );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALT );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALTED_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SIMPLE );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_EXTERNAL );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_ANONYMOUS );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_GSSAPI );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SECURID );

  NODE_SET_PROTOTYPE_METHOD( t, "_mechanisms", GetMechanisms );
  NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
  NODE_SET_PROTOTYPE_METHOD( t, "step", Step );

  target->Set( v8::String::NewSymbol( "ServerSession"), t->GetFunction() );
}

/*
 * Call in JS
 * new ServerSession( "service name" );
 * All other options default to NULL for now
 */
v8::Handle<v8::Value>
ServerSession::New (const v8::Arguments& args)
{
  HandleScope scope;

  REQ_STR_ARG( 0, realm );

  if( args.Length() <= 1 || !args[1]->IsFunction() ) {
    return ThrowException(Exception::TypeError(
                                  String::New("Argument 1 must be a callback")));
  }

  ServerSession *server = new ServerSession( *realm, cb_persist( args[1] ) );
  server->Wrap( args.This() );
  return args.This();
}

ServerSession::ServerSession( const char *realm, Persistent<Function> *cb )
  : ObjectWrap()
  , m_session( NULL )
  , m_callback( cb )
{
}

ServerSession::~ServerSession()
{
}

Handle<Value>
ServerSession::GetMechanisms( const v8::Arguments &args )
{
  ServerSession *sc = Unwrap<ServerSession>( args.This() );

  char *result;

  int mechres = gsasl_server_mechlist( ctx, &result );
  if( mechres != GSASL_OK ) {
    return String::New( "" );
  }

  Handle<String> ret = String::New( result, strlen( result ) );
  free( result );
  return ret;
}

int
ServerSession::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )
{
  ServerSession *sc = static_cast<ServerSession*>(gsasl_session_hook_get( sctx ));
  assert( sc );

  Local<Value> argv[] = { Integer::New( prop ) };
  Local<Value> ret = (*sc->m_callback)->Call( Context::GetCurrent()->Global(), 1, argv );
  std::cerr << "Array " << ret->IsArray();
  std::cerr << "Obj " << ret->IsObject();
  std::cerr << "Integer " << ret->IsInt32();
  std::cerr << "String " << ret->IsString();
  std::cerr << "Null " << ret->IsNull();
  std::cerr << "Undefined " << ret->IsUndefined();
  std::cerr << "True " << ret->IsTrue();
  std::cerr << "False " << ret->IsFalse();
  std::cerr << "Function " << ret->IsFunction();
  std::cerr << "Number " << ret->IsNumber();
  std::cerr << "External " << ret->IsExternal();
  if( ret->IsString() ) {
    std::cerr << "--- Returned " << *String::Utf8Value(ret->ToString());
    gsasl_property_set( sctx, prop, *String::Utf8Value(ret->ToString()) );
    return GSASL_OK;
  }
  return GSASL_NO_CALLBACK;
}

/**
 * Returns a map
 * { status: integer_error_code,
 *   data : data to send to client if error == GSASL_OK }
 */
v8::Handle<v8::Value>
ServerSession::Start( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, mechanismString );

  int res;

  ServerSession *sc = Unwrap<ServerSession>( args.This() );
  if( sc->m_session != NULL ) {
    return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
  }

  res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );
  gsasl_session_hook_set( sc->m_session, sc );
  gsasl_callback_set( ctx, sc->Callback );

  return Integer::New( res );
}

v8::Handle<v8::Value>
ServerSession::Step( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, clientinString );

  ServerSession *sc = Unwrap<ServerSession>( args.This() );

  char *reply;
  size_t len;

  char *b64;
  size_t crap;
  gsasl_base64_from( *clientinString, strlen( *clientinString ), &b64, &crap );
  std::cerr << std::endl << "sasljs: step: " << b64 << std::endl;

  gsasl_base64_from( *clientinString, strlen(*clientinString), &reply, &len );
  int res = gsasl_step64( sc->m_session, *clientinString, &reply );

  Handle<Object> obj = Object::New();
  Local<String> status = String::New( "status" );

  char *d64;
  gsasl_base64_from( reply, strlen(reply), &d64, &len );
  std::cerr << std::endl << "sasljs: step OUT: " << d64 << std::endl;

  if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {
    obj->Set( status, Integer::New( res ) );
    obj->Set( String::New( "data" ), String::New( reply, strlen( reply ) ) );

    return obj;
  }
  else {
    obj->Set( status, Integer::New( res ) );
    obj->Set( String::New( "data" ), String::New( gsasl_strerror( res ) ) );
    return obj;
  }
}
}

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;

  sasljs::ctx = NULL;
  int initres = gsasl_init( &sasljs::ctx );

  if( initres != GSASL_OK ) {
      fprintf( stderr, "Could not initialize gsasl: %s\n", gsasl_strerror( initres ) );
      abort();
  }

  sasljs::ServerSession::Initialize(target);
}
<|endoftext|>