<commit_before>#include <sys/wait.h>
#include <unistd.h>

#include "errors.hpp"
#include "utils/env.hpp"
#include "utils/process.hpp"
#include "utils/string.hpp"

POLYBAR_NS

namespace process_util {
  /**
   * Check if currently in main process
   */
  bool in_parent_process(pid_t pid) {
    return pid != -1 && pid != 0;
  }

  /**
   * Check if currently in subprocess
   */
  bool in_forked_process(pid_t pid) {
    return pid == 0;
  }

  /**
   * Execute command
   */
  void exec(char* cmd, char** args) {
    if (cmd != nullptr) {
      execvp(cmd, args);
      throw system_error("execvp() failed");
    }
  }

  /**
   * Execute command using shell
   */
  void exec_sh(const char* cmd) {
    static const string shell{env_util::get("SHELL", "/bin/sh")};

    if (cmd != nullptr) {
      execlp(shell.c_str(), shell.c_str(), "-c", cmd, nullptr);
      throw system_error("execvp() failed");
    }
  }

  /**
   * Wait for child process
   */
  pid_t wait_for_completion(pid_t process_id, int* status_addr, int waitflags) {
    int saved_errno = errno;
    auto retval = waitpid(process_id, status_addr, waitflags);
    errno = saved_errno;
    return retval;
  }

  /**
   * Wait for child process
   */
  pid_t wait_for_completion(int* status_addr, int waitflags) {
    return wait_for_completion(-1, status_addr, waitflags);
  }

  /**
   * Wait for child process
   */
  pid_t wait_for_completion(pid_t process_id) {
    int status = 0;
    return wait_for_completion(process_id, &status);
  }

  /**
   * Non-blocking wait
   *
   * @see wait_for_completion
   */
  pid_t wait_for_completion_nohang(pid_t process_id, int* status) {
    return wait_for_completion(process_id, status, WNOHANG);
  }

  /**
   * Non-blocking wait
   *
   * @see wait_for_completion
   */
  pid_t wait_for_completion_nohang(int* status) {
    return wait_for_completion_nohang(-1, status);
  }

  /**
   * Non-blocking wait
   *
   * @see wait_for_completion
   */
  pid_t wait_for_completion_nohang() {
    int status = 0;
    return wait_for_completion_nohang(-1, &status);
  }

  /**
   * Non-blocking wait call which returns pid of any child process
   *
   * @see wait_for_completion
   */
  bool notify_childprocess() {
    return wait_for_completion_nohang() > 0;
  }
}

POLYBAR_NS_END
<commit_msg>fix(process_util): Prefix shell env var<commit_after>#include <sys/wait.h>
#include <unistd.h>

#include "errors.hpp"
#include "utils/env.hpp"
#include "utils/process.hpp"
#include "utils/string.hpp"

POLYBAR_NS

namespace process_util {
  /**
   * Check if currently in main process
   */
  bool in_parent_process(pid_t pid) {
    return pid != -1 && pid != 0;
  }

  /**
   * Check if currently in subprocess
   */
  bool in_forked_process(pid_t pid) {
    return pid == 0;
  }

  /**
   * Execute command
   */
  void exec(char* cmd, char** args) {
    if (cmd != nullptr) {
      execvp(cmd, args);
      throw system_error("execvp() failed");
    }
  }

  /**
   * Execute command using shell
   */
  void exec_sh(const char* cmd) {
    if (cmd != nullptr) {
      static const string shell{env_util::get("POLYBAR_SHELL", "/bin/sh")};
      execlp(shell.c_str(), shell.c_str(), "-c", cmd, nullptr);
      throw system_error("execlp() failed");
    }
  }

  /**
   * Wait for child process
   */
  pid_t wait_for_completion(pid_t process_id, int* status_addr, int waitflags) {
    int saved_errno = errno;
    auto retval = waitpid(process_id, status_addr, waitflags);
    errno = saved_errno;
    return retval;
  }

  /**
   * Wait for child process
   */
  pid_t wait_for_completion(int* status_addr, int waitflags) {
    return wait_for_completion(-1, status_addr, waitflags);
  }

  /**
   * Wait for child process
   */
  pid_t wait_for_completion(pid_t process_id) {
    int status = 0;
    return wait_for_completion(process_id, &status);
  }

  /**
   * Non-blocking wait
   *
   * @see wait_for_completion
   */
  pid_t wait_for_completion_nohang(pid_t process_id, int* status) {
    return wait_for_completion(process_id, status, WNOHANG);
  }

  /**
   * Non-blocking wait
   *
   * @see wait_for_completion
   */
  pid_t wait_for_completion_nohang(int* status) {
    return wait_for_completion_nohang(-1, status);
  }

  /**
   * Non-blocking wait
   *
   * @see wait_for_completion
   */
  pid_t wait_for_completion_nohang() {
    int status = 0;
    return wait_for_completion_nohang(-1, &status);
  }

  /**
   * Non-blocking wait call which returns pid of any child process
   *
   * @see wait_for_completion
   */
  bool notify_childprocess() {
    return wait_for_completion_nohang() > 0;
  }
}

POLYBAR_NS_END
<|endoftext|>


<commit_before>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include "os.h"
#include "x86stacktrace.h"

static const int kMaxSymbolNameLength = 256;

X86StackFrame::X86StackFrame(void *frmAddr, void *retAddr, const std::string &name)
	: frmAddr_(frmAddr), retAddr_(retAddr), name_(name)
{
}

std::string X86StackFrame::GetString() const {
	std::stringstream stream;

	stream << std::hex << std::setw(8) << std::setfill('0') << retAddr_;
	if (!name_.empty()) {
		stream << " in " << name_ << " ()";
	} else {
		stream << " in ?? ()";
	}

	return stream.str();
}

static inline void *GetReturnAddress(void *frmAddr) {
	return *reinterpret_cast<void**>(reinterpret_cast<char*>(frmAddr) + 4);
}

static inline void *GetNextFrame(void *frmAddr) {
	return *reinterpret_cast<void**>(frmAddr);
}

X86StackTrace::X86StackTrace(int framesToSkip)
	: frames_()
{
	void *frmAddr;
	void *retAddr;

	void *stackTop = 0;
	void *stackBot = 0;

	int frameCount = 0;

	#if defined _MSC_VER
		__asm {
			mov dword ptr [frmAddr], ebp
			mov eax, fs:[0x04]
			mov dword ptr [stackTop], eax
			mov eax, fs:[0x08]
			mov dword ptr [stackBot], eax
		}
	#elif defined __GNUC__
		__asm__ __volatile__(
			"movl %%ebp, %0;" : "=r"(frmAddr) : : );
		#if defined WIN32
			__asm__ __volatile__(
				"movl %%fs:(0x04), %0;"
				"movl %%fs:(0x08), %1;"
				: "=r"(stackTop), "=r"(stackBot) : : );
		#endif
	#endif

	do {
		if ((frmAddr == 0)
			|| (frmAddr >= stackTop && stackTop != 0)
		    || (frmAddr < stackBot && stackBot != 0)) {
			break;
		}
		retAddr = GetReturnAddress(frmAddr);
		if (retAddr == 0) {
			break;
		}
		frmAddr = GetNextFrame(frmAddr);
		if (++frameCount <= framesToSkip) {
			continue;
		}
		frames_.push_back(X86StackFrame(frmAddr, retAddr, os::GetSymbolName(retAddr)));
	} while (true);
}
<commit_msg>x86stacktrace: Fix return address formatting issue<commit_after>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include "os.h"
#include "x86stacktrace.h"

static const int kMaxSymbolNameLength = 256;

X86StackFrame::X86StackFrame(void *frmAddr, void *retAddr, const std::string &name)
	: frmAddr_(frmAddr), retAddr_(retAddr), name_(name)
{
}

std::string X86StackFrame::GetString() const {
	std::stringstream stream;

	stream << std::hex << std::setw(8) << std::setfill('0')
		<< reinterpret_cast<int32_t>(retAddr_) << std::dec;
	if (!name_.empty()) {
		stream << " in " << name_ << " ()";
	} else {
		stream << " in ?? ()";
	}

	return stream.str();
}

static inline void *GetReturnAddress(void *frmAddr) {
	return *reinterpret_cast<void**>(reinterpret_cast<char*>(frmAddr) + 4);
}

static inline void *GetNextFrame(void *frmAddr) {
	return *reinterpret_cast<void**>(frmAddr);
}

X86StackTrace::X86StackTrace(int framesToSkip)
	: frames_()
{
	void *frmAddr;
	void *retAddr;

	void *stackTop = 0;
	void *stackBot = 0;

	int frameCount = 0;

	#if defined _MSC_VER
		__asm {
			mov dword ptr [frmAddr], ebp
			mov eax, fs:[0x04]
			mov dword ptr [stackTop], eax
			mov eax, fs:[0x08]
			mov dword ptr [stackBot], eax
		}
	#elif defined __GNUC__
		__asm__ __volatile__(
			"movl %%ebp, %0;" : "=r"(frmAddr) : : );
		#if defined WIN32
			__asm__ __volatile__(
				"movl %%fs:(0x04), %0;"
				"movl %%fs:(0x08), %1;"
				: "=r"(stackTop), "=r"(stackBot) : : );
		#endif
	#endif

	do {
		if ((frmAddr == 0)
			|| (frmAddr >= stackTop && stackTop != 0)
		    || (frmAddr < stackBot && stackBot != 0)) {
			break;
		}
		retAddr = GetReturnAddress(frmAddr);
		if (retAddr == 0) {
			break;
		}
		frmAddr = GetNextFrame(frmAddr);
		if (++frameCount <= framesToSkip) {
			continue;
		}
		frames_.push_back(X86StackFrame(frmAddr, retAddr, os::GetSymbolName(retAddr)));
	} while (true);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>

#include "compiler.h"
#include "os.h"
#include "x86stacktrace.h"

static const int kMaxSymbolNameLength = 256;

X86StackFrame::X86StackFrame(void *frmAddr, void *retAddr, const std::string &name)
	: frmAddr_(frmAddr), retAddr_(retAddr), name_(name)
{
}

std::string X86StackFrame::GetString() const {
	std::stringstream stream;

	stream << std::hex << std::setw(8) << std::setfill('0')
		<< reinterpret_cast<long>(retAddr_) << std::dec;
	if (!name_.empty()) {
		stream << " in " << name_ << " ()";
	} else {
		stream << " in ?? ()";
	}

	return stream.str();
}

static inline void *GetReturnAddress(void *frmAddr) {
	return *reinterpret_cast<void**>(reinterpret_cast<char*>(frmAddr) + 4);
}

static inline void *GetNextFrame(void *frmAddr) {
	return *reinterpret_cast<void**>(frmAddr);
}

X86StackTrace::X86StackTrace()
	: maxDepth_(std::numeric_limits<int>::max())
	, skipCount_(0)
	, topFrame_(0)
	, stackTop_(0)
	, stackBottom_(0)
{
}

std::deque<X86StackFrame> X86StackTrace::CollectFrames() const {
	std::deque<X86StackFrame> frames;

	void *frame = topFrame_ == 0
		? compiler::GetFrameAddress()
		: topFrame_;

	for (int i = 0; i < maxDepth_; i++) {
		if (frame == 0
			|| (frame >= stackTop_ && stackTop_ != 0)
			|| (frame < stackBottom_ && stackBottom_ != 0)) {
			break;
		}

		void *ret = GetReturnAddress(frame);
		if (ret == 0) {
			break;
		}

		frame = GetNextFrame(frame);

		if (i >= skipCount_) {
			frames.push_back(X86StackFrame(frame, ret, os::GetSymbolName(ret)));
		}
	}

	return frames;
}
<commit_msg>X86StackTrace: Auto-initialize stackTop_/stackBottom_ in CollectFrames()<commit_after>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>

#include "compiler.h"
#include "os.h"
#include "x86stacktrace.h"

static const int kMaxSymbolNameLength = 256;

X86StackFrame::X86StackFrame(void *frmAddr, void *retAddr, const std::string &name)
	: frmAddr_(frmAddr), retAddr_(retAddr), name_(name)
{
}

std::string X86StackFrame::GetString() const {
	std::stringstream stream;

	stream << std::hex << std::setw(8) << std::setfill('0')
		<< reinterpret_cast<long>(retAddr_) << std::dec;
	if (!name_.empty()) {
		stream << " in " << name_ << " ()";
	} else {
		stream << " in ?? ()";
	}

	return stream.str();
}

static inline void *GetReturnAddress(void *frmAddr) {
	return *reinterpret_cast<void**>(reinterpret_cast<char*>(frmAddr) + 4);
}

static inline void *GetNextFrame(void *frmAddr) {
	return *reinterpret_cast<void**>(frmAddr);
}

X86StackTrace::X86StackTrace()
	: maxDepth_(std::numeric_limits<int>::max())
	, skipCount_(0)
	, topFrame_(0)
	, stackTop_(0)
	, stackBottom_(0)
{
}

std::deque<X86StackFrame> X86StackTrace::CollectFrames() const {
	std::deque<X86StackFrame> frames;

	void *frame = topFrame_ == 0
		? compiler::GetFrameAddress()
		: topFrame_;

	void *top = stackTop_ == 0
		? compiler::GetStackTop()
		: stackTop_;

	void *bot = stackBottom_ == 0
		? compiler::GetStackBottom()
		: stackBottom_;

	for (int i = 0; i < maxDepth_; i++) {
		if (frame == 0
			|| (frame >= top && top != 0)
			|| (frame < bot && bot != 0)) {
			break;
		}

		void *ret = GetReturnAddress(frame);
		if (ret == 0) {
			break;
		}

		frame = GetNextFrame(frame);

		if (i >= skipCount_) {
			frames.push_back(X86StackFrame(frame, ret, os::GetSymbolName(ret)));
		}
	}

	return frames;
}
<|endoftext|>


<commit_before><commit_msg>oldpath is wchar_t, so use arraysize, not sizeof.<commit_after><|endoftext|>


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

#include "umcsession.h"
#include "umcscenario.h"
#include "mrcp_message.h"

UmcSession::UmcSession(const UmcScenario* pScenario) :
	m_pScenario(pScenario),
	m_pMrcpProfile(NULL),
	m_pMrcpApplication(NULL),
	m_pMrcpSession(NULL),
	m_pMrcpMessage(NULL),
	m_Running(false),
	m_Terminating(false)
{
	static int id = 0;
	if(id == INT_MAX)
		id = 0;
	id++;

	int size = apr_snprintf(m_Id,sizeof(m_Id)-1,"%d",id);
	m_Id[size] = '\0';
}

UmcSession::~UmcSession()
{
}

bool UmcSession::Run()
{
	if(m_Running)
		return false;

	if(!m_pMrcpProfile)
		m_pMrcpProfile = m_pScenario->GetMrcpProfile();

	if(!m_pMrcpProfile || !m_pMrcpApplication)
		return false;

	/* create session */
	if(!CreateMrcpSession(m_pMrcpProfile))
		return false;

	m_Running = true;

	bool ret = false;
	if(m_pScenario->IsDiscoveryEnabled())
		ret = ResourceDiscover();
	else
		ret = Start();

	if(!ret)
	{
		m_Running = false;
		DestroyMrcpSession();
	}
	return ret;
}

bool UmcSession::Stop()
{
	if(m_Terminating)
		return false;

	return true;
}

bool UmcSession::Terminate()
{
	if(m_Terminating)
		return false;

	m_Running = false;
	m_Terminating = true;
	return (mrcp_application_session_terminate(m_pMrcpSession) == TRUE);
}

bool UmcSession::OnSessionTerminate(mrcp_sig_status_code_e status)
{
	if(!m_Terminating)
		return false;

	m_Terminating = false;
	return DestroyMrcpSession();
}

bool UmcSession::OnSessionUpdate(mrcp_sig_status_code_e status)
{
	return m_Running;
}

bool UmcSession::OnChannelAdd(mrcp_channel_t *channel, mrcp_sig_status_code_e status)
{
	return m_Running;
}

bool UmcSession::OnChannelRemove(mrcp_channel_t *channel, mrcp_sig_status_code_e status)
{
	return m_Running;
}

bool UmcSession::OnMessageReceive(mrcp_channel_t *channel, mrcp_message_t *message)
{
	if(!m_Running)
		return false;

	if(!m_pMrcpMessage)
		return false;

	/* match request identifiers */
	if(m_pMrcpMessage->start_line.request_id != message->start_line.request_id)
		return false;

	return true;
}

bool UmcSession::OnTerminateEvent(mrcp_channel_t *channel)
{
	if(!m_Running)
		return false;

	return Terminate();
}

bool UmcSession::OnResourceDiscover(mrcp_session_descriptor_t* descriptor, mrcp_sig_status_code_e status)
{
	if(!m_Running)
		return false;

	if(!Start())
		Terminate();
	return true;
}

bool UmcSession::CreateMrcpSession(const char* pProfileName)
{
	m_pMrcpSession = mrcp_application_session_create(m_pMrcpApplication,pProfileName,this);
	return (m_pMrcpSession != NULL);
}

bool UmcSession::DestroyMrcpSession()
{
	if(!m_pMrcpSession)
		return false;

	mrcp_application_session_destroy(m_pMrcpSession);
	m_pMrcpSession = NULL;
	return true;
}

bool UmcSession::AddMrcpChannel(mrcp_channel_t* pMrcpChannel)
{
	if(!m_Running)
		return false;

	return (mrcp_application_channel_add(m_pMrcpSession,pMrcpChannel) == TRUE);
}

bool UmcSession::RemoveMrcpChannel(mrcp_channel_t* pMrcpChannel)
{
	if(!m_Running)
		return false;

	return (mrcp_application_channel_remove(m_pMrcpSession,pMrcpChannel) == TRUE);
}

bool UmcSession::SendMrcpRequest(mrcp_channel_t* pMrcpChannel, mrcp_message_t* pMrcpMessage)
{
	if(!m_Running)
		return false;

	m_pMrcpMessage = pMrcpMessage;
	return (mrcp_application_message_send(m_pMrcpSession,pMrcpChannel,pMrcpMessage) == TRUE);
}

bool UmcSession::ResourceDiscover()
{
	if(!m_Running)
		return false;

	return (mrcp_application_resource_discover(m_pMrcpSession) == TRUE);
}

mrcp_channel_t* UmcSession::CreateMrcpChannel(
						mrcp_resource_id resource_id,
						mpf_termination_t* pTermination,
						mpf_rtp_termination_descriptor_t* pRtpDescriptor,
						void* pObj)
{
	return mrcp_application_channel_create(
			m_pMrcpSession,            /* session, channel belongs to */
			resource_id,               /* MRCP resource identifier */
			pTermination,              /* media termination, used to terminate audio stream */
			NULL,                      /* RTP descriptor, used to create RTP termination (NULL by default) */
			pObj);                     /* object to associate */
}

mpf_termination_t* UmcSession::CreateAudioTermination(
						const mpf_audio_stream_vtable_t* pStreamVtable,
						mpf_stream_capabilities_t* pCapabilities,
						void* pObj)
{
	return mrcp_application_audio_termination_create(
			m_pMrcpSession,  /* session, termination belongs to */
			pStreamVtable,   /* virtual methods table of audio stream */
			pCapabilities,   /* capabilities of audio stream */
			pObj);           /* object to associate */
}

mrcp_message_t* UmcSession::CreateMrcpMessage(
		mrcp_channel_t* pMrcpChannel,
		mrcp_method_id method_id)
{
	return mrcp_application_message_create(m_pMrcpSession,pMrcpChannel,method_id);
}

apr_pool_t* UmcSession::GetSessionPool() const
{
	if(!m_pMrcpSession)
		return NULL;
	return mrcp_application_session_pool_get(m_pMrcpSession);
}

const char* UmcSession::GetMrcpSessionId() const
{
	if(!m_pMrcpSession)
		return NULL;

	const apt_str_t *pId = mrcp_application_session_id_get(m_pMrcpSession);
	return pId->buf;
}
<commit_msg>Set the informative name used for debugging, while creating a new session by umc application.<commit_after>/*
 * Copyright 2008-2010 Arsen Chaloyan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id$
 */

#include "umcsession.h"
#include "umcscenario.h"
#include "mrcp_message.h"

UmcSession::UmcSession(const UmcScenario* pScenario) :
	m_pScenario(pScenario),
	m_pMrcpProfile(NULL),
	m_pMrcpApplication(NULL),
	m_pMrcpSession(NULL),
	m_pMrcpMessage(NULL),
	m_Running(false),
	m_Terminating(false)
{
	static int id = 0;
	if(id == INT_MAX)
		id = 0;
	id++;

	int size = apr_snprintf(m_Id,sizeof(m_Id)-1,"%d",id);
	m_Id[size] = '\0';
}

UmcSession::~UmcSession()
{
}

bool UmcSession::Run()
{
	if(m_Running)
		return false;

	if(!m_pMrcpProfile)
		m_pMrcpProfile = m_pScenario->GetMrcpProfile();

	if(!m_pMrcpProfile || !m_pMrcpApplication)
		return false;

	/* create session */
	if(!CreateMrcpSession(m_pMrcpProfile))
		return false;

	m_Running = true;

	bool ret = false;
	if(m_pScenario->IsDiscoveryEnabled())
		ret = ResourceDiscover();
	else
		ret = Start();

	if(!ret)
	{
		m_Running = false;
		DestroyMrcpSession();
	}
	return ret;
}

bool UmcSession::Stop()
{
	if(m_Terminating)
		return false;

	return true;
}

bool UmcSession::Terminate()
{
	if(m_Terminating)
		return false;

	m_Running = false;
	m_Terminating = true;
	return (mrcp_application_session_terminate(m_pMrcpSession) == TRUE);
}

bool UmcSession::OnSessionTerminate(mrcp_sig_status_code_e status)
{
	if(!m_Terminating)
		return false;

	m_Terminating = false;
	return DestroyMrcpSession();
}

bool UmcSession::OnSessionUpdate(mrcp_sig_status_code_e status)
{
	return m_Running;
}

bool UmcSession::OnChannelAdd(mrcp_channel_t *channel, mrcp_sig_status_code_e status)
{
	return m_Running;
}

bool UmcSession::OnChannelRemove(mrcp_channel_t *channel, mrcp_sig_status_code_e status)
{
	return m_Running;
}

bool UmcSession::OnMessageReceive(mrcp_channel_t *channel, mrcp_message_t *message)
{
	if(!m_Running)
		return false;

	if(!m_pMrcpMessage)
		return false;

	/* match request identifiers */
	if(m_pMrcpMessage->start_line.request_id != message->start_line.request_id)
		return false;

	return true;
}

bool UmcSession::OnTerminateEvent(mrcp_channel_t *channel)
{
	if(!m_Running)
		return false;

	return Terminate();
}

bool UmcSession::OnResourceDiscover(mrcp_session_descriptor_t* descriptor, mrcp_sig_status_code_e status)
{
	if(!m_Running)
		return false;

	if(!Start())
		Terminate();
	return true;
}

bool UmcSession::CreateMrcpSession(const char* pProfileName)
{
	m_pMrcpSession = mrcp_application_session_create(m_pMrcpApplication,pProfileName,this);
	char name[32];
	apr_snprintf(name,sizeof(name),"umc-%s",m_Id);
	mrcp_application_session_name_set(m_pMrcpSession,name);
	return (m_pMrcpSession != NULL);
}

bool UmcSession::DestroyMrcpSession()
{
	if(!m_pMrcpSession)
		return false;

	mrcp_application_session_destroy(m_pMrcpSession);
	m_pMrcpSession = NULL;
	return true;
}

bool UmcSession::AddMrcpChannel(mrcp_channel_t* pMrcpChannel)
{
	if(!m_Running)
		return false;

	return (mrcp_application_channel_add(m_pMrcpSession,pMrcpChannel) == TRUE);
}

bool UmcSession::RemoveMrcpChannel(mrcp_channel_t* pMrcpChannel)
{
	if(!m_Running)
		return false;

	return (mrcp_application_channel_remove(m_pMrcpSession,pMrcpChannel) == TRUE);
}

bool UmcSession::SendMrcpRequest(mrcp_channel_t* pMrcpChannel, mrcp_message_t* pMrcpMessage)
{
	if(!m_Running)
		return false;

	m_pMrcpMessage = pMrcpMessage;
	return (mrcp_application_message_send(m_pMrcpSession,pMrcpChannel,pMrcpMessage) == TRUE);
}

bool UmcSession::ResourceDiscover()
{
	if(!m_Running)
		return false;

	return (mrcp_application_resource_discover(m_pMrcpSession) == TRUE);
}

mrcp_channel_t* UmcSession::CreateMrcpChannel(
						mrcp_resource_id resource_id,
						mpf_termination_t* pTermination,
						mpf_rtp_termination_descriptor_t* pRtpDescriptor,
						void* pObj)
{
	return mrcp_application_channel_create(
			m_pMrcpSession,            /* session, channel belongs to */
			resource_id,               /* MRCP resource identifier */
			pTermination,              /* media termination, used to terminate audio stream */
			NULL,                      /* RTP descriptor, used to create RTP termination (NULL by default) */
			pObj);                     /* object to associate */
}

mpf_termination_t* UmcSession::CreateAudioTermination(
						const mpf_audio_stream_vtable_t* pStreamVtable,
						mpf_stream_capabilities_t* pCapabilities,
						void* pObj)
{
	return mrcp_application_audio_termination_create(
			m_pMrcpSession,  /* session, termination belongs to */
			pStreamVtable,   /* virtual methods table of audio stream */
			pCapabilities,   /* capabilities of audio stream */
			pObj);           /* object to associate */
}

mrcp_message_t* UmcSession::CreateMrcpMessage(
		mrcp_channel_t* pMrcpChannel,
		mrcp_method_id method_id)
{
	return mrcp_application_message_create(m_pMrcpSession,pMrcpChannel,method_id);
}

apr_pool_t* UmcSession::GetSessionPool() const
{
	if(!m_pMrcpSession)
		return NULL;
	return mrcp_application_session_pool_get(m_pMrcpSession);
}

const char* UmcSession::GetMrcpSessionId() const
{
	if(!m_pMrcpSession)
		return NULL;

	const apt_str_t *pId = mrcp_application_session_id_get(m_pMrcpSession);
	return pId->buf;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <list>
#include <string>
#include <queue>

using std::cout;
using std::ifstream;
using std::ofstream;
using std::list;
using std::string;
using std::queue;

list<string> hot_potato(const list<string>& players, int passes) {
  queue<string> circle;
  list<string> players_ranking;

  for (const string& player : players) {
    circle.push(player);
  }

  while (circle.size() > 1) {
    for (int i = 0; i < passes; ++i) {
      const string& current_player = circle.front();
      circle.pop();
      circle.push(current_player);
    }

    players_ranking.push_back(circle.front());
    cout << circle.front() << '\n';
    circle.pop();
  }

  players_ranking.push_back(circle.front());
  cout << circle.front() << '\n';
  circle.pop();

  return players_ranking;
}

list<string> read_game(const char* game_input_file, int& passes) {
  ifstream file(game_input_file);

  int number_of_players;
  file >> number_of_players;

  list<string> players;

  for (int i = 0; i < number_of_players; ++i) {
    string current_player;
    file >> current_player;
    players.push_back(current_player);
  }

  file >> passes;

  file.close();

  return players;
}

void write_game(const list<string>& players_ranking, const char* game_output_file) {
  ofstream file(game_output_file);

  for (const string& player : players_ranking) {
    file << player << '\n';
  }

  file.close();
}

int main() {
  int passes;
  list<string> players = read_game("game-input.txt", passes);

  list<string> players_ranking = hot_potato(players, passes);

  write_game(players_ranking, "game-output.txt");

  return 0;
}
<commit_msg>Add bonus task solution<commit_after>#include <iostream>
#include <fstream>
#include <list>
#include <string>
#include <queue>

using std::cout;
using std::ifstream;
using std::ofstream;
using std::ios;
using std::list;
using std::string;
using std::queue;

list<string> hot_potato(const list<string>& players, int passes) {
  queue<string> circle;
  list<string> players_ranking;

  for (const string& player : players) {
    circle.push(player);
  }

  while (circle.size() > 1) {
    for (int i = 0; i < passes; ++i) {
      const string& current_player = circle.front();
      circle.pop();
      circle.push(current_player);
    }

    players_ranking.push_back(circle.front());
    cout << circle.front() << '\n';
    circle.pop();
  }

  players_ranking.push_back(circle.front());
  cout << circle.front() << '\n';
  circle.pop();

  return players_ranking;
}

list<string> read_game(const char* game_input_file, int& passes) {
  ifstream file(game_input_file);

  int number_of_players;
  file >> number_of_players;

  list<string> players;

  for (int i = 0; i < number_of_players; ++i) {
    string current_player;
    file >> current_player;
    players.push_back(current_player);
  }

  file >> passes;

  file.close();

  return players;
}

void write_game(const list<string>& players_ranking, const char* game_output_file) {
  ofstream file(game_output_file);

  for (const string& player : players_ranking) {
    file << player << '\n';
  }

  file.close();
}

void write_game_binary(const list<string>& players_ranking, const char* game_output_file) {
  ofstream file(game_output_file, ios::binary);

  for (const string& player : players_ranking) {
    file.write((player + "\n").c_str(), player.size() + 1);
  }
}

void read_game_results(const char* game_output_file) {
  ifstream file(game_output_file, ios::binary);

  const int BUFFER_SIZE = 100;
  char buffer[BUFFER_SIZE];

  long read_count = 0;
  while ((read_count = file.read(buffer, BUFFER_SIZE - 1).gcount())) {
    buffer[read_count] = '\0';
    cout << buffer;
  }
}

int main() {
  int passes;
  list<string> players = read_game("game-input.txt", passes);

  list<string> players_ranking = hot_potato(players, passes);

  write_game(players_ranking, "game-output.txt");

  write_game_binary(players_ranking, "game-output.bin");

  read_game_results("game-output.bin");

  return 0;
}
<|endoftext|>


<commit_before>
#include "lispCallbacks.h"

#include "PraxisTexture.h"
#include "PraxisServer.h"
#include "PraxisLog.h"

#include "World.h"

#include "SingleWorldConfiguration.h"

extern s7_scheme * g_pLisp;

static int s7_type_tag_transform = 0;

static s7_pointer s7cbDrawLine(s7_scheme *sc, s7_pointer args)
{
    float x1 = s7_number_to_real(sc, s7_list_ref(sc, args, 0));
    float y1 = s7_number_to_real(sc, s7_list_ref(sc, args, 1));
    float z1 = s7_number_to_real(sc, s7_list_ref(sc, args, 2));
    float x2 = s7_number_to_real(sc, s7_list_ref(sc, args, 3));
    float y2 = s7_number_to_real(sc, s7_list_ref(sc, args, 4));
    float z2 = s7_number_to_real(sc, s7_list_ref(sc, args, 5));

    glBegin(GL_LINES);

    glVertex3f(x1,y1,z1);
    glVertex3f(x2,y2,z2);

    glEnd();

    return(s7_make_integer(sc, 0));
}

static s7_pointer s7cbNewTransform(s7_scheme * sc, s7_pointer args)
{

    return s7_make_object(sc, s7_type_tag_transform, (void *)0);
}

void lispInitCallbacks()
{
    s7_type_tag_transform = s7_new_type("transform", NULL, NULL, NULL, NULL, NULL, NULL);

    s7_define_function(g_pLisp, "draw-line", s7cbDrawLine, 6, 0, false, "");
}
<commit_msg>Focussing on Lisp again<commit_after>
#include "lispCallbacks.h"

#include "PraxisTexture.h"
#include "PraxisServer.h"
#include "PraxisLog.h"

#include "World.h"

#include "SingleWorldConfiguration.h"

extern s7_scheme * g_pLisp;

#include <glm/vec3.hpp> // glm::vec3
#include <glm/vec4.hpp> // glm::vec4
#include <glm/mat4x4.hpp> // glm::mat4
#include <glm/gtc/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective

static int s7_type_tag_transform = 0;

static s7_pointer s7cbDrawLine(s7_scheme *sc, s7_pointer args)
{
    float x1 = s7_number_to_real(sc, s7_list_ref(sc, args, 0));
    float y1 = s7_number_to_real(sc, s7_list_ref(sc, args, 1));
    float z1 = s7_number_to_real(sc, s7_list_ref(sc, args, 2));
    float x2 = s7_number_to_real(sc, s7_list_ref(sc, args, 3));
    float y2 = s7_number_to_real(sc, s7_list_ref(sc, args, 4));
    float z2 = s7_number_to_real(sc, s7_list_ref(sc, args, 5));

    glBegin(GL_LINES);

    glVertex3f(x1,y1,z1);
    glVertex3f(x2,y2,z2);

    glEnd();

    return(s7_make_integer(sc, 0));
}

static s7_pointer s7cbNewTransform(s7_scheme * sc, s7_pointer args)
{

    return s7_make_object(sc, s7_type_tag_transform, (void *)0);
}

void lispInitCallbacks()
{
    s7_type_tag_transform = s7_new_type("transform", NULL, NULL, NULL, NULL, NULL, NULL);

    s7_define_function(g_pLisp, "draw-line", s7cbDrawLine, 6, 0, false, "");
}
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdo_resource.cpp
  \authors   Урусов Андрей (rdo@rk9.bmstu.ru)
  \authors   Лущан Дмитрий (dluschan@rk9.bmstu.ru)
  \date      16.04.2008
  \brief     RDOResource implementation
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/foreach.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_resource.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)
	: RDORuntimeObject   (                                      )
	, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))
	, m_temporary        (temporary                             )
	, m_state            (RDOResource::CS_None                  )
	, m_type             (typeID                                )
	, m_referenceCount   (0                                     )
	, m_resType          (pResType                              )
	, m_db               (pRuntime->getDB()                     )
{
	appendParams(paramList.begin(), paramList.end());
}

/// @todo копирующий конструктор не используется - нужен ли он?
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)
	: RDORuntimeObject   (                 )
	, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())
	, m_paramList        (copy.m_paramList )
	, m_temporary        (copy.m_temporary )
	, m_state            (copy.m_state     )
	, m_type             (copy.m_type      )
	, m_referenceCount   (0                )
	, m_resType          (copy.m_resType   )
	, m_typeId           (copy.m_typeId    )
{
	UNUSED(pRuntime);
	appendParams(copy.m_paramList.begin(), copy.m_paramList.end());
/// @todo посмотреть history и принять решение о комментарии
//	getRuntime()->incrementResourceIdReference( getTraceID() );
}

RDOResource::~RDOResource()
{}

rbool RDOResource::operator!= (RDOResource &other)
{
	if (m_type != other.m_type) return true;
	if (m_paramList.size() != other.m_paramList.size()) return true;

	int size = m_paramList.size();
	for (int i = 0; i < size; ++i)
	{
		if (m_paramList.at(i) != other.m_paramList.at(i)) return true;
	}
	return false;
}

LPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const
{
	LPRDOResource pResource = rdo::Factory<RDOResource>::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);
	ASSERT(pResource);
	pRuntime->insertNewResource(pResource);
	return pResource;
}

tstring RDOResource::getTypeId() const
{
	rdo::ostringstream str;
	str << m_type;
	return str.str();
}

tstring RDOResource::traceParametersValue()
{
	rdo::ostringstream str;
	if(m_paramList.size() > 0)
	{
		ParamList::iterator end = m_paramList.end();
		for (ParamList::iterator it = m_paramList.begin();;)
		{
#ifdef RDOSIM_COMPATIBLE
			rdo::ostringstream _str;
			_str << *it;
			tstring::size_type pos = _str.str().find("e");
			if (pos != tstring::npos)
			{
				tstring __str = _str.str();
				__str.erase(pos + 2, 1);
				str << __str.c_str();
			}
			else
			{
				str << _str.str().c_str();
			}
#else
			str << *it;
#endif
			if (++it == end)
				break;
			str << " ";
		}
	}
	return str.str();
}

tstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)
{
	rdo::ostringstream res;
	if (traceable() || (prefix != '\0'))
	{
		if (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)
			return "";

		if (prefix != '\0')
			res << prefix;

		switch (m_state)
		{
		case RDOResource::CS_Create:
			res << "RC ";
			break;
		case RDOResource::CS_Erase:
			res << "RE "
#ifdef RDOSIM_COMPATIBLE
				<< pRuntime->getCurrentTime() << " "
				<< traceTypeId()              << " "
				<< traceId()                  << std::endl;
			return res.str();
#else
				;
#endif
			break;
		default:
			res << "RK ";
			break;
		}

		res << pRuntime->getCurrentTime() << " "
			<< traceTypeId()              << " "
			<< traceId()                  << " "
			<< traceParametersValue()     << std::endl;
	}
	return res.str();
}

void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
	QSqlQuery query;

	query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
		.arg(getTraceID())
		.arg(index));
	query.next();
	int value_id = query.value(query.record().indexOf("value")).toInt();

	query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
		.arg(value_id));
	query.next();
	QString table_name = query.value(query.record().indexOf("relname")).toString();

	#define DEFINE_RDO_VALUE(Value)                               \
		m_db->queryExec(QString("update %1 set vv=%2 where id=%3")\
		.arg(table_name)                                          \
		.arg(Value)                                               \
		.arg(value_id));

	switch (value.typeID())
	{
	case RDOType::t_unknow        : break;
	case RDOType::t_int           : DEFINE_RDO_VALUE(                                           value.getInt     ()  ); break;
	case RDOType::t_real          : DEFINE_RDO_VALUE(                                           value.getDouble  ()  ); break;
	case RDOType::t_enum          : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
	case RDOType::t_bool          : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
	case RDOType::t_string        : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getString  ()))); break;
	case RDOType::t_identificator : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
	default                       : throw RDOValueException("Данная величина не может быть записана в базу данных");
	}

	ASSERT(index < m_paramList.size());
	setState(CS_Keep);
	m_paramList[index] = value;
}

CREF(RDOValue) RDOResource::getParam(ruint index)
{
	ASSERT(index < m_paramList.size());

#ifndef DB_CACHE_ENABLE
	QSqlQuery query;

	int traceID = getTraceID();
	query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
		.arg(traceID)
		.arg(index));
	query.next();
	int value_id = query.value(query.record().indexOf("value")).toInt();

	query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
		.arg(value_id));
	query.next();
	QString table_name = query.value(query.record().indexOf("relname")).toString();

	query.exec(QString("select vv from %1 where id=%2;")
		.arg(table_name)
		.arg(value_id));
	query.next();

	QVariant varValue = query.value(query.record().indexOf("vv"));

	if (table_name == QString("int_rv"))
	{
		int varValueInt = varValue.toInt();
		if (varValueInt != m_paramList[index].getInt())
		{
			m_paramList[index] = RDOValue(varValueInt);
		}
	}
	else if (table_name == QString("real_rv"))
	{
		double varValueDouble = varValue.toDouble();
		if (varValueDouble != m_paramList[index].getDouble())
		{
			m_paramList[index] = RDOValue(varValueDouble);
		}
	}
	else if (table_name == QString("enum_rv"))
	{
		tstring varValueEnum = varValue.toString().toStdString();
		if (varValueEnum != m_paramList[index].getAsString())
		{
			m_paramList[index] = RDOValue(m_paramList[index].type().object_static_cast<RDOEnumType>(),varValueEnum);
		}
	}
	else if (table_name == QString("bool_rv"))
	{
		bool varValueBool = varValue.toBool();
		if (varValueBool != m_paramList[index].getBool())
		{
			m_paramList[index] = RDOValue(varValueBool);
		}
	}
	else if (table_name == QString("string_rv"))
	{
		tstring varValueString = varValue.toString().toStdString();
		if (varValueString != m_paramList[index].getString())
		{
			m_paramList[index] = RDOValue(varValueString);
		}
	}
	else if (table_name == QString("identificator_rv"))
	{
		tstring varValueIdentificator = varValue.toString().toStdString();
		if (varValueIdentificator != m_paramList[index].getIdentificator())
		{
			m_paramList[index] = RDOValue(varValueIdentificator);
		}
	}
#endif

	return m_paramList[index];
}

void RDOResource::serializeInDB() const
{
	bool a = traceable();
	m_db->insertRow("rss",QString("%1,%2,%3")
		.arg(getTraceID())
		.arg(boost::lexical_cast<int>(getTypeId()))
		.arg(a ? "true" : "false"));
	int rss_id = m_db->queryExecIndex("rss");
	int param_id = -1;

	BOOST_FOREACH(const RDOValue& param, m_paramList)
	{
		param.serializeInDB(*m_db);
		m_db->insertRow("rss_param",QString("%1,%2,%3")
			.arg(rss_id)
			.arg(++param_id)
			.arg(m_db->popContext<int>()));
	}
}

CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - оптимизация запросов в БД<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdo_resource.cpp
  \authors   Урусов Андрей (rdo@rk9.bmstu.ru)
  \authors   Лущан Дмитрий (dluschan@rk9.bmstu.ru)
  \date      16.04.2008
  \brief     RDOResource implementation
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/foreach.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_resource.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)
	: RDORuntimeObject   (                                      )
	, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))
	, m_temporary        (temporary                             )
	, m_state            (RDOResource::CS_None                  )
	, m_type             (typeID                                )
	, m_referenceCount   (0                                     )
	, m_resType          (pResType                              )
	, m_db               (pRuntime->getDB()                     )
{
	appendParams(paramList.begin(), paramList.end());
}

/// @todo копирующий конструктор не используется - нужен ли он?
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)
	: RDORuntimeObject   (                 )
	, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())
	, m_paramList        (copy.m_paramList )
	, m_temporary        (copy.m_temporary )
	, m_state            (copy.m_state     )
	, m_type             (copy.m_type      )
	, m_referenceCount   (0                )
	, m_resType          (copy.m_resType   )
	, m_typeId           (copy.m_typeId    )
{
	UNUSED(pRuntime);
	appendParams(copy.m_paramList.begin(), copy.m_paramList.end());
/// @todo посмотреть history и принять решение о комментарии
//	getRuntime()->incrementResourceIdReference( getTraceID() );
}

RDOResource::~RDOResource()
{}

rbool RDOResource::operator!= (RDOResource &other)
{
	if (m_type != other.m_type) return true;
	if (m_paramList.size() != other.m_paramList.size()) return true;

	int size = m_paramList.size();
	for (int i = 0; i < size; ++i)
	{
		if (m_paramList.at(i) != other.m_paramList.at(i)) return true;
	}
	return false;
}

LPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const
{
	LPRDOResource pResource = rdo::Factory<RDOResource>::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);
	ASSERT(pResource);
	pRuntime->insertNewResource(pResource);
	return pResource;
}

tstring RDOResource::getTypeId() const
{
	rdo::ostringstream str;
	str << m_type;
	return str.str();
}

tstring RDOResource::traceParametersValue()
{
	rdo::ostringstream str;
	if(m_paramList.size() > 0)
	{
		ParamList::iterator end = m_paramList.end();
		for (ParamList::iterator it = m_paramList.begin();;)
		{
#ifdef RDOSIM_COMPATIBLE
			rdo::ostringstream _str;
			_str << *it;
			tstring::size_type pos = _str.str().find("e");
			if (pos != tstring::npos)
			{
				tstring __str = _str.str();
				__str.erase(pos + 2, 1);
				str << __str.c_str();
			}
			else
			{
				str << _str.str().c_str();
			}
#else
			str << *it;
#endif
			if (++it == end)
				break;
			str << " ";
		}
	}
	return str.str();
}

tstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)
{
	rdo::ostringstream res;
	if (traceable() || (prefix != '\0'))
	{
		if (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)
			return "";

		if (prefix != '\0')
			res << prefix;

		switch (m_state)
		{
		case RDOResource::CS_Create:
			res << "RC ";
			break;
		case RDOResource::CS_Erase:
			res << "RE "
#ifdef RDOSIM_COMPATIBLE
				<< pRuntime->getCurrentTime() << " "
				<< traceTypeId()              << " "
				<< traceId()                  << std::endl;
			return res.str();
#else
				;
#endif
			break;
		default:
			res << "RK ";
			break;
		}

		res << pRuntime->getCurrentTime() << " "
			<< traceTypeId()              << " "
			<< traceId()                  << " "
			<< traceParametersValue()     << std::endl;
	}
	return res.str();
}

void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
	QSqlQuery query;

	query.exec(QString("select rss_param.value, pg_class.relname \
		from rss_param, pg_class, rdo_value \
		where rss_param.rss_id=%1 \
		and rss_param.id=%2 \
		and pg_class.relfilenode=rdo_value.table_id \
		and rdo_value.value_id=rss_param.value;")
			.arg(getTraceID())
			.arg(index));
	query.next();
	int value_id = query.value(query.record().indexOf("value")).toInt();
	QString table_name = query.value(query.record().indexOf("relname")).toString();

	#define DEFINE_RDO_VALUE(Value)                               \
		m_db->queryExec(QString("update %1 set vv=%2 where id=%3")\
		.arg(table_name)                                          \
		.arg(Value)                                               \
		.arg(value_id));

	switch (value.typeID())
	{
	case RDOType::t_unknow        : break;
	case RDOType::t_int           : DEFINE_RDO_VALUE(                                           value.getInt     ()  ); break;
	case RDOType::t_real          : DEFINE_RDO_VALUE(                                           value.getDouble  ()  ); break;
	case RDOType::t_enum          : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
	case RDOType::t_bool          : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
	case RDOType::t_string        : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getString  ()))); break;
	case RDOType::t_identificator : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
	default                       : throw RDOValueException("Данная величина не может быть записана в базу данных");
	}

	ASSERT(index < m_paramList.size());
	setState(CS_Keep);
	m_paramList[index] = value;
}

CREF(RDOValue) RDOResource::getParam(ruint index)
{
	ASSERT(index < m_paramList.size());

#ifndef DB_CACHE_ENABLE
	QSqlQuery query;

	int traceID = getTraceID();
	query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
		.arg(traceID)
		.arg(index));
	query.next();
	int value_id = query.value(query.record().indexOf("value")).toInt();

	query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
		.arg(value_id));
	query.next();
	QString table_name = query.value(query.record().indexOf("relname")).toString();

	query.exec(QString("select vv from %1 where id=%2;")
		.arg(table_name)
		.arg(value_id));
	query.next();

	QVariant varValue = query.value(query.record().indexOf("vv"));

	if (table_name == QString("int_rv"))
	{
		int varValueInt = varValue.toInt();
		if (varValueInt != m_paramList[index].getInt())
		{
			m_paramList[index] = RDOValue(varValueInt);
		}
	}
	else if (table_name == QString("real_rv"))
	{
		double varValueDouble = varValue.toDouble();
		if (varValueDouble != m_paramList[index].getDouble())
		{
			m_paramList[index] = RDOValue(varValueDouble);
		}
	}
	else if (table_name == QString("enum_rv"))
	{
		tstring varValueEnum = varValue.toString().toStdString();
		if (varValueEnum != m_paramList[index].getAsString())
		{
			m_paramList[index] = RDOValue(m_paramList[index].type().object_static_cast<RDOEnumType>(),varValueEnum);
		}
	}
	else if (table_name == QString("bool_rv"))
	{
		bool varValueBool = varValue.toBool();
		if (varValueBool != m_paramList[index].getBool())
		{
			m_paramList[index] = RDOValue(varValueBool);
		}
	}
	else if (table_name == QString("string_rv"))
	{
		tstring varValueString = varValue.toString().toStdString();
		if (varValueString != m_paramList[index].getString())
		{
			m_paramList[index] = RDOValue(varValueString);
		}
	}
	else if (table_name == QString("identificator_rv"))
	{
		tstring varValueIdentificator = varValue.toString().toStdString();
		if (varValueIdentificator != m_paramList[index].getIdentificator())
		{
			m_paramList[index] = RDOValue(varValueIdentificator);
		}
	}
#endif

	return m_paramList[index];
}

void RDOResource::serializeInDB() const
{
	bool a = traceable();
	m_db->insertRow("rss",QString("%1,%2,%3")
		.arg(getTraceID())
		.arg(boost::lexical_cast<int>(getTypeId()))
		.arg(a ? "true" : "false"));
	int rss_id = m_db->queryExecIndex("rss");
	int param_id = -1;

	BOOST_FOREACH(const RDOValue& param, m_paramList)
	{
		param.serializeInDB(*m_db);
		m_db->insertRow("rss_param",QString("%1,%2,%3")
			.arg(rss_id)
			.arg(++param_id)
			.arg(m_db->popContext<int>()));
	}
}

CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|>


<commit_before>// @(#)root/gl:$Id$
// Author:  Matevz Tadel, Jun 2007

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TF2GL.h"

#include <TF2.h>
#include <TF3.h>
#include <TH2.h>
#include <TVirtualPad.h>

#include "TGLSurfacePainter.h"
#include "TGLTF3Painter.h"
#include "TGLAxisPainter.h"

#include "TGLRnrCtx.h"

#include "TGLIncludes.h"

//______________________________________________________________________
//
// GL renderer for TF2.
// TGLPlotPainter is used internally.

ClassImp(TF2GL);

//______________________________________________________________________________
TF2GL::TF2GL() : TGLPlot3D(), fM(0), fH(0)
{
   // Constructor.
}

//______________________________________________________________________________
TF2GL::~TF2GL()
{
   // Destructor.

   delete fH;
}

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

//______________________________________________________________________________
Bool_t TF2GL::SetModel(TObject* obj, const Option_t* opt)
{
   // Set model object.

   TString option(opt);
   option.ToLower();

   if (SetModelCheckClass(obj, TF2::Class()))
   {
      fM = dynamic_cast<TF2*>(obj);
      fH = (TH2*) fM->CreateHistogram();
      fH->GetZaxis()->SetLimits(fH->GetMinimum(), fH->GetMaximum());

      if (dynamic_cast<TF3*>(fM))
         SetPainter( new TGLTF3Painter((TF3*)fM, fH, 0, &fCoord) );
      else
         SetPainter( new TGLSurfacePainter(fH, 0, &fCoord) );

      if (option.Index("sph") != kNPOS)
         fCoord.SetCoordType(kGLSpherical);
      else if (option.Index("pol") != kNPOS)
         fCoord.SetCoordType(kGLPolar);
      else if (option.Index("cyl") != kNPOS)
         fCoord.SetCoordType(kGLCylindrical);

      fPlotPainter->AddOption(option);
      fPlotPainter->InitGeometry();
      return kTRUE;
   }
   return kFALSE;
}

//______________________________________________________________________________
void TF2GL::SetBBox()
{
   // Setup bounding-box.

   fBoundingBox.Set(fPlotPainter->RefBackBox().Get3DBox());
}

//______________________________________________________________________________
void TF2GL::DirectDraw(TGLRnrCtx & rnrCtx) const
{
   // Render the object.

   fPlotPainter->RefBackBox().FindFrontPoint();

   glPushAttrib(GL_ENABLE_BIT | GL_LIGHTING_BIT);

   glEnable(GL_NORMALIZE);
   glDisable(GL_COLOR_MATERIAL);

   fPlotPainter->InitGL();
   fPlotPainter->DrawPlot();

   glDisable(GL_CULL_FACE);
   glPopAttrib();

   // Axes
   TGLAxisPainterBox axe_painter;
   axe_painter.SetUseAxisColors(kFALSE);
   axe_painter.SetFontMode(TGLFont::kPixmap);
   axe_painter.PlotStandard(rnrCtx, fH, fBoundingBox);
}
<commit_msg>- cov #11672<commit_after>// @(#)root/gl:$Id$
// Author:  Matevz Tadel, Jun 2007

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TF2GL.h"

#include <TF2.h>
#include <TF3.h>
#include <TH2.h>
#include <TVirtualPad.h>

#include "TGLSurfacePainter.h"
#include "TGLTF3Painter.h"
#include "TGLAxisPainter.h"

#include "TGLRnrCtx.h"

#include "TGLIncludes.h"

//______________________________________________________________________
//
// GL renderer for TF2.
// TGLPlotPainter is used internally.

ClassImp(TF2GL);

//______________________________________________________________________________
TF2GL::TF2GL() : TGLPlot3D(), fM(0), fH(0)
{
   // Constructor.
}

//______________________________________________________________________________
TF2GL::~TF2GL()
{
   // Destructor.

   delete fH;
}

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

//______________________________________________________________________________
Bool_t TF2GL::SetModel(TObject* obj, const Option_t* opt)
{
   // Set model object.

   TString option(opt);
   option.ToLower();

   if (SetModelCheckClass(obj, TF2::Class()))
   {
      fM = dynamic_cast<TF2*>(obj);
      if (!fM) return kFALSE;
      fH = (TH2*) fM->CreateHistogram();
      fH->GetZaxis()->SetLimits(fH->GetMinimum(), fH->GetMaximum());

      if (dynamic_cast<TF3*>(fM))
         SetPainter( new TGLTF3Painter((TF3*)fM, fH, 0, &fCoord) );
      else
         SetPainter( new TGLSurfacePainter(fH, 0, &fCoord) );

      if (option.Index("sph") != kNPOS)
         fCoord.SetCoordType(kGLSpherical);
      else if (option.Index("pol") != kNPOS)
         fCoord.SetCoordType(kGLPolar);
      else if (option.Index("cyl") != kNPOS)
         fCoord.SetCoordType(kGLCylindrical);

      fPlotPainter->AddOption(option);
      fPlotPainter->InitGeometry();
      return kTRUE;
   }
   return kFALSE;
}

//______________________________________________________________________________
void TF2GL::SetBBox()
{
   // Setup bounding-box.

   fBoundingBox.Set(fPlotPainter->RefBackBox().Get3DBox());
}

//______________________________________________________________________________
void TF2GL::DirectDraw(TGLRnrCtx & rnrCtx) const
{
   // Render the object.

   fPlotPainter->RefBackBox().FindFrontPoint();

   glPushAttrib(GL_ENABLE_BIT | GL_LIGHTING_BIT);

   glEnable(GL_NORMALIZE);
   glDisable(GL_COLOR_MATERIAL);

   fPlotPainter->InitGL();
   fPlotPainter->DrawPlot();

   glDisable(GL_CULL_FACE);
   glPopAttrib();

   // Axes
   TGLAxisPainterBox axe_painter;
   axe_painter.SetUseAxisColors(kFALSE);
   axe_painter.SetFontMode(TGLFont::kPixmap);
   axe_painter.PlotStandard(rnrCtx, fH, fBoundingBox);
}
<|endoftext|>


<commit_before>#pragma once

#include <iostream>
#include <memory>
#include <chrono>
#include <random>
#include <mutex>
#include <tuple>

#include <cpprest/http_listener.h>

#include "json.hpp"
#include "loader.hpp"
#include "log.hpp"

namespace nervana
{
    template <typename T>
    class statused_response
    {
    public:
        statused_response(int _status_code, const T& _value)
            : status_code(_status_code)
            , value(_value)
        {
        }
        int status_code;
        T   value;
    };

    using json_response = statused_response<web::json::value>;
    using next_tuple    = std::tuple<web::json::value, std::string>;

    class loader_adapter
    {
    public:
        loader_adapter(const nlohmann::json& config)
            : m_loader(config)
        {
        }
        void        reset();
        std::string next();

        std::string batch_size() const;
        std::string names_and_shapes() const;
        std::string batch_count() const;
        std::string record_count() const;

    private:
        nervana::loader_local m_loader;
        std::mutex            m_mutex;
        bool                  m_is_reset{ true };
    };

    class loader_manager
    {
    public:
        loader_manager()
            : m_id_generator(std::random_device{}())
        {
        }
        uint32_t register_agent(const nlohmann::json& config);
        void                     unregister_agent(uint32_t);
        nervana::loader_adapter& loader(uint32_t id);

    private:
        const uint32_t max_loader_number = 1000;
        std::mt19937   m_id_generator;
        std::mutex     m_mutex;
        std::map<uint32_t, std::unique_ptr<nervana::loader_adapter>> m_loaders;
    };

    class server_parser
    {
    public:
        server_parser();
        json_response post(std::string msg, std::string msg_body);
        json_response del(std::string msg);
        statused_response<next_tuple> get(std::string msg);

    private:
        const std::string version         = "v1";
        const std::string endpoint_prefix = "/" + version + "/dataset";
        typedef web::json::value (server_parser::*msg_process_func_t)(loader_adapter&);
        std::map<std::string, server_parser::msg_process_func_t> process_func;

        loader_manager m_loader_manager;

        statused_response<next_tuple> next(loader_adapter& loader);
        web::json::value batch_size(loader_adapter& loader);
        web::json::value reset(loader_adapter& loader);
        web::json::value names_and_shapes(loader_adapter& loader);
        web::json::value batch_count(loader_adapter& loader);
        web::json::value record_count(loader_adapter& loader);
    };

  class daemon {
  public:
    explicit daemon(const std::string& addr)
      : listener_{ web::http::uri_builder{ addr }.append_path(U("api")).to_uri() }
    {
      listener_.support(web::http::methods::POST,
                        std::bind(&daemon::handle_post, this, std::placeholders::_1));
      listener_.support(web::http::methods::GET,
                        std::bind(&daemon::handle_get, this, std::placeholders::_1));
      listener_.support(web::http::methods::DEL,
                        std::bind(&daemon::handle_delete, this, std::placeholders::_1));

      listener_.open().wait();
    }

    daemon() = delete;

    daemon(const daemon&) = delete;
    daemon& operator = (const daemon&) = delete;

    daemon(daemon&&) = delete;
    daemon& operator = (daemon&&) = delete;

    ~daemon() {
      listener_.close().wait();
    }

  private:
    web::http::experimental::listener::http_listener listener_;
    server_parser server_parser_;

    void handle_post(web::http::http_request r) {
      log::info("POST %s", r.relative_uri().path());
      r.reply(web::http::status_codes::Accepted,
              server_parser_.post(web::uri::decode(r.relative_uri().path()),
                                  r.extract_string().get()));
    }
    void handle_get(web::http::http_request r) {
      log::info("GET %s", r.relative_uri().path());
      auto answer{ server_parser_.get(web::uri::decode(r.relative_uri().path())) };
      r.reply(std::get<1>(answer).empty() ?
              web::http::status_codes::OK : web::http::status_codes::Accepted,
              std::get<0>(answer));
    }
    void handle_delete(web::http::http_request r) {
      log::info("DELETE %s", r.relative_uri().path());
      r.reply(web::http::status_codes::OK,
              server_parser_.del(web::uri::decode(r.relative_uri().path())));
    }
  };
}
<commit_msg>fix compilation error of AEON-Service after rebase<commit_after>#pragma once

#include <iostream>
#include <memory>
#include <chrono>
#include <random>
#include <mutex>
#include <tuple>

#include <cpprest/http_listener.h>

#include "json.hpp"
#include "loader.hpp"
#include "log.hpp"

namespace nervana
{
    template <typename T>
    class statused_response
    {
    public:
        statused_response(int _status_code, const T& _value)
            : status_code(_status_code)
            , value(_value)
        {
        }
        int status_code;
        T   value;
    };

    using json_response = statused_response<web::json::value>;
    using next_tuple    = std::tuple<web::json::value, std::string>;

    class loader_adapter
    {
    public:
        loader_adapter(const nlohmann::json& config)
            : m_loader(config)
        {
        }
        void        reset();
        std::string next();

        std::string batch_size() const;
        std::string names_and_shapes() const;
        std::string batch_count() const;
        std::string record_count() const;

    private:
        nervana::loader_local m_loader;
        std::mutex            m_mutex;
        bool                  m_is_reset{ true };
    };

    class loader_manager
    {
    public:
        loader_manager()
            : m_id_generator(std::random_device{}())
        {
        }
        uint32_t register_agent(const nlohmann::json& config);
        void                     unregister_agent(uint32_t);
        nervana::loader_adapter& loader(uint32_t id);

    private:
        const uint32_t max_loader_number = 1000;
        std::mt19937   m_id_generator;
        std::mutex     m_mutex;
        std::map<uint32_t, std::unique_ptr<nervana::loader_adapter>> m_loaders;
    };

    class server_parser
    {
    public:
        server_parser();
        json_response post(std::string msg, std::string msg_body);
        json_response del(std::string msg);
        statused_response<next_tuple> get(std::string msg);

    private:
        const std::string version         = "v1";
        const std::string endpoint_prefix = "/" + version + "/dataset";
        typedef web::json::value (server_parser::*msg_process_func_t)(loader_adapter&);
        std::map<std::string, server_parser::msg_process_func_t> process_func;

        loader_manager m_loader_manager;

        statused_response<next_tuple> next(loader_adapter& loader);
        web::json::value batch_size(loader_adapter& loader);
        web::json::value reset(loader_adapter& loader);
        web::json::value names_and_shapes(loader_adapter& loader);
        web::json::value batch_count(loader_adapter& loader);
        web::json::value record_count(loader_adapter& loader);
    };

  class daemon {
  public:
    explicit daemon(const std::string& addr)
      : listener_{ web::http::uri_builder{ addr }.append_path(U("api")).to_uri() }
    {
      listener_.support(web::http::methods::POST,
                        std::bind(&daemon::handle_post, this, std::placeholders::_1));
      listener_.support(web::http::methods::GET,
                        std::bind(&daemon::handle_get, this, std::placeholders::_1));
      listener_.support(web::http::methods::DEL,
                        std::bind(&daemon::handle_delete, this, std::placeholders::_1));

      listener_.open().wait();
    }

    daemon() = delete;

    daemon(const daemon&) = delete;
    daemon& operator = (const daemon&) = delete;

    daemon(daemon&&) = delete;
    daemon& operator = (daemon&&) = delete;

    ~daemon() {
      listener_.close().wait();
    }

  private:
    web::http::experimental::listener::http_listener listener_;
    server_parser server_parser_;

    void handle_post(web::http::http_request r) {
      log::info("POST %s", r.relative_uri().path());
      auto answer{ server_parser_.post(web::uri::decode(r.relative_uri().path()), r.extract_string().get()) };
      r.reply(answer.status_code, answer.value);
    }
    void handle_get(web::http::http_request r) {
      log::info("GET %s", r.relative_uri().path());
      auto answer{ server_parser_.get(web::uri::decode(r.relative_uri().path())) };
      if (std::get<1>(answer.value).empty()) {
        r.reply(answer.status_code, std::get<0>(answer.value));
      } else {
        r.reply(answer.status_code, std::get<1>(answer.value));
      }
    }
    void handle_delete(web::http::http_request r) {
      log::info("DELETE %s", r.relative_uri().path());
      auto answer{ server_parser_.del(web::uri::decode(r.relative_uri().path())) };
      r.reply(answer.status_code, answer.value);
    }
  };
}
<|endoftext|>


<commit_before>//============================================================================
// MCKL/example/random/include/random_testu01.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================

#ifndef MCKL_EXAMPLE_RANDOM_TESTU01_HPP
#define MCKL_EXAMPLE_RANDOM_TESTU01_HPP

#include <mckl/random/testu01.hpp>
#include "random_common.hpp"

template <typename RNGType, typename U01Type, typename Battery,
    typename BatteryRepeat>
inline void random_testu01(const std::string &name, Battery &&battery,
    BatteryRepeat &&battery_repeat, mckl::Vector<int> &rep)
{
    mckl::TestU01 &testu01 = mckl::TestU01::instance();
    testu01.reset<RNGType, U01Type>(name);
    rep.size() == 0 ? testu01(std::forward<Battery>(battery)) :
                      testu01(std::forward<BatteryRepeat>(battery_repeat),
                          rep.begin(), rep.end());
}

template <typename RNGType, typename Battery, typename BatteryRepeat>
inline void random_testu01(
    Battery &&battery, BatteryRepeat &&battery_repeat, int argc, char **argv)
{
    std::string filename(*argv);
    filename += ".txt";
    --argc;
    ++argv;

    bool STD = false;
    bool U01 = false;
    bool U01CC = false;
    bool U01CO = false;
    bool U01OC = false;
    bool U01OO = false;
    bool verbose = false;
    bool redirect = true;
    bool all = true;
    mckl::Vector<int> rep;
    while (argc > 0) {
        std::string arg(*argv);
        if (arg.find("STD") != std::string::npos) {
            STD = true;
            all = false;
        } else if (arg.find("U01") != std::string::npos) {
            U01 = true;
            all = false;
        } else if (arg.find("U01CC") != std::string::npos) {
            U01CC = true;
            all = false;
        } else if (arg.find("U01CO") != std::string::npos) {
            U01CO = true;
            all = false;
        } else if (arg.find("U01OC") != std::string::npos) {
            U01OC = true;
            all = false;
        } else if (arg.find("U01OO") != std::string::npos) {
            U01OO = true;
            all = false;
        } else if (arg.find("verbose") != std::string::npos) {
            verbose = true;
        } else if (arg.find("stdout") != std::string::npos) {
            redirect = false;
        } else {
            rep.push_back(std::atoi(arg.c_str()));
        }
        --argc;
        ++argv;
    }

    if (all) {
        STD = true;
        U01 = true;
        U01CC = true;
        U01CO = true;
        U01OC = true;
        U01OO = true;
    }

    if (redirect)
        std::freopen(filename.c_str(), "w", stdout);
    if (!verbose)
        ::swrite_Basic = FALSE;
    if (STD) {
        random_testu01<RNGType, std::uniform_real_distribution<double>>("STD",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01) {
        random_testu01<RNGType, mckl::U01Distribution<double>>("U01",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01CC) {
        random_testu01<RNGType, mckl::U01CCDistribution<double>>("U01CC",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01CO) {
        random_testu01<RNGType, mckl::U01CODistribution<double>>("U01CO",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01OC) {
        random_testu01<RNGType, mckl::U01OCDistribution<double>>("U01OC",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01OO) {
        random_testu01<RNGType, mckl::U01OODistribution<double>>("U01OO",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (redirect)
        std::fclose(stdout);
}

#endif // MCKL_EXAMPLE_RANDOM_TESTU01_HPP
<commit_msg>Fix argument processing<commit_after>//============================================================================
// MCKL/example/random/include/random_testu01.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================

#ifndef MCKL_EXAMPLE_RANDOM_TESTU01_HPP
#define MCKL_EXAMPLE_RANDOM_TESTU01_HPP

#include <mckl/random/testu01.hpp>
#include "random_common.hpp"

template <typename RNGType, typename U01Type, typename Battery,
    typename BatteryRepeat>
inline void random_testu01(const std::string &name, Battery &&battery,
    BatteryRepeat &&battery_repeat, mckl::Vector<int> &rep)
{
    mckl::TestU01 &testu01 = mckl::TestU01::instance();
    testu01.reset<RNGType, U01Type>(name);
    rep.size() == 0 ? testu01(std::forward<Battery>(battery)) :
                      testu01(std::forward<BatteryRepeat>(battery_repeat),
                          rep.begin(), rep.end());
}

template <typename RNGType, typename Battery, typename BatteryRepeat>
inline void random_testu01(
    Battery &&battery, BatteryRepeat &&battery_repeat, int argc, char **argv)
{
    std::string filename(*argv);
    filename += ".txt";
    --argc;
    ++argv;

    bool STD = false;
    bool U01 = false;
    bool U01CC = false;
    bool U01CO = false;
    bool U01OC = false;
    bool U01OO = false;
    bool verbose = false;
    bool redirect = true;
    bool all = true;
    mckl::Vector<int> rep;
    while (argc > 0) {
        std::string arg(*argv);
        if (arg.find("STD") != std::string::npos) {
            STD = true;
            all = false;
        } else if (arg.find("U01CC") != std::string::npos) {
            U01CC = true;
            all = false;
        } else if (arg.find("U01CO") != std::string::npos) {
            U01CO = true;
            all = false;
        } else if (arg.find("U01OC") != std::string::npos) {
            U01OC = true;
            all = false;
        } else if (arg.find("U01OO") != std::string::npos) {
            U01OO = true;
            all = false;
        } else if (arg.find("U01") != std::string::npos) {
            U01 = true;
            all = false;
        } else if (arg.find("verbose") != std::string::npos) {
            verbose = true;
        } else if (arg.find("stdout") != std::string::npos) {
            redirect = false;
        } else {
            rep.push_back(std::atoi(arg.c_str()));
        }
        --argc;
        ++argv;
    }

    if (all) {
        STD = true;
        U01 = true;
        U01CC = true;
        U01CO = true;
        U01OC = true;
        U01OO = true;
    }

    if (redirect)
        std::freopen(filename.c_str(), "w", stdout);
    if (!verbose)
        ::swrite_Basic = FALSE;
    if (STD) {
        random_testu01<RNGType, std::uniform_real_distribution<double>>("STD",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01) {
        random_testu01<RNGType, mckl::U01Distribution<double>>("U01",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01CC) {
        random_testu01<RNGType, mckl::U01CCDistribution<double>>("U01CC",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01CO) {
        random_testu01<RNGType, mckl::U01CODistribution<double>>("U01CO",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01OC) {
        random_testu01<RNGType, mckl::U01OCDistribution<double>>("U01OC",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (U01OO) {
        random_testu01<RNGType, mckl::U01OODistribution<double>>("U01OO",
            std::forward<Battery>(battery),
            std::forward<BatteryRepeat>(battery_repeat), rep);
    }
    if (redirect)
        std::fclose(stdout);
}

#endif // MCKL_EXAMPLE_RANDOM_TESTU01_HPP
<|endoftext|>


<commit_before>
/*!
 *    _________               /\
 *   /   _____/__ ____________)/
 *   \_____  \|  |  \____ \__  \
 *   /        \  |  /  |_> > __ \_
 *  /_______  /____/|   __(____  /
 *          \/      |__|       \/
 *
 *  \author    Michael E. Cotterell <mepcott@uga.edu>
 *  \date      2016-10-18
 *  \warning   Requires strptime(3) from Linux glibc.
 */

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

const char days [7][4] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};

int julian_day(int y, int m, int d);

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

  struct tm tm;                         // tm structure
  char date [11];                       // date string

  int y = atoi(argv[1]);                // year as C string
  int m = atoi(argv[2]);                // month as C string
  int d = atoi(argv[2]);                // day as C string

  sprintf(date, "%d-%d-%d", y, m, d);   // create date string
  strptime(date, "%Y-%m-%d", &tm);      // extract tm structure

  int gday = tm.tm_wday;                // num days since SUN (Gregorian)
  int jday = julian_day(y, m, d);       // num days since SUN (Julian)

  cout << "     Date: " << date << endl;
  cout << "Gregorian: " << gday << " (" << days[gday] << ")" << endl;
  cout << "   Julian: " << jday << " (" << days[jday] << ")" << endl;

  return EXIT_SUCCESS;

} // main

/**
 * Compute the Julian Day.
 * @see https://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_day_number
 */
int julian_day(int year, int month, int day) {
  int a = floor((14 - month) / 12);
  int y = year + 4800 - a;
  int m = month + 12 * a - 3;
  int j = day
    + floor((153 * m + 2) / 5)
    + (365 * y)
    + floor(y / 4)
    - 32083;
  return (j + 1) % 7;
} // julian_day

<commit_msg>reorganized some stuff<commit_after>
/*!
 *    _________               /\
 *   /   _____/__ ____________)/
 *   \_____  \|  |  \____ \__  \
 *   /        \  |  /  |_> > __ \_
 *  /_______  /____/|   __(____  /
 *          \/      |__|       \/
 *
 *  \author    Michael E. Cotterell <mepcott@uga.edu>
 *  \date      2016-10-18
 *  \warning   Requires strptime(3) from Linux glibc.
 */

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

const char days [7][4] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};

int julian_day(int y, int m, int d);
int gregorian_day(int y, int m, int d);

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

  int y = atoi(argv[1]);                // year as C string
  int m = atoi(argv[2]);                // month as C string
  int d = atoi(argv[2]);                // day as C string

  int gday = gregorian_day(y, m, d);    // num days since SUN (Gregorian)
  int jday = julian_day(y, m, d);       // num days since SUN (Julian)

  cout << "     Date: " << y << "-" << m << "-" << d << endl;
  cout << "Gregorian: " << gday << " (" << days[gday] << ")" << endl;
  cout << "   Julian: " << jday << " (" << days[jday] << ")" << endl;

  return EXIT_SUCCESS;

} // main

/**
 * Compute the Julian Day.
 * @see https://en.wikipedia.org/wiki/Julian_day#Converting_Julian_or_Gregorian_calendar_date_to_Julian_day_number
 */
int julian_day(int year, int month, int day) {
  int a = floor((14 - month) / 12);
  int y = year + 4800 - a;
  int m = month + 12 * a - 3;
  int j = day
    + floor((153 * m + 2) / 5)
    + (365 * y)
    + floor(y / 4)
    - 32083;
  return (j + 1) % 7;
} // julian_day

/**
 * Compute the Gregorian day.
 */
int gregorian_day(int y, int m, int d) {
  struct tm tm;                         // tm structure
  char date [11];                       // date string
  sprintf(date, "%d-%d-%d", y, m, d);   // create date string
  strptime(date, "%Y-%m-%d", &tm);      // extract tm structure
  return tm.tm_wday;
} // gregorian_day

<|endoftext|>


<commit_before>#ifndef CPPTEST
#define CPPTEST

#include <iostream>
#include <string>
#include <future>
#include <functional>
#include <list>

namespace cpptest {

class Module {
    std::list<std::future<bool>> results;
    std::list<std::string> cases;
    const std::string module_name;
    void report() {
        if (module_name != "")
            std::cout << '\n' << "Report for module \""
                      << module_name << "\":\n";

        std::list<std::string> failed;
        for (auto& result : results) {
            if (result.get() == false)
                failed.push_back(cases.front());
            cases.pop_front();
        }
        std::cout << '\n'
                  << results.size() - failed.size()
                  << "/" << results.size() << " tests passed.\n";
        if (!failed.empty())
            std::cout << "\nFailed tests:\n";
        for (auto& test : failed)
            std::cout << " * " << test << '\n';

        std::cout << std::endl;
    }
public:
    std::launch policy = std::launch::async;
    Module(const std::string & name = "") : module_name(name) {}
    ~Module() { report(); }
    void fn(const std::string & s, const std::function<bool()> & f) {
        cases.push_back(s);
        results.push_back(std::async(policy, f));
    }
};

} // namespace Test

#endif // CPPTEST
<commit_msg>remove threading.<commit_after>#ifndef CPPTEST
#define CPPTEST

#include <iostream>
#include <string>
#include <functional>
#include <list>

namespace cpptest {

class Module {
    std::list<std::function<bool()>> results;
    std::list<std::string> cases;
    const std::string module_name;

public:
    Module(const std::string & name = "") : module_name(name) {}
    ~Module() {
        if (module_name != "")
            std::cout << '\n' << "Report for module \""
                      << module_name << "\":\n";

        std::list<std::string> failed;
        for (auto& test : results) {
            if (test() == false)
                failed.push_back(cases.front());
            cases.pop_front();
        }
        std::cout << '\n'
                  << results.size() - failed.size()
                  << "/" << results.size() << " tests passed.\n";
        if (!failed.empty())
            std::cout << "\nFailed tests:\n";
        for (auto& test : failed)
            std::cout << " * " << test << '\n';

        std::cout << std::endl;
    }
    void fn(const std::string & s, const std::function<bool()> & fn) {
        cases.push_back(s);
        results.push_back(fn);
    }
};

} // namespace Test

#endif // CPPTEST
<|endoftext|>


<commit_before>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv

#include "evision.h"
#include "tracer.h"
#include "gpio.h"

// Global variables

// GUI globals
cv::Mat guiframe;
bool new_frame = false;
bool running = true;

// Window titles
char main_window_name[] = "Lightning Asystant :: Team eVision";
char settings_window_name[] = "Settings :: Team eVision";

// Settings variables
int settings_show_step = 0;
int settings_contrast = 0;
int settings_blur = 1;

int main(int argc, char** argv)
{
    pthread_t processing_thread, pwm_thread;
    long time_old;
    int fps_counter = 0;

    // GUI setup
	cv::namedWindow(main_window_name);

	// Setup window
	cv::namedWindow(settings_window_name);
	cv::createTrackbar("Show Step", settings_window_name, &settings_show_step, LAST_STEP-1);
	cv::createTrackbar("Contrast    ", settings_window_name, &settings_contrast, 1);
	cv::createTrackbar("Mean Blur  ", settings_window_name, &settings_blur, 1);

	pthread_create(&processing_thread, NULL, processing_thread_function, NULL);
	//pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL);

    while(running){

    	while(!new_frame){ } // loop

		cv::imshow(main_window_name, guiframe);

		// calculate fps
		if(time(NULL) != time_old){
			add_info(fps_counter);
			fps_counter = 1;
			time_old = time(NULL);
		} else {
			fps_counter++;
		}

		new_frame = 0;

		if(cv::waitKey(30) >= 0) {
			running = false;
		}
    }

	pthread_join(processing_thread, NULL);

    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

void send_frame_to_gui(cv::Mat &frame, int step){
	if((new_frame == 0) && (step == settings_show_step)){
		cv::pyrUp(frame, guiframe);
		new_frame = 1;
	}
}

void *processing_thread_function(void* unsused)
{
	cv::VideoCapture 	cap(0); // camera interface
    cv::Mat 			frame, cam_frame, bw_frame, blur_frame, contrast_frame, canny_frame;
    Tracer				processing_tracer;

    if(!cap.isOpened())  // check if we succeeded
    {
        std::cout << "Could not open default video device" << std::endl;
        pthread_exit(NULL);

    }

   	while(running) {
		if( !cap.read(frame) ){
			std::cout << "Camera was disconected";
			break;
		}

		cv::pyrDown(frame, cam_frame);
		send_frame_to_gui(cam_frame, SENSOR_IMAGE);
		processing_tracer.start();

		// All processing are done on gray image
		cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY);
		processing_tracer.event("Convert to Gray");
		send_frame_to_gui(bw_frame, GRAY_IMAGE);

		// Increase contrast by distributing color histogram to contain all values
		if(settings_contrast){
			cv::equalizeHist(bw_frame, contrast_frame);
		} else {
			contrast_frame = bw_frame;
		}
		processing_tracer.event("Equalize histogram");
		send_frame_to_gui(contrast_frame, CONTRAST_IMAGE);

		// Apply a special blur filter which preserves edges
		if(settings_blur){
			cv::medianBlur(contrast_frame, blur_frame, 7);
		} else {
			blur_frame = contrast_frame;
		}
		processing_tracer.event("Median blur");
		send_frame_to_gui(blur_frame, BLUR_IMAGE);

		// detect edges using histeresys
		cv::Canny(contrast_frame, canny_frame, 30, 100);
		processing_tracer.event("Edge detection");
		send_frame_to_gui(canny_frame, CANNY_IMAGE);
	}

	processing_tracer.end();
	pthread_exit(NULL);
}

void *pwm_thread_function(void *unsued){
	GPIO p7(7,"out");

	while(running){
		p7.high();
		usleep(10000);
		p7.low();
		usleep(10000);
	}

	pthread_exit(NULL);
}

void add_info(int fps){
	// white canvas
	cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255));

	cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20),
			cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA);

	cv::imshow(settings_window_name, img_info);
}
<commit_msg>Smaller image<commit_after>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -lpthread -shared-libgcc opencv.cpp -o opencv

#include "evision.h"
#include "tracer.h"
#include "gpio.h"

// Global variables

// GUI globals
cv::Mat guiframe;
bool new_frame = false;
bool running = true;

// Window titles
char main_window_name[] = "Lightning Asystant :: Team eVision";
char settings_window_name[] = "Settings :: Team eVision";

// Settings variables
int settings_show_step = 0;
int settings_contrast = 0;
int settings_blur = 1;

int main(int argc, char** argv)
{
    pthread_t processing_thread, pwm_thread;
    long time_old;
    int fps_counter = 0;

    // GUI setup
	cv::namedWindow(main_window_name);

	// Setup window
	cv::namedWindow(settings_window_name);
	cv::createTrackbar("Show Step", settings_window_name, &settings_show_step, LAST_STEP-1);
	cv::createTrackbar("Contrast    ", settings_window_name, &settings_contrast, 1);
	cv::createTrackbar("Mean Blur  ", settings_window_name, &settings_blur, 1);

	pthread_create(&processing_thread, NULL, processing_thread_function, NULL);
	//pthread_create(&pwm_thread, NULL, pwm_thread_function, NULL);

    while(running){

    	while(!new_frame){ } // loop

		cv::imshow(main_window_name, guiframe);

		// calculate fps
		if(time(NULL) != time_old){
			add_info(fps_counter);
			fps_counter = 1;
			time_old = time(NULL);
		} else {
			fps_counter++;
		}

		new_frame = 0;

		if(cv::waitKey(30) >= 0) {
			running = false;
		}
    }

	pthread_join(processing_thread, NULL);

    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

void send_frame_to_gui(cv::Mat &frame, int step){
	if((new_frame == 0) && (step == settings_show_step)){
		//cv::pyrUp(frame, guiframe);
		guiframe = frame;
		new_frame = 1;
	}
}

void *processing_thread_function(void* unsused)
{
	cv::VideoCapture 	cap(0); // camera interface
    cv::Mat 			frame, cam_frame, bw_frame, blur_frame, contrast_frame, canny_frame;
    Tracer				processing_tracer;

    if(!cap.isOpened())  // check if we succeeded
    {
        std::cout << "Could not open default video device" << std::endl;
        pthread_exit(NULL);

    }

   	while(running) {
		if( !cap.read(frame) ){
			std::cout << "Camera was disconected";
			break;
		}

		cv::pyrDown(frame, cam_frame);
		send_frame_to_gui(cam_frame, SENSOR_IMAGE);
		processing_tracer.start();

		// All processing are done on gray image
		cv::cvtColor(cam_frame, bw_frame, CV_BGR2GRAY);
		processing_tracer.event("Convert to Gray");
		send_frame_to_gui(bw_frame, GRAY_IMAGE);

		// Increase contrast by distributing color histogram to contain all values
		if(settings_contrast){
			cv::equalizeHist(bw_frame, contrast_frame);
		} else {
			contrast_frame = bw_frame;
		}
		processing_tracer.event("Equalize histogram");
		send_frame_to_gui(contrast_frame, CONTRAST_IMAGE);

		// Apply a special blur filter which preserves edges
		if(settings_blur){
			cv::medianBlur(contrast_frame, blur_frame, 7);
		} else {
			blur_frame = contrast_frame;
		}
		processing_tracer.event("Median blur");
		send_frame_to_gui(blur_frame, BLUR_IMAGE);

		// detect edges using histeresys
		cv::Canny(contrast_frame, canny_frame, 30, 100);
		processing_tracer.event("Edge detection");
		send_frame_to_gui(canny_frame, CANNY_IMAGE);
	}

	processing_tracer.end();
	pthread_exit(NULL);
}

void *pwm_thread_function(void *unsued){
	GPIO p7(7,"out");

	while(running){
		p7.high();
		usleep(10000);
		p7.low();
		usleep(10000);
	}

	pthread_exit(NULL);
}

void add_info(int fps){
	// white canvas
	cv::Mat img_info (25, 320, CV_8UC3, cv::Scalar(255, 255, 255));

	cv::putText(img_info, std::string("FPS: ") + std::to_string(fps), cv::Point(5, 20),
			cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,0,255), 1, CV_AA);

	cv::imshow(settings_window_name, img_info);
}
<|endoftext|>