<commit_before>/* <x0/plugins/vhost.cpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 * http://www.xzero.ws/
 *
 * (c) 2011 Christian Parpart <trapni@gentoo.org>
 *
 * --------------------------------------------------------------------------
 *
 * plugin type: hostname resolver
 *
 * description:
 *     Maps the request hostname:port to a dedicated handler.
 *
 * setup API:
 *     void vhost.add(FQDN => handler_ref);
 *
 * request processing API:
 *     handler vhost.map();
 */

#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpHeader.h>
#include <x0/Types.h>

#include <unordered_map>

/**
 * \ingroup plugins
 * \brief virtual host mapping plugin
 */
class vhost_plugin :
	public x0::HttpPlugin
{
private:
	std::unordered_map<std::string, Flow::Value::Function> namedHosts_;

public:
	vhost_plugin(x0::HttpServer& srv, const std::string& name) :
		x0::HttpPlugin(srv, name)
	{
		registerSetupFunction<vhost_plugin, &vhost_plugin::addHost>("vhost.add", Flow::Value::VOID);
		registerHandler<vhost_plugin, &vhost_plugin::mapRequest>("vhost.map");
	}

	~vhost_plugin()
	{
	}

private:
	// vhost.add fqdn => proc, ...
	void addHost(Flow::Value& result, const x0::Params& args)
	{
		for (auto& arg: args)
			registerHost(arg);
	}

	void registerHost(const Flow::Value& arg)
	{
		if (arg.type() == Flow::Value::ARRAY) {
			const Flow::Value* args = arg.toArray();
			if (args[0].isVoid() || args[1].isVoid() || !args[2].isVoid())
				return;

			const Flow::Value& fqdn = args[0];
			const Flow::Value& proc = args[1];

			if (!fqdn.isString())
				return;

			if (!proc.isFunction())
				return;

			registerHost(fqdn.toString(), proc.toFunction());
		}
	}

	void registerHost(const char *fqdn, Flow::Value::Function handler)
	{
		namedHosts_[fqdn] = handler;
	}

	bool mapRequest(x0::HttpRequest *r, const x0::Params& args)
	{
		auto i = namedHosts_.find(r->hostid());
		if (i != namedHosts_.end())
			return i->second(r);

		return false;
	}
};

X0_EXPORT_PLUGIN(vhost)
<commit_msg>[plugins] vhost: added support for mixed qualified/unqualified hostnames (with and without explicit port speicifcation) and renamed vhost.add to vhost.mapping<commit_after>/* <x0/plugins/vhost.cpp>
 *
 * This file is part of the x0 web server project and is released under LGPL-3.
 * http://www.xzero.ws/
 *
 * (c) 2011 Christian Parpart <trapni@gentoo.org>
 *
 * --------------------------------------------------------------------------
 *
 * plugin type: hostname resolver
 *
 * description:
 *     Maps the request hostname:port to a dedicated handler.
 *
 * setup API:
 *     void vhost.mapping(FQDN => handler_ref, ...);
 *
 * request processing API:
 *     handler vhost.map();
 */

#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpHeader.h>
#include <x0/Types.h>

#include <unordered_map>

/**
 * \ingroup plugins
 * \brief virtual host mapping plugin
 */
class vhost_plugin :
	public x0::HttpPlugin
{
private:
	typedef std::map<std::string, Flow::Value::Function> NamedHostMap;

	NamedHostMap qualifiedHosts_;
	NamedHostMap unqualifiedHosts_;

public:
	vhost_plugin(x0::HttpServer& srv, const std::string& name) :
		x0::HttpPlugin(srv, name)
	{
		registerSetupFunction<vhost_plugin, &vhost_plugin::addHost>("vhost.mapping", Flow::Value::VOID);
		registerHandler<vhost_plugin, &vhost_plugin::mapRequest>("vhost.map");
	}

	~vhost_plugin()
	{
	}

private:
	// vhost.add fqdn => proc, ...
	void addHost(Flow::Value& result, const x0::Params& args)
	{
		for (auto& arg: args)
			registerHost(arg);
	}

	void registerHost(const Flow::Value& arg)
	{
		if (arg.type() == Flow::Value::ARRAY) {
			const Flow::Value* args = arg.toArray();
			if (args[0].isVoid() || args[1].isVoid() || !args[2].isVoid())
				return;

			const Flow::Value& fqdn = args[0];
			const Flow::Value& proc = args[1];

			if (!fqdn.isString())
				return;

			if (!proc.isFunction())
				return;

			registerHost(fqdn.toString(), proc.toFunction());
		}
	}

	void registerHost(const char *fqdn, Flow::Value::Function handler)
	{
		if (strchr(fqdn, ':'))
			qualifiedHosts_[fqdn] = handler;
		else
			unqualifiedHosts_[fqdn] = handler;
	}

	bool mapRequest(x0::HttpRequest *r, const x0::Params& args)
	{
		auto i = qualifiedHosts_.find(r->hostid());
		if (i != qualifiedHosts_.end())
			return i->second(r);

		auto k = unqualifiedHosts_.find(r->hostname.str());
		if (k != unqualifiedHosts_.end())
			return k->second(r);

		return false;
	}
};

X0_EXPORT_PLUGIN(vhost)
<|endoftext|>


<commit_before>#include "process_command_line_arguments.h"
#include "get_code.h"
#include "parse.h"
#include "translate.h"
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/format.hpp>

using namespace thewizardplusplus::wizard_basic_3;
using namespace boost;
using namespace boost::property_tree;

const auto XML_INDENT_SYMBOL = ' ';
const auto XML_INDENT_SIZE = 4;

template<FinalStage final_stage, typename ResultType>
void ProcessResult(
	CommandLineArguments command_line_arguments,
	ResultType result
) {
	if (command_line_arguments.final_stage == final_stage) {
		std::cout << result << '\n';
		std::exit(EXIT_SUCCESS);
	}
}

int main(int number_of_arguments, char* arguments[]) try {
	const auto command_line_arguments = ProcessCommandLineArguments(
		number_of_arguments,
		arguments
	);

	const auto code = GetCode(command_line_arguments.script_file);
	ProcessResult<FinalStage::CODE>(command_line_arguments, code);

	const auto ast = Parse(code);
	ProcessResult<FinalStage::AST>(
		command_line_arguments,
		([&] () -> std::string {
			std::stringstream source;
			source << ast;

			ptree property_tree;
			read_xml(source, property_tree);

			std::ostringstream out;
			write_xml(
				out,
				property_tree,
				xml_writer_make_settings<ptree::key_type>(
					XML_INDENT_SYMBOL,
					XML_INDENT_SIZE
				)
			);

			return out.str();
		})()
	);

	const auto ansi_c = Translate(ast);
	ProcessResult<FinalStage::ANSI_C>(command_line_arguments, ansi_c);
} catch (const std::exception& exception) {
	std::cerr << (format("Error: %s.\n") % exception.what()).str();
}
<commit_msg>Correct of AST formatting.<commit_after>#include "process_command_line_arguments.h"
#include "get_code.h"
#include "parse.h"
#include "translate.h"
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/format.hpp>

using namespace thewizardplusplus::wizard_basic_3;
using namespace boost;
using namespace boost::property_tree;

const auto XML_INDENT_SYMBOL = ' ';
const auto XML_INDENT_SIZE = 4;

template<FinalStage final_stage, typename ResultType>
void ProcessResult(
	CommandLineArguments command_line_arguments,
	ResultType result
) {
	if (command_line_arguments.final_stage == final_stage) {
		std::cout << result << '\n';
		std::exit(EXIT_SUCCESS);
	}
}

int main(int number_of_arguments, char* arguments[]) try {
	const auto command_line_arguments = ProcessCommandLineArguments(
		number_of_arguments,
		arguments
	);

	const auto code = GetCode(command_line_arguments.script_file);
	ProcessResult<FinalStage::CODE>(command_line_arguments, code);

	const auto ast = Parse(code);
	ProcessResult<FinalStage::AST>(
		command_line_arguments,
		([&] () -> std::string {
			std::stringstream source;
			source << ast;

			ptree property_tree;
			read_xml(source, property_tree);

			std::ostringstream out;
			write_xml(
				out,
				property_tree,
				xml_writer_make_settings(XML_INDENT_SYMBOL, XML_INDENT_SIZE)
			);

			return out.str();
		})()
	);

	const auto ansi_c = Translate(ast);
	ProcessResult<FinalStage::ANSI_C>(command_line_arguments, ansi_c);
} catch (const std::exception& exception) {
	std::cerr << (format("Error: %s.\n") % exception.what()).str();
}
<|endoftext|>


<commit_before><commit_msg>Support drop of mails on todo list.<commit_after><|endoftext|>


<commit_before>#include "Example1.h"

#include <FrameView.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Button.h>
#include <ScrollLayout.h>
#include <Switch.h>
#include <TextField.h>
#include <ImageElement.h>

#include <iostream>

using namespace std;

Example1::Example1() : FWApplication("com.sometrik.example1")
{
  auto view = std::make_shared<FrameView>();
  view->style("background-color", "#cccccc");
  addChild(view);

  auto layout = std::make_shared<LinearLayout>(FW_VERTICAL);
  view->addChild(layout);

  auto image = std::make_shared<ImageElement>("test.png");
  layout->addChild(image);

  auto title = make_shared<TextLabel>("Hello again!", 1234);
  title->style("font-size", 20);
  title->style("background-color", "#e03030");
  title->style("shadow", 5);
  title->style("border", "#401010");
  title->style("border-radius", 5);
  layout->addChild(title);

  auto nameLayout = make_shared<LinearLayout>(FW_HORIZONTAL);
  layout->addChild(nameLayout);
  nameLayout->addChild(make_shared<TextLabel>("Kirjoita nimesi:"));

  textField = make_shared<TextField>();
  nameLayout->addChild(textField);

  layout->addChild(make_shared<Switch>("On", "Off"));

  auto buttonLayout = std::make_shared<LinearLayout>(FW_HORIZONTAL);
  buttonLayout->addChild(make_shared<Button>("Click me!"));
  buttonLayout->addChild(make_shared<Button>("Cancel"));
  buttonLayout->addChild(make_shared<Button>("Button"));
  layout->addChild(buttonLayout);

  auto scrollLayout = std::make_shared<ScrollLayout>();
  scrollLayout->style("min-height", 200);
  layout->addChild(scrollLayout);
  auto scrollContent = std::make_shared<LinearLayout>(FW_VERTICAL);
  scrollLayout->addChild(scrollContent);

  for (int i = 0; i < 100; i++) {
    scrollContent->addChild(std::make_shared<TextLabel>("Number: " + to_string(i)));
  }

}

void
Example1::onCommandEvent(CommandEvent & ev) {
  getLogger().println("got command event " + textField->getValue());

  getChildById(1234).text("Hello " + textField->getValue() + "!");
}

FWApplication * applicationMain() {
  return new Example1();
}
<commit_msg>make border lighter<commit_after>#include "Example1.h"

#include <FrameView.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Button.h>
#include <ScrollLayout.h>
#include <Switch.h>
#include <TextField.h>
#include <ImageElement.h>

#include <iostream>

using namespace std;

Example1::Example1() : FWApplication("com.sometrik.example1")
{
  auto view = std::make_shared<FrameView>();
  view->style("background-color", "#cccccc");
  addChild(view);

  auto layout = std::make_shared<LinearLayout>(FW_VERTICAL);
  view->addChild(layout);

  auto image = std::make_shared<ImageElement>("test.png");
  layout->addChild(image);

  auto title = make_shared<TextLabel>("Hello again!", 1234);
  title->style("font-size", 20);
  title->style("background-color", "#e03030");
  title->style("shadow", 5);
  title->style("border", "#801010");
  title->style("border-radius", 5);
  layout->addChild(title);

  auto nameLayout = make_shared<LinearLayout>(FW_HORIZONTAL);
  layout->addChild(nameLayout);
  nameLayout->addChild(make_shared<TextLabel>("Kirjoita nimesi:"));

  textField = make_shared<TextField>();
  nameLayout->addChild(textField);

  layout->addChild(make_shared<Switch>("On", "Off"));

  auto buttonLayout = std::make_shared<LinearLayout>(FW_HORIZONTAL);
  buttonLayout->addChild(make_shared<Button>("Click me!"));
  buttonLayout->addChild(make_shared<Button>("Cancel"));
  buttonLayout->addChild(make_shared<Button>("Button"));
  layout->addChild(buttonLayout);

  auto scrollLayout = std::make_shared<ScrollLayout>();
  scrollLayout->style("min-height", 200);
  layout->addChild(scrollLayout);
  auto scrollContent = std::make_shared<LinearLayout>(FW_VERTICAL);
  scrollLayout->addChild(scrollContent);

  for (int i = 0; i < 100; i++) {
    scrollContent->addChild(std::make_shared<TextLabel>("Number: " + to_string(i)));
  }

}

void
Example1::onCommandEvent(CommandEvent & ev) {
  getLogger().println("got command event " + textField->getValue());

  getChildById(1234).text("Hello " + textField->getValue() + "!");
}

FWApplication * applicationMain() {
  return new Example1();
}
<|endoftext|>


<commit_before>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

/**************************************************************************
  Connections

  Commonality across all platforms -- move out as required.

**************************************************************************/

#include "ink_unused.h"   /* MAGIC_EDITING_TAG */
#include "inktomi++.h"

#include "P_Net.h"

#define SET_TCP_NO_DELAY
#define SET_NO_LINGER
// set in the OS
// #define RECV_BUF_SIZE            (1024*64)
// #define SEND_BUF_SIZE            (1024*64)
#define FIRST_RANDOM_PORT        16000
#define LAST_RANDOM_PORT         32000

#define ROUNDUP(x, y) ((((x)+((y)-1))/(y))*(y))

int
get_listen_backlog(void)
{
  int listen_backlog = 1024;

  IOCORE_ReadConfigInteger(listen_backlog, "proxy.config.net.listen_backlog");
  return listen_backlog;
};

//
// Functions
//
char const*
NetVCOptions::toString(addr_bind_style s) {
  return ANY_ADDR == s ? "any"
    : INTF_ADDR == s ? "interface"
    : "foreign"
    ;
}

Connection::Connection()
  : fd(NO_FD)
  , is_bound(false)
  , is_connected(false)
{
  memset(&sa, 0, sizeof(struct sockaddr_in));
}

Connection::~Connection()
{
  close();
}

int
Server::accept(Connection * c)
{
  int res = 0;
  socklen_t sz = sizeof(c->sa);

  res = socketManager.accept(fd, (struct sockaddr *)&c->sa, &sz);
  if (res < 0)
    return res;
  c->fd = res;

#ifdef SET_CLOSE_ON_EXEC
  if ((res = safe_fcntl(fd, F_SETFD, 1)) < 0)
    goto Lerror;
#endif
  if ((res = safe_nonblocking(c->fd)) < 0)
    goto Lerror;
#ifdef SEND_BUF_SIZE
  socketManager.set_sndbuf_size(c->fd, SEND_BUF_SIZE);
#endif
#ifdef SET_SO_KEEPALIVE
  // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, ON, sizeof(int))) < 0)
    goto Lerror;
#endif

  return 0;
Lerror:
  c->close();
  return res;
}

int
Connection::close()
{
  is_connected = false;
  is_bound = false;
  // don't close any of the standards
  if (fd >= 2) {
    int fd_save = fd;
    fd = NO_FD;
    return socketManager.close(fd_save);
  } else {
    fd = NO_FD;
    return -EBADF;
  }
}

int
Server::setup_fd_for_listen(bool non_blocking, int recv_bufsize, int send_bufsize)
{
  int res = 0;
#ifdef SEND_BUF_SIZE
  {
    int send_buf_size = SEND_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &send_buf_size, sizeof(int)) < 0))
      goto Lerror;
  }
#endif
#ifdef RECV_BUF_SIZE
  {
    int recv_buf_size = RECV_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &recv_buf_size, sizeof(int))) < 0)
      goto Lerror;
  }
#endif

  if (recv_bufsize) {
    // coverity[negative_sink_in_call]
    if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) {
      // Round down until success
      int rbufsz = ROUNDUP(recv_bufsize, 1024);
      while (rbufsz) {
        if (socketManager.set_rcvbuf_size(fd, rbufsz)) {
          rbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
  if (send_bufsize) {
    if (socketManager.set_sndbuf_size(fd, send_bufsize)) {
      // Round down until success
      int sbufsz = ROUNDUP(send_bufsize, 1024);
      while (sbufsz) {
        if (socketManager.set_sndbuf_size(fd, sbufsz)) {
          sbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
#ifdef SET_NO_LINGER
  {
    struct linger l;
    l.l_onoff = 0;
    l.l_linger = 0;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof(l))) < 0)
      goto Lerror;
  }
#endif
#ifdef SET_TCP_NO_DELAY
  if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, ON, sizeof(int))) < 0)
    goto Lerror;
#endif
#ifdef SET_SO_KEEPALIVE
  // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, ON, sizeof(int))) < 0)
    goto Lerror;
#endif

#if defined(linux)
  if (NetProcessor::accept_mss > 0)
    if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *) &NetProcessor::accept_mss, sizeof(int)) < 0))
      goto Lerror;
#endif

  /*
   * dg: this has been removed since the ISS patch under solaris seems
   * to not like the socket being listened on twice. This is first done
   * in the manager when the socket is created.
   */
  if (non_blocking)
    if ((res = safe_nonblocking(fd)) < 0)
      goto Lerror;
  {
    int namelen = sizeof(sa);
    if ((res = safe_getsockname(fd, (struct sockaddr *) &sa, &namelen)))
      goto Lerror;
  }
  return 0;
Lerror:
  res = -errno;
  // coverity[check_after_sink]
  if (fd != NO_FD)
    close();
  return res;
}

int
Server::listen(int port_number, bool non_blocking, int recv_bufsize, int send_bufsize)
{
  ink_assert(fd == NO_FD);
  int res = 0;

  res = socketManager.socket(AF_INET, SOCK_STREAM, 0);
  if (res < 0)
    return res;
  fd = res;

#ifdef SEND_BUF_SIZE
  {
    int send_buf_size = SEND_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &send_buf_size, sizeof(int)) < 0))
      goto Lerror;
  }
#endif
#ifdef RECV_BUF_SIZE
  {
    int recv_buf_size = RECV_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &recv_buf_size, sizeof(int))) < 0)
      goto Lerror;
  }
#endif

  if (recv_bufsize) {
    if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) {
      // Round down until success
      int rbufsz = ROUNDUP(recv_bufsize, 1024);
      while (rbufsz) {
        if (socketManager.set_rcvbuf_size(fd, rbufsz)) {
          rbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
  if (send_bufsize) {
    if (socketManager.set_sndbuf_size(fd, send_bufsize)) {
      // Round down until success
      int sbufsz = ROUNDUP(send_bufsize, 1024);
      while (sbufsz) {
        if (socketManager.set_sndbuf_size(fd, sbufsz)) {
          sbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
#ifdef SET_CLOSE_ON_EXEC
  if ((res = safe_fcntl(fd, F_SETFD, 1)) < 0)
    goto Lerror;
#endif

  memset(&sa, 0, sizeof(sa));
  //
  // Accept_ip should already be in network byte order..
  //
  sa.sin_addr.s_addr = accept_ip;
  sa.sin_port = htons(port_number);
  sa.sin_family = AF_INET;

#ifdef SET_NO_LINGER
  {
    struct linger l;
    l.l_onoff = 0;
    l.l_linger = 0;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof(l))) < 0)
      goto Lerror;
  }
#endif

  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, ON, sizeof(int))) < 0)
    goto Lerror;

  if ((res = socketManager.ink_bind(fd, (struct sockaddr *) &sa, sizeof(sa), IPPROTO_TCP)) < 0) {
    goto Lerror;
  }
#ifdef SET_TCP_NO_DELAY
  if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, ON, sizeof(int))) < 0)
    goto Lerror;
#endif
#ifdef SET_SO_KEEPALIVE
  // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, ON, sizeof(int))) < 0)
    goto Lerror;
#endif

#if defined(linux)
  if (NetProcessor::accept_mss > 0)
    if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *) &NetProcessor::accept_mss, sizeof(int))) < 0)
      goto Lerror;
#endif

  if ((res = safe_listen(fd, get_listen_backlog())) < 0)
    goto Lerror;
  if (non_blocking)
    if ((res = safe_nonblocking(fd)) < 0)
      goto Lerror;
  if (!port_number) {
    int namelen = sizeof(sa);
    if ((res = safe_getsockname(fd, (struct sockaddr *) &sa, &namelen)))
      goto Lerror;
  }
  return 0;

Lerror:
  if (fd != NO_FD)
    close();
  return res;
}
<commit_msg>TS-247: Errors on failing to bind / listen on a specified port.<commit_after>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

/**************************************************************************
  Connections

  Commonality across all platforms -- move out as required.

**************************************************************************/

#include "ink_unused.h"   /* MAGIC_EDITING_TAG */
#include "inktomi++.h"

#include "P_Net.h"

#define SET_TCP_NO_DELAY
#define SET_NO_LINGER
// set in the OS
// #define RECV_BUF_SIZE            (1024*64)
// #define SEND_BUF_SIZE            (1024*64)
#define FIRST_RANDOM_PORT        16000
#define LAST_RANDOM_PORT         32000

#define ROUNDUP(x, y) ((((x)+((y)-1))/(y))*(y))

int
get_listen_backlog(void)
{
  int listen_backlog = 1024;

  IOCORE_ReadConfigInteger(listen_backlog, "proxy.config.net.listen_backlog");
  return listen_backlog;
};

//
// Functions
//
char const*
NetVCOptions::toString(addr_bind_style s) {
  return ANY_ADDR == s ? "any"
    : INTF_ADDR == s ? "interface"
    : "foreign"
    ;
}

Connection::Connection()
  : fd(NO_FD)
  , is_bound(false)
  , is_connected(false)
{
  memset(&sa, 0, sizeof(struct sockaddr_in));
}

Connection::~Connection()
{
  close();
}

int
Server::accept(Connection * c)
{
  int res = 0;
  socklen_t sz = sizeof(c->sa);

  res = socketManager.accept(fd, (struct sockaddr *)&c->sa, &sz);
  if (res < 0)
    return res;
  c->fd = res;

#ifdef SET_CLOSE_ON_EXEC
  if ((res = safe_fcntl(fd, F_SETFD, 1)) < 0)
    goto Lerror;
#endif
  if ((res = safe_nonblocking(c->fd)) < 0)
    goto Lerror;
#ifdef SEND_BUF_SIZE
  socketManager.set_sndbuf_size(c->fd, SEND_BUF_SIZE);
#endif
#ifdef SET_SO_KEEPALIVE
  // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, ON, sizeof(int))) < 0)
    goto Lerror;
#endif

  return 0;
Lerror:
  c->close();
  return res;
}

int
Connection::close()
{
  is_connected = false;
  is_bound = false;
  // don't close any of the standards
  if (fd >= 2) {
    int fd_save = fd;
    fd = NO_FD;
    return socketManager.close(fd_save);
  } else {
    fd = NO_FD;
    return -EBADF;
  }
}

int
Server::setup_fd_for_listen(bool non_blocking, int recv_bufsize, int send_bufsize)
{
  int res = 0;
#ifdef SEND_BUF_SIZE
  {
    int send_buf_size = SEND_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &send_buf_size, sizeof(int)) < 0))
      goto Lerror;
  }
#endif
#ifdef RECV_BUF_SIZE
  {
    int recv_buf_size = RECV_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &recv_buf_size, sizeof(int))) < 0)
      goto Lerror;
  }
#endif

  if (recv_bufsize) {
    // coverity[negative_sink_in_call]
    if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) {
      // Round down until success
      int rbufsz = ROUNDUP(recv_bufsize, 1024);
      while (rbufsz) {
        if (socketManager.set_rcvbuf_size(fd, rbufsz)) {
          rbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
  if (send_bufsize) {
    if (socketManager.set_sndbuf_size(fd, send_bufsize)) {
      // Round down until success
      int sbufsz = ROUNDUP(send_bufsize, 1024);
      while (sbufsz) {
        if (socketManager.set_sndbuf_size(fd, sbufsz)) {
          sbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
#ifdef SET_NO_LINGER
  {
    struct linger l;
    l.l_onoff = 0;
    l.l_linger = 0;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof(l))) < 0)
      goto Lerror;
  }
#endif
#ifdef SET_TCP_NO_DELAY
  if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, ON, sizeof(int))) < 0)
    goto Lerror;
#endif
#ifdef SET_SO_KEEPALIVE
  // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, ON, sizeof(int))) < 0)
    goto Lerror;
#endif

#if defined(linux)
  if (NetProcessor::accept_mss > 0)
    if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *) &NetProcessor::accept_mss, sizeof(int)) < 0))
      goto Lerror;
#endif

  /*
   * dg: this has been removed since the ISS patch under solaris seems
   * to not like the socket being listened on twice. This is first done
   * in the manager when the socket is created.
   */
  if (non_blocking)
    if ((res = safe_nonblocking(fd)) < 0)
      goto Lerror;
  {
    int namelen = sizeof(sa);
    if ((res = safe_getsockname(fd, (struct sockaddr *) &sa, &namelen)))
      goto Lerror;
  }
  return 0;
Lerror:
  res = -errno;
  // coverity[check_after_sink]
  if (fd != NO_FD)
    close();
  return res;
}

int
Server::listen(int port_number, bool non_blocking, int recv_bufsize, int send_bufsize)
{
  ink_assert(fd == NO_FD);
  int res = 0;

  res = socketManager.socket(AF_INET, SOCK_STREAM, 0);
  if (res < 0)
    return res;
  fd = res;

#ifdef SEND_BUF_SIZE
  {
    int send_buf_size = SEND_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &send_buf_size, sizeof(int)) < 0))
      goto Lerror;
  }
#endif
#ifdef RECV_BUF_SIZE
  {
    int recv_buf_size = RECV_BUF_SIZE;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &recv_buf_size, sizeof(int))) < 0)
      goto Lerror;
  }
#endif

  if (recv_bufsize) {
    if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) {
      // Round down until success
      int rbufsz = ROUNDUP(recv_bufsize, 1024);
      while (rbufsz) {
        if (socketManager.set_rcvbuf_size(fd, rbufsz)) {
          rbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
  if (send_bufsize) {
    if (socketManager.set_sndbuf_size(fd, send_bufsize)) {
      // Round down until success
      int sbufsz = ROUNDUP(send_bufsize, 1024);
      while (sbufsz) {
        if (socketManager.set_sndbuf_size(fd, sbufsz)) {
          sbufsz -= 1024;
        } else {
          break;
        }
      }
    }
  }
#ifdef SET_CLOSE_ON_EXEC
  if ((res = safe_fcntl(fd, F_SETFD, 1)) < 0)
    goto Lerror;
#endif

  memset(&sa, 0, sizeof(sa));
  //
  // Accept_ip should already be in network byte order..
  //
  sa.sin_addr.s_addr = accept_ip;
  sa.sin_port = htons(port_number);
  sa.sin_family = AF_INET;

#ifdef SET_NO_LINGER
  {
    struct linger l;
    l.l_onoff = 0;
    l.l_linger = 0;
    if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof(l))) < 0)
      goto Lerror;
  }
#endif

  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, ON, sizeof(int))) < 0)
    goto Lerror;

  if ((res = socketManager.ink_bind(fd, (struct sockaddr *) &sa, sizeof(sa), IPPROTO_TCP)) < 0) {
    goto Lerror;
  }
#ifdef SET_TCP_NO_DELAY
  if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, ON, sizeof(int))) < 0)
    goto Lerror;
#endif
#ifdef SET_SO_KEEPALIVE
  // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
  if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, ON, sizeof(int))) < 0)
    goto Lerror;
#endif

#if defined(linux)
  if (NetProcessor::accept_mss > 0)
    if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *) &NetProcessor::accept_mss, sizeof(int))) < 0)
      goto Lerror;
#endif

  if ((res = safe_listen(fd, get_listen_backlog())) < 0)
    goto Lerror;
  if (non_blocking)
    if ((res = safe_nonblocking(fd)) < 0)
      goto Lerror;
  if (!port_number) {
    int namelen = sizeof(sa);
    if ((res = safe_getsockname(fd, (struct sockaddr *) &sa, &namelen)))
      goto Lerror;
  }
  return 0;

Lerror:
  if (fd != NO_FD)
    close();
  MachineFatal("Could not bind or listen to port %d (error: %d)", port_number, res);
  return res;
}
<|endoftext|>


<commit_before>// This is the program to simulate the dynamic of a rocking block by using the Siconos platform
//==================================================================================================================
#include "SiconosKernel.hpp"
#include <stdlib.h>
using namespace std;
#define PI 3.14159
#define GGearth  9.8100
//---------------------------------Decalre global variables ---------------------------------------------------
double LengthBlock = 1.;        // Length of the rocking block
double HeightBlock = 1.5;        // Height of the rocking block
unsigned int Nfreedom = 3;       // Number of degrees of freedom
unsigned int Ncontact = 2;       // Number of contacts
double MassBlock = 1.0;          // Mass of the rocking block
double PosXiniPointA = 0.0;      // Initial coordinate X of the point A
double PosYiniPointA = 0.5;      // Initial coordinate Y of the point A
double AngleThetaIni = PI / 10.0; // Initial angle theta of the block
double VelXiniPointA = 0.0 ;     // Initial relative velocity Vx of the point A
double VelYiniPointA = 0.0 ;     // Initial relative velocity Vy of the point A
double RotVelBlockIni = 0.0;    // Initial angular velocity of the block
double e = 0.5;          // Restitution coefficient
double TimeInitial = 0.0;        // Initial time of the simulation
double TimeFinal =  2.0;     // Final time of the simulation
double StepSize = 0.01;         // Time step size
unsigned int NpointSave = 200;   //
unsigned int SizeOutput = 9;     //
double criterion = 0.05;
unsigned int maxIter = 20000;
//==========================================================================================================
//                                             Main function
//==========================================================================================================
int main(int argc, char* argv[])
{
  //---------------------------- calculate the computation time --------------------------------------------------
  boost::timer time;
  time.restart();
  try
  {
    //===========================================================================================================
    //                  I: Declare the dynamical systems
    //===========================================================================================================
    DynamicalSystemsSet allDS;
    //1. Set the mass matrix
    SP::SiconosMatrix Mass(new SimpleMatrix(Nfreedom, Nfreedom));
    double InertiaBlock;
    InertiaBlock = (MassBlock / 12.0) * (pow(HeightBlock, 2) + pow(LengthBlock, 2)); // moment of inertia
    (*Mass)(0, 0) = MassBlock;
    (*Mass)(1, 1) = MassBlock;
    (*Mass)(2, 2) = InertiaBlock;
    //2. Set the initial position of the block in function of the initial position of the contact point A (left-hand contact)
    SP::SimpleVector PosIniBlock(new SimpleVector(Nfreedom));
    (*PosIniBlock)(0) = PosXiniPointA + 0.5 * LengthBlock * cos(AngleThetaIni) - 0.5 * HeightBlock * sin(AngleThetaIni);
    (*PosIniBlock)(1) = PosYiniPointA + 0.5 * LengthBlock * sin(AngleThetaIni) + 0.5 * HeightBlock * cos(AngleThetaIni);
    (*PosIniBlock)(2) = AngleThetaIni;

    (*PosIniBlock)(0) = 0.0;
    (*PosIniBlock)(1) = 1.;
    (*PosIniBlock)(2) = 0.2;

    //3. Set the initial velocity of the block in function of the initial relative velocity of the contact point A
    SP::SimpleVector VelIniBlock(new SimpleVector(Nfreedom));
    (*VelIniBlock)(0) = VelXiniPointA - (0.5 * LengthBlock * sin(AngleThetaIni) + 0.5 * HeightBlock * cos(AngleThetaIni)) * RotVelBlockIni;
    (*VelIniBlock)(1) = VelYiniPointA + (0.5 * LengthBlock * cos(AngleThetaIni) - 0.5 * HeightBlock * sin(AngleThetaIni)) * RotVelBlockIni;
    (*VelIniBlock)(2) = RotVelBlockIni;
    /*
    (*VelIniBlock)(0) = 0.0;
    (*VelIniBlock)(1) = 0.0;
    (*VelIniBlock)(2) = 0.0;
    */
    //4. Instantiate the object of "LagrangianTIDS"
    SP::LagrangianLinearTIDS RockingBlock(new LagrangianLinearTIDS(PosIniBlock, VelIniBlock, Mass));
    //5. Set the external force
    SP::SimpleVector ForceExtern(new SimpleVector(Nfreedom));
    (*ForceExtern)(1) = -MassBlock * GGearth;
    RockingBlock->setFExtPtr(ForceExtern);
    //
    allDS.insert(RockingBlock);
    //----------------------------- Display variables of the dynamical system---------------------------------------
    cout << "Initial position of the rocking block:" << endl;
    PosIniBlock->display();
    cout << "Initial velocity of the rocking block:" << endl;
    VelIniBlock->display();
    cout << "Mass matrix of the rocking block:" << endl;
    Mass->display();
    cout << "External force applied on the rocking block:"  << endl;
    ForceExtern->display();
    //==================================================================================================================
    //              II: Declare the relation et interaction between dynamical systems
    //==================================================================================================================
    InteractionsSet allInteractions;
    // Impact law
    SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
    // Interaction at contact point 1
    SP::Relation relation1(new LagrangianScleronomousR("RockingBlockPlugin:h1", "RockingBlockPlugin:G1"));
    SP::Interaction inter1(new Interaction("contact1", allDS, 1, 1, nslaw, relation1));
    // Interaction at contact point 2
    SP::Relation relation2(new LagrangianScleronomousR("RockingBlockPlugin:h2", "RockingBlockPlugin:G2"));
    SP::Interaction inter2(new Interaction("contact2", allDS, 2, 1, nslaw, relation2));
    // Interactions for the whole dynamical system
    allInteractions.insert(inter1);
    allInteractions.insert(inter2);
    //================================================================================================================
    //            III. Create the "model" object
    //================================================================================================================
    SP::Model RoBlockModel(new Model(TimeInitial, TimeFinal, allDS, allInteractions));
    //================================================================================================================
    //            IV. Create the simulation
    //================================================================================================================
    //1. Time discretization
    SP::TimeDiscretisation TimeDiscret(new TimeDiscretisation(TimeInitial, StepSize));
    //2. Integration solver for one step
    SP::OneStepIntegrator OSI(new Moreau(allDS, 0.50001));
    //3. Nonsmooth problem
    SP::OneStepNSProblem impact(new LCP());
    SP::OneStepNSProblem impact_pos(new MLCPProjectOnConstraints());
    //4. Simulation with (1), (2), (3)
    SP::TimeStepping TSscheme(new TimeSteppingProjectOnConstraints(TimeDiscret, OSI, impact, impact_pos, 0));
    //==================================================================================================================
    //                    V. Process the simulation
    //==================================================================================================================
    // -------------------------------- Simulation initialization ------------------------------------------------------
    cout << "====> Simulation initialisation ..." << endl << endl;
    RoBlockModel->initialize(TSscheme); // initialize the model
    SP::SiconosVector PosBlock = RockingBlock->q();        // pointer points to the position vector of the rocking block
    SP::SiconosVector VelBlock = RockingBlock->velocity(); // pointer points to the velocity of the rocking block
    //-------------------- Save the output during simulation ---------------------------------------------------------
    SimpleMatrix DataPlot(NpointSave, SizeOutput);
    //------------- At the initial time -----------------------------------------------------------------------------
    DataPlot(0, 0) = RoBlockModel->t0();
    DataPlot(0, 1) = (*PosBlock)(0); // Position X
    DataPlot(0, 2) = (*PosBlock)(1); // Position Y
    DataPlot(0, 3) = (*PosBlock)(2); // Angle theta
    DataPlot(0, 4) = (*VelBlock)(0); // Velocity Vx
    DataPlot(0, 5) = (*VelBlock)(1); // Velocity Vy
    DataPlot(0, 6) = (*VelBlock)(2); // Angular velocity

    SP::SiconosVector tmp(new SimpleVector(Nfreedom));
    prod(*Mass, *VelBlock, *tmp, true);
    double kineticEnergy = 0.5 * inner_prod(*VelBlock, *tmp);
    DataPlot(0, 7) = kineticEnergy;

    SP::SiconosVector PosRef(new SimpleVector(Nfreedom));
    (*PosRef)(0) = 0.0;
    (*PosRef)(1) = HeightBlock / 2.0;
    (*PosRef)(2) = 0.0;
    double potentialEnergy = -1.0 * inner_prod(*PosBlock - *PosRef, *ForceExtern);
    DataPlot(0, 8) = potentialEnergy;

    //----------------------------------- Simulation starts ----------------------------------------------------------
    cout << "====> Start computation ... " << endl << endl;
    unsigned int k = 1;
    boost::progress_display show_progress(NpointSave);
    while (k < NpointSave)
    {
      TSscheme->computeOneStep();
      DataPlot(k, 0) = TSscheme->nextTime();
      DataPlot(k, 1) = (*PosBlock)(0); //Position X
      DataPlot(k, 2) = (*PosBlock)(1); //Position Y
      DataPlot(k, 3) = (*PosBlock)(2); // Position theta
      DataPlot(k, 4) = (*VelBlock)(0); // Velocity Vx
      DataPlot(k, 5) = (*VelBlock)(1); // Velocity Vy
      DataPlot(k, 6) = (*VelBlock)(2); // Velocity Vtheta

      prod(*Mass, *VelBlock, *tmp, true);
      kineticEnergy = 0.5 * inner_prod(*VelBlock, *tmp);
      DataPlot(k, 7) = kineticEnergy;

      potentialEnergy = -1.0 * inner_prod(*PosBlock - *PosRef, *ForceExtern);
      DataPlot(k, 8) = potentialEnergy;

      // go to the next time step
      k++;
      ++show_progress;
      TSscheme->nextStep();
    };
    //----------------------- At the end of the simulation --------------------------
    cout << "End of the simulation" << endl;
    cout << "====> Output file writing ..." << endl << endl;
    ioMatrix io("result.dat", "ascii");
    io.write(DataPlot, "noDim");
  }
  //============================== Catch exceptions ===================================================================
  catch (SiconosException e)
  {
    cout << e.report() << endl;
  }
  catch (...)
  {
    cout << "Exception caught." << endl;
  }
  cout << "Computation Time: " << time.elapsed()  << endl;
}
<commit_msg>add computation with lambda[0] and p[0] for NewtonEuler<commit_after>// This is the program to simulate the dynamic of a rocking block by using the Siconos platform
//==================================================================================================================
#include "SiconosKernel.hpp"
#include <stdlib.h>
using namespace std;
#define PI 3.14159
#define GGearth  9.8100
//---------------------------------Decalre global variables ---------------------------------------------------
double LengthBlock = 1.;        // Length of the rocking block
double HeightBlock = 1.5;        // Height of the rocking block
unsigned int Nfreedom = 3;       // Number of degrees of freedom
unsigned int Ncontact = 2;       // Number of contacts
double MassBlock = 1.0;          // Mass of the rocking block
double PosXiniPointA = 0.0;      // Initial coordinate X of the point A
double PosYiniPointA = 0.5;      // Initial coordinate Y of the point A
double AngleThetaIni = PI / 10.0; // Initial angle theta of the block
double VelXiniPointA = 0.0 ;     // Initial relative velocity Vx of the point A
double VelYiniPointA = 0.0 ;     // Initial relative velocity Vy of the point A
double RotVelBlockIni = 0.0;    // Initial angular velocity of the block
double e = 0.5;          // Restitution coefficient
double TimeInitial = 0.0;        // Initial time of the simulation
double TimeFinal =  2.0;     // Final time of the simulation
double StepSize = 0.01;         // Time step size
unsigned int NpointSave = 200;   //
unsigned int SizeOutput = 9;     //
double criterion = 0.05;
unsigned int maxIter = 20000;
//==========================================================================================================
//                                             Main function
//==========================================================================================================
int main(int argc, char* argv[])
{
  //---------------------------- calculate the computation time --------------------------------------------------
  boost::timer time;
  time.restart();
  try
  {
    //===========================================================================================================
    //                  I: Declare the dynamical systems
    //===========================================================================================================
    DynamicalSystemsSet allDS;
    //1. Set the mass matrix
    SP::SiconosMatrix Mass(new SimpleMatrix(Nfreedom, Nfreedom));
    double InertiaBlock;
    InertiaBlock = (MassBlock / 12.0) * (pow(HeightBlock, 2) + pow(LengthBlock, 2)); // moment of inertia
    (*Mass)(0, 0) = MassBlock;
    (*Mass)(1, 1) = MassBlock;
    (*Mass)(2, 2) = InertiaBlock;
    //2. Set the initial position of the block in function of the initial position of the contact point A (left-hand contact)
    SP::SimpleVector PosIniBlock(new SimpleVector(Nfreedom));
    (*PosIniBlock)(0) = PosXiniPointA + 0.5 * LengthBlock * cos(AngleThetaIni) - 0.5 * HeightBlock * sin(AngleThetaIni);
    (*PosIniBlock)(1) = PosYiniPointA + 0.5 * LengthBlock * sin(AngleThetaIni) + 0.5 * HeightBlock * cos(AngleThetaIni);
    (*PosIniBlock)(2) = AngleThetaIni;

    (*PosIniBlock)(0) = 0.0;
    (*PosIniBlock)(1) = 1.;
    (*PosIniBlock)(2) = 0.2;

    //3. Set the initial velocity of the block in function of the initial relative velocity of the contact point A
    SP::SimpleVector VelIniBlock(new SimpleVector(Nfreedom));
    (*VelIniBlock)(0) = VelXiniPointA - (0.5 * LengthBlock * sin(AngleThetaIni) + 0.5 * HeightBlock * cos(AngleThetaIni)) * RotVelBlockIni;
    (*VelIniBlock)(1) = VelYiniPointA + (0.5 * LengthBlock * cos(AngleThetaIni) - 0.5 * HeightBlock * sin(AngleThetaIni)) * RotVelBlockIni;
    (*VelIniBlock)(2) = RotVelBlockIni;
    /*
    (*VelIniBlock)(0) = 0.0;
    (*VelIniBlock)(1) = 0.0;
    (*VelIniBlock)(2) = 0.0;
    */
    //4. Instantiate the object of "LagrangianTIDS"
    SP::LagrangianLinearTIDS RockingBlock(new LagrangianLinearTIDS(PosIniBlock, VelIniBlock, Mass));
    //5. Set the external force
    SP::SimpleVector ForceExtern(new SimpleVector(Nfreedom));
    (*ForceExtern)(1) = -MassBlock * GGearth;
    RockingBlock->setFExtPtr(ForceExtern);
    //
    allDS.insert(RockingBlock);
    //----------------------------- Display variables of the dynamical system---------------------------------------
    cout << "Initial position of the rocking block:" << endl;
    PosIniBlock->display();
    cout << "Initial velocity of the rocking block:" << endl;
    VelIniBlock->display();
    cout << "Mass matrix of the rocking block:" << endl;
    Mass->display();
    cout << "External force applied on the rocking block:"  << endl;
    ForceExtern->display();
    //==================================================================================================================
    //              II: Declare the relation et interaction between dynamical systems
    //==================================================================================================================
    InteractionsSet allInteractions;
    // Impact law
    SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
    // Interaction at contact point 1
    SP::Relation relation1(new LagrangianScleronomousR("RockingBlockPlugin:h1", "RockingBlockPlugin:G1"));
    SP::Interaction inter1(new Interaction("contact1", allDS, 1, 1, nslaw, relation1));
    // Interaction at contact point 2
    SP::Relation relation2(new LagrangianScleronomousR("RockingBlockPlugin:h2", "RockingBlockPlugin:G2"));
    SP::Interaction inter2(new Interaction("contact2", allDS, 2, 1, nslaw, relation2));
    // Interactions for the whole dynamical system
    allInteractions.insert(inter1);
    allInteractions.insert(inter2);
    //================================================================================================================
    //            III. Create the "model" object
    //================================================================================================================
    SP::Model RoBlockModel(new Model(TimeInitial, TimeFinal, allDS, allInteractions));
    //================================================================================================================
    //            IV. Create the simulation
    //================================================================================================================
    //1. Time discretization
    SP::TimeDiscretisation TimeDiscret(new TimeDiscretisation(TimeInitial, StepSize));
    //2. Integration solver for one step
    SP::MoreauProjectOnConstraintsOSI OSI(new MoreauProjectOnConstraintsOSI(allDS, 0.5001));
    //3. Nonsmooth problem
    SP::OneStepNSProblem impact(new LCP());
    SP::OneStepNSProblem impact_pos(new MLCPProjectOnConstraints());
    //4. Simulation with (1), (2), (3)
    SP::TimeStepping TSscheme(new TimeSteppingProjectOnConstraints(TimeDiscret, OSI, impact, impact_pos, 0));
    //==================================================================================================================
    //                    V. Process the simulation
    //==================================================================================================================
    // -------------------------------- Simulation initialization ------------------------------------------------------
    cout << "====> Simulation initialisation ..." << endl << endl;
    RoBlockModel->initialize(TSscheme); // initialize the model
    SP::SiconosVector PosBlock = RockingBlock->q();        // pointer points to the position vector of the rocking block
    SP::SiconosVector VelBlock = RockingBlock->velocity(); // pointer points to the velocity of the rocking block
    //-------------------- Save the output during simulation ---------------------------------------------------------
    SimpleMatrix DataPlot(NpointSave, SizeOutput);
    //------------- At the initial time -----------------------------------------------------------------------------
    DataPlot(0, 0) = RoBlockModel->t0();
    DataPlot(0, 1) = (*PosBlock)(0); // Position X
    DataPlot(0, 2) = (*PosBlock)(1); // Position Y
    DataPlot(0, 3) = (*PosBlock)(2); // Angle theta
    DataPlot(0, 4) = (*VelBlock)(0); // Velocity Vx
    DataPlot(0, 5) = (*VelBlock)(1); // Velocity Vy
    DataPlot(0, 6) = (*VelBlock)(2); // Angular velocity

    SP::SiconosVector tmp(new SimpleVector(Nfreedom));
    prod(*Mass, *VelBlock, *tmp, true);
    double kineticEnergy = 0.5 * inner_prod(*VelBlock, *tmp);
    DataPlot(0, 7) = kineticEnergy;

    SP::SiconosVector PosRef(new SimpleVector(Nfreedom));
    (*PosRef)(0) = 0.0;
    (*PosRef)(1) = HeightBlock / 2.0;
    (*PosRef)(2) = 0.0;
    double potentialEnergy = -1.0 * inner_prod(*PosBlock - *PosRef, *ForceExtern);
    DataPlot(0, 8) = potentialEnergy;

    //----------------------------------- Simulation starts ----------------------------------------------------------
    cout << "====> Start computation ... " << endl << endl;
    unsigned int k = 1;
    boost::progress_display show_progress(NpointSave);
    while (k < NpointSave)
    {
      TSscheme->computeOneStep();
      DataPlot(k, 0) = TSscheme->nextTime();
      DataPlot(k, 1) = (*PosBlock)(0); //Position X
      DataPlot(k, 2) = (*PosBlock)(1); //Position Y
      DataPlot(k, 3) = (*PosBlock)(2); // Position theta
      DataPlot(k, 4) = (*VelBlock)(0); // Velocity Vx
      DataPlot(k, 5) = (*VelBlock)(1); // Velocity Vy
      DataPlot(k, 6) = (*VelBlock)(2); // Velocity Vtheta

      prod(*Mass, *VelBlock, *tmp, true);
      kineticEnergy = 0.5 * inner_prod(*VelBlock, *tmp);
      DataPlot(k, 7) = kineticEnergy;

      potentialEnergy = -1.0 * inner_prod(*PosBlock - *PosRef, *ForceExtern);
      DataPlot(k, 8) = potentialEnergy;

      // go to the next time step
      k++;
      ++show_progress;
      TSscheme->nextStep();
    };
    //----------------------- At the end of the simulation --------------------------
    cout << "End of the simulation" << endl;
    cout << "====> Output file writing ..." << endl << endl;
    ioMatrix io("result.dat", "ascii");
    io.write(DataPlot, "noDim");
  }
  //============================== Catch exceptions ===================================================================
  catch (SiconosException e)
  {
    cout << e.report() << endl;
  }
  catch (...)
  {
    cout << "Exception caught." << endl;
  }
  cout << "Computation Time: " << time.elapsed()  << endl;
}
<|endoftext|>


<commit_before>/*=========================================================================
 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperCompositeApplication.h"
#include "otbWrapperApplicationFactory.h"

namespace otb
{
namespace Wrapper
{

class TrainImagesClassifier: public CompositeApplication
{
public:
  /** Standard class typedefs. */
  typedef TrainImagesClassifier Self;
  typedef CompositeApplication Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self)

  itkTypeMacro(TrainImagesClassifier, otb::Wrapper::CompositeApplication)

protected:

private:

void DoInit() ITK_OVERRIDE
{
  SetName("TrainImagesClassifier");
  SetDescription(
    "Train a classifier from multiple pairs of images and training vector data.");

  // Documentation
  SetDocName("Train a classifier from multiple images");
  SetDocLongDescription(
    "This application performs a classifier training from multiple pairs of input images and training vector data. "
    "Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by "
    "the ComputeImagesStatistics application.\n The training vector data must contain polygons with a positive integer field "
    "representing the class label. The name of this field can be set using the \"Class label field\" parameter. Training and validation "
    "sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio "
    "between the number of samples in training and validation sets. Two parameters allow managing the size of the training and "
    "validation sets per class and per image.\n Several classifier parameters can be set depending on the chosen classifier. In the "
    "validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. "
    "In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels"
    " are ordered according to the rows/columns of the confusion matrix.\n This application is based on LibSVM and OpenCV Machine Learning "
    "(2.3.1 and later).");
  SetDocLimitations("None");
  SetDocAuthors("OTB-Team");
  SetDocSeeAlso("OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html ");

  //Group IO
  AddParameter(ParameterType_Group, "io", "Input and output data");
  SetParameterDescription("io", "This group of parameters allows setting input and output data.");

  // Doc example parameter settings
  SetDocExampleParameterValue("io.il", "QB_1_ortho.tif");
  SetDocExampleParameterValue("io.vd", "VectorData_QB1.shp");
  SetDocExampleParameterValue("io.imstat", "EstimateImageStatisticsQB1.xml");
  SetDocExampleParameterValue("sample.mv", "100");
  SetDocExampleParameterValue("sample.mt", "100");
  SetDocExampleParameterValue("sample.vtr", "0.5");
  SetDocExampleParameterValue("sample.edg", "false");
  SetDocExampleParameterValue("sample.vfn", "Class");
  SetDocExampleParameterValue("classifier", "libsvm");
  SetDocExampleParameterValue("classifier.libsvm.k", "linear");
  SetDocExampleParameterValue("classifier.libsvm.c", "1");
  SetDocExampleParameterValue("classifier.libsvm.opt", "false");
  SetDocExampleParameterValue("io.out", "svmModelQB1.txt");
  SetDocExampleParameterValue("io.confmatout", "svmConfusionMatrixQB1.csv");
}

void DoUpdateParameters() ITK_OVERRIDE
{
  // Nothing to do here : all parameters are independent
}

void DoExecute() ITK_OVERRIDE
{

}

};

} // end namespace Wrapper
} // end namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::TrainImagesClassifier)
<commit_msg>ENH: re-write TrainImagesClassifier as composite application (WIP)<commit_after>/*=========================================================================
 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperCompositeApplication.h"
#include "otbWrapperApplicationFactory.h"

namespace otb
{
namespace Wrapper
{

class TrainImagesClassifier: public CompositeApplication
{
public:
  /** Standard class typedefs. */
  typedef TrainImagesClassifier Self;
  typedef CompositeApplication Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self)

  itkTypeMacro(TrainImagesClassifier, otb::Wrapper::CompositeApplication)

protected:

private:

void DoInit() ITK_OVERRIDE
{
  SetName("TrainImagesClassifier");
  SetDescription(
    "Train a classifier from multiple pairs of images and training vector data.");

  // Documentation
  SetDocName("Train a classifier from multiple images");
  SetDocLongDescription(
    "This application performs a classifier training from multiple pairs of input images and training vector data. "
    "Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by "
    "the ComputeImagesStatistics application.\n The training vector data must contain polygons with a positive integer field "
    "representing the class label. The name of this field can be set using the \"Class label field\" parameter. Training and validation "
    "sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio "
    "between the number of samples in training and validation sets. Two parameters allow managing the size of the training and "
    "validation sets per class and per image.\n Several classifier parameters can be set depending on the chosen classifier. In the "
    "validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. "
    "In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels"
    " are ordered according to the rows/columns of the confusion matrix.\n This application is based on LibSVM and OpenCV Machine Learning "
    "(2.3.1 and later).");
  SetDocLimitations("None");
  SetDocAuthors("OTB-Team");
  SetDocSeeAlso("OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html ");

  AddApplication("PolygonClassStatistics", "polystat","Polygon analysis");
  AddApplication("MultiImageSamplingRate", "rates", "Sampling rates");
  AddApplication("SampleSelection", "select", "Sample selection");
  AddApplication("SampleExtraction","extraction", "Sample extraction");
  AddApplication("TrainVectorClassifier", "training", "Model training");

  //Group IO
  AddParameter(ParameterType_Group, "io", "Input and output data");
  SetParameterDescription("io", "This group of parameters allows setting input and output data.");

  AddParameter(ParameterType_InputImageList, "io.il", "Input Image List");
  SetParameterDescription("io.il", "A list of input images.");
  AddParameter(ParameterType_InputVectorDataList, "io.vd", "Input Vector Data List");
  SetParameterDescription("io.vd", "A list of vector data to select the training samples.");

  ShareParameter("io.imstat","training.io.stats");
  ShareParameter("io.confmatout","training.io.confmatout");
  ShareParameter("io.out","training.io.out");

  // TODO : handle elev parameters ?

  // Sampling settings
  AddParameter(ParameterType_Group, "sample", "Training and validation samples parameters");
  SetParameterDescription("sample",
    "This group of parameters allows you to set training and validation sample lists parameters.");
  AddParameter(ParameterType_Int, "sample.mt", "Maximum training sample size per class");
  SetDefaultParameterInt("sample.mt", 1000);
  SetParameterDescription("sample.mt", "Maximum size per class (in pixels) of "
    "the training sample list (default = 1000) (no limit = -1). If equal to -1,"
    " then the maximal size of the available training sample list per class "
    "will be equal to the surface area of the smallest class multiplied by the"
    " training sample ratio.");
  AddParameter(ParameterType_Int, "sample.mv", "Maximum validation sample size per class");
  SetDefaultParameterInt("sample.mv", 1000);
  SetParameterDescription("sample.mv", "Maximum size per class (in pixels) of "
    "the validation sample list (default = 1000) (no limit = -1). If equal to -1,"
    " then the maximal size of the available validation sample list per class "
    "will be equal to the surface area of the smallest class multiplied by the "
    "validation sample ratio.");
  AddParameter(ParameterType_Int, "sample.bm", "Bound sample number by minimum");
  SetDefaultParameterInt("sample.bm", 1);
  SetParameterDescription("sample.bm", "Bound the number of samples for each "
    "class by the number of available samples by the smaller class. Proportions "
    "between training and validation are respected. Default is true (=1).");
  AddParameter(ParameterType_Float, "sample.vtr", "Training and validation sample ratio");
  SetParameterDescription("sample.vtr",
    "Ratio between training and validation samples (0.0 = all training, 1.0 = "
    "all validation) (default = 0.5).");
  SetParameterFloat("sample.vtr", 0.5);

  ShareParameter("sample.vfn","training.cfield");
  ShareParameter("sample.strategy","rates.strategy");
  ShareParameter("sample.mim","rates.mim");

  // Classifier settings
  ShareParameter("classifier","training.classifier");

  ShareParameter("rand","training.rand");

  // Synchronization between applications
  Connect("select.field", "polystat.field");
  Connect("select.layer", "polystat.layer");

  Connect("extraction.in",    "select.in");
  Connect("extraction.vec",   "select.vec");
  Connect("extraction.field", "select.field");
  Connect("extraction.layer", "select.layer");

  Connect("select.rand", "training.rand");

  // Doc example parameter settings
  SetDocExampleParameterValue("io.il", "QB_1_ortho.tif");
  SetDocExampleParameterValue("io.vd", "VectorData_QB1.shp");
  SetDocExampleParameterValue("io.imstat", "EstimateImageStatisticsQB1.xml");
  SetDocExampleParameterValue("sample.mv", "100");
  SetDocExampleParameterValue("sample.mt", "100");
  SetDocExampleParameterValue("sample.vtr", "0.5");
  SetDocExampleParameterValue("sample.edg", "false");
  SetDocExampleParameterValue("sample.vfn", "Class");
  SetDocExampleParameterValue("classifier", "libsvm");
  SetDocExampleParameterValue("classifier.libsvm.k", "linear");
  SetDocExampleParameterValue("classifier.libsvm.c", "1");
  SetDocExampleParameterValue("classifier.libsvm.opt", "false");
  SetDocExampleParameterValue("io.out", "svmModelQB1.txt");
  SetDocExampleParameterValue("io.confmatout", "svmConfusionMatrixQB1.csv");
}

void DoUpdateParameters() ITK_OVERRIDE
{
  // TODO : if an image is present, check number of bands and fill training.field ListView
  if (HasValue("io.il"))
    {
    FloatVectorImageListType* imageList = GetParameterImageList("io.il");
    FloatVectorImageType::Pointer image = imageList->GetNthElement(imgIndex);
    //image->UpdateOutputInformation();
    unsigned int nbBands = image->GetNumberOfComponentsPerPixel();
    GetInternalApplication("training")->ClearChoices("feat");
    std::string key("feat.value");
    std::string value("value_");
    for (unsigned int i=0 ; i<nbBands ; i++)
      {
      std::ostringstream oss;
      oss << i;
      GetInternalApplication("training")->AddChoices(key+oss.str(),value+oss.str());
      }
    }
}

void DoExecute() ITK_OVERRIDE
{
  FloatVectorImageListType* imageList = GetParameterImageList("io.il");
  std::vector<std::string> vectorFileList = GetParameterStringList("io.vd");
  unsigned int nbInputs = imageList->Size();
  std::string outModel(GetParameterString("io.out"));
  std::vector<std::string> polyStatOutputs;
  std::vector<std::string> ratesOutputs;

  // Polygons stats
  for (unsigned int i=0 ; i<nbInputs ; i++)
    {
    std::ostringstream oss;
    oss << outModel << "_stats"<<i<<".xml";
    polyStatOutputs.push_back(oss.str());
    GetInternalApplication("polystat")->SetParameterInputImage("in",imageList->GetNthElement(i));
    GetInternalApplication("polystat")->SetParameterString("vec",vectorFileList[i]);
    GetInternalApplication("polystat")->SetParameterString("out",oss.str());
    }
}

};

} // end namespace Wrapper
} // end namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::TrainImagesClassifier)
<|endoftext|>


<commit_before>#ifndef REMAPFILTERFACTORY_HPP
#define REMAPFILTERFACTORY_HPP

#include "bridge.h"
#include "ApplicationFilter.hpp"
#include "ConfigFilter.hpp"
#include "DeviceFilter.hpp"
#include "ElapsedTimeSinceLastPressedFilter.hpp"
#include "IOLogWrapper.hpp"
#include "InputSourceFilter.hpp"
#include "LastPressedPhysicalKeyFilter.hpp"
#include "ModifierFilter.hpp"
#include "PressingPhysicalKeysFilter.hpp"
#include "UIElementRoleFilter.hpp"
#include "WindowNameFilter.hpp"

namespace org_pqrs_Karabiner {
namespace RemapFilter {
class RemapFilterFactory final {
public:
  static RemapFilterBase* create(const unsigned int* vec, size_t length) {
    // ------------------------------------------------------------
    // check parameters.
    //
    if (!vec || length == 0) {
      IOLOG_ERROR("RemapFilterFactory::create invalid parameter %p, %ld.\n", vec, length);
      return nullptr;
    }

    // ------------------------------------------------------------
    unsigned int type = vec[0];
    ++vec;
    --length;

    switch (type) {
    case BRIDGE_FILTERTYPE_APPLICATION_NOT:
    case BRIDGE_FILTERTYPE_APPLICATION_ONLY:
      return new ApplicationFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_CONFIG_NOT:
    case BRIDGE_FILTERTYPE_CONFIG_ONLY:
      return new ConfigFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_DEVICE_NOT:
    case BRIDGE_FILTERTYPE_DEVICE_ONLY:
      return new DeviceFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_ELAPSEDTIMESINCELASTPRESSED_GREATERTHAN:
    case BRIDGE_FILTERTYPE_ELAPSEDTIMESINCELASTPRESSED_LESSTHAN:
      return new ElapsedTimeSinceLastPressedFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_INPUTSOURCE_NOT:
    case BRIDGE_FILTERTYPE_INPUTSOURCE_ONLY:
      return new InputSourceFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_LASTPRESSEDPHYSICALKEY_NOT:
    case BRIDGE_FILTERTYPE_LASTPRESSEDPHYSICALKEY_ONLY:
      return new LastPressedPhysicalKeyFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_MODIFIER_NOT:
    case BRIDGE_FILTERTYPE_MODIFIER_ONLY:
    case BRIDGE_FILTERTYPE_MODIFIER_LOCKED_NOT:
    case BRIDGE_FILTERTYPE_MODIFIER_LOCKED_ONLY:
    case BRIDGE_FILTERTYPE_MODIFIER_STUCK_NOT:
    case BRIDGE_FILTERTYPE_MODIFIER_STUCK_ONLY:
      return new ModifierFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_PRESSINGPHYSICALKEYS_GREATERTHAN:
    case BRIDGE_FILTERTYPE_PRESSINGPHYSICALKEYS_LESSTHAN:
      return new PressingPhysicalKeysFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_WINDOWNAME_NOT:
    case BRIDGE_FILTERTYPE_WINDOWNAME_ONLY:
      return new WindowNameFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_UIELEMENTROLE_NOT:
    case BRIDGE_FILTERTYPE_UIELEMENTROLE_ONLY:
      return new UIElementRoleFilter(type, vec, length);
    }

    IOLOG_ERROR("RemapFilterFactory::create unknown type:%d.\n", type);
    return nullptr;
  }
};
}
}

#endif
<commit_msg>add ElapsedTimeSinceLastReleasedFilter, LastReleasedPhysicalKeyFilter into RemapFilterFactory<commit_after>#ifndef REMAPFILTERFACTORY_HPP
#define REMAPFILTERFACTORY_HPP

#include "bridge.h"
#include "ApplicationFilter.hpp"
#include "ConfigFilter.hpp"
#include "DeviceFilter.hpp"
#include "ElapsedTimeSinceLastPressedFilter.hpp"
#include "ElapsedTimeSinceLastReleasedFilter.hpp"
#include "IOLogWrapper.hpp"
#include "InputSourceFilter.hpp"
#include "LastPressedPhysicalKeyFilter.hpp"
#include "LastReleasedPhysicalKeyFilter.hpp"
#include "ModifierFilter.hpp"
#include "PressingPhysicalKeysFilter.hpp"
#include "UIElementRoleFilter.hpp"
#include "WindowNameFilter.hpp"

namespace org_pqrs_Karabiner {
namespace RemapFilter {
class RemapFilterFactory final {
public:
  static RemapFilterBase* create(const unsigned int* vec, size_t length) {
    // ------------------------------------------------------------
    // check parameters.
    //
    if (!vec || length == 0) {
      IOLOG_ERROR("RemapFilterFactory::create invalid parameter %p, %ld.\n", vec, length);
      return nullptr;
    }

    // ------------------------------------------------------------
    unsigned int type = vec[0];
    ++vec;
    --length;

    switch (type) {
    case BRIDGE_FILTERTYPE_APPLICATION_NOT:
    case BRIDGE_FILTERTYPE_APPLICATION_ONLY:
      return new ApplicationFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_CONFIG_NOT:
    case BRIDGE_FILTERTYPE_CONFIG_ONLY:
      return new ConfigFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_DEVICE_NOT:
    case BRIDGE_FILTERTYPE_DEVICE_ONLY:
      return new DeviceFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_ELAPSEDTIMESINCELASTPRESSED_GREATERTHAN:
    case BRIDGE_FILTERTYPE_ELAPSEDTIMESINCELASTPRESSED_LESSTHAN:
      return new ElapsedTimeSinceLastPressedFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_ELAPSEDTIMESINCELASTRELEASED_GREATERTHAN:
    case BRIDGE_FILTERTYPE_ELAPSEDTIMESINCELASTRELEASED_LESSTHAN:
      return new ElapsedTimeSinceLastReleasedFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_INPUTSOURCE_NOT:
    case BRIDGE_FILTERTYPE_INPUTSOURCE_ONLY:
      return new InputSourceFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_LASTPRESSEDPHYSICALKEY_NOT:
    case BRIDGE_FILTERTYPE_LASTPRESSEDPHYSICALKEY_ONLY:
      return new LastPressedPhysicalKeyFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_LASTRELEASEDPHYSICALKEY_NOT:
    case BRIDGE_FILTERTYPE_LASTRELEASEDPHYSICALKEY_ONLY:
      return new LastReleasedPhysicalKeyFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_MODIFIER_NOT:
    case BRIDGE_FILTERTYPE_MODIFIER_ONLY:
    case BRIDGE_FILTERTYPE_MODIFIER_LOCKED_NOT:
    case BRIDGE_FILTERTYPE_MODIFIER_LOCKED_ONLY:
    case BRIDGE_FILTERTYPE_MODIFIER_STUCK_NOT:
    case BRIDGE_FILTERTYPE_MODIFIER_STUCK_ONLY:
      return new ModifierFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_PRESSINGPHYSICALKEYS_GREATERTHAN:
    case BRIDGE_FILTERTYPE_PRESSINGPHYSICALKEYS_LESSTHAN:
      return new PressingPhysicalKeysFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_WINDOWNAME_NOT:
    case BRIDGE_FILTERTYPE_WINDOWNAME_ONLY:
      return new WindowNameFilter(type, vec, length);

    case BRIDGE_FILTERTYPE_UIELEMENTROLE_NOT:
    case BRIDGE_FILTERTYPE_UIELEMENTROLE_ONLY:
      return new UIElementRoleFilter(type, vec, length);
    }

    IOLOG_ERROR("RemapFilterFactory::create unknown type:%d.\n", type);
    return nullptr;
  }
};
}
}

#endif
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : A.cpp
 * Author  : Kazune Takahashi
 * Created : 11/2/2019, 1:43:18 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

constexpr int MOD{40};
constexpr int dx[4] = {-1, 1, 0, 0};
constexpr int dy[4] = {0, 0, -1, 1};
constexpr char direction[4] = {'U', 'D', 'L', 'R'};
constexpr int reverse_direction[4] = {1, 0, 3, 2};

using Point = tuple<int, int>;
Point operator+(Point const &lhs, Point const &rhs)
{
  return Point((get<0>(lhs) + get<0>(rhs) + MOD) % MOD, (get<1>(lhs) + get<1>(rhs) + MOD) % MOD);
}

void TLE()
{
  while (true)
  {
    cout << "";
  }
}

enum class State
{
  Empty,
  Robot,
  Block,
  Goal,
  Invalid
};

class Field
{
public:
  static int N;
  int M, B;
  static vector<Point> V;
  static vector<vector<Point>> P;
  vector<vector<int>> D;
  vector<vector<State>> S;
  bool is_sample_one;

  Field();
  void solve();
  void flush();

  State get_state(Point const &p) const
  {
    return S[get<0>(p)][get<1>(p)];
  }

  State &set_state(Point const &p, State s)
  {
    return S[get<0>(p)][get<1>(p)] = s;
  }

  int get_direction(Point const &p) const
  {
    return D[get<0>(p)][get<1>(p)];
  }

  int &set_direction(Point const &p, int d)
  {
    return D[get<0>(p)][get<1>(p)] = d;
  }

private:
  void good_place();
  void other_place();
  void fill_empty();
};

int Field::N;
vector<Point> Field::V;
vector<vector<Point>> Field::P;

Field::Field()
{
  cin >> M >> B;
  D = vector<vector<int>>(N, vector<int>(N, -1));
  S = vector<vector<State>>(N, vector<State>(N, State::Empty));
  int gx, gy;
  cin >> gx >> gy;
  int x, y;
  char c;
  for (auto i = 0; i < M; i++)
  {
    cin >> x >> y >> c;
    S[x][y] = State::Robot;
  }
  for (auto i = 0; i < B; i++)
  {
    cin >> x >> y;
    S[x][y] = State::Block;
  }
  S[gx][gy] = State::Goal;
  is_sample_one = (gx == 32 && gy == 8);
}

void Field::solve()
{
  if (is_sample_one)
  {
    good_place();
    other_place();
    fill_empty();
  }
  else
  {
    TLE();
  }
}

void Field::good_place()
{
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (S[i][j] == State::Robot)
      {
        for (auto k = 0; k < 4; k++)
        {
          Point p{P[i][j] + V[k]};
          State s{get_state(p)};
          if (s == State::Block || s == State::Robot)
          {
            D[i][j] = k;
            break;
          }
        }
      }
    }
  }
}

void Field::other_place()
{
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (S[i][j] == State::Robot && D[i][j] == -1)
      {
        for (auto k = 0; k < 4; k++)
        {
          Point p{P[i][j] + V[k]};
          int d{get_direction(p)};
          // State s{get_state(p)};
          if (d != -1)
          {
            D[i][j] = k;
            break;
          }
        }
        if (D[i][j] != -1)
        {
          continue;
        }
        for (auto k = 0; k < 4; k++)
        {
          Point p{P[i][j] + V[k]};
          // int d{get_direction(p)};
          State s{get_state(p)};
          if (s == State::Empty)
          {
            D[i][j] = k;
            if (get_direction(p) == -1)
            {
              set_direction(p, reverse_direction[k]);
            }
            break;
          }
        }
        assert(D[i][j] != -1);
      }
    }
  }
}

void Field::fill_empty()
{
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (D[i][j] == -1)
      {
        D[i][j] = 0;
      }
    }
  }
}

void Field::flush()
{
  int K{0};
  for (auto x = 0; x < N; x++)
  {
    for (auto y = 0; y < N; y++)
    {
      if (0 <= D[x][y] && D[x][y] < 4)
      {
        ++K;
      }
    }
  }
  cout << K << endl;
  for (auto x = 0; x < N; x++)
  {
    for (auto y = 0; y < N; y++)
    {
      if (0 <= D[x][y] && D[x][y] < 4)
      {
        cout << x << " " << y << " " << direction[D[x][y]] << endl;
      }
    }
  }
}

int main()
{
  cin >> Field::N;
  for (auto i = 0; i < 4; i++)
  {
    Field::V.push_back(Point{dy[i], dx[i]});
  }
  Field::P = vector<vector<Point>>(Field::N, vector<Point>(Field::N));
  for (auto i = 0; i < Field::N; i++)
  {
    for (auto j = 0; j < Field::N; j++)
    {
      Field::P[i][j] = Point{i, j};
    }
  }
  Field f;
  f.solve();
  f.flush();
}<commit_msg>submit A.cpp to 'A - ロボットの誘導' (future-contest-2020-qual) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
 * File    : A.cpp
 * Author  : Kazune Takahashi
 * Created : 11/2/2019, 1:43:18 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

constexpr int MOD{40};
constexpr int dx[4] = {-1, 1, 0, 0};
constexpr int dy[4] = {0, 0, -1, 1};
constexpr char direction[4] = {'U', 'D', 'L', 'R'};
constexpr int reverse_direction[4] = {1, 0, 3, 2};

using Point = tuple<int, int>;
Point operator+(Point const &lhs, Point const &rhs)
{
  return Point((get<0>(lhs) + get<0>(rhs) + MOD) % MOD, (get<1>(lhs) + get<1>(rhs) + MOD) % MOD);
}

void TLE()
{
  while (true)
  {
    cout << "";
  }
}

namespace Tools
{

template <typename T>
T get(Point const &p, vector<vector<T>> const &X)
{
  return X[get<0>(p)][get<1>(p)];
}

template <typename T>
void set(Point const &p, T val, vector<vector<T>> &X)
{
  X[get<0>(p)][get<1>(p)] = val;
}

}; // namespace Tools

enum class State
{
  Empty,
  Robot,
  Block,
  Goal,
  Invalid
};

class Field
{
public:
  static int N;
  static vector<Point> V;
  static vector<vector<Point>> P;
  int M, B;
  vector<vector<int>> D;
  vector<vector<State>> S;
  vector<Point> robots;
  bool is_sample_one;

  Field();
  void solve();
  void flush();
  int score();
  int direction_count();

  State get_state(Point const &p) const { return Tools::get(p, S); }
  void set_state(Point const &p, State s) { Tools::set(p, s, S); }
  int get_direction(Point const &p) const { return Tools::get(p, D); }
  void set_direction(Point const &p, int d) { Tools::set(p, d, D); }

private:
  bool reach(Point const &p, vector<vector<bool>> &used);
  void good_place();
  void other_place();
  void fill_empty();
};

int Field::N;
vector<Point> Field::V;
vector<vector<Point>> Field::P;

Field::Field()
{
  cin >> M >> B;
  D = vector<vector<int>>(N, vector<int>(N, -1));
  S = vector<vector<State>>(N, vector<State>(N, State::Empty));
  int gx, gy;
  cin >> gx >> gy;
  int x, y;
  char c;
  for (auto i = 0; i < M; i++)
  {
    cin >> x >> y >> c;
    S[x][y] = State::Robot;
    robots.emplace_back(x, y);
  }
  for (auto i = 0; i < B; i++)
  {
    cin >> x >> y;
    S[x][y] = State::Block;
  }
  S[gx][gy] = State::Goal;
  is_sample_one = (gx == 32 && gy == 8); // これで十分のようだ。
}

void Field::solve()
{
  if (!is_sample_one)
  {
    good_place();
    other_place();
    fill_empty();
  }
  else
  {
    good_place();
    other_place();
    fill_empty();
  }
}

void Field::good_place()
{
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (S[i][j] == State::Robot)
      {
        for (auto k = 0; k < 4; k++)
        {
          Point p{P[i][j] + V[k]};
          State s{get_state(p)};
          if (s == State::Block || s == State::Robot)
          {
            D[i][j] = k;
            break;
          }
        }
      }
    }
  }
}

void Field::other_place()
{
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (S[i][j] == State::Robot && D[i][j] == -1)
      {
        for (auto k = 0; k < 4; k++)
        {
          Point p{P[i][j] + V[k]};
          int d{get_direction(p)};
          if (d != -1)
          {
            D[i][j] = k;
            break;
          }
        }
        if (D[i][j] != -1)
        {
          continue;
        }
        for (auto k = 0; k < 4; k++)
        {
          Point p{P[i][j] + V[k]};
          State s{get_state(p)};
          if (s == State::Empty)
          {
            D[i][j] = k;
            if (get_direction(p) == -1)
            {
              set_direction(p, reverse_direction[k]);
            }
            break;
          }
        }
        assert(D[i][j] != -1);
      }
    }
  }
}

void Field::fill_empty()
{
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (D[i][j] == -1)
      {
        D[i][j] = 0;
      }
    }
  }
}

int Field::direction_count()
{
  int K{0};
  for (auto x = 0; x < N; x++)
  {
    for (auto y = 0; y < N; y++)
    {
      if (S[x][y] != State::Goal && S[x][y] != State::Block && 0 <= D[x][y] && D[x][y] < 4)
      {
        ++K;
      }
    }
  }
  return K;
}

void Field::flush()
{
  int K{Field::direction_count()};
  cout << K << endl;
  for (auto x = 0; x < N; x++)
  {
    for (auto y = 0; y < N; y++)
    {
      if (S[x][y] != State::Goal && S[x][y] != State::Block && 0 <= D[x][y] && D[x][y] < 4)
      {
        cout << x << " " << y << " " << direction[D[x][y]] << endl;
      }
    }
  }
}

bool Field::reach(Point const &p, vector<vector<bool>> &used)
{
  stack<Point> st;
  vector<vector<bool>> visited(N, vector<bool>(N, false));
  st.push(p);
  while (!st.empty())
  {
    Point p{st.top()};
    st.pop();
    if (!Tools::get(p, visited))
    {
      Tools::set(p, true, visited);
      Tools::set(p, true, used);
      if (Tools::get(p, S) == State::Goal)
      {
        return true;
      }
      int k{get_direction(p)};
      assert(k != -1);
      Point q{p + V[k]};
      if (get_state(q) == State::Block)
      {
        return false;
      }
      st.push(q);
    }
  }
  return false;
}

int Field::score()
{
  int ans{0};
  vector<vector<bool>> used(N, vector<bool>(N, false));
  for (auto const &x : robots)
  {
    if (reach(x, used))
    {
      ans += 1000;
    }
  }
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (used[i][j])
      {
        ++ans;
      }
    }
  }
  ans -= 10 * direction_count();
  return ans;
}

int main()
{
  cin >> Field::N;
  for (auto i = 0; i < 4; i++)
  {
    Field::V.push_back(Point{dx[i], dy[i]});
  }
  Field::P = vector<vector<Point>>(Field::N, vector<Point>(Field::N));
  for (auto i = 0; i < Field::N; i++)
  {
    for (auto j = 0; j < Field::N; j++)
    {
      Field::P[i][j] = Point{i, j};
    }
  }
  Field f;
  f.solve();
  cerr << f.score() << endl;
  f.flush();
}<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <map>
#include <node.h>

#include "PSATResult.h"
#include "calculator/EstimateFLA.h"

using namespace v8;
using namespace std;

Isolate* iso;
Local<Object> inp;

//todo assert exist
double Get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}

void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();
  auto r = Object::New(iso);

  auto drive = (Pump::Drive)(int)Get("drive");
  auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");

  Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_rated_speed"),drive,
      Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
  Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
      effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
  Financial fin(Get("fraction"),Get("cost"));
  FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
      Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
  PSATResult psat(pump,motor,fin,fd);
  psat.calculate();
  auto ex = psat.getExisting();

  map<const char *,vector<double>> out = {
    {"Pump Efficiency",{ex.pumpEfficiency_*100,0}},
    {"Motor Rated Power",{ex.motorRatedPower_,0}},
    {"Motor Shaft Power",{ex.motorShaftPower_,0}},
    {"Pump Shaft Power",{ex.pumpShaftPower_,0}},
    {"Motor Efficiency",{ex.motorEfficiency_,0}},
    {"Motor Power Factor",{ex.motorPowerFactor_,0}},
    {"Motor Current",{ex.motorCurrent_,0}},
    {"Motor Power", {ex.motorPower_,0}},
    {"Annual Energy", {ex.annualEnergy_,0}},
    {"Annual Cost", {ex.annualCost_*1000,0}},
    {"Savings Potential", {psat.getAnnualSavingsPotential(),0}},
    {"Optimization Rating", {psat.getOptimizationRating(),0}}
  };
  for(auto p: out) {
    auto a = Array::New(iso);
    a->Set(0,Number::New(iso,p.second[0]));
    a->Set(1,Number::New(iso,p.second[1]));
    r->Set(String::NewFromUtf8(iso,p.first),a);
  }
  args.GetReturnValue().Set(r);
}

void EstFLA(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();

  EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
    Get("efficiency"),Get("motor_rated_voltage"));
  fla.calculate();
  args.GetReturnValue().Set(fla.getEstimatedFLA());
}

void Check(double exp, double act, const char* nm="") {
  if (abs(exp-act)>.01*exp) {
    printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
    assert(!"equal");
  }
}

void Check100(double exp, double act, const char* nm="") {
  Check(exp,act*100,nm);
}

void TestSame() {
  // auto msp = (new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460));
  for (int i=1; i<=10000; i=i+2) {
    // Check(msp->calculate(),msp->calculate(),"SAME");
  }
}
// void Test(const FunctionCallbackInfo<Value>& args) {
//   TestSame();
//   //assume power load meth, est fla, line=60
//   auto msp = new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(101.9,msp->calculate());
//   Check100(95,msp->calculateEfficiency());
//   Check100(79.1,msp->calculatePowerFactor());
//   Check(127,msp->calculateCurrent());

//   msp = new MotorShaftPower(200,111.855,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(143.4,msp->calculate());
//   Check100(95.6,msp->calculateEfficiency());
//   Check100(84.3,msp->calculatePowerFactor());
//   Check(166.5,msp->calculateCurrent());

//   msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,260);
//   Check(101.9,msp->calculate());
//   Check100(95,msp->calculateEfficiency());
//   Check100(138.8,msp->calculatePowerFactor());
//   Check(128,msp->calculateCurrent());

//   msp = new MotorShaftPower(100,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(101.8,msp->calculate());
//   Check100(94.9,msp->calculateEfficiency());
//   Check100(86.7,msp->calculatePowerFactor());
//   Check(115.8,msp->calculateCurrent());

//   msp = new MotorShaftPower(200,80,1200,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(101.4,msp->calculate());
//   Check100(94.5,msp->calculateEfficiency());
//   Check100(74.3,msp->calculatePowerFactor());
//   Check(135.1,msp->calculateCurrent());

//   // msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,200,460);
//   // Check(101.9,msp->calculate());
//   // Check100(95,msp->calculateEfficiency());
//   // Check100(35.2,msp->calculatePowerFactor());
//   // Check(285,msp->calculateCurrent());

//   auto ae = (new AnnualEnergy(80,1))->calculate();
//   Check(700.8,ae);

//   ae = (new AnnualEnergy(150,.25))->calculate();
//   Check(328.5,ae);

//   auto ac = (new AnnualCost(328.5,.05))->calculate();
//   Check(16.4,ac);

// }

void Test2(const FunctionCallbackInfo<Value>& args) {
  Pump pump((Pump::Style)0,1780,(Pump::Drive)0,
      1,1,1,(Pump::Speed)1);
  Motor motor((Motor::LineFrequency)1,200,1780,
      (Motor::EfficiencyClass)1,0,460,225,0);
  Financial fin(1,.05);
  FieldData fd(2000,277,(FieldData::LoadEstimationMethod)0,150,
      0,460);
  PSATResult psat(pump,motor,fin,fd);
  psat.calculate();
  auto ex = psat.getExisting();
  cout << ex.motorCurrent_;
}
void TestFLA(const FunctionCallbackInfo<Value>& args) {
  EstimateFLA fla(200,1780,(Motor::EfficiencyClass)(1),0,460);
  fla.calculate();
  Check(225.8,fla.getEstimatedFLA());
}
void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
  NODE_SET_METHOD(exports, "estFLA", EstFLA);
  NODE_SET_METHOD(exports, "test", TestFLA);
}

NODE_MODULE(bridge, Init)

<commit_msg>no message<commit_after>#include <iostream>
#include <vector>
#include <map>
#include <node.h>

#include "PSATResult.h"
#include "calculator/EstimateFLA.h"

using namespace v8;
using namespace std;

Isolate* iso;
Local<Object> inp;

//todo assert exist
double Get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}

void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();
  auto r = Object::New(iso);

  auto drive = (Pump::Drive)(int)Get("drive");
  auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");

  Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_rated_speed"),drive,
      Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
  Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
      effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
  Financial fin(Get("fraction"),Get("cost"));
  FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
      Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
  PSATResult psat(pump,motor,fin,fd);
  psat.calculate();
  auto ex = psat.getExisting();

  map<const char *,vector<double>> out = {
    {"Pump Efficiency",{ex.pumpEfficiency_*100,0}},
    {"Motor Rated Power",{ex.motorRatedPower_,0}},
    {"Motor Shaft Power",{ex.motorShaftPower_,0}},
    {"Pump Shaft Power",{ex.pumpShaftPower_,0}},
    {"Motor Efficiency",{ex.motorEfficiency_,0}},
    {"Motor Power Factor",{ex.motorPowerFactor_,0}},
    {"Motor Current",{ex.motorCurrent_,0}},
    {"Motor Power", {ex.motorPower_,0}},
    {"Annual Energy", {ex.annualEnergy_,0}},
    {"Annual Cost", {ex.annualCost_*1000,0}},
    {"Savings Potential", {psat.getAnnualSavingsPotential(),0}},
    {"Optimization Rating", {psat.getOptimizationRating(),0}}
  };
  for(auto p: out) {
    auto a = Array::New(iso);
    a->Set(0,Number::New(iso,p.second[0]));
    a->Set(1,Number::New(iso,p.second[1]));
    r->Set(String::NewFromUtf8(iso,p.first),a);
  }
  args.GetReturnValue().Set(r);
}

void EstFLA(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();

  EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
    Get("efficiency"),Get("motor_rated_voltage"));
  fla.calculate();
  args.GetReturnValue().Set(fla.getEstimatedFLA());
}

void Check(double exp, double act, const char* nm="") {
  cout << "e " << exp << "; a " << act << endl;
  if (abs(exp-act)>.1*exp) {
    printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
    assert(!"equal");
  }
}

void Check100(double exp, double act, const char* nm="") {
  Check(exp,act*100,nm);
}

void TestSame() {
  // auto msp = (new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460));
  for (int i=1; i<=10000; i=i+2) {
    // Check(msp->calculate(),msp->calculate(),"SAME");
  }
}
// void Test(const FunctionCallbackInfo<Value>& args) {
//   TestSame();
//   //assume power load meth, est fla, line=60
//   auto msp = new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(101.9,msp->calculate());
//   Check100(95,msp->calculateEfficiency());
//   Check100(79.1,msp->calculatePowerFactor());
//   Check(127,msp->calculateCurrent());

//   msp = new MotorShaftPower(200,111.855,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(143.4,msp->calculate());
//   Check100(95.6,msp->calculateEfficiency());
//   Check100(84.3,msp->calculatePowerFactor());
//   Check(166.5,msp->calculateCurrent());

//   msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,260);
//   Check(101.9,msp->calculate());
//   Check100(95,msp->calculateEfficiency());
//   Check100(138.8,msp->calculatePowerFactor());
//   Check(128,msp->calculateCurrent());

//   msp = new MotorShaftPower(100,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(101.8,msp->calculate());
//   Check100(94.9,msp->calculateEfficiency());
//   Check100(86.7,msp->calculatePowerFactor());
//   Check(115.8,msp->calculateCurrent());

//   msp = new MotorShaftPower(200,80,1200,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460);
//   Check(101.4,msp->calculate());
//   Check100(94.5,msp->calculateEfficiency());
//   Check100(74.3,msp->calculatePowerFactor());
//   Check(135.1,msp->calculateCurrent());

//   // msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,200,460);
//   // Check(101.9,msp->calculate());
//   // Check100(95,msp->calculateEfficiency());
//   // Check100(35.2,msp->calculatePowerFactor());
//   // Check(285,msp->calculateCurrent());

//   auto ae = (new AnnualEnergy(80,1))->calculate();
//   Check(700.8,ae);

//   ae = (new AnnualEnergy(150,.25))->calculate();
//   Check(328.5,ae);

//   auto ac = (new AnnualCost(328.5,.05))->calculate();
//   Check(16.4,ac);

// }

void Test2(const FunctionCallbackInfo<Value>& args) {
  Pump pump((Pump::Style)0,1780,(Pump::Drive)0,
      1,1,1,(Pump::Speed)1);
  Motor motor((Motor::LineFrequency)1,200,1780,
      (Motor::EfficiencyClass)1,0,460,225,0);
  Financial fin(1,.05);
  FieldData fd(2000,277,(FieldData::LoadEstimationMethod)0,150,
      0,460);
  PSATResult psat(pump,motor,fin,fd);
  psat.calculate();
  auto ex = psat.getExisting();
  cout << ex.motorCurrent_;
}
void TestFLA(const FunctionCallbackInfo<Value>& args) {
  EstimateFLA fla(200,1780,(Motor::EfficiencyClass)(1),0,460);
  fla.calculate();
  Check(225.8,fla.getEstimatedFLA());
}
void Test3(const FunctionCallbackInfo<Value>& args) {
  // Pump pump(Pump::Style::END_SUCTION_ANSI_API,1780,Pump::Drive::DIRECT_DRIVE,
  //     1,1,1,Pump::Speed::NOT_FIXED_SPEED);
  // Motor motor(Motor::LineFrequency::FREQ60,200,1780,
  //     Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.4,0);
  // Financial fin(1,.05);
  // FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,
  //     150,0,460);
  // PSATResult psat(pump,motor,fin,fd);
  // psat.calculate();
  // auto ex = psat.getExisting();

  Pump pump(Pump::Style::END_SUCTION_ANSI_API,1780,Pump::Drive::DIRECT_DRIVE,
      1,1,1,Pump::Speed::NOT_FIXED_SPEED);
  Motor motor(Motor::LineFrequency::FREQ60,200,1780,
      Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);
  Financial fin(1,.05);
  FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,
      150,0,460);
  PSATResult psat(pump,motor,fin,fd);
  psat.calculate();
  auto ex = psat.getExisting();
  Check(217.1,ex.motorCurrent_);

  Pump pump2(Pump::Style::END_SUCTION_ANSI_API,1780,Pump::Drive::DIRECT_DRIVE,
      1,1,1,Pump::Speed::NOT_FIXED_SPEED);
  Motor motor2(Motor::LineFrequency::FREQ60,200,1780,
      Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);
  Financial fin2(1,.05);
  FieldData fd2(2000,277,FieldData::LoadEstimationMethod::CURRENT,
      0,218,460);
  PSATResult psat2(pump2,motor2,fin2,fd2);
  psat2.calculate();
  auto ex2 = psat2.getExisting();
  Check(150.7,ex2.motorPower_);

}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
  NODE_SET_METHOD(exports, "estFLA", EstFLA);
  NODE_SET_METHOD(exports, "test", Test3);
}

NODE_MODULE(bridge, Init)

<|endoftext|>


<commit_before><commit_msg>Power: Fix compile error from previous push.<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ooxtablefilter (1.1.2); FILE ADDED 2008/06/10 11:57:47 sj 1.1.2.2: updating license text 2008/03/28 20:02:31 sj 1.1.2.1: initial version<commit_after><|endoftext|>