<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <bse/bse.hh>

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> server;

static void
print_usage (bool help)
{
  if (!help)
    {
      Bse::printout ("beast-sound-engine version %s\n", Bse::version());
      return;
    }
  Bse::printout ("Usage: beast-sound-engine [OPTIONS]\n");
  Bse::printout ("  --help     Print command line help\n");
  Bse::printout ("  --version  Print program version\n");
}

static Bse::ServerH bse_server;

// Configure websocket server
struct CustomServerConfig : public websocketpp::config::asio {
  static const size_t connection_read_buffer_size = 16384;
};
using ServerEndpoint = websocketpp::server<CustomServerConfig>;
static ServerEndpoint websocket_server;

static void
ws_message (websocketpp::connection_hdl con, server::message_ptr msg)
{
  const std::string &message = msg->get_payload();
  // send message to BSE thread and block until its been handled
  Aida::ScopedSemaphore sem;
  auto handle_wsmsg = [&message, &con, &sem] () {
    const std::string reply = "ECHO: " + message;
    if (!reply.empty())
      websocket_server.send (con, reply, websocketpp::frame::opcode::text);
    sem.post();
  };
  bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg);
  sem.wait();
}

int
main (int argc, char *argv[])
{
  Bse::init_async (&argc, argv, argv[0]); // Bse::cstrings_to_vector (NULL)
  bse_server = Bse::init_server_instance();

  // parse arguments
  bool seen_dashdash = false;
  std::vector<std::string> words;
  for (size_t i = 0; i < argc; i++)
    if (!argv[i])
      continue;
    else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0)
      seen_dashdash = true;
    else if (!seen_dashdash && argv[i][0] == '-')
      {
        const char *arg = argv[i] + 1 + (argv[i][1] == '-');
        const char *eq = strchr (arg, '=');
        const std::string arg_name = !eq ? arg : std::string (arg, eq - arg);
        if (arg_name == "version")
          {
            print_usage (false);
            return 0;
          }
        else if (arg_name == "h" || arg_name == "help")
          {
            print_usage (true);
            return 0;
          }
        else
          {
            Bse::printerr ("%s: invalid argument: %s\n", argv[0], argv[i]);
            print_usage (true);
            return 1;
          }
      }
    else
      words.push_back (argv[i]);

  const int BEAST_AUDIO_ENGINE_PORT = 27239;    // 0x3ea67 % 32768

  // setup websocket and run asio loop
  websocket_server.set_message_handler (&ws_message);
  websocket_server.init_asio();
  websocket_server.clear_access_channels (websocketpp::log::alevel::all);
  websocket_server.set_reuse_addr (true);
  namespace IP = boost::asio::ip;
  IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string ("127.0.0.1"), BEAST_AUDIO_ENGINE_PORT);
  websocket_server.listen (endpoint_local);
  websocket_server.start_accept();

  Bse::printout ("LISTEN: ws://localhost:%d/\n", BEAST_AUDIO_ENGINE_PORT);

  websocket_server.run();

  return 0;
}
<commit_msg>BSE: beast-sound-engine: add tiny bit of color<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <bse/bse.hh>
#include <bse/platform.hh>

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> server;

static void
print_usage (bool help)
{
  if (!help)
    {
      Bse::printout ("beast-sound-engine version %s\n", Bse::version());
      return;
    }
  Bse::printout ("Usage: beast-sound-engine [OPTIONS]\n");
  Bse::printout ("  --help     Print command line help\n");
  Bse::printout ("  --version  Print program version\n");
}

static Bse::ServerH bse_server;

// Configure websocket server
struct CustomServerConfig : public websocketpp::config::asio {
  static const size_t connection_read_buffer_size = 16384;
};
using ServerEndpoint = websocketpp::server<CustomServerConfig>;
static ServerEndpoint websocket_server;

static void
ws_message (websocketpp::connection_hdl con, server::message_ptr msg)
{
  const std::string &message = msg->get_payload();
  // send message to BSE thread and block until its been handled
  Aida::ScopedSemaphore sem;
  auto handle_wsmsg = [&message, &con, &sem] () {
    const std::string reply = "ECHO: " + message;
    if (!reply.empty())
      websocket_server.send (con, reply, websocketpp::frame::opcode::text);
    sem.post();
  };
  bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg);
  sem.wait();
}

int
main (int argc, char *argv[])
{
  Bse::init_async (&argc, argv, argv[0]); // Bse::cstrings_to_vector (NULL)
  bse_server = Bse::init_server_instance();

  // parse arguments
  bool seen_dashdash = false;
  std::vector<std::string> words;
  for (size_t i = 0; i < argc; i++)
    if (!argv[i])
      continue;
    else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0)
      seen_dashdash = true;
    else if (!seen_dashdash && argv[i][0] == '-')
      {
        const char *arg = argv[i] + 1 + (argv[i][1] == '-');
        const char *eq = strchr (arg, '=');
        const std::string arg_name = !eq ? arg : std::string (arg, eq - arg);
        if (arg_name == "version")
          {
            print_usage (false);
            return 0;
          }
        else if (arg_name == "h" || arg_name == "help")
          {
            print_usage (true);
            return 0;
          }
        else
          {
            Bse::printerr ("%s: invalid argument: %s\n", argv[0], argv[i]);
            print_usage (true);
            return 1;
          }
      }
    else
      words.push_back (argv[i]);

  const int BEAST_AUDIO_ENGINE_PORT = 27239;    // 0x3ea67 % 32768

  // setup websocket and run asio loop
  websocket_server.set_message_handler (&ws_message);
  websocket_server.init_asio();
  websocket_server.clear_access_channels (websocketpp::log::alevel::all);
  websocket_server.set_reuse_addr (true);
  namespace IP = boost::asio::ip;
  IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string ("127.0.0.1"), BEAST_AUDIO_ENGINE_PORT);
  websocket_server.listen (endpoint_local);
  websocket_server.start_accept();

#undef B0 // pollution from termios.h
  using namespace Bse::AnsiColors;
  auto B1 = color (BOLD);
  auto B0 = color (BOLD_OFF);
  Bse::printout ("%sLISTEN:%s ws://localhost:%d/\n", B1, B0, BEAST_AUDIO_ENGINE_PORT);

  websocket_server.run();

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************/
/*  input.cpp                                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "input.h"
#include "input_map.h"
#include "os/os.h"
#include "globals.h"
Input *Input::singleton=NULL;

Input *Input::get_singleton() {

	return singleton;
}

void Input::set_mouse_mode(MouseMode p_mode) {
	ERR_FAIL_INDEX(p_mode,3);
	OS::get_singleton()->set_mouse_mode((OS::MouseMode)p_mode);
}

Input::MouseMode Input::get_mouse_mode() const {

	return (MouseMode)OS::get_singleton()->get_mouse_mode();
}

void Input::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("is_key_pressed","scancode"),&Input::is_key_pressed);
	ObjectTypeDB::bind_method(_MD("is_mouse_button_pressed","button"),&Input::is_mouse_button_pressed);
	ObjectTypeDB::bind_method(_MD("is_joy_button_pressed","device","button"),&Input::is_joy_button_pressed);
	ObjectTypeDB::bind_method(_MD("is_action_pressed","action"),&Input::is_action_pressed);
	ObjectTypeDB::bind_method(_MD("get_joy_axis","device","axis"),&Input::get_joy_axis);
	ObjectTypeDB::bind_method(_MD("get_joy_name","device"),&Input::get_joy_name);
	ObjectTypeDB::bind_method(_MD("get_accelerometer"),&Input::get_accelerometer);
	ObjectTypeDB::bind_method(_MD("get_mouse_pos"),&Input::get_mouse_pos);
	ObjectTypeDB::bind_method(_MD("get_mouse_speed"),&Input::get_mouse_speed);
	ObjectTypeDB::bind_method(_MD("get_mouse_button_mask"),&Input::get_mouse_button_mask);
	ObjectTypeDB::bind_method(_MD("set_mouse_mode","mode"),&Input::set_mouse_mode);
	ObjectTypeDB::bind_method(_MD("get_mouse_mode"),&Input::get_mouse_mode);
	ObjectTypeDB::bind_method(_MD("warp_mouse_pos","to"),&Input::warp_mouse_pos);
	ObjectTypeDB::bind_method(_MD("action_press"),&Input::action_press);
	ObjectTypeDB::bind_method(_MD("action_release"),&Input::action_release);

	BIND_CONSTANT( MOUSE_MODE_VISIBLE );
	BIND_CONSTANT( MOUSE_MODE_HIDDEN );
	BIND_CONSTANT( MOUSE_MODE_CAPTURED );

	ADD_SIGNAL( MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "connected")) );
}

void Input::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
#ifdef TOOLS_ENABLED

	String pf=p_function;
	if (p_idx==0 && (pf=="is_action_pressed" || pf=="action_press" || pf=="action_release")) {

		List<PropertyInfo> pinfo;
		Globals::get_singleton()->get_property_list(&pinfo);

		for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
			const PropertyInfo &pi=E->get();

			if (!pi.name.begins_with("input/"))
				continue;

			String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
			r_options->push_back("\""+name+"\"");

		}
	}
#endif

}

Input::Input() {

	singleton=this;
}

//////////////////////////////////////////////////////////

void InputDefault::SpeedTrack::update(const Vector2& p_delta_p) {

	uint64_t tick = OS::get_singleton()->get_ticks_usec();
	uint32_t tdiff = tick-last_tick;
	float delta_t = tdiff / 1000000.0;
	last_tick=tick;

	accum+=p_delta_p;
	accum_t+=delta_t;

	if (accum_t>max_ref_frame*10)
		accum_t=max_ref_frame*10;

	while( accum_t>=min_ref_frame ) {

		float slice_t = min_ref_frame / accum_t;
		Vector2 slice = accum*slice_t;
		accum=accum-slice;
		accum_t-=min_ref_frame;

		speed=(slice/min_ref_frame).linear_interpolate(speed,min_ref_frame/max_ref_frame);
	}

}

void InputDefault::SpeedTrack::reset() {
	last_tick = OS::get_singleton()->get_ticks_usec();
	speed=Vector2();
	accum_t=0;
}

InputDefault::SpeedTrack::SpeedTrack() {

	 min_ref_frame=0.1;
	 max_ref_frame=0.3;
	 reset();
}

bool InputDefault::is_key_pressed(int p_scancode) {

	_THREAD_SAFE_METHOD_
	return keys_pressed.has(p_scancode);
}

bool InputDefault::is_mouse_button_pressed(int p_button) {

	_THREAD_SAFE_METHOD_
	return (mouse_button_mask&(1<<p_button))!=0;
}

static int _combine_device(int p_value,int p_device) {

	return p_value|(p_device<<20);
}

bool InputDefault::is_joy_button_pressed(int p_device, int p_button) {

	_THREAD_SAFE_METHOD_
	return joy_buttons_pressed.has(_combine_device(p_button,p_device));
}

bool InputDefault::is_action_pressed(const StringName& p_action) {

	if (custom_action_press.has(p_action))
		return true; //simpler

	const List<InputEvent> *alist = InputMap::get_singleton()->get_action_list(p_action);
	if (!alist)
		return NULL;

	for (const List<InputEvent>::Element *E=alist->front();E;E=E->next()) {

		int device=E->get().device;

		switch(E->get().type) {

			case InputEvent::KEY: {

				const InputEventKey &iek=E->get().key;
				if ((keys_pressed.has(iek.scancode)))
					return true;
			} break;
			case InputEvent::MOUSE_BUTTON: {

				const InputEventMouseButton &iemb=E->get().mouse_button;
				 if(mouse_button_mask&(1<<iemb.button_index))
					 return true;
			} break;
			case InputEvent::JOYSTICK_BUTTON: {

				const InputEventJoystickButton &iejb=E->get().joy_button;
				int c = _combine_device(iejb.button_index,device);
				if (joy_buttons_pressed.has(c))
					return true;
			} break;
		}
	}

	return false;
}

float InputDefault::get_joy_axis(int p_device,int p_axis) {

	_THREAD_SAFE_METHOD_
	int c = _combine_device(p_axis,p_device);
	if (joy_axis.has(c)) {
		return joy_axis[c];
	} else {
		return 0;
	}
}

String InputDefault::get_joy_name(int p_idx) {

	_THREAD_SAFE_METHOD_
	return joy_names[p_idx];
};

void InputDefault::joy_connection_changed(int p_idx, bool p_connected, String p_name) {

	_THREAD_SAFE_METHOD_
	joy_names[p_idx] = p_connected ? p_name : "";

	emit_signal("joy_connection_changed", p_idx, p_connected);
};

Vector3 InputDefault::get_accelerometer() {

	_THREAD_SAFE_METHOD_
	return accelerometer;
}

void InputDefault::parse_input_event(const InputEvent& p_event) {

	_THREAD_SAFE_METHOD_
	switch(p_event.type) {

		case InputEvent::KEY: {

			if (p_event.key.echo)
				break;
			if (p_event.key.scancode==0)
				break;

		//	print_line(p_event);

			if (p_event.key.pressed)
				keys_pressed.insert(p_event.key.scancode);
			else
				keys_pressed.erase(p_event.key.scancode);
		} break;
		case InputEvent::MOUSE_BUTTON: {

			if (p_event.mouse_button.doubleclick)
				break;

			if (p_event.mouse_button.pressed)
				mouse_button_mask|=(1<<p_event.mouse_button.button_index);
			else
				mouse_button_mask&=~(1<<p_event.mouse_button.button_index);
		} break;
		case InputEvent::JOYSTICK_BUTTON: {

			int c = _combine_device(p_event.joy_button.button_index,p_event.device);

			if (p_event.joy_button.pressed)
				joy_buttons_pressed.insert(c);
			else
				joy_buttons_pressed.erase(c);
		} break;
		case InputEvent::JOYSTICK_MOTION: {
			set_joy_axis(p_event.device, p_event.joy_motion.axis, p_event.joy_motion.axis_value);
		} break;

	}

	if (main_loop)
		main_loop->input_event(p_event);

}

void InputDefault::set_joy_axis(int p_device,int p_axis,float p_value) {

	_THREAD_SAFE_METHOD_
	int c = _combine_device(p_axis,p_device);
	joy_axis[c]=p_value;
}

void InputDefault::set_accelerometer(const Vector3& p_accel) {

	_THREAD_SAFE_METHOD_

	accelerometer=p_accel;

}

void InputDefault::set_main_loop(MainLoop *p_main_loop) {
	main_loop=p_main_loop;

}

void InputDefault::set_mouse_pos(const Point2& p_posf) {

	mouse_speed_track.update(p_posf-mouse_pos);
	mouse_pos=p_posf;
}

Point2 InputDefault::get_mouse_pos() const {

	return mouse_pos;
}
Point2 InputDefault::get_mouse_speed() const {

	return mouse_speed_track.speed;
}

int InputDefault::get_mouse_button_mask() const {

	return OS::get_singleton()->get_mouse_button_state();
}

void InputDefault::warp_mouse_pos(const Vector2& p_to) {

	OS::get_singleton()->warp_mouse_pos(p_to);
}

void InputDefault::iteration(float p_step) {

}

void InputDefault::action_press(const StringName& p_action) {

	if (custom_action_press.has(p_action)) {

		custom_action_press[p_action]++;
	} else {
		custom_action_press[p_action]=1;
	}
}

void InputDefault::action_release(const StringName& p_action){

	ERR_FAIL_COND(!custom_action_press.has(p_action));
	custom_action_press[p_action]--;
	if (custom_action_press[p_action]==0) {
		custom_action_press.erase(p_action);
	}
}

InputDefault::InputDefault() {

	mouse_button_mask=0;
	main_loop=NULL;
}
<commit_msg>-removed get_mouse_pos from Input, as it only caused problems<commit_after>/*************************************************************************/
/*  input.cpp                                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "input.h"
#include "input_map.h"
#include "os/os.h"
#include "globals.h"
Input *Input::singleton=NULL;

Input *Input::get_singleton() {

	return singleton;
}

void Input::set_mouse_mode(MouseMode p_mode) {
	ERR_FAIL_INDEX(p_mode,3);
	OS::get_singleton()->set_mouse_mode((OS::MouseMode)p_mode);
}

Input::MouseMode Input::get_mouse_mode() const {

	return (MouseMode)OS::get_singleton()->get_mouse_mode();
}

void Input::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("is_key_pressed","scancode"),&Input::is_key_pressed);
	ObjectTypeDB::bind_method(_MD("is_mouse_button_pressed","button"),&Input::is_mouse_button_pressed);
	ObjectTypeDB::bind_method(_MD("is_joy_button_pressed","device","button"),&Input::is_joy_button_pressed);
	ObjectTypeDB::bind_method(_MD("is_action_pressed","action"),&Input::is_action_pressed);
	ObjectTypeDB::bind_method(_MD("get_joy_axis","device","axis"),&Input::get_joy_axis);
	ObjectTypeDB::bind_method(_MD("get_joy_name","device"),&Input::get_joy_name);
	ObjectTypeDB::bind_method(_MD("get_accelerometer"),&Input::get_accelerometer);
	//ObjectTypeDB::bind_method(_MD("get_mouse_pos"),&Input::get_mouse_pos);
	ObjectTypeDB::bind_method(_MD("get_mouse_speed"),&Input::get_mouse_speed);
	ObjectTypeDB::bind_method(_MD("get_mouse_button_mask"),&Input::get_mouse_button_mask);
	ObjectTypeDB::bind_method(_MD("set_mouse_mode","mode"),&Input::set_mouse_mode);
	ObjectTypeDB::bind_method(_MD("get_mouse_mode"),&Input::get_mouse_mode);
	ObjectTypeDB::bind_method(_MD("warp_mouse_pos","to"),&Input::warp_mouse_pos);
	ObjectTypeDB::bind_method(_MD("action_press"),&Input::action_press);
	ObjectTypeDB::bind_method(_MD("action_release"),&Input::action_release);

	BIND_CONSTANT( MOUSE_MODE_VISIBLE );
	BIND_CONSTANT( MOUSE_MODE_HIDDEN );
	BIND_CONSTANT( MOUSE_MODE_CAPTURED );

	ADD_SIGNAL( MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "connected")) );
}

void Input::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
#ifdef TOOLS_ENABLED

	String pf=p_function;
	if (p_idx==0 && (pf=="is_action_pressed" || pf=="action_press" || pf=="action_release")) {

		List<PropertyInfo> pinfo;
		Globals::get_singleton()->get_property_list(&pinfo);

		for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
			const PropertyInfo &pi=E->get();

			if (!pi.name.begins_with("input/"))
				continue;

			String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
			r_options->push_back("\""+name+"\"");

		}
	}
#endif

}

Input::Input() {

	singleton=this;
}

//////////////////////////////////////////////////////////

void InputDefault::SpeedTrack::update(const Vector2& p_delta_p) {

	uint64_t tick = OS::get_singleton()->get_ticks_usec();
	uint32_t tdiff = tick-last_tick;
	float delta_t = tdiff / 1000000.0;
	last_tick=tick;

	accum+=p_delta_p;
	accum_t+=delta_t;

	if (accum_t>max_ref_frame*10)
		accum_t=max_ref_frame*10;

	while( accum_t>=min_ref_frame ) {

		float slice_t = min_ref_frame / accum_t;
		Vector2 slice = accum*slice_t;
		accum=accum-slice;
		accum_t-=min_ref_frame;

		speed=(slice/min_ref_frame).linear_interpolate(speed,min_ref_frame/max_ref_frame);
	}

}

void InputDefault::SpeedTrack::reset() {
	last_tick = OS::get_singleton()->get_ticks_usec();
	speed=Vector2();
	accum_t=0;
}

InputDefault::SpeedTrack::SpeedTrack() {

	 min_ref_frame=0.1;
	 max_ref_frame=0.3;
	 reset();
}

bool InputDefault::is_key_pressed(int p_scancode) {

	_THREAD_SAFE_METHOD_
	return keys_pressed.has(p_scancode);
}

bool InputDefault::is_mouse_button_pressed(int p_button) {

	_THREAD_SAFE_METHOD_
	return (mouse_button_mask&(1<<p_button))!=0;
}

static int _combine_device(int p_value,int p_device) {

	return p_value|(p_device<<20);
}

bool InputDefault::is_joy_button_pressed(int p_device, int p_button) {

	_THREAD_SAFE_METHOD_
	return joy_buttons_pressed.has(_combine_device(p_button,p_device));
}

bool InputDefault::is_action_pressed(const StringName& p_action) {

	if (custom_action_press.has(p_action))
		return true; //simpler

	const List<InputEvent> *alist = InputMap::get_singleton()->get_action_list(p_action);
	if (!alist)
		return NULL;

	for (const List<InputEvent>::Element *E=alist->front();E;E=E->next()) {

		int device=E->get().device;

		switch(E->get().type) {

			case InputEvent::KEY: {

				const InputEventKey &iek=E->get().key;
				if ((keys_pressed.has(iek.scancode)))
					return true;
			} break;
			case InputEvent::MOUSE_BUTTON: {

				const InputEventMouseButton &iemb=E->get().mouse_button;
				 if(mouse_button_mask&(1<<iemb.button_index))
					 return true;
			} break;
			case InputEvent::JOYSTICK_BUTTON: {

				const InputEventJoystickButton &iejb=E->get().joy_button;
				int c = _combine_device(iejb.button_index,device);
				if (joy_buttons_pressed.has(c))
					return true;
			} break;
		}
	}

	return false;
}

float InputDefault::get_joy_axis(int p_device,int p_axis) {

	_THREAD_SAFE_METHOD_
	int c = _combine_device(p_axis,p_device);
	if (joy_axis.has(c)) {
		return joy_axis[c];
	} else {
		return 0;
	}
}

String InputDefault::get_joy_name(int p_idx) {

	_THREAD_SAFE_METHOD_
	return joy_names[p_idx];
};

void InputDefault::joy_connection_changed(int p_idx, bool p_connected, String p_name) {

	_THREAD_SAFE_METHOD_
	joy_names[p_idx] = p_connected ? p_name : "";

	emit_signal("joy_connection_changed", p_idx, p_connected);
};

Vector3 InputDefault::get_accelerometer() {

	_THREAD_SAFE_METHOD_
	return accelerometer;
}

void InputDefault::parse_input_event(const InputEvent& p_event) {

	_THREAD_SAFE_METHOD_
	switch(p_event.type) {

		case InputEvent::KEY: {

			if (p_event.key.echo)
				break;
			if (p_event.key.scancode==0)
				break;

		//	print_line(p_event);

			if (p_event.key.pressed)
				keys_pressed.insert(p_event.key.scancode);
			else
				keys_pressed.erase(p_event.key.scancode);
		} break;
		case InputEvent::MOUSE_BUTTON: {

			if (p_event.mouse_button.doubleclick)
				break;

			if (p_event.mouse_button.pressed)
				mouse_button_mask|=(1<<p_event.mouse_button.button_index);
			else
				mouse_button_mask&=~(1<<p_event.mouse_button.button_index);
		} break;
		case InputEvent::JOYSTICK_BUTTON: {

			int c = _combine_device(p_event.joy_button.button_index,p_event.device);

			if (p_event.joy_button.pressed)
				joy_buttons_pressed.insert(c);
			else
				joy_buttons_pressed.erase(c);
		} break;
		case InputEvent::JOYSTICK_MOTION: {
			set_joy_axis(p_event.device, p_event.joy_motion.axis, p_event.joy_motion.axis_value);
		} break;

	}

	if (main_loop)
		main_loop->input_event(p_event);

}

void InputDefault::set_joy_axis(int p_device,int p_axis,float p_value) {

	_THREAD_SAFE_METHOD_
	int c = _combine_device(p_axis,p_device);
	joy_axis[c]=p_value;
}

void InputDefault::set_accelerometer(const Vector3& p_accel) {

	_THREAD_SAFE_METHOD_

	accelerometer=p_accel;

}

void InputDefault::set_main_loop(MainLoop *p_main_loop) {
	main_loop=p_main_loop;

}

void InputDefault::set_mouse_pos(const Point2& p_posf) {

	mouse_speed_track.update(p_posf-mouse_pos);
	mouse_pos=p_posf;
}

Point2 InputDefault::get_mouse_pos() const {

	return mouse_pos;
}
Point2 InputDefault::get_mouse_speed() const {

	return mouse_speed_track.speed;
}

int InputDefault::get_mouse_button_mask() const {

	return OS::get_singleton()->get_mouse_button_state();
}

void InputDefault::warp_mouse_pos(const Vector2& p_to) {

	OS::get_singleton()->warp_mouse_pos(p_to);
}

void InputDefault::iteration(float p_step) {

}

void InputDefault::action_press(const StringName& p_action) {

	if (custom_action_press.has(p_action)) {

		custom_action_press[p_action]++;
	} else {
		custom_action_press[p_action]=1;
	}
}

void InputDefault::action_release(const StringName& p_action){

	ERR_FAIL_COND(!custom_action_press.has(p_action));
	custom_action_press[p_action]--;
	if (custom_action_press[p_action]==0) {
		custom_action_press.erase(p_action);
	}
}

InputDefault::InputDefault() {

	mouse_button_mask=0;
	main_loop=NULL;
}
<|endoftext|>


<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <blackhole/record.hpp>
#include <blackhole/sink/console.hpp>

namespace blackhole {
namespace testing {
namespace sink {

using ::testing::StrictMock;
using ::testing::internal::CaptureStdout;
using ::testing::internal::GetCapturedStdout;

using ::blackhole::sink::console_t;

TEST(console_t, ByDefaultUseStandardOutput) {
    console_t sink;

    const string_view message("");
    const attribute_pack pack;
    record_t record(42, message, pack);

    CaptureStdout();
    sink.execute(record, "expected");

    const std::string actual = GetCapturedStdout();
    EXPECT_EQ("expected\n", actual);
}

TEST(console_t, AcceptsAll) {
    const string_view message("");
    const attribute_pack pack;
    record_t record(42, message, pack);

    console_t sink;

    EXPECT_TRUE(sink.filter(record));
}

TEST(console_t, Type) {
    EXPECT_EQ("console", std::string(factory<sink::console_t>::type()));
}

}  // namespace sink
}  // namespace testing
}  // namespace blackhole
<commit_msg>chore(tests): make tiny renaming<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <blackhole/record.hpp>
#include <blackhole/sink/console.hpp>

namespace blackhole {
namespace testing {
namespace sink {

using ::testing::StrictMock;
using ::testing::internal::CaptureStdout;
using ::testing::internal::GetCapturedStdout;

using ::blackhole::sink::console_t;

TEST(console_t, ByDefaultUseStandardOutput) {
    console_t sink;

    const string_view message("");
    const attribute_pack pack;
    record_t record(42, message, pack);

    CaptureStdout();
    sink.execute(record, "expected");

    const std::string actual = GetCapturedStdout();
    EXPECT_EQ("expected\n", actual);
}

TEST(console_t, FilterAcceptsAll) {
    const string_view message("");
    const attribute_pack pack;
    record_t record(42, message, pack);

    console_t sink;

    EXPECT_TRUE(sink.filter(record));
}

TEST(console_t, Type) {
    EXPECT_EQ("console", std::string(factory<sink::console_t>::type()));
}

}  // namespace sink
}  // namespace testing
}  // namespace blackhole
<|endoftext|>


<commit_before>/*{{{
    Copyright (C) 2012 Matthias Kretz <kretz@kde.org>

    Permission to use, copy, modify, and distribute this software
    and its documentation for any purpose and without fee is hereby
    granted, provided that the above copyright notice appear in all
    copies and that both that the copyright notice and this
    permission notice and warranty disclaimer appear in supporting
    documentation, and that the name of the author not be used in
    advertising or publicity pertaining to distribution of the
    software without specific, written prior permission.

    The author disclaim all warranties with regard to this
    software, including all implied warranties of merchantability
    and fitness.  In no event shall the author be liable for any
    special, indirect or consequential damages or any damages
    whatsoever resulting from loss of use, data or profits, whether
    in an action of contract, negligence or other tortious action,
    arising out of or in connection with the use or performance of
    this software.

}}}*/

#include "unittest-old.h"
#include <Vc/Allocator>
#include <vector>
#include <array>
#include <forward_list>
#include <list>
#include <deque>

#include "common/macros.h"

template<typename Vec> size_t alignmentMask()
{
    if (Vec::Size == 1) {
        // on 32bit the maximal alignment is 4 Bytes, even for 8-Byte doubles.
        return std::min(sizeof(void*), sizeof(typename Vec::EntryType)) - 1;
    }
    // AVX::VectorAlignment is too large
    return std::min<size_t>(sizeof(Vec), Vc::VectorAlignment) - 1;
}

template<typename T> struct SomeStruct { char a; T x; };

template<typename V> void stdVectorAlignment()
{
    const size_t mask = alignmentMask<V>();
    const char *const null = 0;

    std::vector<V> v(11);
    for (int i = 0; i < 11; ++i) {
        COMPARE((reinterpret_cast<char *>(&v[i]) - null) & mask, 0u) << "&v[i] = " << &v[i] << ", mask = " << mask << ", i = " << i;
    }

    std::vector<SomeStruct<V>, Vc::Allocator<SomeStruct<V> > > v2(11);
    for (int i = 0; i < 11; ++i) {
        COMPARE((reinterpret_cast<char *>(&v2[i]) - null) & mask, 0u) << "&v2[i] = " << &v2[i] << ", mask = " << mask << ", i = " << i;
    }

    std::vector<V> v3(v);
    std::vector<SomeStruct<V>, Vc::Allocator<SomeStruct<V> > > v4(v2);

    typedef typename V::EntryType T;
    for (int i = 1; i < 100; ++i) {
        std::vector<T, Vc::Allocator<T>> v5(i);
        const size_t expectedAlignment = alignof(V);
        COMPARE((&v5[0] - static_cast<const T *>(0)) * sizeof(T) & (expectedAlignment - 1), 0u);
    }
}

template<typename V, typename Container> void listInitialization()
{
    typedef typename V::EntryType T;
    const auto data = Vc::makeContainer<Container>({ T(1), T(2), T(3), T(4), T(5), T(6), T(7), T(8), T(9) });
    V reference = V::IndexesFromZero() + 1;
    for (const auto &v : data) {
        reference.setZero(reference > 9);
        COMPARE(v, reference);
        reference += V::Size;
    }
}
template<typename V> void listInitialization()
{
    listInitialization<V, std::vector<V>>();
    listInitialization<V, std::array<V, 9>>();
    listInitialization<V, std::deque<V>>();

    // The following two crash (at least with AVX). Probably unaligned memory access.
    //listInitialization<V, std::forward_list<V>>();
    //listInitialization<V, std::list<V>>();
}

void testmain()
{
    using namespace Vc;
    testAllTypes(stdVectorAlignment);
    testAllTypes(listInitialization);
}
<commit_msg>stlcontainer: convert to new unittest interface<commit_after>/*{{{
    Copyright (C) 2012 Matthias Kretz <kretz@kde.org>

    Permission to use, copy, modify, and distribute this software
    and its documentation for any purpose and without fee is hereby
    granted, provided that the above copyright notice appear in all
    copies and that both that the copyright notice and this
    permission notice and warranty disclaimer appear in supporting
    documentation, and that the name of the author not be used in
    advertising or publicity pertaining to distribution of the
    software without specific, written prior permission.

    The author disclaim all warranties with regard to this
    software, including all implied warranties of merchantability
    and fitness.  In no event shall the author be liable for any
    special, indirect or consequential damages or any damages
    whatsoever resulting from loss of use, data or profits, whether
    in an action of contract, negligence or other tortious action,
    arising out of or in connection with the use or performance of
    this software.

}}}*/

#include "unittest.h"
#include <Vc/Allocator>
#include <vector>
#include <array>
#include <forward_list>
#include <list>
#include <deque>

#include "common/macros.h"

template<typename Vec> size_t alignmentMask()
{
    if (Vec::Size == 1) {
        // on 32bit the maximal alignment is 4 Bytes, even for 8-Byte doubles.
        return std::min(sizeof(void*), sizeof(typename Vec::EntryType)) - 1;
    }
    // AVX::VectorAlignment is too large
    return std::min<size_t>(sizeof(Vec), Vc::VectorAlignment) - 1;
}

template<typename T> struct SomeStruct { char a; T x; };

TEST_TYPES(V, stdVectorAlignment, (ALL_VECTORS))
{
    const size_t mask = alignmentMask<V>();
    const char *const null = 0;

    std::vector<V> v(11);
    for (int i = 0; i < 11; ++i) {
        COMPARE((reinterpret_cast<char *>(&v[i]) - null) & mask, 0u) << "&v[i] = " << &v[i] << ", mask = " << mask << ", i = " << i;
    }

    std::vector<SomeStruct<V>, Vc::Allocator<SomeStruct<V> > > v2(11);
    for (int i = 0; i < 11; ++i) {
        COMPARE((reinterpret_cast<char *>(&v2[i]) - null) & mask, 0u) << "&v2[i] = " << &v2[i] << ", mask = " << mask << ", i = " << i;
    }

    std::vector<V> v3(v);
    std::vector<SomeStruct<V>, Vc::Allocator<SomeStruct<V> > > v4(v2);

    typedef typename V::EntryType T;
    for (int i = 1; i < 100; ++i) {
        std::vector<T, Vc::Allocator<T>> v5(i);
        const size_t expectedAlignment = alignof(V);
        COMPARE((&v5[0] - static_cast<const T *>(0)) * sizeof(T) & (expectedAlignment - 1), 0u);
    }
}

template<typename V, typename Container> void listInitializationImpl()
{
    typedef typename V::EntryType T;
    const auto data = Vc::makeContainer<Container>({ T(1), T(2), T(3), T(4), T(5), T(6), T(7), T(8), T(9) });
    V reference = V::IndexesFromZero() + 1;
    for (const auto &v : data) {
        reference.setZero(reference > 9);
        COMPARE(v, reference);
        reference += V::Size;
    }
}
TEST_TYPES(V, listInitialization, (ALL_VECTORS))
{
    listInitializationImpl<V, std::vector<V>>();
    listInitializationImpl<V, std::array<V, 9>>();
    listInitializationImpl<V, std::deque<V>>();

    // The following two crash (at least with AVX). Probably unaligned memory access.
    //listInitialization<V, std::forward_list<V>>();
    //listInitialization<V, std::list<V>>();
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "simulatorvideorenderercontrol.h"
#include <QFile>
#include <QAbstractVideoSurface>
#include <QVideoFrame>
#include <QVideoSurfaceFormat>
#include <QColor>
#include <QPainter>

QSimulatorVideoRendererControl::QSimulatorVideoRendererControl(QObject *parent) :
    QVideoRendererControl(parent)
        , mSurface(0)
        , mRunning(false)
{
}

QSimulatorVideoRendererControl::~QSimulatorVideoRendererControl()
{
}

QAbstractVideoSurface *QSimulatorVideoRendererControl::surface() const
{
    return mSurface;
}

void QSimulatorVideoRendererControl::setSurface(QAbstractVideoSurface *surface)
{
    mSurface = surface;
}

void QSimulatorVideoRendererControl::setImagePath(const QString &imagePath)
{
    if (QFile::exists(imagePath)) {
        mImage = QImage(imagePath);
    } else {
        mImage = QImage(800, 600, QImage::Format_RGB32);
        mImage.fill(qRgb(200, 50, 50));
        QPainter painter(&mImage);
        painter.drawText(0, 0, 800, 600, Qt::AlignCenter, imagePath);
    }
    if (mRunning)
        start();
}

void QSimulatorVideoRendererControl::start()
{
    if (!mSurface)
        return;
    stop();
    QVideoSurfaceFormat format(mImage.size(), QVideoFrame::Format_RGB32);
    mSurface->start(format);
    mSurface->present(mImage);
    mRunning = true;
}

void QSimulatorVideoRendererControl::stop()
{
    if (!mSurface)
        return;

    if (mSurface->isActive())
        mSurface->stop();
    mRunning = false;
}

const QImage * QSimulatorVideoRendererControl::image() const
{
    return &mImage;
}
<commit_msg>Don't use camelcase header includes for multimedia plugins<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "simulatorvideorenderercontrol.h"
#include <qabstractvideosurface.h>
#include <qvideoframe.h>
#include <qvideosurfaceformat.h>
#include <QFile>
#include <QColor>
#include <QPainter>

QSimulatorVideoRendererControl::QSimulatorVideoRendererControl(QObject *parent) :
    QVideoRendererControl(parent)
        , mSurface(0)
        , mRunning(false)
{
}

QSimulatorVideoRendererControl::~QSimulatorVideoRendererControl()
{
}

QAbstractVideoSurface *QSimulatorVideoRendererControl::surface() const
{
    return mSurface;
}

void QSimulatorVideoRendererControl::setSurface(QAbstractVideoSurface *surface)
{
    mSurface = surface;
}

void QSimulatorVideoRendererControl::setImagePath(const QString &imagePath)
{
    if (QFile::exists(imagePath)) {
        mImage = QImage(imagePath);
    } else {
        mImage = QImage(800, 600, QImage::Format_RGB32);
        mImage.fill(qRgb(200, 50, 50));
        QPainter painter(&mImage);
        painter.drawText(0, 0, 800, 600, Qt::AlignCenter, imagePath);
    }
    if (mRunning)
        start();
}

void QSimulatorVideoRendererControl::start()
{
    if (!mSurface)
        return;
    stop();
    QVideoSurfaceFormat format(mImage.size(), QVideoFrame::Format_RGB32);
    mSurface->start(format);
    mSurface->present(mImage);
    mRunning = true;
}

void QSimulatorVideoRendererControl::stop()
{
    if (!mSurface)
        return;

    if (mSurface->isActive())
        mSurface->stop();
    mRunning = false;
}

const QImage * QSimulatorVideoRendererControl::image() const
{
    return &mImage;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/NDC.hh"

int main(int argc, char** argv) {
    log4cpp::Appender* appender =
        new log4cpp::OstreamAppender("default", &std::cout);

    log4cpp::Layout* layout = new log4cpp::BasicLayout();
    appender->setLayout(layout);

    log4cpp::Category& root = log4cpp::Category::getRoot();
    root.setAppender(appender);
    root.setPriority(log4cpp::Priority::ERROR);

    log4cpp::Category& sub1 =
        log4cpp::Category::getInstance(std::string("sub1"));

    log4cpp::Category& sub2 =
        log4cpp::Category::getInstance(std::string("sub1.sub2"));

    std::cout << " root priority = " << root.getPriority() << std::endl;
    std::cout << " sub1 priority = " << sub1.getPriority() << std::endl;
    std::cout << " sub2 priority = " << sub2.getPriority() << std::endl;

    root.error("root error");
    root.warn("root warn");
    sub1.error("sub1 error");
    sub1.warn("sub1 warn");
    sub2.error("sub2 error");
    sub2.warn("sub2 warn");

    sub1.setPriority(log4cpp::Priority::INFO);
    std::cout << " root priority = " << root.getPriority() << std::endl;
    std::cout << " sub1 priority = " << sub1.getPriority() << std::endl;
    std::cout << " sub2 priority = " << sub2.getPriority() << std::endl;

    std::cout << "priority info" << std::endl;
    root.error("root error");
    root.warn("root warn");
    sub1.error("sub1 error");
    sub1.warn("sub1 warn");
    sub2.error("sub2 error");
    sub2.warn("sub2 warn");

    sub2.warnStream() << "streamed warn";

    sub2 << log4cpp::Priority::WARN << "warn2.." << "..warn3..value=" << 0 <<
        log4cpp::CategoryStream::ENDLINE << "..warn4";

    log4cpp::Category::shutdown();
}
<commit_msg>Added test line for printf style logging: ie. info("%s%d", "bla", 123)<commit_after>#include <stdio.h>
#include <iostream>
#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/NDC.hh"

int main(int argc, char** argv) {
    log4cpp::Appender* appender =
        new log4cpp::OstreamAppender("default", &std::cout);

    log4cpp::Layout* layout = new log4cpp::BasicLayout();
    appender->setLayout(layout);

    log4cpp::Category& root = log4cpp::Category::getRoot();
    root.setAppender(appender);
    root.setPriority(log4cpp::Priority::ERROR);

    log4cpp::Category& sub1 =
        log4cpp::Category::getInstance(std::string("sub1"));

    log4cpp::Category& sub2 =
        log4cpp::Category::getInstance(std::string("sub1.sub2"));

    std::cout << " root priority = " << root.getPriority() << std::endl;
    std::cout << " sub1 priority = " << sub1.getPriority() << std::endl;
    std::cout << " sub2 priority = " << sub2.getPriority() << std::endl;

    root.error("root error");
    root.warn("root warn");
    sub1.error("sub1 error");
    sub1.warn("sub1 warn");
    sub2.error("sub2 error");
    sub2.warn("sub2 warn");

    sub1.setPriority(log4cpp::Priority::INFO);
    std::cout << " root priority = " << root.getPriority() << std::endl;
    std::cout << " sub1 priority = " << sub1.getPriority() << std::endl;
    std::cout << " sub2 priority = " << sub2.getPriority() << std::endl;

    std::cout << "priority info" << std::endl;
    root.error("root error");
    root.warn("root warn");
    sub1.error("sub1 error");
    sub1.warn("sub1 warn");
    sub2.error("sub2 error");
    sub2.warn("sub2 warn");
    sub2.error("%s %s %d", "test", "vform", 123);
    sub2.warnStream() << "streamed warn";

    sub2 << log4cpp::Priority::WARN << "warn2.." << "..warn3..value=" << 0 <<
        log4cpp::CategoryStream::ENDLINE << "..warn4";

    log4cpp::Category::shutdown();
}
<|endoftext|>


<commit_before>#include <smartref/smartref.h>

#include <type_traits>

REFLECTABLE(member);

namespace tests {

using smartref::using_;

//! These tests check for existence of the member() member-function.
namespace test_existence {

template<typename T>
constexpr auto has_member(int) -> decltype(std::declval<T &>().member(), bool{}) {return true;}
template<typename T>
constexpr auto has_member(...) {return false;}

struct EmptyClass {};

struct NonConstMemberClass
{
  void member() {}
};

struct ConstMemberClass
{
  void member() const {}
};

struct MixedMemberClass
{
  void member() {}
  void member() const {}
};

////////////////////////////////
// non-const member functions //
////////////////////////////////

static_assert(!has_member<using_<EmptyClass>>(0),
              "TEST FAILED: using_<EmptyClass> seems to have a member-function!");

static_assert(has_member<using_<NonConstMemberClass>>(0),
              "TEST FAILED: using_<NonConstMemberClass> doesn't seem to have a member-function!");

static_assert(has_member<using_<ConstMemberClass>>(0),
              "TEST FAILED: using_<ConstMemberClass> doesn't seem to have a member-function!");

static_assert(has_member<using_<MixedMemberClass>>(0),
              "TEST FAILED: using_<MixedMemberClass> doesn't seem to have a member-function!");

////////////////////////////
// const member functions //
////////////////////////////

static_assert(!has_member<const using_<EmptyClass>>(0),
              "TEST FAILED: const using_<EmptyClass> seems to have a const member-function!");

static_assert(!has_member<const using_<NonConstMemberClass>>(0),
              "TEST FAILED: const using_<NonConstMemberClass> seem to have a const member-function!");

static_assert(has_member<const using_<ConstMemberClass>>(0),
              "TEST FAILED: const using_<ConstMemberClass> doesn't seem to have a const member-function!");

static_assert(has_member<const using_<MixedMemberClass>>(0),
              "TEST FAILED: const using_<MixedMemberClass> doesn't seem to have a const member-function!");

} // namespace test_existence
} // namespace tests
<commit_msg>Temporary work around for the __LINE__ conflict.<commit_after>#include <smartref/smartref.h>

#include <type_traits>

// TODO: Fix the issue that causes conflicts when using REFLECTABLE from within two separate files on the same line.
REFLECTABLE(member);

namespace tests {

using smartref::using_;

//! These tests check for existence of the member() member-function.
namespace test_existence {

template<typename T>
constexpr auto has_member(int) -> decltype(std::declval<T &>().member(), bool{}) {return true;}
template<typename T>
constexpr auto has_member(...) {return false;}

struct EmptyClass {};

struct NonConstMemberClass
{
  void member() {}
};

struct ConstMemberClass
{
  void member() const {}
};

struct MixedMemberClass
{
  void member() {}
  void member() const {}
};

////////////////////////////////
// non-const member functions //
////////////////////////////////

static_assert(!has_member<using_<EmptyClass>>(0),
              "TEST FAILED: using_<EmptyClass> seems to have a member-function!");

static_assert(has_member<using_<NonConstMemberClass>>(0),
              "TEST FAILED: using_<NonConstMemberClass> doesn't seem to have a member-function!");

static_assert(has_member<using_<ConstMemberClass>>(0),
              "TEST FAILED: using_<ConstMemberClass> doesn't seem to have a member-function!");

static_assert(has_member<using_<MixedMemberClass>>(0),
              "TEST FAILED: using_<MixedMemberClass> doesn't seem to have a member-function!");

////////////////////////////
// const member functions //
////////////////////////////

static_assert(!has_member<const using_<EmptyClass>>(0),
              "TEST FAILED: const using_<EmptyClass> seems to have a const member-function!");

static_assert(!has_member<const using_<NonConstMemberClass>>(0),
              "TEST FAILED: const using_<NonConstMemberClass> seem to have a const member-function!");

static_assert(has_member<const using_<ConstMemberClass>>(0),
              "TEST FAILED: const using_<ConstMemberClass> doesn't seem to have a const member-function!");

static_assert(has_member<const using_<MixedMemberClass>>(0),
              "TEST FAILED: const using_<MixedMemberClass> doesn't seem to have a const member-function!");

} // namespace test_existence
} // namespace tests
<|endoftext|>


<commit_before>/**
 * @author : xiaozhuai
 * @date   : 17/3/19
 */

#include "EventLoop.h"

ClientInfo* EventLoop::client_list[MAX_ALLOWED_CLIENT];
struct ev_loop* EventLoop::main_loop;
ev_io EventLoop::ev_io_accept;
int EventLoop::serv_sock;
http_parser_settings EventLoop::settings;
string EventLoop::listen_addr;
int EventLoop::port;

int EventLoop::on_url(http_parser *parser, const char *at, size_t length) {
    int fd = ((ClientInfo*)parser->data)->fd;
    string url(at, length);
    ClientInfo* client = client_list[fd];

    client->url = url;

    client->urlEndWithSlash = (url[url.length()-1] == '/');

    client->parser = parser;

    string filePath = SERV_ENV.getAbsoluteWebRoot()+url;
    client->file = new FileHandler(filePath);
    LOGI("GET %s [%d]", url, fd);
    return 0;
}

int EventLoop::on_message_complete(http_parser *parser) {
    int fd = ((ClientInfo*)parser->data)->fd;
    ClientInfo* client = client_list[fd];
    client->read_complete = true;
    LOGD("on_message_complete [%d]", fd);

    return 0;
}

void EventLoop::close_client(int fd) {
    ClientInfo *client = client_list[fd];
    if(client != NULL){
        if(client->io!=NULL){
            ev_io_stop(main_loop, client->io);
        }
        delete(client);
        client_list[fd] = NULL;
    }
}

void EventLoop::accept_handler(struct ev_loop *loop, ev_io *ev_io_accept, int e) {
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    int client_sock;
    ev_io *ev_io_client = (struct ev_io*) malloc(sizeof(struct ev_io));
    if(ev_io_client == NULL) {
        LOGW("malloc error in accept_cb");
        return ;
    }
    if(EV_ERROR & e) {
        LOGW("error event in accept");
        return ;
    }
    client_sock = accept(ev_io_accept->fd, (struct sockaddr*)&client_addr, &client_len);
    if(client_sock < 0){
        LOGW("accept error");
        return;
    }
    if(client_sock > MAX_ALLOWED_CLIENT) {
        LOGW("fd out of range [%d]", client_sock);
        close(client_sock);
        return;
    }
    if(client_list[client_sock] != NULL) {
        printf("client_sock not NULL, fd is [%d]\n", client_sock);
        return;
    }
    LOGD("client connected [%d]", client_sock);
    client_list[client_sock] = new ClientInfo(client_sock, ev_io_client);

    ev_io_init(ev_io_client, client_io_handler, client_sock, EV_READ | EV_WRITE);
    ev_io_start(main_loop, ev_io_client);
}

void EventLoop::client_io_handler(struct ev_loop *loop, struct ev_io *ev_io_client, int e) {

    int fd = ev_io_client->fd;
    ClientInfo* client = client_list[fd];

    if(EV_ERROR & e){
        LOGW("error client io event [%d]", fd);
        close_client(fd);
        return;
    }

    if(EV_READ & e){
        LOGD("client io read event [%d]", fd);
        char buffer[READ_SOCKET_BUFFER_MAX_SIZE+1];     // last byte '\0'
        int n;
        if(ioctl(fd, FIONREAD, &n)){
            LOGW("ioctl socket FIONREAD err [%d]", fd);
            close_client(fd);
            return;
        }

        size_t readSize = (size_t)(n<READ_SOCKET_BUFFER_MAX_SIZE ? n : READ_SOCKET_BUFFER_MAX_SIZE);

        size_t recved = (size_t)recv(fd, buffer, readSize, 0);
        if(recved < 0) {
            LOGW("read client err [%d]", fd);
            return;
        }
        if(recved == 0) {
            LOGD("client disconnected [%d]", fd);
            close_client(fd);
            return;
        } else {
            buffer[recved] = '\0';
            //LOGI("receive client message [%d]: %s\n", fd, buffer);
            http_parser *parser = client->parser;
            if(parser==NULL){
                parser = (http_parser *)malloc(sizeof(http_parser));
                http_parser_init(parser, HTTP_REQUEST);
                parser->data = client;
            }
            size_t nparsed = http_parser_execute(parser, &settings, buffer, recved);
            if (parser->upgrade) {
                LOGW("do not support protocol upgrade [%d]", fd);
                close_client(fd);
            } else if (nparsed != recved) {
                LOGW("parse http error, msg: %s [%d]", http_errno_description(parser->http_errno), fd);
                close_client(fd);
            }
        }
        return;
    }

    if((EV_WRITE & e) && client->read_complete){
        LOGD("client io write event [%d]", fd);

        if(!ACCESS_RULE.permissible(client->url)){             // check permission in .efserv_access
            Response::respondErr(fd, 403);
            goto end_write;
        }

        if(!client->file->exist()){                            // 404
            Response::respondErr(fd, 404);
            goto end_write;
        }

        if(outOfWebRoot(client)){
            Response::respondErr(fd, 403);
            goto end_write;
        }

        if(client->file->isFile()){                                                // is file

            if(client->urlEndWithSlash){                                           // if end with '/', it's considered to be a directory, but it's a file, so 404
                Response::respondErr(fd, 404);
                goto end_write;
            }

            FILE* file_fp = client->file_fp;
            if(file_fp == NULL){
                file_fp = fopen(client->file->getAbsolutePath().c_str(), "rb");
                if(file_fp==NULL){             // 404
                    Response::respondErr(fd, 404);
                    goto end_write;
                }
                client->file_fp = file_fp;
                off_t content_length = client->file->size();
                Response::respondHeader(fd, client->file->getMimeType(), content_length);
            }

            if(feof(file_fp)) goto end_write;

            int file_fd = fileno(file_fp);
            int n;
            if(ioctl(file_fd, FIONREAD, &n)){
                LOGW("ioctl file FIONREAD err [%d]", fd);
                close_client(fd);
                return;
            }

            char buffer[READ_FILE_BUFFER_MAX_SIZE];
            size_t readSize = (size_t)(n<READ_FILE_BUFFER_MAX_SIZE ? n : READ_FILE_BUFFER_MAX_SIZE);

            if(readSize==0) readSize ++;    // attempt to reach eof

            size_t len = fread(buffer, 1, readSize, file_fp);

            if(len==0) goto wait_next_write;

            Response::respondContent(fd, buffer, len);
            goto wait_next_write;
        }else if(client->file->isDir()){                                             // is dir

            if(!client->urlEndWithSlash){                                            // if not end with '/', it's considered to be a file, but it's a dir, redirect to add a '/'
                Response::respondRedirection(fd, 301, client->url+"/");
                goto end_write;
            }

            if(stoi(SERV_ENV.getConfig(KEY_DIR_INDEXS, DEFAULT_DIR_INDEXS))) {       // dir indexs enable
                vector<FileHandler> files = client->file->listDir();
                Response::respondIndexs(fd, files, client->url);
                goto end_write;
            }else{                                                                   // of course 403
                Response::respondErr(fd, 403);
                goto end_write;
            }
        }else{                                                                       // 500
            Response::respondErr(fd, 500);
            goto end_write;
        }

        end_write:
        close_client(fd);

        wait_next_write:

        return;
    }

}

void EventLoop::init() {
    main_loop = ev_default_loop(0);

    settings.on_url = on_url;
    settings.on_message_complete = on_message_complete;

    Response::loadTpl();
}

void EventLoop::start() {
    serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;

    listen_addr = SERV_ENV.getConfig(KEY_LISTEN, DEFAULT_LISTEN);
    int port = stoi(SERV_ENV.getConfig(KEY_PORT, DEFAULT_PORT));

    serv_addr.sin_addr.s_addr = inet_addr(listen_addr.c_str());
    serv_addr.sin_port = htons(port);

    if( ::bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) != 0 ){
        LOGE("addr bind error");
        exit(1);
    }

    if( listen(serv_sock, SOMAXCONN) < 0 ) {
        LOGE("listen error");
        exit(1);
    }

    int bReuseaddr=1;
    if(setsockopt(serv_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&bReuseaddr, sizeof(bReuseaddr)) != 0) {
        printf("set sock option error in reuse addr[%d]", serv_sock);
        exit(1);
    }

    LOGI("Listen %s%s:%d%s ......",
         ANSI_COLOR_BLUE,
         SERV_ENV.getConfig(KEY_LISTEN, DEFAULT_LISTEN),
         stoi(SERV_ENV.getConfig(KEY_PORT, DEFAULT_PORT)),
         ANSI_COLOR_NORMAL
    );

    ev_io_init(&ev_io_accept, accept_handler, serv_sock, EV_READ);
    ev_io_start(main_loop, &ev_io_accept);
    ev_run(main_loop, 0);

}<commit_msg>type conversion<commit_after>/**
 * @author : xiaozhuai
 * @date   : 17/3/19
 */

#include "EventLoop.h"

ClientInfo* EventLoop::client_list[MAX_ALLOWED_CLIENT];
struct ev_loop* EventLoop::main_loop;
ev_io EventLoop::ev_io_accept;
int EventLoop::serv_sock;
http_parser_settings EventLoop::settings;
string EventLoop::listen_addr;
int EventLoop::port;

int EventLoop::on_url(http_parser *parser, const char *at, size_t length) {
    int fd = ((ClientInfo*)parser->data)->fd;
    string url(at, length);
    ClientInfo* client = client_list[fd];

    client->url = url;

    client->urlEndWithSlash = (url[url.length()-1] == '/');

    client->parser = parser;

    string filePath = SERV_ENV.getAbsoluteWebRoot()+url;
    client->file = new FileHandler(filePath);
    LOGI("GET %s [%d]", url, fd);
    return 0;
}

int EventLoop::on_message_complete(http_parser *parser) {
    int fd = ((ClientInfo*)parser->data)->fd;
    ClientInfo* client = client_list[fd];
    client->read_complete = true;
    LOGD("on_message_complete [%d]", fd);

    return 0;
}

void EventLoop::close_client(int fd) {
    ClientInfo *client = client_list[fd];
    if(client != NULL){
        if(client->io!=NULL){
            ev_io_stop(main_loop, client->io);
        }
        delete(client);
        client_list[fd] = NULL;
    }
}

void EventLoop::accept_handler(struct ev_loop *loop, ev_io *ev_io_accept, int e) {
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    int client_sock;
    ev_io *ev_io_client = (struct ev_io*) malloc(sizeof(struct ev_io));
    if(ev_io_client == NULL) {
        LOGW("malloc error in accept_cb");
        return ;
    }
    if(EV_ERROR & e) {
        LOGW("error event in accept");
        return ;
    }
    client_sock = accept(ev_io_accept->fd, (struct sockaddr*)&client_addr, &client_len);
    if(client_sock < 0){
        LOGW("accept error");
        return;
    }
    if(client_sock > MAX_ALLOWED_CLIENT) {
        LOGW("fd out of range [%d]", client_sock);
        close(client_sock);
        return;
    }
    if(client_list[client_sock] != NULL) {
        printf("client_sock not NULL, fd is [%d]\n", client_sock);
        return;
    }
    LOGD("client connected [%d]", client_sock);
    client_list[client_sock] = new ClientInfo(client_sock, ev_io_client);

    ev_io_init(ev_io_client, client_io_handler, client_sock, EV_READ | EV_WRITE);
    ev_io_start(main_loop, ev_io_client);
}

void EventLoop::client_io_handler(struct ev_loop *loop, struct ev_io *ev_io_client, int e) {

    int fd = ev_io_client->fd;
    ClientInfo* client = client_list[fd];

    if(EV_ERROR & e){
        LOGW("error client io event [%d]", fd);
        close_client(fd);
        return;
    }

    if(EV_READ & e){
        LOGD("client io read event [%d]", fd);
        char buffer[READ_SOCKET_BUFFER_MAX_SIZE+1];     // last byte '\0'
        int n;
        if(ioctl(fd, FIONREAD, &n)){
            LOGW("ioctl socket FIONREAD err [%d]", fd);
            close_client(fd);
            return;
        }

        size_t readSize = (size_t)(n<READ_SOCKET_BUFFER_MAX_SIZE ? n : READ_SOCKET_BUFFER_MAX_SIZE);

        ssize_t recved = (size_t)recv(fd, buffer, readSize, 0);
        if(recved < 0) {
            LOGW("read client err [%d]", fd);
            return;
        }
        if(recved == 0) {
            LOGD("client disconnected [%d]", fd);
            close_client(fd);
            return;
        } else {
            buffer[recved] = '\0';
            //LOGI("receive client message [%d]: %s\n", fd, buffer);
            http_parser *parser = client->parser;
            if(parser==NULL){
                parser = (http_parser *)malloc(sizeof(http_parser));
                http_parser_init(parser, HTTP_REQUEST);
                parser->data = client;
            }
            size_t nparsed = http_parser_execute(parser, &settings, buffer, (size_t)recved);
            if (parser->upgrade) {
                LOGW("do not support protocol upgrade [%d]", fd);
                close_client(fd);
            } else if (nparsed != (size_t)recved) {
                LOGW("parse http error, msg: %s [%d]", http_errno_description(parser->http_errno), fd);
                close_client(fd);
            }
        }
        return;
    }

    if((EV_WRITE & e) && client->read_complete){
        LOGD("client io write event [%d]", fd);

        if(!ACCESS_RULE.permissible(client->url)){             // check permission in .efserv_access
            Response::respondErr(fd, 403);
            goto end_write;
        }

        if(!client->file->exist()){                            // 404
            Response::respondErr(fd, 404);
            goto end_write;
        }

        if(outOfWebRoot(client)){
            Response::respondErr(fd, 403);
            goto end_write;
        }

        if(client->file->isFile()){                                                // is file

            if(client->urlEndWithSlash){                                           // if end with '/', it's considered to be a directory, but it's a file, so 404
                Response::respondErr(fd, 404);
                goto end_write;
            }

            FILE* file_fp = client->file_fp;
            if(file_fp == NULL){
                file_fp = fopen(client->file->getAbsolutePath().c_str(), "rb");
                if(file_fp==NULL){             // 404
                    Response::respondErr(fd, 404);
                    goto end_write;
                }
                client->file_fp = file_fp;
                off_t content_length = client->file->size();
                Response::respondHeader(fd, client->file->getMimeType(), content_length);
            }

            if(feof(file_fp)) goto end_write;

            int file_fd = fileno(file_fp);
            int n;
            if(ioctl(file_fd, FIONREAD, &n)){
                LOGW("ioctl file FIONREAD err [%d]", fd);
                close_client(fd);
                return;
            }

            char buffer[READ_FILE_BUFFER_MAX_SIZE];
            size_t readSize = (size_t)(n<READ_FILE_BUFFER_MAX_SIZE ? n : READ_FILE_BUFFER_MAX_SIZE);

            if(readSize==0) readSize ++;    // attempt to reach eof

            size_t len = fread(buffer, 1, readSize, file_fp);

            if(len==0) goto wait_next_write;

            Response::respondContent(fd, buffer, len);
            goto wait_next_write;
        }else if(client->file->isDir()){                                             // is dir

            if(!client->urlEndWithSlash){                                            // if not end with '/', it's considered to be a file, but it's a dir, redirect to add a '/'
                Response::respondRedirection(fd, 301, client->url+"/");
                goto end_write;
            }

            if(stoi(SERV_ENV.getConfig(KEY_DIR_INDEXS, DEFAULT_DIR_INDEXS))) {       // dir indexs enable
                vector<FileHandler> files = client->file->listDir();
                Response::respondIndexs(fd, files, client->url);
                goto end_write;
            }else{                                                                   // of course 403
                Response::respondErr(fd, 403);
                goto end_write;
            }
        }else{                                                                       // 500
            Response::respondErr(fd, 500);
            goto end_write;
        }

        end_write:
        close_client(fd);

        wait_next_write:

        return;
    }

}

void EventLoop::init() {
    main_loop = ev_default_loop(0);

    settings.on_url = on_url;
    settings.on_message_complete = on_message_complete;

    Response::loadTpl();
}

void EventLoop::start() {
    serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;

    listen_addr = SERV_ENV.getConfig(KEY_LISTEN, DEFAULT_LISTEN);
    int port = stoi(SERV_ENV.getConfig(KEY_PORT, DEFAULT_PORT));

    serv_addr.sin_addr.s_addr = inet_addr(listen_addr.c_str());
    serv_addr.sin_port = htons(port);

    if( ::bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) != 0 ){
        LOGE("addr bind error");
        exit(1);
    }

    if( listen(serv_sock, SOMAXCONN) < 0 ) {
        LOGE("listen error");
        exit(1);
    }

    int bReuseaddr=1;
    if(setsockopt(serv_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&bReuseaddr, sizeof(bReuseaddr)) != 0) {
        printf("set sock option error in reuse addr[%d]", serv_sock);
        exit(1);
    }

    LOGI("Listen %s%s:%d%s ......",
         ANSI_COLOR_BLUE,
         SERV_ENV.getConfig(KEY_LISTEN, DEFAULT_LISTEN),
         stoi(SERV_ENV.getConfig(KEY_PORT, DEFAULT_PORT)),
         ANSI_COLOR_NORMAL
    );

    ev_io_init(&ev_io_accept, accept_handler, serv_sock, EV_READ);
    ev_io_start(main_loop, &ev_io_accept);
    ev_run(main_loop, 0);

}<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "stan/prob/distributions_uniform.hpp"
#include "stan/agrad/agrad.hpp"

using stan::agrad::var;

template<typename T_y, typename T_lb, typename T_ub, bool propto=true>
var getResult(T_y y1, T_y y2, T_lb lb, T_ub ub) {
  return stan::prob::uniform_log<propto,T_y,T_lb,T_ub>(y1,lb,ub)
    - stan::prob::uniform_log<propto,T_y,T_lb,T_ub>(y2,lb,ub);
}

class AgradDistributionsPropto : public testing::Test {
  protected:
  virtual void SetUp() {
    y1 = 0.3;
    y2 = 5.0;
    lb = 0.5;
    ub = 11.0;

    expected = getResult<var,var,var,false>(y1,y2,lb,ub);
  }
  double y1;
  double y2;
  double lb;
  double ub;
  var expected;
  var result;
};
TEST_F(AgradDistributionsPropto,Uniform) {
  result = getResult<var,var,var>(y1,y2,lb,ub);
  EXPECT_FLOAT_EQ(expected.val(),result.val());
}
TEST_F(AgradDistributionsPropto,UniformY) {
  result = getResult<double,var,var>(y1,y2,lb,ub);
  EXPECT_FLOAT_EQ(expected.val(),result.val());
}
TEST_F(AgradDistributionsPropto,UniformYLb) {
  result = getResult<double,double,var>(y1,y2,lb,ub);
  EXPECT_FLOAT_EQ(expected.val(),result.val());
}
TEST_F(AgradDistributionsPropto,UniformYUb) {
  result = getResult<double,var,double>(y1,y2,lb,ub);
  EXPECT_FLOAT_EQ(expected.val(),result.val());
}
TEST_F(AgradDistributionsPropto,UniformLb) {
  result = getResult<var,double,var>(y1,y2,lb,ub);
  EXPECT_FLOAT_EQ(expected.val(),result.val());
}
TEST_F(AgradDistributionsPropto,UniformLbUb) {
  result = getResult<var,double,double>(y1,y2,lb,ub);
  EXPECT_FLOAT_EQ(expected.val(),result.val());
}
TEST_F(AgradDistributionsPropto,UniformUb) {
  result = getResult<var,var,double>(y1,y2,lb,ub);
  EXPECT_FLOAT_EQ(expected.val(),result.val());
}
<commit_msg>refactoring distributions: uniform<commit_after><|endoftext|>


<commit_before>#include "MEMCARD.H"

#include "SPECIFIC.H"

#include <LIBMCRD.H>

unsigned char mcInit;
unsigned char mcStatus;
unsigned long mcNumFiles;
unsigned char mcBlocksFree;
char mcFileNames[7][20];
int mcFileLengths[7];
static unsigned char mcActualStatus;

int dword_A1AA0 = 0x2A;//init me 0x2a? looks like name string

void mcDir()//61EE8
{
	int i; // $s3
	int j; // $s4
	int k; // $s1
	struct DIRENTRY* dir;// $s2

#if 0
	int a0 = 0;
	int a1 = dword_A1AA0;

	//lui	$v0, 0x001F0000
	//sw	$s2, 0x30 + var_10($sp)
	struct TSV* a2 = &tsv_buffer[0];

	//sw	$s0, 0x30 + var_18($sp)
	int s0 = 0xF;
	a3 = &mcNumFiles;
	//sw	$ra, 0x30 + var_4($sp)
	//sw	$s4, 0x30 + var_8($sp)
	//sw	$s3, 0x30 + var_C($sp)
	//sw	$s1, 0x30 + var_14($sp)
	//sw	$zero, 0x30 + var_20($sp)

	MemCardGetDirentry(0, dword_A1AA0, &tsv_buffer[0], &mcNumFiles, 0, 0);//	jal	sub_6B08C
	//sw	$s0, 0x30 + var_1C($sp)
	int s4 = 0;//j
	int s3 = 0;//i

	lw	$v0, 0x41E0($gp)
	sb	$s0, 0x41DC($gp)
	beqz	$v0, loc_62028
	move	$s1, $zero
	move	$s0, $s2
	addiu	$s2, $gp, 0x41E4

				 loc_61F50:
			 lw	$v0, 0x18($s0)
				 nop
				 addiu	$v1, $v0, 0x1FFF
				 bgez	$v1, loc_61F68
				 move	$a1, $s0
				 addiu	$v1, $v0, 0x3FFE

				 loc_61F68:
			 sra	$v1, 13
				 lbu	$v0, 0x41DC($gp)
				 lw	$a0, dword_800A202C
				 subu	$v0, $v1
				 sb	$v0, 0x41DC($gp)
				 lhu	$v1, 0x194($a0)
				 lw	$a0, dword_800A203C
				 li	$a2, 0xC
				 jal	sub_68A84
				 addu	$a0, $v1
				 bnez	$v0, loc_62014
				 nop
				 lwl	$v0, 3($s0)
				 lwr	$v0, 0($s0)
				 lwl	$v1, 7($s0)
				 lwr	$v1, 4($s0)
				 lwl	$a0, 0xB($s0)
				 lwr	$a0, 8($s0)
				 lwl	$a1, 0xF($s0)
				 lwr	$a1, 0xC($s0)
				 swl	$v0, 3($s2)
				 swr	$v0, 0($s2)
				 swl	$v1, 7($s2)
				 swr	$v1, 4($s2)
				 swl	$a0, 0xB($s2)
				 swr	$a0, 8($s2)
				 swl	$a1, 0xF($s2)
				 swr	$a1, 0xC($s2)
				 lwl	$v0, 0x13($s0)
				 lwr	$v0, 0x10($s0)
				 nop
				 swl	$v0, 0x13($s2)
				 swr	$v0, 0x10($s2)
				 addiu	$s2, 0x14
				 sll	$v0, $s4, 2
				 addiu	$s4, 1
				 addiu	$s1, 1
				 addiu	$v1, $gp, 0x4274
				 lw	$a0, 0x18($s0)
				 addu	$v0, $v1
				 sw	$a0, 0($v0)

				 loc_62014:
			 lw	$v0, 0x41E0($gp)
				 addiu	$s3, 1
				 sltu	$v0, $s3, $v0
				 bnez	$v0, loc_61F50
				 addiu	$s0, 0x28

				 loc_62028 :
				 lw	$ra, 0x30 + var_4($sp)
				 lw	$s4, 0x30 + var_8($sp)
				 lw	$s3, 0x30 + var_C($sp)
				 lw	$s2, 0x30 + var_10($sp)
				 sw	$s1, 0x41E0($gp)
				 lw	$s1, 0x30 + var_14($sp)
				 lw	$s0, 0x30 + var_18($sp)
				 jr	$ra
				 addiu	$sp, 0x30
				 # End of function sub_61EE8
#endif

}

void mcOpen(int sync)//6204C(<), 62730(<) (F)
{
	int i;

	mcInit = 1;
	mcNumFiles = 0;
	mcBlocksFree = 0;
	mcStatus = 4;
	mcActualStatus = 0;

	MemCardStart();

	if (sync != 0)
	{
		for (i = 0; i < 4; i++)
		{
			//loc_62084
			mcGetStatus();
			VSync(0);
		}
	}

	//loc_6209C
	return;
}

void mcClose()//620AC
{
	MemCardStop();
	mcInit = 0;

	return;
}

unsigned char mcGetStatus()//620CC,
{
	long stat; // $a0
	unsigned long cmd; // stack offset -16
	unsigned long res; // stack offset -12
#if 0

	int a0 = 1;

	//addiu	$a1, $sp, 0x20 + var_10
	//addiu	$a2, $sp, 0x20 + var_C
	//sw	$ra, 0x20 + var_4($sp)

	int v0 = 3;
	stat = MemCardSync(a0, &cmd, &res);
	if (stat != 0)
	{
		if (stat < 0)
		{
			if (stat == -1)
			{
				//loc_62120
				MemCardExist(0);
			}// j	loc_622C4 else on outer most brace
		}

		//loc_62110
		v0 = 2;
		if (stat == 1)
		{
			//loc_62178

		}//j	loc_622C4

	}//loc_62130

	//sw	$s0, 0x20 + var_8($sp)

				 loc_62130 :
			 lw	$v1, 0x20 + var_10($sp)
				 nop
				 bne	$v1, $v0, loc_62150
				 li	$v0, 6
				 li	$v0, 5
				 sb	$v0, 0x4270($gp)
				 j	loc_622C4
				 nop

				 loc_62150 :
			 bne	$v1, $v0, loc_62164
				 li	$v0, 2
				 sb	$v1, 0x4270($gp)
				 j	loc_622C4
				 nop

				 loc_62164 :
			 bne	$v1, $v0, loc_622C4
				 li	$v0, 4
				 sb	$v0, 0x4270($gp)
				 j	loc_622C4
				 nop

				 loc_62178 :
			 lw	$v1, 0x20 + var_10($sp)
				 nop
				 beq	$v1, $v0, loc_62210
				 sltiu	$v0, $v1, 3
				 beqz	$v0, loc_621A0
				 li	$s0, 3
				 beq	$v1, $a0, loc_621B8
				 nop
				 j	loc_622C4
				 nop

				 loc_621A0 :
			 beq	$v1, $s0, loc_6227C
				 li	$v0, 6
				 beq	$v1, $v0, loc_62298
				 nop
				 j	loc_622C4
				 nop

				 loc_621B8 :
			 lw	$v1, 0x20 + var_C($sp)
				 nop
				 beqz	$v1, loc_621D8
				 li	$v0, 3
				 beq	$v1, $v0, loc_621EC
				 li	$v0, 1
				 j	loc_62204
				 nop

				 loc_621D8 :
			 lbu	$v0, 0x41D8($gp)
				 nop
				 sb	$v0, 0x4270($gp)
				 j	loc_622C4
				 nop

				 loc_621EC :
			 jal	sub_6A6E4
				 move	$a0, $zero
				 li	$v1, 4
				 sb	$v1, 0x4270($gp)
				 j	loc_622C4
				 nop

				 loc_62204 :
			 sb	$v0, 0x4270($gp)
				 j	loc_622C4
				 nop

				 loc_62210 :
			 lw	$a0, 0x20 + var_C($sp)
				 li	$v0, 3
				 beq	$a0, $v0, loc_62248
				 sltiu	$v0, $a0, 4
				 beqz	$v0, loc_62238
				 li	$v0, 4
				 beqz	$a0, loc_6228C
				 li	$v0, 3
				 j	loc_6226C
				 nop

				 loc_62238 :
			 beq	$a0, $v0, loc_6225C
				 li	$v0, 3
				 j	loc_6226C
				 nop

				 loc_62248 :
			 jal	sub_61EE8
				 nop
				 sb	$zero, 0x41D8($gp)
				 j	loc_6228C
				 nop

				 loc_6225C :
			 sb	$v1, 0x4270($gp)
				 sb	$v1, 0x41D8($gp)
				 j	loc_622C4
				 nop

				 loc_6226C :
			 sb	$v0, 0x4270($gp)
				 sb	$v0, 0x41D8($gp)
				 j	loc_622C4
				 nop

				 loc_6227C :
			 lw	$v0, 0x20 + var_C($sp)
				 nop
				 bnez	$v0, loc_622B8
				 nop

				 loc_6228C :
			 sb	$zero, 0x4270($gp)
				 j	loc_622C4
				 nop

				 loc_62298 :
			 lw	$v0, 0x20 + var_C($sp)
				 nop
				 bnez	$v0, loc_622B8
				 nop
				 jal	sub_61EE8
				 nop
				 j	loc_6228C
				 nop

				 loc_622B8 :
			 jal	sub_6A6E4
				 move	$a0, $zero
				 sb	$s0, 0x4270($gp)

				 loc_622C4 :
				 lbu	$v0, 0x4270($gp)
				 lw	$ra, 0x20 + var_4($sp)
				 lw	$s0, 0x20 + var_8($sp)
				 jr	$ra
				 addiu	$sp, 0x20
				 # End of function sub_620CC
#endif

				 return -1;
}

long mcFormat()//622D8(<), 629BC(<) (F)
{
	unsigned long cmd;
	unsigned long res;

	MemCardSync(0, &cmd, &res);

	res = MemCardFormat(0);
	if (res == 0)
	{
		mcActualStatus = 0;
		mcDir();
	}

	//loc_6230C
	return res;
}<commit_msg>Add mcGetStatus<commit_after>#include "MEMCARD.H"

#include "SPECIFIC.H"

#include <LIBMCRD.H>

unsigned char mcInit;
unsigned char mcStatus;
unsigned long mcNumFiles;
unsigned char mcBlocksFree;
char mcFileNames[7][20];
int mcFileLengths[7];
static unsigned char mcActualStatus;

int dword_A1AA0 = 0x2A;//init me 0x2a? looks like name string

void mcDir()//61EE8
{
	int i; // $s3
	int j; // $s4
	int k; // $s1
	struct DIRENTRY* dir;// $s2

#if 0
	int a0 = 0;
	int a1 = dword_A1AA0;

	//lui	$v0, 0x001F0000
	//sw	$s2, 0x30 + var_10($sp)
	struct TSV* a2 = &tsv_buffer[0];

	//sw	$s0, 0x30 + var_18($sp)
	int s0 = 0xF;
	a3 = &mcNumFiles;
	//sw	$ra, 0x30 + var_4($sp)
	//sw	$s4, 0x30 + var_8($sp)
	//sw	$s3, 0x30 + var_C($sp)
	//sw	$s1, 0x30 + var_14($sp)
	//sw	$zero, 0x30 + var_20($sp)

	MemCardGetDirentry(0, dword_A1AA0, &tsv_buffer[0], &mcNumFiles, 0, 0);//	jal	sub_6B08C
	//sw	$s0, 0x30 + var_1C($sp)
	int s4 = 0;//j
	int s3 = 0;//i

	lw	$v0, 0x41E0($gp)
	sb	$s0, 0x41DC($gp)
	beqz	$v0, loc_62028
	move	$s1, $zero
	move	$s0, $s2
	addiu	$s2, $gp, 0x41E4

				 loc_61F50:
			 lw	$v0, 0x18($s0)
				 nop
				 addiu	$v1, $v0, 0x1FFF
				 bgez	$v1, loc_61F68
				 move	$a1, $s0
				 addiu	$v1, $v0, 0x3FFE

				 loc_61F68:
			 sra	$v1, 13
				 lbu	$v0, 0x41DC($gp)
				 lw	$a0, dword_800A202C
				 subu	$v0, $v1
				 sb	$v0, 0x41DC($gp)
				 lhu	$v1, 0x194($a0)
				 lw	$a0, dword_800A203C
				 li	$a2, 0xC
				 jal	sub_68A84
				 addu	$a0, $v1
				 bnez	$v0, loc_62014
				 nop
				 lwl	$v0, 3($s0)
				 lwr	$v0, 0($s0)
				 lwl	$v1, 7($s0)
				 lwr	$v1, 4($s0)
				 lwl	$a0, 0xB($s0)
				 lwr	$a0, 8($s0)
				 lwl	$a1, 0xF($s0)
				 lwr	$a1, 0xC($s0)
				 swl	$v0, 3($s2)
				 swr	$v0, 0($s2)
				 swl	$v1, 7($s2)
				 swr	$v1, 4($s2)
				 swl	$a0, 0xB($s2)
				 swr	$a0, 8($s2)
				 swl	$a1, 0xF($s2)
				 swr	$a1, 0xC($s2)
				 lwl	$v0, 0x13($s0)
				 lwr	$v0, 0x10($s0)
				 nop
				 swl	$v0, 0x13($s2)
				 swr	$v0, 0x10($s2)
				 addiu	$s2, 0x14
				 sll	$v0, $s4, 2
				 addiu	$s4, 1
				 addiu	$s1, 1
				 addiu	$v1, $gp, 0x4274
				 lw	$a0, 0x18($s0)
				 addu	$v0, $v1
				 sw	$a0, 0($v0)

				 loc_62014:
			 lw	$v0, 0x41E0($gp)
				 addiu	$s3, 1
				 sltu	$v0, $s3, $v0
				 bnez	$v0, loc_61F50
				 addiu	$s0, 0x28

				 loc_62028 :
				 lw	$ra, 0x30 + var_4($sp)
				 lw	$s4, 0x30 + var_8($sp)
				 lw	$s3, 0x30 + var_C($sp)
				 lw	$s2, 0x30 + var_10($sp)
				 sw	$s1, 0x41E0($gp)
				 lw	$s1, 0x30 + var_14($sp)
				 lw	$s0, 0x30 + var_18($sp)
				 jr	$ra
				 addiu	$sp, 0x30
				 # End of function sub_61EE8
#endif

}

void mcOpen(int sync)//6204C(<), 62730(<) (F)
{
	int i;

	mcInit = 1;
	mcNumFiles = 0;
	mcBlocksFree = 0;
	mcStatus = 4;
	mcActualStatus = 0;

	MemCardStart();

	if (sync != 0)
	{
		for (i = 0; i < 4; i++)
		{
			//loc_62084
			mcGetStatus();
			VSync(0);
		}
	}

	//loc_6209C
	return;
}

void mcClose()//620AC
{
	MemCardStop();
	mcInit = 0;

	return;
}

unsigned char mcGetStatus()//620CC(<), ? (F)
{
	long stat;
	unsigned long cmd;
	unsigned long res;

	stat = MemCardSync(1, &cmd, &res);

	//Locked, Asynchronous memory card function is running.
	if (stat == 0)
	{
		//loc_62130
		if(cmd == McFuncReadFile)
		{
			return mcStatus = 5;
		}
		else if(cmd == McFuncWriteData)
		{
			//loc_62150
			return mcStatus = 6;
		}
		else if(cmd == McFuncAccept)
		{
			//loc_62164
			return mcStatus = 4;
		}
	}
	else if(stat > 0)
	{
		//loc_62110
		if(stat == 1)
		{
			//loc_62178
			if(cmd == McFuncAccept)
			{
				//loc_62210
				if(res == 3)
				{
					//loc_62248
					mcDir();
					mcActualStatus = 0;
					mcStatus = 0;
				}
				else if(res > 3)
				{
					//loc_62238
					if(res == 4)
					{
						//loc_6225C
						mcActualStatus = mcStatus = cmd;
					}
					else
					{
						mcActualStatus = mcStatus = 3;
					}
				}
				else if(res == 0)
				{
					//loc_6228C
					mcStatus = 0;
				}
				else
				{
					mcActualStatus = mcStatus = 3;
				}

				return 3;
			}
			else if(cmd > McFuncAccept)
			{
				//loc_621A0
				if(cmd == McFuncReadFile)
				{
					//loc_6227C
					if(res != 0)
					{
						//loc_622B8
						MemCardAccept(0);
						mcStatus = 3;
					}
					else
					{
						//loc_6228C
						mcStatus = 0;
					}

					return res;
				}
				else if(cmd == McFuncWriteData)
				{
					//loc_62298
					if(res != 0)
					{
						MemCardAccept(0);
						mcStatus = 3;
					}
					else
					{
						mcStatus = 0;
					}

					return res;
				}

				return 6;
			}
			else if(cmd == stat)
			{
				//loc_621B8
				if(res == 0)
				{
					//loc_621D8
					return mcStatus = mcActualStatus;
				}
				else if(res == 3)
				{
					//loc_621EC
					MemCardAccept(0);
					mcStatus = 4;
					return 1;
				}
				else
				{
					//loc_62204
					mcStatus = 1;
					return 1;
				}
			}
		}

		return 2;
	}
	else if(stat == -1)
	{
		//loc_62120
		MemCardExist(0);
	}

	return -1;
}

long mcFormat()//622D8(<), 629BC(<) (F)
{
	unsigned long cmd;
	unsigned long res;

	MemCardSync(0, &cmd, &res);

	res = MemCardFormat(0);
	if (res == 0)
	{
		mcActualStatus = 0;
		mcDir();
	}

	//loc_6230C
	return res;
}<|endoftext|>


<commit_before>/*	____________________________________________________________________________

	                 Scanner Component for the Micro A Compiler

	                                mscan.h

	                              Version 2007 - 2016

	                           James L. Richards
	                     Last Update: August 28, 2007
	                      	   Nelson A Castillo
	                     Last Update: January 31, 2016

	The routines in this unit are based on those provided in the book
	"Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr.,
	Benjamin Cummings Publishing Co. (1991).

	See Section 2.2, pp. 25-29.
	____________________________________________________________________________
*/

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

extern ifstream sourceFile;
extern ofstream outFile, listFile;

#include "mscan.h"

// *******************
// **  Constructor  **
// *******************

Scanner::Scanner()
{
	tokenBuffer = "";
	lineBuffer = "";
	lineNumber = 0;
}

// ********************************
// **  Private Member Functions  **
// ********************************

void Scanner::BufferChar(char c)
{
	if (tokenBuffer.length() < ID_STRING_LEN){
		tokenBuffer += c;
	}
	//cerr << tokenBuffer << endl;
}
void Scanner::BufferString(char c)
{
	stringBuffer += c;
	//cerr << tokenBuffer << endl;
}

Token Scanner::CheckReserved()
{
	if (tolower(tokenBuffer) == "bool") return BOOL_SYM;
	if (tolower(tokenBuffer) == "break") return BREAK_SYM;
	if (tolower(tokenBuffer) == "case") return CASE_SYM;
	if (tolower(tokenBuffer) == "cheese") return CHEESE_SYM;
	if (tolower(tokenBuffer) == "decs") return DECS_SYM;
	if (tolower(tokenBuffer) == "do") return DO_SYM;
	if (tolower(tokenBuffer) == "else") return ELSE_SYM;
	if (tolower(tokenBuffer) == "end") return END_SYM;
	if (tolower(tokenBuffer) == "false") return FALSE_SYM;
	if (tolower(tokenBuffer) == "float") return FLOAT_SYM;
	if (tolower(tokenBuffer) == "for") return FOR_SYM;
	if (tolower(tokenBuffer) == "hiphip") return HIPHIP_SYM;
	if (tolower(tokenBuffer) == "if") return IF_SYM;
	if (tolower(tokenBuffer) == "int") return INT_SYM;
	if (tolower(tokenBuffer) == "listen") return LISTEN_SYM;
	if (tolower(tokenBuffer) == "otherwise") return OTHERWISE_SYM;
	if (tolower(tokenBuffer) == "select") return SELECT_SYM;
	if (tolower(tokenBuffer) == "shout") return SHOUT_SYM;
	if (tolower(tokenBuffer) == "then") return THEN_SYM;
	if (tolower(tokenBuffer) == "true") return TRUE_SYM;
	if (tolower(tokenBuffer) == "while") return WHILE_SYM;

	return ID;
}

void Scanner::ClearBuffer()
{
	tokenBuffer = "";
	stringBuffer = "";
}

void Scanner::LexicalError(char& c, string& errorExp="")
{
	cout << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber+1 << '.' << endl;
	listFile << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber+1 << '.' << endl;
	if(errorExp!=""){
		//TODO :: I was starting with the comment but
		//I need to ampliate the code
	}
	c = NextChar();
}

char Scanner::NextChar()
{
	char c;

	sourceFile.get(c);
	if (c == '\n')
	{
		listFile.width(6);
		listFile << ++lineNumber << "  " << lineBuffer << endl;
		lineBuffer = "";
	} else{
		lineBuffer += c;
	}
	return c;
}

// *******************************
// **  Public Member Functions  **
// *******************************

Token Scanner::GetNextToken()
{
	char currentChar, c;

	ClearBuffer();
	currentChar = NextChar();
	while (!sourceFile.eof())
	{
		if (isspace(currentChar)){
			currentChar = NextChar(); // do nothing
		} else if (isalpha(currentChar))
		{ // identifier
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isalnum(c) || c == '_')
			{
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			return CheckReserved();
		} else if (isdigit(currentChar)){ // integer or float literals
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isdigit(c))
			{
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			/* Check if it is a float */
			if (c == '.')
			{
				currentChar = NextChar();
				c = sourceFile.peek();
				if (!isdigit(c))
					LexicalError(currentChar);
				BufferChar(currentChar);
				while (isdigit(c))
				{
					currentChar = NextChar();
					BufferChar(currentChar);
					c = sourceFile.peek();
				}
				if (c == 'e' || c == 'E')
				{
					currentChar = NextChar();
					c = sourceFile.peek();
					if(c != '+' && c!= '-'){
						LexicalError(currentChar);
					}
					BufferChar(currentChar);
					currentChar = NextChar();
					c = sourceFile.peek();
					if (!isdigit(c))
						LexicalError(currentChar);
					BufferChar(currentChar);
					while (isdigit(c))
					{
						currentChar = NextChar();
						BufferChar(currentChar);
						c = sourceFile.peek();
					}
				}
				return FLOAT_LIT;
			}
			return INT_LIT;
		} else if (currentChar == '"'){
			// string literal
			// BufferString(currentChar);
			do
			{
				currentChar = NextChar();
				// cout << currentChar <<endl;
				if(currentChar == '"' & sourceFile.peek()!='"'){
					// BufferString(currentChar);
					// cout << "________________________" <<endl;
					// cout << stringBuffer <<endl;
					// cout << "________________________" <<endl;
					return CHEESE_LIT;
				}else if(currentChar == '"' & sourceFile.peek()=='"'){
					currentChar = NextChar();
				}
				BufferString(currentChar);
			} while (sourceFile.peek()!='\n');
			return CHEESE_LIT;
		} else if (currentChar == '('){
			return LBANANA;
		} else if (currentChar == ')'){
			return RBANANA;
		} else if (currentChar == '['){
			return LSTAPLE;
		} else if (currentChar == ']'){
			return RSTAPLE;
		} else if (currentChar == '{'){
			return LMUSTACHE;
		} else if (currentChar == '}'){
			return RMUSTACHE;
		} else if (currentChar == ';'){
			return SEMICOLON;
		} else if (currentChar == ':'){
			return COLON;
		} else if (currentChar == ','){
			return COMMA;
		} else if (currentChar == '+'){
			BufferChar(currentChar);
			return PLUS_OP;
		} else if (currentChar == '*'){
			BufferChar(currentChar);
			return MULT_OP;
		} else if (currentChar == '/'){
			if (sourceFile.peek() == ':') {// comment
				do{  // skip comment
					currentChar = NextChar();
					if(currentChar == ':'){
						currentChar = NextChar();
						if(currentChar == '/'){
							break;
						}
					}
				} while (!sourceFile.eof());
			}
			BufferChar(currentChar);
			return DIV_OP;
		} else if (currentChar == '=') {
			if (sourceFile.peek() == '=')
			{
				currentChar = NextChar();
				return EQ_OP1;
			}
			currentChar = NextChar();
			return ASSIGN_OP;
		} else if (currentChar == '!') {
			if (sourceFile.peek() == '!')
			{
				currentChar = NextChar();
				return EQ_OP2;
			}
			else if(sourceFile.peek() == '='){
				currentChar = NextChar();
				return NE_OP;
			}
		} else if (currentChar == '<') {
			if (sourceFile.peek() == '=')
			{
				currentChar = NextChar();
				return LE_OP;
			}
			currentChar = NextChar();
			return LT_OP;
		} else if (currentChar == '>') {
			if (sourceFile.peek() == '=')
			{
				currentChar = NextChar();
				return GE_OP;
			}
			currentChar = NextChar();
			return GT_OP;
		} else if (currentChar == '-'){
			if (sourceFile.peek() == '-') {// comment
				do{ // skip comment
					currentChar = NextChar();
				} while (currentChar != '\n');
			} else{
				BufferChar(currentChar); // minus operator
				return MINUS_OP;
			}
		} else{
			LexicalError(currentChar);
		}
	} // end while

	return EOF_SYM;
}
<commit_msg>Fix code style.<commit_after>/*	____________________________________________________________________________

	                 Scanner Component for the Micro A Compiler

	                                mscan.h

	                              Version 2007 - 2016

	                           James L. Richards
	                     Last Update: August 28, 2007
	                      	   Nelson A Castillo
	                     Last Update: January 31, 2016

	The routines in this unit are based on those provided in the book
	"Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr.,
	Benjamin Cummings Publishing Co. (1991).

	See Section 2.2, pp. 25-29.
	____________________________________________________________________________
*/

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

extern ifstream sourceFile;
extern ofstream outFile, listFile;

#include "mscan.h"

// *******************
// **  Constructor  **
// *******************

Scanner::Scanner()
{
	tokenBuffer = "";
	lineBuffer = "";
	lineNumber = 0;
}

// ********************************
// **  Private Member Functions  **
// ********************************

void Scanner::BufferChar(char c)
{
	if (tokenBuffer.length() < ID_STRING_LEN){
		tokenBuffer += c;
	}
	//cerr << tokenBuffer << endl;
}
void Scanner::BufferString(char c)
{
	stringBuffer += c;
	//cerr << tokenBuffer << endl;
}

Token Scanner::CheckReserved()
{
	if (tolower(tokenBuffer) == "bool") return BOOL_SYM;
	if (tolower(tokenBuffer) == "break") return BREAK_SYM;
	if (tolower(tokenBuffer) == "case") return CASE_SYM;
	if (tolower(tokenBuffer) == "cheese") return CHEESE_SYM;
	if (tolower(tokenBuffer) == "decs") return DECS_SYM;
	if (tolower(tokenBuffer) == "do") return DO_SYM;
	if (tolower(tokenBuffer) == "else") return ELSE_SYM;
	if (tolower(tokenBuffer) == "end") return END_SYM;
	if (tolower(tokenBuffer) == "false") return FALSE_SYM;
	if (tolower(tokenBuffer) == "float") return FLOAT_SYM;
	if (tolower(tokenBuffer) == "for") return FOR_SYM;
	if (tolower(tokenBuffer) == "hiphip") return HIPHIP_SYM;
	if (tolower(tokenBuffer) == "if") return IF_SYM;
	if (tolower(tokenBuffer) == "int") return INT_SYM;
	if (tolower(tokenBuffer) == "listen") return LISTEN_SYM;
	if (tolower(tokenBuffer) == "otherwise") return OTHERWISE_SYM;
	if (tolower(tokenBuffer) == "select") return SELECT_SYM;
	if (tolower(tokenBuffer) == "shout") return SHOUT_SYM;
	if (tolower(tokenBuffer) == "then") return THEN_SYM;
	if (tolower(tokenBuffer) == "true") return TRUE_SYM;
	if (tolower(tokenBuffer) == "while") return WHILE_SYM;

	return ID;
}

void Scanner::ClearBuffer()
{
	tokenBuffer = "";
	stringBuffer = "";
}

void Scanner::LexicalError(char& c, string& errorExp="")
{
	cout << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << endl;
	listFile << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << endl;
	if (errorExp != "") {
		/*TODO: I was starting with the comment but
		 * I need to ampliate the code
		 */
	}
	c = NextChar();
}

char Scanner::NextChar()
{
	char c;

	sourceFile.get(c);
	if (c == '\n')
	{
		listFile.width(6);
		listFile << ++lineNumber << "  " << lineBuffer << endl;
		lineBuffer = "";
	} else{
		lineBuffer += c;
	}
	return c;
}

// *******************************
// **  Public Member Functions  **
// *******************************

Token Scanner::GetNextToken()
{
	char currentChar, c;

	ClearBuffer();
	currentChar = NextChar();
	while (!sourceFile.eof())
	{
		if (isspace(currentChar)) {
			/* do nothing */
			currentChar = NextChar();
		} else if (isalpha(currentChar)) {
			/* identifier */
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isalnum(c) || c == '_') {
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			return CheckReserved();
		} else if (isdigit(currentChar)) {
			/* integer or float literals */
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isdigit(c)) {
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			/* check if it is a float */
			if (c == '.') {
				currentChar = NextChar();
				c = sourceFile.peek();
				/* check for a digit after the '.' */
				if (!isdigit(c))
					LexicalError(currentChar);
				BufferChar(currentChar);
				while (isdigit(c)) {
					currentChar = NextChar();
					BufferChar(currentChar);
					c = sourceFile.peek();
				}
				/* check for power of 10 multipliers */
				if (c == 'e' || c == 'E') {
					currentChar = NextChar();
					c = sourceFile.peek();
					if (c != '+' && c!= '-') {
						LexicalError(currentChar);
					}
					BufferChar(currentChar);
					currentChar = NextChar();
					c = sourceFile.peek();
					if (!isdigit(c))
						LexicalError(currentChar);
					BufferChar(currentChar);
					while (isdigit(c)) {
						currentChar = NextChar();
						BufferChar(currentChar);
						c = sourceFile.peek();
					}
				}
				return FLOAT_LIT;
			}
			return INT_LIT;
		} else if (currentChar == '"') {
			// string literal
			// BufferString(currentChar);
			do {
				currentChar = NextChar();
				// cout << currentChar <<endl;
				if (currentChar == '"' \
						& sourceFile.peek() != '"') {
					// BufferString(currentChar);
					// cout << "________________________" <<endl;
					// cout << stringBuffer <<endl;
					// cout << "________________________" <<endl;
					return CHEESE_LIT;
				} else if (currentChar == '"' \
						& sourceFile.peek() == '"') {
					currentChar = NextChar();
				}
				BufferString(currentChar);
			} while (sourceFile.peek()!='\n');
			return CHEESE_LIT;
		} else if (currentChar == '(') {
			return LBANANA;
		} else if (currentChar == ')') {
			return RBANANA;
		} else if (currentChar == '[') {
			return LSTAPLE;
		} else if (currentChar == ']') {
			return RSTAPLE;
		} else if (currentChar == '{') {
			return LMUSTACHE;
		} else if (currentChar == '}') {
			return RMUSTACHE;
		} else if (currentChar == ';') {
			return SEMICOLON;
		} else if (currentChar == ':') {
			return COLON;
		} else if (currentChar == ',') {
			return COMMA;
		} else if (currentChar == '+') {
			BufferChar(currentChar);
			return PLUS_OP;
		} else if (currentChar == '*') {
			BufferChar(currentChar);
			return MULT_OP;
		} else if (currentChar == '/') {
			/* check if it is a multiline comment */
			if (sourceFile.peek() == ':') {
				do { /* skip comment */
					currentChar = NextChar();
					if (currentChar == ':') {
						currentChar = NextChar();
						if (currentChar == '/') {
							break;
						}
					}
				} while (!sourceFile.eof());
			}
			BufferChar(currentChar);
			return DIV_OP;
		} else if (currentChar == '=') {
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return EQ_OP1;
			}
			currentChar = NextChar();
			return ASSIGN_OP;
		} else if (currentChar == '!') {
			if (sourceFile.peek() == '!') {
				currentChar = NextChar();
				return EQ_OP2;
			} else if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return NE_OP;
			}
		} else if (currentChar == '<') {
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return LE_OP;
			}
			currentChar = NextChar();
			return LT_OP;
		} else if (currentChar == '>') {
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return GE_OP;
			}
			currentChar = NextChar();
			return GT_OP;
		} else if (currentChar == '-') {
			/* check if it is a comment or a minus symbol */
			if (sourceFile.peek() == '-') { /* comment */
				do { /* skip comment */
					currentChar = NextChar();
				} while (currentChar != '\n');
			} else { /* minus operator */
				BufferChar(currentChar);
				return MINUS_OP;
			}
		} else {
			/* Unrecognized character */
			LexicalError(currentChar);
		}
	} /* end while */

	return EOF_SYM;
}
<|endoftext|>