text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef SCOPE_CORE_H
#define SCOPE_CORE_H
#ifdef SCOPE_CORE
#include "modules/scope/src/scope_core.h"
#include "modules/scope/src/generated/g_scope_core_interface.h"
#include "modules/idle/idle_detector.h"
class OpScopeCore
: public OpScopeCore_SI
, public OpActivityListener
{
public:
OpScopeCore();
virtual ~OpScopeCore();
// OpScopeService
virtual OP_STATUS OnServiceEnabled();
virtual OP_STATUS OnServiceDisabled();
// OpActivityListener.
virtual OP_STATUS OnActivityStateChanged(OpActivityState state);
// Request/Response functions
virtual OP_STATUS DoGetBrowserInformation(BrowserInformation &out);
virtual OP_STATUS DoClearPrivateData(const ClearPrivateDataArg &in);
private:
};
#endif // SCOPE_CORE
#endif // SCOPE_CORE_H
|
#ifndef ACTION_LISTENER_H
#define ACTION_LISTENER_H
#include <mqtt/async_client.h>
#include <iostream>
extern void log(std::string msg);
class action_listener : public virtual mqtt::iaction_listener {
std::string name_;
protected:
virtual void on_failure(const mqtt::itoken &tok);
virtual void on_success(const mqtt::itoken &tok);
public:
action_listener(const std::string &name) : name_(name) {}
action_listener() {}
};
#endif // ACTION_LISTENER_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef DOM2_TRAVERSAL
#include "modules/dom/src/domtraversal/treewalker.h"
#include "modules/dom/src/domtraversal/nodefilter.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domcore/node.h"
class DOM_TreeWalker_State
: public DOM_Object
{
private:
class NodeItem
{
public:
DOM_Node *node;
NodeItem *next;
};
NodeItem *first_tried;
NodeItem *first_rejected;
unsigned private_name;
public:
DOM_TreeWalker_State();
virtual ~DOM_TreeWalker_State();
OP_STATUS AddTried(DOM_Node *node);
BOOL HasTried(DOM_Node *node);
OP_STATUS AddRejected(DOM_Node *node);
BOOL HasAnyRejected();
BOOL HasRejected(DOM_Node *node);
};
DOM_TreeWalker_State::DOM_TreeWalker_State()
: first_tried(NULL),
first_rejected(NULL),
private_name(0)
{
}
DOM_TreeWalker_State::~DOM_TreeWalker_State()
{
NodeItem *item;
item = first_tried;
while (item)
{
NodeItem *next = item->next;
OP_DELETE(item);
item = next;
}
item = first_rejected;
while (item)
{
NodeItem *next = item->next;
OP_DELETE(item);
item = next;
}
}
OP_STATUS
DOM_TreeWalker_State::AddTried(DOM_Node *node)
{
RETURN_IF_ERROR(PutPrivate(private_name++, *node));
NodeItem *item = OP_NEW(NodeItem, ());
if (!item)
return OpStatus::ERR_NO_MEMORY;
item->node = node;
item->next = first_tried;
first_tried = item;
return OpStatus::OK;
}
BOOL
DOM_TreeWalker_State::HasTried(DOM_Node *node)
{
NodeItem *item = first_tried;
while (item)
{
if (item->node == node)
return TRUE;
item = item->next;
}
return FALSE;
}
OP_STATUS
DOM_TreeWalker_State::AddRejected(DOM_Node *node)
{
RETURN_IF_ERROR(PutPrivate(private_name++, *node));
NodeItem *item = OP_NEW(NodeItem, ());
if (!item)
return OpStatus::ERR_NO_MEMORY;
item->node = node;
item->next = first_rejected;
first_rejected = item;
return OpStatus::OK;
}
BOOL
DOM_TreeWalker_State::HasAnyRejected()
{
return first_rejected != NULL;
}
BOOL
DOM_TreeWalker_State::HasRejected(DOM_Node *node)
{
NodeItem *item = first_rejected;
while (item)
{
if (item->node == node)
return TRUE;
item = item->next;
}
return FALSE;
}
DOM_TreeWalker::DOM_TreeWalker()
: current_node(NULL),
current_candidate(NULL),
best_candidate(NULL),
state(NULL)
{
}
/* static */ OP_STATUS
DOM_TreeWalker::Make(DOM_TreeWalker *&tree_walker, DOM_EnvironmentImpl *environment, DOM_Node *root,
unsigned what_to_show, ES_Object *filter, BOOL entity_reference_expansion)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
RETURN_IF_ERROR(DOMSetObjectRuntime(tree_walker = OP_NEW(DOM_TreeWalker, ()), runtime, runtime->GetPrototype(DOM_Runtime::TREEWALKER_PROTOTYPE), "TreeWalker"));
if (filter)
RETURN_IF_ERROR(tree_walker->PutPrivate(DOM_PRIVATE_filter, filter));
tree_walker->root = root;
tree_walker->what_to_show = what_to_show;
tree_walker->filter = filter;
tree_walker->entity_reference_expansion = entity_reference_expansion;
tree_walker->current_node = root;
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_TreeWalker::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_root:
DOMSetObject(value, root);
return GET_SUCCESS;
case OP_ATOM_whatToShow:
DOMSetNumber(value, what_to_show);
return GET_SUCCESS;
case OP_ATOM_filter:
DOMSetObject(value, filter);
return GET_SUCCESS;
case OP_ATOM_expandEntityReferences:
DOMSetBoolean(value, entity_reference_expansion);
return GET_SUCCESS;
case OP_ATOM_currentNode:
DOMSetObject(value, current_node);
return GET_SUCCESS;
default:
return GET_FAILED;
}
}
/* virtual */ ES_PutState
DOM_TreeWalker::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_root:
case OP_ATOM_whatToShow:
case OP_ATOM_filter:
case OP_ATOM_expandEntityReferences:
return PUT_READ_ONLY;
case OP_ATOM_currentNode:
if (state)
return DOM_PUTNAME_DOMEXCEPTION(INVALID_STATE_ERR);
else if (value->type == VALUE_OBJECT)
{
DOM_HOSTOBJECT_SAFE(new_node, value->value.object, DOM_TYPE_NODE, DOM_Node);
if (new_node && new_node->GetEnvironment() == GetEnvironment())
{
current_node = new_node;
return PUT_SUCCESS;
}
}
return DOM_PUTNAME_DOMEXCEPTION(NOT_SUPPORTED_ERR);
default:
return PUT_FAILED;
}
}
/* virtual */ void
DOM_TreeWalker::GCTrace()
{
DOM_TraversalObject::GCTrace();
if (state) GetRuntime()->GCMark(state);
if (current_node) GetRuntime()->GCMark(current_node);
if (current_candidate) GetRuntime()->GCMark(current_candidate);
if (best_candidate) GetRuntime()->GCMark(best_candidate);
}
/* static */ int
DOM_TreeWalker::move(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
DOM_TreeWalker *tree_walker;
if (argc >= 0)
{
DOM_THIS_OBJECT_EXISTING(tree_walker, DOM_TYPE_TREEWALKER, DOM_TreeWalker);
/* Recursive call, probably from the filter's acceptNode function. */
if (tree_walker->state)
return DOM_CALL_DOMEXCEPTION(INVALID_STATE_ERR);
tree_walker->current_candidate = NULL;
}
else
this_object = tree_walker = DOM_VALUE2OBJECT(*return_value, DOM_TreeWalker);
DOM_TreeWalker_State *state = tree_walker->state;
tree_walker->state = NULL;
DOM_Node *candidate = NULL;
int result;
DOM_Node *last_possible = NULL;
switch (data)
{
case PARENT_NODE:
case PREVIOUS_NODE:
last_possible = tree_walker->root;
break;
case FIRST_CHILD:
CALL_FAILED_IF_ERROR(tree_walker->current_node->GetLastChild(last_possible));
if (last_possible)
while (1)
{
DOM_Node *last_child;
CALL_FAILED_IF_ERROR(last_possible->GetLastChild(last_child));
if (!last_child)
break;
else
last_possible = last_child;
}
break;
case LAST_CHILD:
CALL_FAILED_IF_ERROR(tree_walker->current_node->GetFirstChild(last_possible));
break;
case PREVIOUS_SIBLING:
if (tree_walker->current_node != tree_walker->root)
{
DOM_Node *parent = tree_walker->current_node;
while (parent && parent != tree_walker->root)
{
DOM_Node *previous_sibling;
CALL_FAILED_IF_ERROR(parent->GetPreviousSibling(previous_sibling));
if (previous_sibling)
last_possible = previous_sibling;
CALL_FAILED_IF_ERROR(parent->GetParentNode(parent));
}
DOM_Node *previous_sibling = last_possible;
while (previous_sibling)
{
last_possible = previous_sibling;
CALL_FAILED_IF_ERROR(last_possible->GetPreviousSibling(previous_sibling));
}
}
break;
case NEXT_SIBLING:
if (tree_walker->current_node != tree_walker->root)
{
DOM_Node *parent = tree_walker->current_node, *next_sibling;
while (parent && parent != tree_walker->root)
{
CALL_FAILED_IF_ERROR(parent->GetNextSibling(next_sibling));
if (next_sibling)
last_possible = next_sibling;
CALL_FAILED_IF_ERROR(parent->GetParentNode(parent));
}
next_sibling = last_possible;
while (next_sibling)
{
last_possible = next_sibling;
CALL_FAILED_IF_ERROR(last_possible->GetNextSibling(next_sibling));
}
next_sibling = last_possible;
while (next_sibling)
{
last_possible = next_sibling;
CALL_FAILED_IF_ERROR(last_possible->GetLastChild(next_sibling));
}
}
break;
case NEXT_NODE:
{
DOM_Node *last_child = tree_walker->root;
last_possible = last_child;
while (last_child)
{
CALL_FAILED_IF_ERROR(last_child->GetLastChild(last_child));
if (last_child)
last_possible = last_child;
}
}
}
if (last_possible == tree_walker->current_node)
last_possible = NULL;
BOOL reset_candidate = TRUE;
/* Yep, this is grotesque. */
while (1)
{
if (tree_walker->current_candidate)
{
candidate = tree_walker->current_candidate;
tree_walker->current_candidate = NULL;
reset_candidate = TRUE;
}
else
{
if (reset_candidate)
{
candidate = tree_walker->current_node;
reset_candidate = FALSE;
}
while (1)
{
// Check if we've reached the end of the line in our search
if (!candidate || candidate == last_possible || !last_possible)
{
if (tree_walker->best_candidate)
{
DOMSetObject(return_value, tree_walker->current_node = tree_walker->best_candidate);
tree_walker->best_candidate = NULL;
}
else
DOMSetNull(return_value);
return ES_VALUE;
}
OP_STATUS status = OpStatus::OK;
OpStatus::Ignore(status);
switch (data)
{
case PARENT_NODE:
status = candidate->GetParentNode(candidate);
break;
case FIRST_CHILD:
status = candidate->GetNextNode(candidate, state && state->HasRejected(candidate));
break;
case LAST_CHILD:
{
DOM_Node *temp = NULL;
if (!state || !state->HasRejected(candidate))
CALL_FAILED_IF_ERROR(candidate->GetLastChild(temp));
while (candidate && !temp)
{
CALL_FAILED_IF_ERROR(candidate->GetPreviousSibling(temp));
if (!temp)
{
CALL_FAILED_IF_ERROR(candidate->GetParentNode(temp));
if (temp)
{
candidate = temp;
CALL_FAILED_IF_ERROR(candidate->GetPreviousSibling(temp));
}
}
}
candidate = temp;
}
break;
case PREVIOUS_SIBLING:
case PREVIOUS_NODE:
{
DOM_Node *temp;
BOOL consider_children = candidate != tree_walker->current_node && (!state || !state->HasRejected(candidate));
if (consider_children)
{
DOM_Node *parent = tree_walker->current_node;
while (parent)
{
CALL_FAILED_IF_ERROR(parent->GetParentNode(parent));
if (parent == candidate)
{
consider_children = FALSE;
break;
}
}
}
if (consider_children)
CALL_FAILED_IF_ERROR(candidate->GetLastChild(temp));
else
CALL_FAILED_IF_ERROR(candidate->GetPreviousSibling(temp));
if ((!consider_children || !temp) && tree_walker->best_candidate == candidate)
{
DOMSetObject(return_value, tree_walker->current_node = candidate);
tree_walker->best_candidate = NULL;
return ES_VALUE;
}
while (candidate && !temp)
{
CALL_FAILED_IF_ERROR(candidate->GetPreviousSibling(temp));
if (!temp)
{
CALL_FAILED_IF_ERROR(candidate->GetParentNode(temp));
candidate = temp;
if (temp)
{
DOM_Node *parent = tree_walker->current_node;
while (parent)
{
CALL_FAILED_IF_ERROR(parent->GetParentNode(parent));
if (parent == temp)
{
temp = NULL;
break;
}
}
if (temp)
CALL_FAILED_IF_ERROR(candidate->GetPreviousSibling(temp));
else
{
temp = candidate;
break;
}
}
}
}
candidate = temp;
}
break;
case NEXT_SIBLING:
{
DOM_Node *temp;
BOOL consider_children = candidate != tree_walker->current_node && (!state || !state->HasRejected(candidate));
if (consider_children)
{
DOM_Node *parent = tree_walker->current_node;
while (parent)
{
CALL_FAILED_IF_ERROR(parent->GetParentNode(parent));
if (parent == candidate)
{
consider_children = FALSE;
break;
}
}
}
if (consider_children)
CALL_FAILED_IF_ERROR(candidate->GetFirstChild(temp));
else
CALL_FAILED_IF_ERROR(candidate->GetNextSibling(temp));
while (candidate && !temp)
{
CALL_FAILED_IF_ERROR(candidate->GetNextSibling(temp));
if (!temp)
{
CALL_FAILED_IF_ERROR(candidate->GetParentNode(temp));
candidate = temp;
if (temp)
{
DOM_Node *parent = tree_walker->current_node;
while (parent)
{
CALL_FAILED_IF_ERROR(parent->GetParentNode(parent));
if (parent == temp)
{
temp = NULL;
break;
}
}
if (temp)
CALL_FAILED_IF_ERROR(candidate->GetNextSibling(temp));
else
{
temp = candidate;
break;
}
}
}
}
candidate = temp;
}
break;
case NEXT_NODE:
status = candidate->GetNextNode(candidate, state && state->HasRejected(candidate));
}
CALL_FAILED_IF_ERROR(status);
if (candidate && (!state || !state->HasTried(candidate)))
break;
}
}
result = tree_walker->AcceptNode(candidate, origining_runtime, *return_value);
if (result == DOM_NodeFilter::FILTER_ACCEPT)
{
if (data == PREVIOUS_SIBLING || data == NEXT_SIBLING)
{
DOM_Node *parent = tree_walker->current_node;
while (parent)
{
CALL_FAILED_IF_ERROR(parent->GetParentNode(parent));
if (parent == candidate)
{
DOMSetNull(return_value);
return ES_VALUE;
}
}
}
if (data == PREVIOUS_NODE)
tree_walker->best_candidate = candidate;
else
{
DOMSetObject(return_value, tree_walker->current_node = candidate);
return ES_VALUE;
}
}
else if (result == DOM_NodeFilter::FILTER_FAILED)
return ES_FAILED;
else if (result == DOM_NodeFilter::FILTER_EXCEPTION)
return ES_EXCEPTION;
else if (result == DOM_NodeFilter::FILTER_OOM)
return ES_NO_MEMORY;
else if (result == DOM_NodeFilter::FILTER_DELAY)
{
if (!state)
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(state = OP_NEW(DOM_TreeWalker_State, ()), tree_walker->GetRuntime()));
if (OpStatus::IsMemoryError(state->AddTried(candidate)))
return ES_NO_MEMORY;
tree_walker->current_candidate = candidate;
tree_walker->state = state;
DOMSetObject(return_value, tree_walker);
return ES_SUSPEND | ES_RESTART;
}
else if (result == DOM_NodeFilter::FILTER_REJECT)
{
OP_ASSERT(state);
CALL_FAILED_IF_ERROR(state->AddRejected(candidate));
}
}
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_WITH_DATA_START(DOM_TreeWalker)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_TreeWalker, DOM_TreeWalker::move, DOM_TreeWalker::PARENT_NODE, "parentNode", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_TreeWalker, DOM_TreeWalker::move, DOM_TreeWalker::FIRST_CHILD, "firstChild", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_TreeWalker, DOM_TreeWalker::move, DOM_TreeWalker::LAST_CHILD, "lastChild", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_TreeWalker, DOM_TreeWalker::move, DOM_TreeWalker::PREVIOUS_SIBLING, "previousSibling", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_TreeWalker, DOM_TreeWalker::move, DOM_TreeWalker::NEXT_SIBLING, "nextSibling", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_TreeWalker, DOM_TreeWalker::move, DOM_TreeWalker::PREVIOUS_NODE, "previousNode", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_TreeWalker, DOM_TreeWalker::move, DOM_TreeWalker::NEXT_NODE, "nextNode", 0)
DOM_FUNCTIONS_WITH_DATA_END(DOM_TreeWalker)
#endif // DOM2_TRAVERSAL
|
/**
* @file payload.cpp
*/
/*
* The following license applies to the code in this file:
*
* **************************************************************************
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* **************************************************************************
*
* Author: Dr. Rüdiger Berlich of Gemfony scientific UG (haftungsbeschraenkt)
* See http://www.gemfony.eu for further information.
*
* This code is based on the Beast Websocket library by Vinnie Falco, as published
* together with Boost 1.66 and above. For further information on Beast, see
* https://github.com/boostorg/beast for the latest release, or download
* Boost 1.66 or newer from http://www.boost.org .
*/
#include "payload.hpp"
/******************************************************************************************/
BOOST_CLASS_EXPORT_IMPLEMENT(command_container) // NOLINT
BOOST_CLASS_EXPORT_IMPLEMENT(stored_number) // NOLINT
BOOST_CLASS_EXPORT_IMPLEMENT(container_payload) // NOLINT
BOOST_CLASS_EXPORT_IMPLEMENT(sleep_payload) // NOLINT
/******************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************/
void payload_base::process() {
this->process_();
}
/******************************************************************************************/
bool payload_base::is_processed() {
return this->is_processed_();
}
/******************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************/
std::string to_string(const payload_base* payload_ptr) {
if(!payload_ptr) {
throw std::runtime_error("to_string: payload_ptr is empty");
}
std::ostringstream oss(std::ios::out
#if defined(BINARYARCHIVE)
| std::ios::binary);
#else
);
#endif
{
#if defined(BINARYARCHIVE)
boost::archive::binary_oarchive oa(oss);
#elif defined(XMLARCHIVE)
boost::archive::xml_oarchive oa(oss);
#elif defined(TEXTARCHIVE)
boost::archive::text_oarchive oa(oss);
#else
boost::archive::xml_oarchive oa(oss);
#endif
oa << boost::serialization::make_nvp("payload_base", payload_ptr);
} // archive and stream closed at end of scope
return oss.str();
}
/******************************************************************************************/
payload_base *from_string(const std::string& descr) {
payload_base * payload_ptr;
std::istringstream iss(descr, std::ios::in
#if defined(BINARYARCHIVE)
| std::ios::binary); // de-serialize
#else
);
#endif
{
#if defined(BINARYARCHIVE)
boost::archive::binary_iarchive ia(iss);
#elif defined(XMLARCHIVE)
boost::archive::xml_iarchive ia(iss);
#elif defined(TEXTARCHIVE)
boost::archive::text_iarchive ia(iss);
#else
boost::archive::xml_iarchive ia(iss);
#endif
ia >> boost::serialization::make_nvp("payload_base", payload_ptr);
} // archive and stream closed at end of scope
return payload_ptr;
}
/******************************************************************************************/
std::string to_xml(const payload_base* payload_ptr) {
if(!payload_ptr) {
throw std::runtime_error("to_xml: payload_ptr is empty");
}
std::ostringstream oss; // serialize
{
boost::archive::xml_oarchive oa(oss);
oa << boost::serialization::make_nvp("payload_base", payload_ptr);
} // archive and stream closed at end of scope
return oss.str();
}
/******************************************************************************************/
std::string to_binary(const payload_base* payload_ptr) {
if(!payload_ptr) {
throw std::runtime_error("to_string: payload_ptr is empty");
}
std::ostringstream oss; // serialize
{
boost::archive::binary_oarchive oa(oss);
oa << boost::serialization::make_nvp("payload_base", payload_ptr);
} // archive and stream closed at end of scope
return oss.str();
}
/******************************************************************************************/
payload_base *from_binary(const std::string& descr) {
payload_base * payload_ptr;
std::istringstream iss(descr); // de-serialize
{
boost::archive::binary_iarchive ia(iss);
ia >> boost::serialization::make_nvp("payload_base", payload_ptr);
} // archive and stream closed at end of scope
return payload_ptr;
}
/******************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************/
command_container::command_container(payload_command command)
: m_command(command)
{ /* nothing */ }
/******************************************************************************************/
command_container::command_container(
payload_command command
, payload_base *payload_ptr
)
: m_command(command)
, m_payload_ptr(payload_ptr)
{ /* nothing */ }
/******************************************************************************************/
command_container::command_container(command_container&& cp) noexcept {
m_command = cp.m_command; cp.m_command = payload_command::NONE;
if(m_payload_ptr) delete m_payload_ptr;
m_payload_ptr = cp.m_payload_ptr; cp.m_payload_ptr = nullptr;
}
/******************************************************************************************/
command_container::~command_container() {
if(m_payload_ptr) delete m_payload_ptr;
}
/******************************************************************************************/
command_container& command_container::operator=(command_container&& cp) noexcept {
m_command = cp.m_command; cp.m_command = payload_command::NONE;
if(m_payload_ptr) delete m_payload_ptr;
m_payload_ptr = cp.m_payload_ptr; cp.m_payload_ptr = nullptr;
return *this;
}
/******************************************************************************************/
const command_container& command_container::reset(
payload_command command
, payload_base *payload_ptr
) {
m_command = command;
if(m_payload_ptr) {
delete m_payload_ptr;
}
m_payload_ptr = payload_ptr;
return *this;
}
/******************************************************************************************/
void command_container::set_command(payload_command command) {
m_command = command;
}
/******************************************************************************************/
payload_command command_container::get_command() const noexcept {
return m_command;
}
/******************************************************************************************/
void command_container::process() {
if(m_payload_ptr) {
m_payload_ptr->process();
} else {
throw std::runtime_error("command_container::process(): No processing possible as m_payload_ptr is empty.");
}
}
/******************************************************************************************/
bool command_container::is_processed() {
if(m_payload_ptr) {
return m_payload_ptr->is_processed();
} else {
return false;
}
}
/******************************************************************************************/
std::string command_container::to_string() const {
// Reset the internal stream
#ifdef BINARYARCHIVE
std::stringstream(std::ios::out | std::ios::binary).swap(m_stringstream);
#else
std::stringstream(std::ios::out).swap(m_stringstream);
#endif
{
#if defined(BINARYARCHIVE)
boost::archive::binary_oarchive oa(m_stringstream);
#elif defined(XMLARCHIVE)
boost::archive::xml_oarchive oa(m_stringstream);
#elif defined(TEXTARCHIVE)
boost::archive::text_oarchive oa(m_stringstream);
#else
boost::archive::xml_oarchive oa(m_stringstream);
#endif
oa << boost::serialization::make_nvp("command_container", *this);
} // archive and stream closed at end of scope
return m_stringstream.str();
}
/******************************************************************************************/
std::string command_container::to_xml() const {
// Reset the internal stream
std::stringstream(std::ios::out).swap(m_stringstream);
{
boost::archive::xml_oarchive oa(m_stringstream);
oa << boost::serialization::make_nvp("command_container", *this);
} // archive and stream closed at end of scope
return m_stringstream.str();
}
/******************************************************************************************/
void command_container::from_string(const std::string& descr) {
command_container local_command_container{payload_command::NONE};
// Reset the internal stream
#ifdef BINARYARCHIVE
std::stringstream(descr, std::ios::in | std::ios::binary).swap(m_stringstream);
#else
std::stringstream(descr, std::ios::in).swap(m_stringstream);
#endif
{
#if defined(BINARYARCHIVE)
boost::archive::binary_iarchive ia(m_stringstream);
#elif defined(XMLARCHIVE)
boost::archive::xml_iarchive ia(m_stringstream);
#elif defined(TEXTARCHIVE)
boost::archive::text_iarchive ia(m_stringstream);
#else
boost::archive::xml_iarchive ia(m_stringstream);
#endif
ia >> boost::serialization::make_nvp("command_container", local_command_container);
} // archive and stream closed at end of scope
// Move the data from local_command_container
*this = std::move(local_command_container);
}
/******************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************/
stored_number::stored_number(double secret) : m_secret(secret)
{ /* nothing */ }
/******************************************************************************************/
std::shared_ptr<stored_number> stored_number::clone() {
return std::shared_ptr<stored_number>(new stored_number(*this));
}
/******************************************************************************************/
double stored_number::value() const {
return m_secret;
}
/******************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************/
container_payload::container_payload(const container_payload& cp) : payload_base(cp)
{
m_data.clear();
for(const auto& d: cp.m_data) {
m_data.push_back(d->clone());
}
}
/******************************************************************************************/
container_payload& container_payload::operator=(const container_payload& cp) {
m_data.clear();
for(const auto& d: cp.m_data) {
m_data.push_back(d->clone());
}
return *this;
}
/******************************************************************************************/
void container_payload::container_payload::sort(){
std::sort(
m_data.begin()
, m_data.end()
, [](std::shared_ptr<stored_number> x, std::shared_ptr<stored_number> y) -> bool { return x->value() < y->value(); }
);
}
/******************************************************************************************/
std::size_t container_payload::size() const {
return m_data.size();
}
/******************************************************************************************/
std::shared_ptr<stored_number> container_payload::member(std::size_t pos) const {
return m_data.at(pos);
}
/******************************************************************************************/
void container_payload::process_() {
this->sort();
}
/******************************************************************************************/
bool container_payload::is_processed_() {
return std::is_sorted(
m_data.begin()
, m_data.end()
, [](const std::shared_ptr<stored_number>& x_ptr, const std::shared_ptr<stored_number>& y_ptr) -> bool {
return (x_ptr->value() < y_ptr->value());
}
);
}
/******************************************************************************************/
void container_payload::add(std::shared_ptr<stored_number> p) {
m_data.push_back(p);
}
/******************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************/
sleep_payload::sleep_payload(double sleep_time) : m_sleep_time(sleep_time)
{ /* default */ }
/******************************************************************************************/
void sleep_payload::process_() {
std::this_thread::sleep_for(std::chrono::duration<double>(m_sleep_time));
}
/******************************************************************************************/
bool sleep_payload::is_processed_() {
return true;
}
/******************************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************/
|
\context Staff = "violín" <<
\set Staff.instrumentName = "Violín"
\set Staff.shortInstrumentName = "V."
\set Score.skipBars = ##t
\set Staff.printKeyCancellation = ##f
\new Voice \global
\new Voice \globalTempo
\context Voice = "voice 1" {
\override Voice.TextScript #'padding = #2.0
\override MultiMeasureRest #'expand-limit = 1
\clef "treble"
\key g \major
r4 d'' g'' a'' |
b'' 1 |
r8 b' d'' e'' fis'' g'' a'' fis'' |
g'' 1 |
%% 5
r8 e' fis' g' a' b' c'' d'' |
e'' 2. e'' 4 |
fis'' 2. fis'' 4 |
g'' 2 a'' 4 fis'' |
g'' 1 |
%% 10
R1 |
r4 g'' g'' g'' |
fis'' 4 e'' 8 d'' ~ d'' 2 |
e'' 1 ~ |
e'' 2. e'' 4 |
%% 15
fis'' 4 e'' 8 d'' ~ d'' 2 ~ |
d'' 4 d'' g'' a'' |
b'' 1 |
r8 b' d'' e'' fis'' g'' a'' fis'' |
g'' 1 |
%% 20
r8 e' fis' g' a' b' c'' d'' |
e'' 2. e'' 4 |
fis'' 2. fis'' 4 |
g'' 2 a'' 4 fis'' |
g'' 1 |
\bar "|."
} % Voice
>> % Staff ends
|
#include <iostream>
#include "sha1.h"
using namespace std;
int main(int argc, char *argv[])
{
cout<<"This is the fourth extra-class assignment of the course CE2103 of Tecnologico de Costa Rica, \nWhich consists of investigating and implementing the SHA1 algorithm for information preservation. \nThe example provided is a 100% public domain code which exemplifies how SHA1 generates a completely different hexadecimal code when making changes to an inserted word.\n"<<endl;
bool loop = true;
while (loop) {
cout << "\n MAIN MENU" << endl << " 1. Insert word \n 2. Exit \n" << endl;
int option;
cout << "\nEnter an option:";
cin >> option;
switch (option) {
case 1:
char word[15];
cout << "Enter the word you want to generate a UNIQUE hexadecimal code:";
scanf("%s", word);
cout <<"\nThe word " << word <<" in hexadecimal unique code is " <<sha1(word) << endl;
cout<<"Please make a change to the above word to generate another single hexadecimal"<<endl;
break;
case 2:
cout << "\nThanks for use SHA1 PROGRAM\n";
loop = false;
break;
default:
cout << "\nOption is not in range. Please enter a valid option\n";
return 0;
}
}
}
|
#include <Adafruit_NeoPixel.h>
#include "BouncingAnimation.h"
BouncingAnimation::BouncingAnimation(void) { }
void BouncingAnimation::reset(variables_t *vars) {
Serial.println("changing to bounce");
int i;
boolean j = true;
for(i = 0; i < vars->objectCount; i++) {
vars->color_store[i] = Adafruit_NeoPixel::Color(0, rand()%64+128, 0);
vars->color_pos[i] = i*5+2;
vars->color_hom[i] = i*5+2;
vars->color_dir[i] = j;
j=!j;
}
vars->lastTime = 0;
}
void BouncingAnimation::loop(variables_t *vars) {
int i = 0;
int j = 0;
if(millis() > vars->lastTime+50) {
vars->lastTime = millis();
for(i = 0; i < vars->objectCount; i++) {
vars->color_store[i] = Adafruit_NeoPixel::Color(96, 127, 127);
}
for (i = 0; i < vars->color_len; i++) {//clear
vars->color[i] = Adafruit_NeoPixel::Color(rand()%64+63,0,0);
}
for (i=0; i< vars->objectCount; i++) {//set
for(j = 0; j < 2; j++) {
if(vars->color_pos[i]+j < vars->color_len) {
vars->color[vars->color_pos[i]+j]= vars->color_store[i];
}
}
}
for (i=0; i<vars->objectCount; i++) {//move
if(vars->color_dir[i]) {
vars->color_pos[i] = vars->color_pos[i]+1;
}else{
vars->color_pos[i] = vars->color_pos[i]-1;
}
if((vars->color_pos[i] >= vars->color_hom[i]+2) || (vars->color_pos[i] <= vars->color_hom[i]-2)) { vars->color_dir[i] = !vars->color_dir[i]; }
}
}
}
|
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <fstream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
enum class Color {red, green, blue};
enum class Size {small, medium, large};
struct Product {
string name;
Color color;
Size size;
};
struct ProductFilter {
vector<Product*> by_color(vector<Product*> items, Color color) {
vector<Product*> result;
for (auto& i: items)
if (i->color == color)
result.push_back(i);
return result;
}
};
template<typename T>
struct Specification {
virtual bool is_satisfied(T* term) = 0;
AndSpecification<T> operator&&(Specification<T>&& other) {
return AndSpecification<T>(*this, other);
}
};
template<typename T>
struct AndSpecification : Specification<T> {
Specification<T>& first;
Specification<T>& second;
AndSpecification(Specification<T> &first, Specification<T> &second) :
first(first), second(second)
{}
bool is_satisfied(T* term) override {
return first.is_satisfied(term) && second.is_satisfied(term);
}
};
struct ColorSpecification : Specification<Product> {
Color color;
explicit ColorSpecification(Color color) : color(color) {}
bool is_satisfied(Product* item) override {
return item->color == color;
}
};
struct SizeSpecification : Specification<Product> {
Size size;
explicit SizeSpecification(Size size) : size(size) {}
bool is_satisfied(Product* item) override {
return item->size == size;
}
};
template<typename T>
struct Filter {
virtual vector<T*> filter(vector<T*> items, Specification<T>& spec) = 0;
};
struct BetterFilter : Filter<Product> {
vector<Product*> filter(vector<Product*> items, Specification<Product>& spec)
override {
vector<Product*> result;
for (auto& item: items)
if (spec.is_satisfied(item))
result.push_back(item);
return result;
}
};
int main() {
// getchar();
Product apple {"Apple", Color::green, Size::small};
Product tree {"Tree", Color::green, Size::large};
Product house {"House", Color::blue, Size::large};
vector<Product*> items {&apple, &tree, &house};
ProductFilter pf;
auto green_things = pf.by_color(items, Color::green);
for (auto& item : green_things)
cout << item->name << " is green\n";
BetterFilter bf;
ColorSpecification green(Color::green);
for (auto& item : bf.filter(items, green))
cout << item->name << " is green\n";
SizeSpecification large(Size::large);
AndSpecification<Product> green_and_large (green, large);
for (auto& item : bf.filter(items, green_and_large))
cout << item->name << " is green and large\n";
return 0;
}
|
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> names{"john", "jane", "jill", "jack"};
vector<string>::iterator it = names.begin(); // or begin(names)
cout << "first name is " << *it << "\n";
++it; // advance the iterator
it->append(string(" goodall"));
cout << "second name is " << *it << "\n";
while (++it != names.end()) {
cout << "another name: " << *it << "\n";
}
// traversing the entire vector backwards
// note global rbegin/rend, note ++ not --
// expand auto here
for (auto ri = rbegin(names); ri != rend(names); ++ri) {
cout << *ri;
if (ri + 1 != rend(names)) // iterator arithmetic
cout << ", ";
}
cout << endl;
// constant iterators
vector<string>::const_reverse_iterator jack = crbegin(names);
// won't work
// *jack += "test";
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
int maxFreqInRange(int l[],int r[],int n){
vector<int> arr[1000]; //max constraint on values in l[],r[].
for(int i=0;i<n;i++){
arr[l[i]]+=1;
arr[r[i]+1]-=1;
}
int maxm=arr[0],res=0;
for(int i=1;i<1000;i++){
arr[i]+=arr[i-1];
if(maxm<arr[i]){
maxm=arr[i];
res=i;
}
}
return res;
}
int main(int argc, char const *argv[]) {
int l[]={1,2,3};
int r[]={3,5,7};
int n=sizeof(l)/sizeof(l[0]);
cout<<"Max occuring element is "<<maxFreqInRange(l,r,n);
return 0;
}
|
#pragma once
#include <nclgl\OGLRenderer.h>
#include <nclgl\Matrix4.h>
#include <ncltech\Object.h>
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
#include <vector>
#include "XPBDConstraints.h"
#include "XPBD_ConstraintLayer.h"
class XPBD : public Object
{
friend class XPBD_ConstraintLayer;
friend class FluidClothCoupler;
public:
XPBD();
virtual ~XPBD();
void Release();
void InitializeCloth(int div_x, int div_y, const Matrix4& transform);
inline void SetTextureFront(GLuint tex, bool managed = true)
{
m_glTexFront = tex;
m_glManageTexFront = managed;
}
inline void SetTextureBack(GLuint tex, bool managed = true)
{
m_glTexBack = tex;
m_glManageTexBack = managed;
}
std::vector<XPBDSphereConstraint> m_SphereConstraints;
void Update(float dt);
void GenerateNormals(bool reverseOrder);
void UpdateGLBuffers();
protected:
void InitializeCuda(const Vector4* initial_positions);
void InitializeGL(const Vector4* initial_positions);
virtual void OnRenderObject() override;
virtual void OnUpdateObject(float dt) override;
protected:
//Host
int m_SolverIterations = 120;
float m_MaterialBend = 0.1f;
float m_MaterialStretchWeft = 0.6f;// 0.8f;
float m_MaterialStretchWarp = 0.7f;// 0.95f;
float m_MaterialShear = 0.5f;// 0.8f;
float m_MaterialDamp = 0.01f;
int m_NumParticles, m_NumIndicies, m_NumConstraintIndicies, m_NumX, m_NumY;
//Constraints
std::vector<XPBD_ConstraintLayer> m_ConstraintLayers;
//Device
CudaTextureWrapper m_cuParticlePosOld;
CudaTextureWrapper m_cuParticlePos; //float4 -> [x,y,z,(invmass)]
CudaTextureWrapper m_cuParticlePosTmp;
CudaTextureWrapper m_cuParticleFaceNormals;
CudaTextureWrapper m_cuParticleVertNormals;
//Rendering
bool m_glManageTexFront, m_glManageTexBack;
GLuint m_glTexFront;
GLuint m_glTexBack;
GLuint m_glArr;
GLuint m_glBuffers[5]; //0: Verts, 1: Normals, 2: Tex-Coords, 3: Indicies (tris), 4: Indicies (constraints)
cudaGraphicsResource_t m_cuVerticesRef;
cudaGraphicsResource_t m_cuNormalsRef;
float4* m_cuVerticesBufRef;
};
|
#include<iostream>
using namespace std;
class A{
int i;
public:
A(int x) : i(x) { }
A() {}
friend A operator++ (A a);
friend A operator++ (A a,int);
friend A operator+ (A p,A q);
friend void display (A a);
};
A operator++ (A a)
{
cout<< "pre-increament ++a"<<a.i<<endl;
A temp;
++a.i;
return *this;
}
A operator++ (A a,int)
{
cout<< "post-increament"<<a.i<<endl;
A b(a.i);
a.i++;
return b;
}
A operator+ (A p ,A q)
{
return A(q.i+p.i);
}
void display( A a)
{
cout<<a.i<<endl;
}
int main()
{
A a(5),b(10),c;
// ++a;
// a.display();
// b++;
// b.display();
c=a++ + ++b;
display(c);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2007 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef SVG_ANIMATION_TIME_H
#define SVG_ANIMATION_TIME_H
#ifdef SVG_SUPPORT
#include "modules/svg/src/SVGObject.h"
#if defined(HAVE_INT64)
typedef INT64 SVG_ANIMATION_TIME;
# if defined(_MSC_VER) && _MSC_VER <= 1200
# define SUFFIX_64(X) X##I64
# else
# define SUFFIX_64(X) X##LL
# endif
# ifndef INT64_MAX
# define INT64_MAX SUFFIX_64(9223372036854775807)
# endif
# ifndef INT64_MIN
# define INT64_MIN (-INT64_MAX-SUFFIX_64(1))
# endif
#else
typedef int SVG_ANIMATION_TIME;
#endif
class SVGAnimationTime
{
public:
#ifdef HAVE_INT64
static SVG_ANIMATION_TIME Unresolved() { return INT64_MAX; }
static SVG_ANIMATION_TIME Indefinite() { return INT64_MAX - 1; }
static SVG_ANIMATION_TIME Latest() { return INT64_MAX - 2; }
static SVG_ANIMATION_TIME Earliest() { return INT64_MIN; }
#else
static SVG_ANIMATION_TIME Unresolved() { return INT_MAX; }
static SVG_ANIMATION_TIME Indefinite() { return INT_MAX - 1; }
static SVG_ANIMATION_TIME Latest() { return INT_MAX - 2; }
static SVG_ANIMATION_TIME Earliest() { return INT_MIN; }
#endif
static double ToSeconds(SVG_ANIMATION_TIME animation_time) { return ((double)animation_time) / 1000.0; }
static SVG_ANIMATION_TIME FromSeconds(double seconds) { return (SVG_ANIMATION_TIME)(seconds * 1000.0); }
static BOOL IsNumeric(SVG_ANIMATION_TIME animation_time) { return animation_time < Indefinite(); }
static BOOL IsIndefinite(SVG_ANIMATION_TIME animation_time) { return animation_time == Indefinite(); }
static BOOL IsUnresolved(SVG_ANIMATION_TIME animation_time) { return animation_time == Unresolved(); }
};
/**
* Simple wrapper object for animation times. Used for storing durations,
* clock-values and the like in attributes of animation elements.
*/
class SVGAnimationTimeObject : public SVGObject
{
public:
/* The clock-value in milli-seconds relative to the beginning of
* the animation */
SVG_ANIMATION_TIME value;
SVGAnimationTimeObject(SVG_ANIMATION_TIME v) :
SVGObject(SVGOBJECT_ANIMATION_TIME),
value(v) {}
virtual SVGObject *Clone() const;
virtual BOOL IsEqual(const SVGObject& other) const;
virtual OP_STATUS LowLevelGetStringRepresentation(TempBuffer* buffer) const;
};
#endif // SVG_SUPPORT
#endif // !SVG_ANIMATION_TIME_H
|
//use the following command
//mex libport_ss.cpp SerialPort.cpp SerialStream.cc SerialStreamBuf.cc PosixSignalDispatcher.cpp -lpthread
#include "SerialStream.h"
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <sstream>
#include <string>
#include <iomanip>
#include "mex.h"
using namespace std;
using namespace LibSerial ;
SerialStream serial_port ;
#define NUM_STATES 16
#define CMD_STATES 3
const int CMD_OPEN_PORT =0;
const int CMD_READ = 1;
const int CMD_WRITE = 2;
const int CMD_CLOSE_PORT = 3;
const int CMD_START_MOTOR = 4;
const int CMD_STOP_MOTOR = 5;
const int CMD_READ_GAIN=6;
const int CMD_UPDATE_GAIN=7;
const int CMD_START_UPDATE_GAIN=8;
const int CMD_CALIB=9;
const int CMD_ANG_GAIN=10;
const int CMD_POS_GAIN=11;
const int CMD_WRITE_CLIMB=12;
const int CMD_GAIN_STATES=9;
const int CMD_WRITE_CLIMB_ASSIST=13;
double inputData[NUM_STATES]={0};
//Name: SetUp
//Function: Set up the serial port. Including the port number and the baud rate
//Input: None
//Output: None
void SetUp(char* port)
{
//
// Open the serial port.
//
//serial_port.Open( string(port) ) ;
serial_port.Open( "/dev/ttyUSB0" ) ;
//
// Set the baud rate of the serial port.
//
serial_port.SetBaudRate( SerialStreamBuf::BAUD_57600) ;
//
// Set the number of data bits.
//
serial_port.SetCharSize( SerialStreamBuf::CHAR_SIZE_8 ) ;
//
// Disable parity.
//
serial_port.SetParity( SerialStreamBuf::PARITY_NONE ) ;
//
// Set the number of stop bits.
//
serial_port.SetNumOfStopBits( 1 ) ;
// Turn off hardware flow control.
//
serial_port.SetFlowControl( SerialStreamBuf::FLOW_CONTROL_NONE ) ;
}
//Name: WriteGain
//Function: update the gain for the LQR controller
//Input: state array (NUM_STATES x 1)
//Output: None
void WriteGain(double state[],int cmd)
{
stringstream ss;
//formate the input. Begin with d
if (cmd==CMD_ANG_GAIN)
{
ss<<fixed<<setprecision(3)<<'a';
}
else if (cmd==CMD_POS_GAIN)
{
ss<<fixed<<setprecision(3)<<'g';
}
for (int i =0; i<CMD_GAIN_STATES; i++){
ss<<state[i]<<'z';
}
ss<<endl;
cout<<ss.str();
//convert from string stream to char array
string str;
str=ss.str();
//write it to the port
serial_port.write(str.c_str(),str.length());
}
//Name: WriteData
//Function: Write the data in a special format to the serial port
//Input: state array (NUM_STATESx1)
//Output: None
void WriteData(double state[],int flag)
{
stringstream ss;
if (flag==CMD_WRITE_CLIMB)
{
//formate the input. Begin with d
ss<<fixed<<setprecision(3)<<'e';
for (int i =0; i<CMD_STATES; i++)
{
ss<<state[i]<<'z';
}
}
else if (flag==CMD_WRITE_CLIMB_ASSIST)
{
ss<<fixed<<setprecision(3)<<'f';//start with f
for (int i =0; i<CMD_STATES; i++)
{
ss<<state[i]<<'z';
}
}
else
{
ss<<fixed<<setprecision(0)<<'d';
for (int i =0; i<4; i++)
{
ss<<state[i]<<'z';
}
}
ss<<endl;
cout<<ss.str();
//convert from string stream to char array
string str;
str=ss.str();
//write it to the port
serial_port.write(str.c_str(),str.length());
}
//Name: WriteCmd
//Function: Write the command to the serial port
//Input: cmd
//Output: None
void WriteCmd(int cmd)
{
stringstream ss;
string str;
if (cmd==CMD_START_MOTOR)
{
ss<<'t'<<'\n';
}
else if (cmd==CMD_STOP_MOTOR)
{
ss<<'o'<<'\n';
}
else if (cmd==CMD_CALIB)
{
ss<<'c'<<'\n';
}
str=ss.str();
serial_port.write(str.c_str(),str.length());
}
//Name: GetData
//Function: Read the data and parse the input to get the angles.
//Input: None
//Output: None
void GetData(int inputNum)
{
int count=0;
int timecount=0;
//read until timeout or get something in the buffer
while( serial_port.rdbuf()->in_avail() == 0 &&timecount<10) //add a timeout
{
usleep(100) ;
timecount++;
}
//keep reading until it gets the new line
stringstream ss;
string str;
char next_byte;
serial_port.get(next_byte);
count=0;
timecount=0;
while( next_byte!='\n'&&count<inputNum && timecount<200)
{
//reading until it gets a comma
if (next_byte!=',')
{
ss<<next_byte;
}
else
{
//convert the data to a double variable and store it to an array
ss>>inputData[count];
count=count+1;
ss.clear();
ss.str("");//reset the stringstream
}
serial_port.get(next_byte);
timecount=timecount+1;
}
}
//Name: GetData
//Function: Read the data and parse the input to get the angles.
//Input: inputNum is the number to read.
// : ptData is a pointer to the storage
//Output: None
void GetGainData(int inputNum,double * ptData)
{
int count=0;
int timecount=0;
cout<<"stuck here"<<endl;
//read until timeout or get something in the buffer
while( serial_port.rdbuf()->in_avail() == 0 &&timecount<100) //add a timeout
{
usleep(100) ;
timecount++;
cout<<"timecount"<<timecount;
}
//keep reading until it gets the new line
stringstream ss;
string str;
char next_byte;
serial_port.get(next_byte);
count=0;
cout<<"get input1"<<endl;
timecount=0;
while( count<inputNum && timecount<200)
{
//reading until it gets a comma
if (next_byte!=',')
{
ss<<next_byte;
}
else
{
//convert the data to a double variable and store it to an array
ss>>ptData[count];
cout<<"get input2"<<endl;
cout << ptData[count]<< endl;
count=count+1;
ss.clear();
ss.str("");//reset the stringstream
}
serial_port.get(next_byte);
timecount=timecount+1;
}
}
void mexFunction(int nlhs,mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
double *inputGain;
double* state;
char* port;
double *cmd1;
double *cmd2;
double *cmd3;
double *cmd4;
size_t mrows,ncols;
size_t buflen;
//get the command number, which determines what will happen afterwards.
int cmd = (int)(*(mxGetPr(prhs[0]) ) );
switch(cmd)
{
case CMD_OPEN_PORT:
/*initialize the serial*/
//input must be a string
if (!mxIsChar(prhs[1]))
mexErrMsgIdAndTxt( "MATLAB:libport_ss:inputNotString",
"Input must be a string.");
// input must be a row vector
if (mxGetM(prhs[0])!=1)
mexErrMsgIdAndTxt( "MATLAB:libport_ss:inputNotVector",
"Input must be a row vector.");
// Copy string buffer into port variable
port = mxArrayToString(prhs[1]);
// Call the setup subroutine
SetUp(port);
cout << "Initialize Serial" << endl;
// Free the memory allocated by the mxArrayToString function
mxFree(port);
break;
case CMD_READ:
//read from serial
//ensure correct number of outputs
if(nlhs != 3){
mexErrMsgIdAndTxt("MATLAB:libport_ss:outputIncorrect",
"Expecting 4 output parameters");
}
//read data from the serial buffer
//read four motor speed
GetData(3);
plhs[0]=mxCreateDoubleMatrix(1,1,mxREAL);
plhs[1]=mxCreateDoubleMatrix(1,1,mxREAL);
plhs[2]=mxCreateDoubleMatrix(1,1,mxREAL);
cmd1 = mxGetPr(plhs[0]);
cmd2 = mxGetPr(plhs[1]);
cmd3 = mxGetPr(plhs[2]);
*cmd1 = inputData[0];
*cmd2 = inputData[1];
*cmd3 = inputData[2];
//write data to outputs
// *s_dis=demo.distance;
//set up output variables
break;
case CMD_WRITE_CLIMB_ASSIST:
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) ||
!(mrows==CMD_STATES && ncols==1) ) {
mexErrMsgIdAndTxt( "MATLAB:libport_ss:inputNotCorrect",
"Input must be a noncomplex NUM_STATESx1 double array.");
}
// extract the data from the arguments (as an array)
state = mxGetPr(prhs[1]);
// pass it to this function which will deal with it
WriteData(state,CMD_WRITE_CLIMB_ASSIST);
break;
case CMD_WRITE_CLIMB:
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) ||
!(mrows==CMD_STATES && ncols==1) ) {
mexErrMsgIdAndTxt( "MATLAB:libport_ss:inputNotCorrect",
"Input must be a noncomplex NUM_STATESx1 double array.");
}
// extract the data from the arguments (as an array)
state = mxGetPr(prhs[1]);
// pass it to this function which will deal with it
WriteData(state,CMD_WRITE_CLIMB);
break;
case CMD_WRITE:
// write the command
// check that data is correct size
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) ||
!(mrows==4 && ncols==1) ) {
mexErrMsgIdAndTxt( "MATLAB:libport_ss:inputNotCorrect",
"Input must be a noncomplex NUM_STATESx1 double array.");
}
// extract the data from the arguments (as an array)
state = mxGetPr(prhs[1]);
// pass it to this function which will deal with it
WriteData(state,CMD_WRITE);
break;
case CMD_ANG_GAIN:
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) ||
!(mrows==CMD_GAIN_STATES && ncols==1) ) {
mexErrMsgIdAndTxt( "MATLAB:libport_ss:inputNotCorrect",
"Input must be a noncomplex NUM_STATESx1 double array.");
}
// extract the data from the arguments (as an array)
state = mxGetPr(prhs[1]);
// pass it to this function which will deal with it
WriteGain(state,CMD_ANG_GAIN);
break;
case CMD_POS_GAIN:
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) ||
!(mrows==CMD_GAIN_STATES && ncols==1) ) {
mexErrMsgIdAndTxt( "MATLAB:libport_ss:inputNotCorrect",
"Input must be a noncomplex NUM_STATESx1 double array.");
}
// extract the data from the arguments (as an array)
state = mxGetPr(prhs[1]);
// pass it to this function which will deal with it
WriteGain(state,CMD_POS_GAIN);
break;
case CMD_READ_GAIN:
if(nlhs != 1){
mexErrMsgIdAndTxt("MATLAB:libport_ss:outputIncorrect",
"Expecting 4 output parameters");
}
plhs[0]=mxCreateDoubleMatrix(1,16,mxREAL);
inputGain=mxGetPr(plhs[0]);//get the value
GetGainData(16,inputGain);
break;
case CMD_CALIB:
WriteCmd(CMD_CALIB);
break;
case CMD_CLOSE_PORT:
//close the serial
if (serial_port.IsOpen()==1)
{
serial_port.Close();
}
break;
case CMD_START_MOTOR:
WriteCmd(CMD_START_MOTOR);
break;
case CMD_STOP_MOTOR:
WriteCmd(CMD_STOP_MOTOR);
break;
}
return;
}
|
#include <iostream>
#include <vector>
using namespace std;
const int N = 100000;
const int M = 18; // log2(N) => log2(100000) ~ 17
struct sparseTable {
vector<int> lg;
vector<vector<int> > sp; // for find min value in segment
vector<vector<int> > tp; // for find max value in segment
sparseTable(int n)
{
lg.resize(n + 1);
sp.resize(n + 1);
tp.resize(n + 1);
lg[1] = 0;
for (int i = 2; i <= n; ++i) {
lg[i] = lg[i / 2] + 1;
}
int m = lg[n] + 1;
for (int i = 1; i <= n; ++i) {
sp[i].resize(m + 1);
tp[i].resize(m + 1);
}
}
void build(int n, const int a[])
{
for (int i = 1; i <= n; ++i) {
sp[i][0] = a[i];
tp[i][0] = a[i];
}
for (int i = 1; (1 << i) <= n; ++i) {
int len = (1 << i);
for (int j = 1; j + len - 1 <= n; j++) {
int tail = j + len - 1;
sp[j][i] = min(sp[j][i - 1], sp[tail - len / 2 + 1][i - 1]);
tp[j][i] = max(tp[j][i - 1], tp[tail - len / 2 + 1][i - 1]);
}
}
}
int getMin(int l, int r)
{
int len = r - l + 1;
int pw = lg[len];
return min(sp[l][pw], sp[r - (1 << pw) + 1][pw]);
}
int getMax(int l, int r)
{
int len = r - l + 1;
int pw = lg[len];
return max(tp[l][pw], tp[r - (1 << pw) + 1][pw]);
}
};
int a[N + 1];
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
sparseTable table(n);
table.build(n, a);
int m;
cin >> m;
for (int i = 0; i < m; ++i) {
int l;
int r;
cin >> l >> r;
cout << table.getMin(l, r) << " " << table.getMax(l, r) << endl;
}
}
|
#pragma once
// CIPNotFound 对话框
class CIPNotFound : public CDialogEx
{
DECLARE_DYNAMIC(CIPNotFound)
public:
CIPNotFound(CWnd* pParent = NULL); // 标准构造函数
virtual ~CIPNotFound();
protected:
virtual BOOL OnInitDialog();
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
HICON m_hIcon;
DECLARE_MESSAGE_MAP()
public:
// afx_msg void OnStnClickedIpnotfoundtipStatic();
};
|
// Created on: 1997-11-21
// Created by: Mister rmi
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _UTL_HeaderFile
#define _UTL_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_CString.hxx>
#include <Storage_Error.hxx>
#include <Storage_OpenMode.hxx>
#include <Standard_Integer.hxx>
class TCollection_ExtendedString;
class Storage_BaseDriver;
class Storage_Data;
class OSD_Path;
class OSD_FileIterator;
class TCollection_AsciiString;
class Standard_GUID;
class Resource_Manager;
class UTL
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT static TCollection_ExtendedString xgetenv (const Standard_CString aCString);
Standard_EXPORT static Storage_Error OpenFile (const Handle(Storage_BaseDriver)& aFile,
const TCollection_ExtendedString& aName,
const Storage_OpenMode aMode);
Standard_EXPORT static void AddToUserInfo (const Handle(Storage_Data)& aData, const TCollection_ExtendedString& anInfo);
Standard_EXPORT static OSD_Path Path (const TCollection_ExtendedString& aFileName);
Standard_EXPORT static TCollection_ExtendedString Disk (const OSD_Path& aPath);
Standard_EXPORT static TCollection_ExtendedString Trek (const OSD_Path& aPath);
Standard_EXPORT static TCollection_ExtendedString Name (const OSD_Path& aPath);
Standard_EXPORT static TCollection_ExtendedString Extension (const OSD_Path& aPath);
Standard_EXPORT static OSD_FileIterator FileIterator (const OSD_Path& aPath, const TCollection_ExtendedString& aMask);
Standard_EXPORT static TCollection_ExtendedString Extension (const TCollection_ExtendedString& aFileName);
Standard_EXPORT static TCollection_ExtendedString LocalHost();
Standard_EXPORT static TCollection_ExtendedString ExtendedString (const TCollection_AsciiString& anAsciiString);
Standard_EXPORT static Standard_GUID GUID (const TCollection_ExtendedString& anXString);
Standard_EXPORT static Standard_Boolean Find (const Handle(Resource_Manager)& aResourceManager, const TCollection_ExtendedString& aResourceName);
Standard_EXPORT static TCollection_ExtendedString Value (const Handle(Resource_Manager)& aResourceManager, const TCollection_ExtendedString& aResourceName);
Standard_EXPORT static Standard_Integer IntegerValue (const TCollection_ExtendedString& anExtendedString);
Standard_EXPORT static Standard_CString CString (const TCollection_ExtendedString& anExtendedString);
Standard_EXPORT static Standard_Boolean IsReadOnly (const TCollection_ExtendedString& aFileName);
protected:
private:
};
#endif // _UTL_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2002-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#if defined LOC_LNGFILELANGMAN && !defined OPPREFSFILELANGUAGEMANAGER_H
#define OPPREFSFILELANGUAGEMANAGER_H
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
class PrefsFile;
class OpFileDescriptor;
/**
* Platform-independent file-based locale string manager.
*
* This class handles the locale strings used in the UI and elsewhere for
* Opera. This implementation of the OpLanguageManager reads from the
* supplied translation file. Platforms with special needs can re-implement
* the OpLanguageManager interface in a manner they see fit. Similarly,
* extensions to the translation file format can be handled by subclassing
* this.
*
* @author Peter Krefting
*/
class OpPrefsFileLanguageManager : public OpLanguageManager
#ifdef LANGUAGEMANAGER_CAN_RELOAD
, public PrefsCollectionFilesListener
#endif
{
public:
OpPrefsFileLanguageManager();
virtual ~OpPrefsFileLanguageManager();
#ifdef LANGUAGE_FILE_SUPPORT
/** Load a translation into the language manager. It will fetch the file
* to load from the preferences and load it up. Any errors that occur
* during load will cause a LEAVE and abort the start-up procedure.
*
* If LANGUAGEMANAGER_CAN_RELOAD is set and this method is called after
* the initial setup (from the listener interface), it will retain the
* currently loaded strings on failure.
*
* Do not use this method on the global language manager interface
* (g_languageManager) outside of the locale module. If you are using
* the OpPrefsFileLanguageManager as a stand-alone object, you should
* probably use LoadTranslationL() instead of LoadL().
*
* Must only be called from LocaleModule or OpPrefsFileLanguageManager
* itself.
*/
void LoadL();
#endif
/** Load a translation into the language manager. The file to load must
* be set up before the call to this method. The PrefsFile should use
* a PREFS_LNG type file, although that is up to the implementation.
* Cascading of language files are handled by the PrefsFile object.
*
* Do not use this method on the global language manager interface
* (g_languageManager) outside of the locale module. If you are using
* the OpPrefsFileLanguageManager as a stand-alone object, you should
* probably use this API instead of LoadL().
*
* @param file A pointer to the file to read. The language manager takes
* ownership of this object.
*/
void LoadTranslationL(PrefsFile *file);
// Inherited interfaces; see OpLanguageManager for descriptions
virtual const OpStringC GetLanguage()
{ return m_language; }
virtual unsigned int GetDatabaseVersionFromFileL()
{ return m_db; }
virtual OP_STATUS GetString(Str::LocaleString num, UniString &s);
virtual WritingDirection GetWritingDirection()
{ return m_direction; }
#ifdef LANGUAGEMANAGER_CAN_RELOAD
// Inherited interfaces; see PrefsCollectionFilesListener for descriptions
virtual void FileChangedL(PrefsCollectionFiles::filepref pref, const OpFile *newvalue);
#endif
private:
static int entrycmp(const void *, const void *);
OpString m_language;
unsigned int m_db;
struct stringdb_s
{
int id;
union
{
size_t ofs;
const uni_char *string;
} s;
};
stringdb_s *m_stringdb;
UniString m_strings;
int m_number_of_strings;
WritingDirection m_direction;
};
#endif // LOC_LNGFILELANGMAN && !OPPREFSFILELANGUAGEMANAGER_H
|
#include "ECore.h"
#include "CoreSystems.h"
#include "Render2DSystem.h"
#include "EMovementSystem.h"
#include "EJobManager.h"
#include "ETableManager.h"
#include "MutiThreading.h"
DEFINITION_SINGLE(ECore)
bool ECore::m_bLoop = true;
ECore::ECore()
{
// _CRTDBG_ALLOC_MEM_DF : DF(define) 할당하는 메모리를 체크함.
// _CRTDBG_LEAK_CHECK_DF : 누수된 메모리를 체크
// *디버그 모드*로 실행하고 메모리 누수가 있으면 출력 -> 디버그 탭에 누수가 되고있는 위치가 표시된다.
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// 평소에 주석으로 가려두고 사용하지 않는다.
// 디버그 모드에서 메모리 누수를 발견하면 누수된 메모리 블록 번호가 디버그 출력창에 표신된다.
// 표시된 메모리 블록번호를 아래에 입력하면 해당 코드가 출력되는 시점에서 예외가 발생한다.
// 위에서 표시된 메모리 블록의 번호를 아래에 매개변수로 넘기면 해당 위치로 이동한다.
//_CrtSetBreakAlloc(1733);
//pStore = new Store();
//pAccountHandler = new BAccountHandler();
//pPlayer = new Player();
}
ECore::~ECore()
{
DESTROY_SINGLE(EJobManager);
DESTROY_SINGLE(EGameInstance);
DESTROY_SINGLE(Render2DSystem);
DESTROY_SINGLE(EMovementSystem);
DESTROY_SINGLE(EInputManager);
DESTROY_SINGLE(ETimer);
DESTROY_SINGLE(ETableManager);
ReleaseDC(m_hWnd, m_hDC);//수동으로 dc 를 풀어준다.
//SAFE_DEL(pPlayer);
//SAFE_DEL(pStore);
//SAFE_DEL(pAccountHandler);
//DESTROY_SINGLE(ResourceManager);
}
bool ECore::Init(HINSTANCE hInst)
{
// 인자로 받은 메인 인스턴스 핸드를 저장
m_hInst = hInst;
// 윈도우창 클래스(스펙) 등록
MyRegisterClass();
// 해상도 설정
m_RS.Wideth = 1200;
m_RS.Height = 900;
// 윈도우 메인 창 생성 //
CreateWnd();
// 윈도우 사각형 구하기
GetClientRect(m_hWnd, &m_rtClient);
//게임 클래스에 쓸 dc를 hwdn로 얻어오기 // 해제는 소멸자에서
m_hDC = GetDC(m_hWnd);
// 서브 시스템 초기화
if (GET_SINGLE(ETableManager)->Init() == false)
return false;
if (GET_SINGLE(ETimer)->Init() == false)
return false;
if (GET_SINGLE(EInputManager)->Init() == false)
return false;
if (GET_SINGLE(EMovementSystem)->Init() == false)
return false;
if (GET_SINGLE(Render2DSystem)->Init(m_hDC) == false)
return false;
if (GET_SINGLE(EGameInstance)->Init() == false)
return false;
m_pGI = GET_SINGLE(EGameInstance);
if (GET_SINGLE(EJobManager)->Init() == false)
return false;
// 무브먼트 매니저
// 월드 매니저
//게임모드
//레벨
// 지역
// 레이어 (지정이 없으면 모두 기본으로 0번 레이어)
// 스테이지
// HUD(렌더에서 가장 나중에 찍힘)
//
// 렌더 매니저
//
//
// AssetManage한테 타이틀화면 레벨
return true;
}
void ECore::BeginPlay()
{
// 모든 컴포넌트 시스템의 틱을 호출하는 구문...// 아직 모든 시스템의 틱이 구현되지 않음
//vector<SystemBase*>::const_iterator Iter;
//Iter = m_pGI->GetComponentSystems()->begin();
//vector<SystemBase*>::const_iterator EndIter;
//EndIter = m_pGI->GetComponentSystems()->end();
//// TODO : 이 값은 Enum으로 대체해야한다.
//int ComponentSystemTickIndex = 0;
//// 모든 Component System의 Tick 함수를 시작합니다.
//// Tick 처리가 없는 함수는 아무 동작 없이 함수가 호출되었다가 반환합니다.
//for (Iter; Iter != EndIter; Iter++)
//{
// (*Iter)->GetSystemOperationByIndex(ComponentSystemTickIndex)();
//}
GET_SINGLE(EJobManager)->InitThreadPool();
}
int ECore::Run()
{
// 메시지 구조체 선언
MSG msg = {};
BeginPlay();
GET_SINGLE(ETimer)->Reset();
// TODO : 적절한 위치로 이동하기
int Render2DComponentID = (EComponentSystemIndex::Render2D << 24);
// m_bLoop가 msg.message != WM_QUIT 를대체함
while (m_bLoop)
{
// 메시지 큐에 메시지가 있으면 꺼내오고 없으면 바로 반환합니다.
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg); // 메시지를 적절한 형태로 가공합니다.
DispatchMessage(&msg); // 메시지 따라서 지정된 처리를 합니다.
}
GET_SINGLE(ETimer)->Tick();
AccumDelta += (GET_SINGLE(ETimer)->DeltaTime());
if (AccumDelta > 0.015f)
{
AccumDelta = 0.f;
// TODO : 되게 위험한 부분인게 이전의 렌더링 처리가 아직이면 크래쉬의 원인이 된다.
GET_SINGLE(EJobManager)->PushJob(0, Render2DComponentID, 0, EActiveOperation::True);
}
//else
// 1. 초기화 함수는 외부에서 호출함. 초기화 함수가 실패하면 바로 종료 프로세스
// 2. 윈도우 메시지는 Input Manager에서 처리함
// 3. Timer 처리는 Callback으로 처리됨
// 4. 입력에 대한 처리, InputManager의 Update를 가장 먼저 불러서 InputState를 설정한다.
// 5. InputManager에 바인드된 Event처리
// 6. 모든 객체의 InputProcess() 가상함수 실행
InputProcess();
// 7. AI 로직 수행
AIProcess();
// 8. 모든 객체의 Tick()함수 호출
Tick();
// 10. 충돌처리
CalculateCollision();
}
GET_SINGLE(EJobManager)->DestroyThreadPool();
return (int) msg.wParam;
}
// 함수: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 용도: 주 창의 메시지를 처리합니다.
//
// WM_COMMAND - 애플리케이션 메뉴를 처리합니다.
// WM_PAINT - 주 창을 그립니다.
// WM_DESTROY - 종료 메시지를 게시하고 반환합니다.
LRESULT ECore::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
// App이 시작할때 한번만 실행되는 초기화 구간
case WM_CREATE:
{
// 게임 관련 윈도우 메시지 처리 미리 추가
}
break;
// 이거는 참고용으로 남겨둠 이제 사용 안함.
case WM_KEYDOWN:
{
/*if (g_game.KeyCheck() == TRUE)
{
break;
}*/
switch (wParam)
{
case VK_ESCAPE:
DestroyWindow(hWnd);//종료 메시지를 발동하는함수
break;
// 소문자로 하면 제대로 작동이 안 된다. 그런데 대문자로 하면 소문자 입력까지 커버한다.
case 'P':
//g_game.UpdatePause();
break;
case VK_F3:
//g_game.ToggleFrame();
break;
default:
break;
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: 여기에 hdc를 사용하는 그리기 코드를 추가합니다...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
// 이 변수가 flase면 게임 루프가 종료된다.
m_bLoop = false;
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
ATOM ECore::MyRegisterClass()
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc; // class 내부에 만들어진 전역함수
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = m_hInst;
wcex.hIcon = LoadIcon(m_hInst, MAKEINTRESOURCE(IDI_E2));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = nullptr; // MAKEINTRESOURCEW(IDC_E2); // 이부분을 지우면 메뉴바가 사라짐
wcex.lpszClassName = WND_CLASS_NAME;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
BOOL ECore::CreateWnd()
{
// 여기서 설정한 윈도우 클라이언트 영역은 아래에서 다시 설정되므로 중요하지 않다.
// 기본코드로 대체해도 무관하다.
// param 4,5 App 윈도우창이 데스크톱 화면 위에 어떤 좌표에 생성될지(레프트탑의 위치)
// param 6,7 윈도우 클라이어트 영역의 크기
m_hWnd = CreateWindowW(WND_CLASS_NAME, WND_TITLE_NAME,
WS_OVERLAPPEDWINDOW,
100, 100, m_RS.Wideth, m_RS.Height, nullptr, nullptr, m_hInst, nullptr);
// 윈도우창 생성에 실패하면 바로 반환
if (!m_hWnd)
{
return FALSE;
}
// 현재 클라이언트 영역을 Rect 구조체로 만듬
RECT rcClient = { 0, 0, m_RS.Wideth, m_RS.Height };
// 현재 윈도우의 크기가 클라이언트 영역이 되도록 크기를 조정(현재 윈도우 크기, 윈도우 모양 스타일, 메뉴 여부)
// AdjustWindowRect()함수는 윈도우창 전체영역의 크기와 모양을 설정함.
// Rect 구조체에는 전체창 크기가 변하면서 수정된 client 영역의 크기가 저장된다.
AdjustWindowRect(&rcClient, WS_OVERLAPPEDWINDOW, FALSE);
// 얻어온 rc의 클라이언트 사각형의 사이즈 정보로 윈도우 사이즈를 다시세팅
// https://imagej.tistory.com/83
// https://goodgaym.tistory.com/22
SetWindowPos(m_hWnd, NULL,
100, 100, // 변경할 위치(X, Y)
(rcClient.right - rcClient.left), (rcClient.bottom - rcClient.top), // 변경할 크기(가로, 세로)
SWP_NOZORDER | SWP_NOMOVE // 깊이변경 금지 | 이동 금지
);
ShowWindow(m_hWnd, SW_SHOW);
UpdateWindow(m_hWnd);
return TRUE;
}
bool ECore::SetStartLevel()
{
return false;
}
void ECore::InputProcess()
{
}
void ECore::AIProcess()
{
}
void ECore::LoadAsset()
{
}
void ECore::Tick()
{
}
void ECore::CalculateCollision()
{
}
|
#include "TFile.h"
#include "TChain.h"
#include "TStopwatch.h"
#include <iostream>
#include "TTH/Plotting/interface/Event.h"
#include "TTH/Plotting/interface/categories.h"
using namespace std;
const Configuration parseArgs(int argc, const char** argv) {
if (argc != 2) {
cerr << "Usage: ./melooper conf.json" << endl;
cerr << "No json file specified, exiting" << endl;
exit(EXIT_FAILURE);
}
const string jsonFilename(argv[1]);
Configuration conf = parseJsonConf(jsonFilename);
cout << "Done loading configuration" << endl;
cout << conf.to_string() << endl;
return conf;
}
TChain* loadFiles(const Configuration& conf) {
cout << "Loading input files" << endl;
TChain* tree = new TChain("tree");
for (auto& fn : conf.filenames) {
cout << "Adding file " << fn << endl;
int isgood = tree->AddFile(fn.c_str());
if (!isgood) {
cerr << "Failed to load file " << fn << endl;
exit(EXIT_FAILURE);
}
}
//https://root.cern.ch/doc/master/classTTreeCache.html
//tree->SetCacheSize(10 * 1024 * 1024);
//tree->AddBranchToCache("*");
return tree;
}
const vector<CategoryKey::CategoryKey> emptykey;
int main(int argc, const char** argv) {
//Switch off histogram naming for memory management
TH1::AddDirectory(false);
const Configuration conf = parseArgs(argc, argv);
TChain* tree = loadFiles(conf);
// Note: this vector is made const, so that it is fully known and will not change at runtime.
const vector<const CategoryProcessor*> categorymap = makeCategories(conf);
cout << "Attaching branches..." << endl;
TreeData data;
data.loadTree(tree);
long nentries = 0;
long nbytes = 0;
ResultMap results;
if (conf.recalculateBTagWeight) {
TPython::Exec("import os");
TPython::Exec("from PhysicsTools.Heppy.physicsutils.BTagWeightCalculator import BTagWeightCalculator");
TPython::Exec("csvpath = os.environ['CMSSW_BASE']+'/src/PhysicsTools/Heppy/data'");
TPython::Exec("bweightcalc = BTagWeightCalculator(csvpath + '/csv_rwt_fit_hf_2015_11_20.root', csvpath + '/csv_rwt_fit_lf_2015_11_20.root')");
}
TStopwatch timer;
timer.Start();
long maxEntries = 0;
if (conf.numEntries >= 0) {
maxEntries = conf.firstEntry + conf.numEntries;
} else {
maxEntries = tree->GetEntries();
}
cout << "Looping over events [" << conf.firstEntry << "," << maxEntries << ")" << endl;
for (long iEntry=conf.firstEntry; iEntry < maxEntries; iEntry++) {
const bool do_print = (conf.printEvery>0 && iEntry % conf.printEvery == 0);
//std::vector<long> randoms;
//
//for (int ir=0; ir<1000; ir++) {
//}
data.init();
nbytes += tree->GetEntry(iEntry);
nentries += 1;
if (iEntry == conf.firstEntry) {
cout << "first entry " << data.run << ":" << data.lumi << ":" << data.evt << endl;
}
if (iEntry == maxEntries - 1) {
cout << "last entry " << data.run << ":" << data.lumi << ":" << data.evt << endl;
}
if (do_print) {
cout << "------" << endl;
cout << "entry " << iEntry << endl;
}
const unordered_map<SystematicKey::SystematicKey, Event, std::hash<int> > systmap = {
{SystematicKey::nominal, EventFactory::makeNominal(data, conf)},
//{SystematicKey::CMS_scale_jUp, EventFactory::makeJESUp(data, conf)},
//{SystematicKey::CMS_scale_jDown, EventFactory::makeJESDown(data, conf)},
//{SystematicKey::CMS_scale_jUp, EventFactory::makeJERUp(data, conf)},
//{SystematicKey::CMS_scale_jDown, EventFactory::makeJERDown(data, conf)}
};
for (auto& kvSyst : systmap) {
//cout << " syst " << SystematicKey::to_string(kvSyst.first) << endl;
const Event& event = kvSyst.second;
//FIXME: seems that some DL events pass, even though no jets were identified
if (event.jets.size() == 0) {
continue;
}
Configuration ev_conf(conf);
ev_conf.process = getProcessKey(event, conf.process);
if (do_print) {
cout << SystematicKey::to_string(kvSyst.first) << " " << event.to_string();
}
for (auto& cat : categorymap) {
cat->process(event, ev_conf, results, {}, kvSyst.first);
} //categorymap
} // systmap
} //entries
timer.Stop();
double t_real = timer.RealTime();
double t_cpu = timer.CpuTime();
//Finalize with output
cout << "Read " << nbytes/1024/1024 << " MB" << endl;
cout << "speedMB " << (double)nbytes/1024.0/1024.0 / t_real << " MB/s (real) " << (double)nbytes/1024.0/1024.0 / t_cpu << " MB/s (cpu)" << endl;
cout << "speedEV " << (double)nentries / t_real << " ev/s (real) " << (double)nentries / t_cpu << " ev/s (cpu)" << endl;
cout << to_string(results) << endl;
const string outname = conf.prefix;
saveResults(results, outname, conf.outputFile);
return 0;
}
|
/*
* Mowcatl.cpp
* Mowcatl
*
* Created by UNK, Sherri Harms, harmssk@unk.edu Wed Feb 09 2005.
* Copyright (c) 2004 __MyCompanyName__. All rights reserved.
*
*/
#include <iostream>
#include "mowcatl.h"
#include "xmlintface.h"
using namespace std;
string Mowcatl::getMowcatlResults( string inputXML )
{
XMLIntFace XMLIF;
return XMLIF.runMo(inputXML);
// cout<<results<<endl;
// return inputXML;
}
|
#ifndef _DX11_TEXTURE_H_
#define _DX11_TEXTURE_H_
#include "d3d11.h"
#include "Texture.h"
#include "MyString.h"
namespace HW{
class RenderSystem;
class DX11RenderSystem;
// The Texture Resource for DX11
// Only support texture2D now
// D3D11_USAGE_DEFAULT now
class DX11Texture : public Texture{
public:
DX11Texture();
virtual ~DX11Texture();
virtual void releaseInternalRes();
virtual void createInternalRes();
virtual void useTexture(){};
void SetTextureParams(UINT bindFlag, UINT cpuAccessFlag, D3D11_USAGE usage);
void SetFormat(Texture::PixelFormat format); // Set format
void SetWAndH(UINT width, UINT height); // Set width and height
void SetRenderSystem(RenderSystem* renderSystem);
void SetSamplerStateName(String& name);
String GetSamplerStateName(){ return m_SamplerStateName; }
ID3D11Resource* GetResource();
const D3D11_SAMPLER_DESC& GetSamplerDesc() const;
private:
UINT m_uBindFlag; // Default: D3D11_BIND_SHADER_RESOURCE
UINT m_uCPUAccessFlag; // Default: 0
D3D11_USAGE m_Usage; // Default: D3D11_USAGE_DEFAULT
DX11RenderSystem* m_pRenderSystem; // A quick access to render system
//DXGI_FORMAT m_eFormat;
ID3D11Texture2D* m_pTexture2D; // Only support texture2D now
D3D11_SAMPLER_DESC m_SamplerDesc;
String m_SamplerStateName; // The name of sampler state that this texture used in shader
};
class DX11TextureFactory : public TextureFactory{
public:
virtual Texture* createTexture(){
return new DX11Texture();
}
};
}
#endif
|
// Carl Borillo
// CECS 282-01
// Prog 1- Solitaire Prime
// Due- February 8,2021
#include "Card.h"
#include <iomanip>
Card::Card() {};
Card::Card(char r, char s)
{
rank = r;
suit = s;
faceUp = false;
}
char Card::getRank() {
return rank;
}
char Card::getSuit() {
return suit;
}
bool Card::isFaceUp() {
return faceUp;
}
void Card::setCard(int n) {
value = n;
}
int Card::getValue() {
return value;
}
void Card::showCard() {
if (getRank() == 'T') {
cout << "10";
}
else {
cout << setfill(' ') << setw(2) << getRank();
}
cout << getSuit();
}
Pile::Pile()
{
}
int Pile::getNumOfCards() {
return numOfCards;
}
void Pile::addCard(Card c) {
cards[numOfCards] = c;
numOfCards++;
}
int Pile::getTotal() {
sum = 0;
for (int i = 0; i < this->getNumOfCards(); i++) {
sum += cards[i].getValue();
}
return sum;
}
bool Pile::isPrime() {
if (numOfCards > 0) {
int s = this->getTotal();
if (s != 1) {
for (int i = 2; i < s - 1; i++) {
if (s%i == 0) {
return false;
}
}
return true;
}
else {
return false;
}
}
else {
return false;
}
}
void Pile::displayPile() {
cout << "New Pile: ";
for (int i = 0; i < numOfCards; i++) {
cards[i].showCard();
cout << ", ";
}
if (sum > 1) {
cout << "Prime: " << sum << endl;
}
else {
}
}
void Pile::displayLastPile() {
cout << "Your Final Pile: ";
for (int i = 0; i < numOfCards; i++) {
cards[i].showCard();
cout << ", ";
}
if (isPrime()) {
cout << "Prime: " << sum;
cout << "\nWINNER: IN ";
}
else {
cout << "\nLOSER: IN ";
}
}
|
#include <math.h>
#include <iostream>
#include "mass_index.h"
namespace BMI
{
<<<<<<< HEAD
//Тут есть изменения ыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыыы)
=======
//ssssssssssssssssssssssssssssssssss
>>>>>>> develop
float Mass_Index(float w, float h) {
return w / pow(h, 2);
}
}
|
//////////////////////////////
// Filename: LightClass.h
//////////////////////////////
#pragma once
#include <D3DX10math.h>
class LightClass
{
private:
D3DXVECTOR4 m_ambientColor;
D3DXVECTOR4 m_diffuseColor;
D3DXVECTOR3 m_direction;
public:
LightClass();
LightClass(const LightClass&);
~LightClass();
void SetAmbientColor(float, float, float, float);
void SetDiffuseColor(float, float, float, float);
void SetDirection(float, float, float);
D3DXVECTOR4 GetAmbientColor();
D3DXVECTOR4 GetDiffuseColor();
D3DXVECTOR3 GetDirection();
};
|
// Siva Sankar Kannan - 267605 - siva.kannan@student.tut.fi
#include <iostream>
#include <string>
#include "stack.hh"
using namespace std;
// Constructor
Stack::Stack() {
// Initialize the first and last pointers along with the stack size.
first_ptr = nullptr;
last_ptr = nullptr;
list_size = 0;
}
// Destructor
Stack::~Stack() {
// Traverse the whole list and remove the elements one by one.
while (first_ptr != nullptr) {
Cell *temp = first_ptr;
first_ptr = temp->next_ptr;
list_size = 0;
delete temp;
}
}
// Returns true if the list is empty.
bool Stack::empty() const {
return first_ptr == nullptr;
}
// Returns the size of the stack.
int Stack::size() const {
return list_size;
}
// Erases the element at the desired position and updates the total chores.
void Stack::erase(const int& remove_number, int& total_chores) {
Cell *temp = first_ptr;
// Condition to remove the first element.
if (remove_number == 1) {
first_ptr = first_ptr->next_ptr;
list_size = list_size - 1;
total_chores = total_chores - 1;
delete temp;
return;
}
Cell* temp2 = first_ptr->next_ptr;
int i = 2;
while (temp2 != nullptr) {
// Condition to remove the last element.
if (temp2 == last_ptr) {
last_ptr = temp;
temp->next_ptr = nullptr;
list_size = list_size - 1;
total_chores = total_chores - 1;
delete temp2;
return;
}
// Condition to remove any element in between.
if (i == remove_number) {
temp->next_ptr = temp2->next_ptr;
list_size = list_size - 1;
total_chores = total_chores - 1;
delete temp2;
return;
}
temp = temp->next_ptr;
temp2 = temp2->next_ptr;
++i;
}
}
// Removes the first element on the stack.
bool Stack::pop_front(string &removed_value) {
Cell *temp = first_ptr;
if (temp != nullptr) {
removed_value = temp->chore_description;
// Update first and last values according to the number of elements in the stack.
if (first_ptr == last_ptr) {
first_ptr = nullptr;
last_ptr = nullptr;
} else {
first_ptr = temp->next_ptr;
}
list_size = list_size - 1;
delete temp;
} else {
return false;
}
return true;
}
// Add an element to the end of the stack.
void Stack::push_back(const string& new_value) {
Cell *element = new Cell;
element->chore_description = new_value;
element->next_ptr = nullptr;
list_size = list_size + 1;
// Update first and last values according to the number of elements in the stack.
if (last_ptr == nullptr) {
last_ptr = element;
first_ptr = element;
} else {
last_ptr->next_ptr = element;
last_ptr = element;
}
}
// Print the elements in the list in FIFO order.
void Stack::print(int &running_number) const {
Cell *temp = first_ptr;
for ( ; temp; temp = temp->next_ptr) {
cout << " " << running_number << ". "
<< temp->chore_description << endl;
running_number = running_number + 1;
}
}
|
#include "NanoGui.h"
#include <glm/glm.hpp>
#include <nanogui/nanogui.h>
#include "../Core/Engine.h"
#include "../Display/Window.h"
using namespace nanogui;
NanoGui::NanoGui(Engine* engine) {
nanogui::init();
Screen *screen = new Screen();
screen->initialize(engine->getWindow()->getInstance(), false);
bool enabled = true;
FormHelper *gui = new FormHelper(screen);
ref<nanogui::Window> win = gui->add_window(Vector2i(10, 10), "Form helper example");
gui->add_group("Basic types");
bool bvar = true;
gui->add_variable("bool", bvar);
screen->set_visible(true);
screen->perform_layout();
win->center();
nanogui::mainloop();
}
NanoGui::~NanoGui() {
}
|
#pragma once
#include <unordered_map>
#include "IDataBase.hpp"
class MapDB : public IDataBase {
public:
virtual void insert(std::string const &collection, ptree const &doc);
virtual ptree findOne(std::string const &collection, ptree const &query);
virtual std::vector<ptree> find(std::string const &collection, ptree const &query);
virtual void update(std::string const &collection, ptree const &query, ptree const &update, bool upsert = false);
virtual void remove(std::string const &collection, ptree const &query);
private:
static bool cmpQuery(IDataBase::ptree const &doc, IDataBase::ptree const &query);
private:
std::unordered_map<std::string, std::vector<IDataBase::ptree>> _db;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include "OpAccountDropdown.h"
#include "adjunct/quick/Application.h"
#include "modules/inputmanager/inputmanager.h"
#include "adjunct/quick_toolkit/widgets/OpToolbar.h"
#include "adjunct/m2/src/engine/accountmgr.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/dragdrop/dragdrop_manager.h"
/***********************************************************************************
**
** OpAccountDropDown
**
***********************************************************************************/
DEFINE_CONSTRUCT(OpAccountDropDown)
OpAccountDropDown::OpAccountDropDown()
{
RETURN_VOID_IF_ERROR(init_status);
SetListener(this);
if (g_application->ShowM2())
{
g_m2_engine->AddEngineListener(this);
}
PopulateAccountDropDown();
}
void OpAccountDropDown::OnDeleted()
{
if (g_application->ShowM2())
{
g_m2_engine->RemoveEngineListener(this);
}
OpDropDown::OnDeleted();
}
/***********************************************************************************
**
** PopulateAccountDropDown
**
***********************************************************************************/
void OpAccountDropDown::PopulateAccountDropDown()
{
if (!g_application->ShowM2())
return;
Clear();
AccountManager* account_manager = g_m2_engine->GetAccountManager();
Account* account = NULL;
int i, got_index;
int active_account;
OpString active_account_category;
OpStatus::Ignore(account_manager->GetActiveAccount(active_account, active_account_category));
OpString entry_string;
g_languageManager->GetString(Str::S_ACCOUNT_SELECTOR_ALL, entry_string);
if (OpStatus::IsSuccess(AddItem(entry_string.CStr(), -1, &got_index, 0)))
{
if (active_account == 0)
{
SelectItem(got_index, TRUE);
}
}
g_languageManager->GetString(Str::S_ACCOUNT_SELECTOR_MAIL, entry_string);
if (OpStatus::IsSuccess(AddItem(entry_string.CStr(), -1, &got_index, -3)))
{
if (active_account == -3)
{
SelectItem(got_index, TRUE);
}
}
g_languageManager->GetString(Str::S_ACCOUNT_SELECTOR_NEWS, entry_string);
if (OpStatus::IsSuccess(AddItem(entry_string.CStr(), -1, &got_index, -4)))
{
if (active_account == -4)
{
SelectItem(got_index, TRUE);
}
}
BOOL seperator = FALSE;
OpAutoVector<OpString> categories;
for (i = 0; i < account_manager->GetAccountCount(); i++)
{
account = account_manager->GetAccountByIndex(i);
if (account)
{
OpString category;
account->GetAccountCategory(category);
if (category.HasContent())
{
BOOL used_already = FALSE;
for (UINT32 j = 0; j < categories.GetCount(); j++)
{
if (categories.Get(j)->CompareI(category.CStr()) == 0)
{
used_already = TRUE;
break;
}
}
if (!used_already)
{
if (!seperator)
{
if (OpStatus::IsSuccess(AddItem(NULL, -1, &got_index)))
ih.GetItemAtNr(got_index)->SetSeperator(TRUE);
seperator = TRUE;
}
OpString* string = OP_NEW(OpString, ());
if (string)
{
string->Set(category.CStr());
categories.Add(string);
}
if (OpStatus::IsSuccess(AddItem(category.CStr(), -1, &got_index, -1)))
{
if (active_account == -1 && category.CompareI(active_account_category) == 0)
{
SelectItem(got_index, TRUE);
}
}
}
}
}
}
seperator = FALSE;
for (i = 0; i < account_manager->GetAccountCount(); i++)
{
account = account_manager->GetAccountByIndex(i);
if (account)
{
switch (account->GetIncomingProtocol())
{
case AccountTypes::NEWS:
case AccountTypes::IMAP:
case AccountTypes::POP:
{
if (!seperator)
{
if (OpStatus::IsSuccess(AddItem(NULL, -1, &got_index)))
ih.GetItemAtNr(got_index)->SetSeperator(TRUE);
seperator = TRUE;
}
int id = account->GetAccountId();
if (OpStatus::IsSuccess(AddItem(account->GetAccountName().CStr(), -1, &got_index, id)))
{
if (id == active_account)
{
SelectItem(got_index, TRUE);
}
}
break;
}
}
}
}
}
/***********************************************************************************
**
** OnActiveAccountChanged
**
***********************************************************************************/
void OpAccountDropDown::OnActiveAccountChanged()
{
PopulateAccountDropDown();
}
/***********************************************************************************
**
** OnSettingsChanged
**
***********************************************************************************/
void OpAccountDropDown::OnSettingsChanged(DesktopSettings* settings)
{
OpDropDown::OnSettingsChanged(settings);
if (settings->IsChanged(SETTINGS_ACCOUNT_SELECTOR))
{
PopulateAccountDropDown();
}
}
/***********************************************************************************
**
** OnInputAction
**
***********************************************************************************/
BOOL OpAccountDropDown::OnInputAction(OpInputAction* action)
{
return OpDropDown::OnInputAction(action);
}
/***********************************************************************************
**
** OnChange
**
***********************************************************************************/
void OpAccountDropDown::OnChange(OpWidget *widget, BOOL changed_by_mouse)
{
if (widget == this && g_application->ShowM2())
{
g_m2_engine->GetAccountManager()->SetActiveAccount((INTPTR) GetItemUserData(GetSelectedItem()), GetItemText(GetSelectedItem()));
}
}
/***********************************************************************************
**
** OnMouseEvent
**
***********************************************************************************/
void OpAccountDropDown::OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks)
{
if (widget == this)
{
((OpWidgetListener*)GetParent())->OnMouseEvent(this, pos, x, y, button, down, nclicks);
}
else
{
OpDropDown::OnMouseEvent(widget, pos, x, y, button, down, nclicks);
}
}
/***********************************************************************************
**
** OnDragStart
**
***********************************************************************************/
void OpAccountDropDown::OnDragStart(OpWidget* widget, INT32 pos, INT32 x, INT32 y)
{
if (!g_application->IsDragCustomizingAllowed())
return;
DesktopDragObject* drag_object = GetDragObject(OpTypedObject::DRAG_TYPE_ACCOUNT_DROPDOWN, x, y);
if (drag_object)
{
drag_object->SetObject(this);
g_drag_manager->StartDrag(drag_object, NULL, FALSE);
}
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef DOM_JIL_API_SUPPORT
#include "modules/dom/src/domjil/domjilaccountinfo.h"
#include "modules/doc/frm_doc.h"
#include "modules/dom/src/domruntime.h"
#include "modules/ecmascript/ecmascript.h"
#include "modules/ecmascript_utils/esasyncif.h"
#include "modules/formats/encoder.h"
#include "modules/libcrypto/include/CryptoHash.h"
#include "modules/url/url_enum.h" // just for an enum required to base64 encode a piece of data
#include "modules/dom/src/domsuspendcallback.h"
#include "modules/dom/src/domcallstate.h"
#include "modules/pi/device_api/OpSubscriberInfo.h"
#include "modules/device_api/jil/JILNetworkResources.h"
struct GetUserAccountBalanceCallbackSuspendingImpl: public DOM_SuspendCallback<JilNetworkResources::GetUserAccountBalanceCallback>
{
OpString16 m_currency;
double m_cash;
GetUserAccountBalanceCallbackSuspendingImpl(): m_cash(0) {}
virtual void SetCash(const double &cash)
{
m_cash = cash;
}
virtual OP_STATUS SetCurrency(const uni_char* currency)
{
RETURN_IF_ERROR(m_currency.Set(currency));
return OpStatus::OK;
}
virtual void Finished(OP_STATUS error)
{
if (OpStatus::IsError(error))
OnFailed(error);
else
OnSuccess();
}
virtual OP_STATUS SetErrorCodeAndDescription(int code, const uni_char* description)
{
#ifdef OPERA_CONSOLE
if (g_console->IsLogging())
{
OpConsoleEngine::Message message(OpConsoleEngine::Gadget, OpConsoleEngine::Information);
RETURN_IF_ERROR(message.message.AppendFormat(UNI_L("JIL Network Protocol: GetSelfLocation returned error: %d (%s)"), code, description));
TRAP_AND_RETURN(res, g_console->PostMessageL(&message));
}
return OpStatus::OK;
#endif // OPERA_CONSOLE
}
};
struct GetUserSubscriptionTypeCallbackSuspendingImpl: public DOM_SuspendCallback<JilNetworkResources::GetUserSubscriptionTypeCallback>
{
OpString16 m_type;
virtual OP_STATUS SetType(const uni_char* type)
{
return m_type.Set(type);
}
virtual void Finished(OP_STATUS error)
{
if (OpStatus::IsError(error))
OnFailed(error);
else
OnSuccess();
}
virtual OP_STATUS SetErrorCodeAndDescription(int code, const uni_char* description)
{
#ifdef OPERA_CONSOLE
if (g_console->IsLogging())
{
OpConsoleEngine::Message message(OpConsoleEngine::Gadget, OpConsoleEngine::Information);
RETURN_IF_ERROR(message.message.AppendFormat(UNI_L("JIL Network Protocol: GetSelfLocation returned error: %d (%s)"), code, description));
TRAP_AND_RETURN(res, g_console->PostMessageL(&message));
}
return OpStatus::OK;
#endif // OPERA_CONSOLE
}
};
/* static */
OP_STATUS DOM_JILAccountInfo::Make(DOM_JILAccountInfo*& new_account, DOM_Runtime* runtime)
{
OP_ASSERT(runtime);
new_account = OP_NEW(DOM_JILAccountInfo, ());
return DOMSetObjectRuntime(new_account, runtime, runtime->GetPrototype(DOM_Runtime::JIL_ACCOUNTINFO_PROTOTYPE), "AccountInfo");
}
OP_STATUS DOM_JILAccountInfo::ComputeUniqueUserId(OpString& id)
{
OpString8 msisdn;
OpString8 imsi;
RETURN_IF_ERROR(g_op_subscriber_info->GetSubscriberMSISDN(&msisdn));
RETURN_IF_ERROR(g_op_subscriber_info->GetSubscriberIMSI(&imsi));
OpAutoPtr<CryptoHash> ap_hash(CryptoHash::CreateSHA256());
RETURN_OOM_IF_NULL(ap_hash.get());
RETURN_IF_ERROR(ap_hash->InitHash());
ap_hash->CalculateHash(imsi.CStr());
ap_hash->CalculateHash(msisdn.CStr());
// As we know the hash is SHA256 we know that the size of the hash is 32 bytes
// - no need to do dynamic allocations
UINT8 result[32];
OP_ASSERT(ARRAY_SIZE(result) == ap_hash->Size());
ap_hash->ExtractHash(result);
char* encoded = NULL;
int encoded_length;
MIME_Encode_Error encode_status =
MIME_Encode_SetStr(encoded, encoded_length, reinterpret_cast<const char*>(result), ARRAY_SIZE(result), NULL, GEN_BASE64_ONELINE);
if (encode_status != MIME_NO_ERROR)
return OpStatus::ERR;
OP_STATUS status = id.Set(encoded, encoded_length);
OP_DELETEA(encoded);
return status;
}
/* virtual */
ES_GetState DOM_JILAccountInfo::InternalGetName(OpAtom property_atom, ES_Value* value, DOM_Runtime* origining_runtime, ES_Value* restart_value)
{
DOM_CHECK_OR_RESTORE_PERFORMED; // hack so that
switch (property_atom)
{
case OP_ATOM_phoneUserUniqueId:
{
if (value)
{
OpString subscriber_id;
GET_FAILED_IF_ERROR(ComputeUniqueUserId(subscriber_id));
TempBuffer* buffer = GetEmptyTempBuf();
GET_FAILED_IF_ERROR(buffer->Append(subscriber_id.CStr()));
DOMSetString(value, buffer);
}
return GET_SUCCESS;
}
case OP_ATOM_phoneOperatorName:
{
if (value)
{
OpString operator_name;
GET_FAILED_IF_ERROR(g_op_subscriber_info->GetOperatorName(&operator_name));
TempBuffer* buffer = GetEmptyTempBuf();
GET_FAILED_IF_ERROR(buffer->Append(operator_name.CStr()));
DOMSetString(value, buffer);
}
return GET_SUCCESS;
}
case OP_ATOM_phoneMSISDN:
{
if (value)
{
OpString8 msisdn;
GET_FAILED_IF_ERROR(g_op_subscriber_info->GetSubscriberMSISDN(&msisdn));
TempBuffer* buffer = GetEmptyTempBuf();
GET_FAILED_IF_ERROR(buffer->Append(msisdn.CStr()));
DOMSetString(value, buffer);
}
return GET_SUCCESS;
}
case OP_ATOM_userAccountBalance:
{
if (value)
{
DOM_SuspendingCall call(this, NULL, 0, value, restart_value, origining_runtime, DOM_CallState::PHASE_EXECUTION_0);
NEW_SUSPENDING_CALLBACK(GetUserAccountBalanceCallbackSuspendingImpl, callback, restart_value, call, ());
OpMemberFunctionObject1<JilNetworkResources, JilNetworkResources::GetUserAccountBalanceCallback*>
function(g_DAPI_network_resources, &JilNetworkResources::GetUserAccountBalance, callback);
DOM_SUSPENDING_CALL(call, function, GetUserAccountBalanceCallbackSuspendingImpl, callback);
OP_ASSERT(callback);
if (callback->HasFailed())
DOMSetUndefined(value);
else
DOMSetNumber(value, callback->m_cash);
}
return GET_SUCCESS;
}
case OP_ATOM_userSubscriptionType:
{
if (value)
{
DOM_SuspendingCall call(this, NULL, 0, value, restart_value, origining_runtime, DOM_CallState::PHASE_EXECUTION_0);
NEW_SUSPENDING_CALLBACK(GetUserSubscriptionTypeCallbackSuspendingImpl, callback, restart_value, call, ());
OpMemberFunctionObject1<JilNetworkResources, JilNetworkResources::GetUserSubscriptionTypeCallback*>
function(g_DAPI_network_resources, &JilNetworkResources::GetUserSubscriptionType, callback);
DOM_SUSPENDING_CALL(call, function, GetUserSubscriptionTypeCallbackSuspendingImpl, callback);
OP_ASSERT(callback);
if (callback->HasFailed())
DOMSetUndefined(value);
else
{
TempBuffer* buffer = GetEmptyTempBuf();
GET_FAILED_IF_ERROR(buffer->Append(callback->m_type));
DOMSetString(value, buffer);
}
}
return GET_SUCCESS;
}
}
return GET_FAILED;
}
/* virtual */
ES_PutState DOM_JILAccountInfo::InternalPutName(OpAtom property_atom, ES_Value* value, DOM_Runtime* origining_runtime, ES_Value* restart_value)
{
switch (property_atom)
{
case OP_ATOM_phoneUserUniqueId:
case OP_ATOM_phoneOperatorName:
case OP_ATOM_phoneMSISDN:
case OP_ATOM_userAccountBalance:
case OP_ATOM_userSubscriptionType:
return PUT_SUCCESS;
}
return PUT_FAILED;
}
/* static */
int DOM_JILAccountInfo::HandleAccountError(OP_STATUS error_code, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
switch (error_code)
{
case OpStatus::ERR_NO_SUCH_RESOURCE:
return CallException(DOM_Object::JIL_UNKNOWN_ERR, return_value, origining_runtime, UNI_L("No SIM card"));
case OpStatus::ERR_NOT_SUPPORTED:
return CallException(DOM_Object::JIL_UNSUPPORTED_ERR, return_value, origining_runtime);
default:
return HandleJILError(error_code, return_value, origining_runtime);
}
}
#endif // DOM_JIL_API_SUPPORT
|
///
/// @author Florian Feuerstein
///
/// @date 02/2017
///
/// @class IntrinsicCameraCalibration
///
/// @brief
///
#pragma once
#include <ComputerVisionLib/CameraModel/CameraModel.h>
#include <ComputerVisionLib/Common/Match.h>
#include <ComputerVisionLib/Common/EigenFunctorBase.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <vector>
#include <tuple>
namespace Cvl
{
class IntrinsicCameraCalibration
{
public:
static std::tuple<bool, double> calibrate(
Eigen::Array2Xd const& templatePoints,
std::vector<Eigen::Array2Xd> const & imagePointsPerFrame,
std::vector<std::vector<Match>> const & matchesPerFrame,
CameraModel & cameraModel);
private:
IntrinsicCameraCalibration() = delete;
~IntrinsicCameraCalibration() = delete;
static std::vector<std::tuple<Eigen::Array2Xd, Eigen::Array2Xd>> alignPoints(
Eigen::Array2Xd const& templatePoints,
std::vector<Eigen::Array2Xd> const & imagePointsPerFrame,
std::vector<std::vector<Match>> const & matchesPerFrame);
static std::vector<Eigen::Matrix3d> calculateHomographies(
std::vector<std::tuple<Eigen::Array2Xd, Eigen::Array2Xd>> & alignedPointsPerFrame);
static std::vector<Eigen::Matrix3d> calculateHomographies2(
std::vector<std::tuple<Eigen::Array2Xd, Eigen::Array2Xd>> & alignedPinholePointsPerFrame,
std::vector<std::tuple<Eigen::Array2Xd, Eigen::Array2Xd>> & alignedPointsPerFrame);
static bool initializeWithHomographies(
std::vector<Eigen::Matrix3d> const& homographies,
CameraModel & cameraModel);
static std::tuple<bool, double> optimize(
std::vector<std::tuple<Eigen::Array2Xd, Eigen::Array2Xd>> const & alignedPointsPerFrame,
std::vector<Eigen::Affine3d> & modelViews,
CameraModel & cameraModel);
class Functor : public FunctorBase<double>
{
public:
Functor(
size_t numberOfIntrinsicParameters,
std::vector<std::tuple<Eigen::Array2Xd, Eigen::Array2Xd>> const & alignedPointsPerFrame,
CameraModel & cameraModel);
int operator() (Eigen::VectorXd const & x, Eigen::VectorXd & fvec) const;
private:
size_t mNumberOfIntrinsicParameters;
std::vector<std::tuple<Eigen::Array2Xd, Eigen::Array2Xd>> const & mAlignedPointsPerFrame;
CameraModel & mCameraModel;
};
};
}
|
#include<bits/stdc++.h>
using namespace std;
#define eps 1e-8
const int maxn=50010;
int prime[maxn],primesize,phi[maxn];
bool isprime[maxn];
void getlist(int listsize) {
memset(isprime,1,sizeof(isprime));
isprime[1]=false;
for(int i=2; i<=listsize; i++) {
if(isprime[i])prime[++primesize]=i;
for(int j=1; j<=primesize&&i*prime[j]<=listsize; j++) {
isprime[i*prime[j]]=false;
if(i%prime[j]==0)break;
}
}
}
double ans;
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
getlist(maxn);
ios::sync_with_stdio(false);
cin.tie(0);
int n;
// cout<<111<<"\n";
while(cin>>n&&n) {
if(n==1) {
cout<<0<<"\n";
continue;
}
ans=n*1.0;
for(int i=2; i*i<=n&&n>1; i++) {
if(isprime[i]) {
bool flag=false;
while(n%i==0) {
flag=true;
n/=i;
}
if(flag) {
// cout<<i<<"\n";
ans*=(1.0-1.0/(i*1.0));
}
}
}
// cout<<n<<"\n";
if(n>1)
ans*=(1.0-1.0/(n*1.0));
cout<<(long long)(ans+eps)<<"\n";
}
return 0;
}
|
( English:'Dutch';
Native:'Nederlands';
LangFile:'';
DicFile:'hollands.dic';
FlagID:'nl';
Letters:'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
LetterCount:'6,2,2,5,18,2,3,2,4,2,3,3,3,10,6,2,1,5,5,5,3,2,2,1,1,2';
LetterValue:'1,3,5,2,1,4,3,4,1,4,3,3,3,1,1,3,10,2,2,2,4,4,5,8,8,4';
NumberOfJokers:2;
ReadingDirection:rdLeftToRight;
ExcludedCat:'';
RulesValid:true;
NumberOfLetters:7;
NumberOfRandoms:0;
TimeControl:2;
TimeControlEnd:false;
TimeControlBuy:true;
TimePerGame:'0:50:00'; //page 22, 5.3.5
PenaltyValue:10; //page 21, 5.3.2
PenaltyCount:10; //page 21, 5.3.3
GameLostByTime:true; //page 21, 5.3.3
WordCheckMode:2;
ChallengePenalty:5; //one of the possibilities according to WESPA v2, see page 17, 3.10.15 and page 18, 3.10.15 (d)
ChallengeTime:20; //chosen arbitrarily, not enshrined in the rules, see page 15, 3.10.3
JokerExchange:false;
ChangeIsPass:true; //page 21, 5.2
CambioSecco:false;
SubstractLetters:true; //page 21, 5.1.4
AddLetters:true; //page 21, 5.1.4
JokerPenalty:0;
NumberOfPasses:3; //page 21, 5.2
LimitExchange:7; //page 11, 3.2.1
EndBonus:0;
ScrabbleBonus:50)
{Comment:
There are two official Scrabble Federations for Dutch Scrabble: one in the Netherlands and one in Belgium,
and therefore there are official rules for Scrabble tournaments in Dutch language indeed, but those
rules have not been published on internet and they cannot be downloaded either:
http://www.scrabblebond.nl/www/inh.htm
http://www.ntsv.net/
Whoever wants to read those rules has to buy them from one of the Scrabble Federations for Dutch Scrabble.
That's the reason why for the present and temporarily the English WESPA rules have arbitrarily
been chosen instead of the Dutch rules.
-
References:
http://www.wespa.org/rules/RulesV2nov11.pdf (WESPA 2.0 from 2010-11-17)
Current state of implementation in this *.inc file: 2012-08-10 }
|
#include "stdafx.h"
#include <iostream>
#include "BelmannFordListAlgorithm.h"
BelmannFordListAlgorithm::BelmannFordListAlgorithm(Graph & graph) :BelmannFordMatrixAlgorithm(graph)
{
}
BelmannFordListAlgorithm::~BelmannFordListAlgorithm()
{
}
void BelmannFordListAlgorithm::startAlgorithm()
{
for (int i = 0; i <= numberVertices - 1; i++)// V-1 razy relaksacja dla kazdej krawedzi
{
if (czy == true)
relaxationForAllEdges();
}
for (int j = 0; j < numberVertices; j++) //macierzowo
{
int size = graph.neighborhoodListTable[j].size();
for (int i = 0; i < size; i++)
{
int k = graph.neighborhoodListTable[j].getVertrex(i);
int weight = graph.neighborhoodListTable[j].getWeight(i);//getWeightOfVertex(k);//FRIENDSHIP HERE IS NEEDED
long long int x = shortestPaths[k], y = shortestPaths[j];
if (x > y + weight)
{
std::cout << "STOP BELMAN LIST\n";
return;
}
}
}
}
void BelmannFordListAlgorithm::relaxationForAllEdges()
{
for (int j = 0; j < numberVertices; j++) //macierzowo
{
if (j == 0)
czy = false;
int size = graph.neighborhoodListTable[j].size();
for (int i = 0; i < size; i++)
{
MyList::elementOfList e = graph.neighborhoodListTable[j].get(i);//FRIENDSHIP HERE IS NEEDED
int ver = e.vertex;//graph.neighborhoodListTable[j].getVertrex(i);
int we = e.weight;
relaxation(j, ver, we);
}
}
}
void BelmannFordListAlgorithm::relaxation(int u, int v, int weight)
{
//int weight = graph.neighborhoodListTable[u].getWeightOfVertex(v);//FRIENDSHIP HERE IS NEEDED
long long int x = shortestPaths[v], y = shortestPaths[u];
//std::cout << u << " " << v << "\n";
//std::cout << x << ">" << y + weight << "\n";
if (x > y + weight)
{
//std::cout << "ELO " <<shortestPaths[u] <<" "<< weight <<"\n";
shortestPaths[v] = shortestPaths[u] + weight;
previousVertices[v] = u;
czy = true;
}
//std::cout << "\n";
}
|
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int> smallQ, bigQ;
void addNum(int num) {
if(smallQ.empty() || num <= smallQ.top()){
smallQ.push(num);
if(smallQ.size() > bigQ.size() + 1){
int x = smallQ.top();
smallQ.pop();
bigQ.push(-x);
}
}
else{
bigQ.push(-num);
if(bigQ.size() > smallQ.size()){
int x = -bigQ.top();
bigQ.pop();
smallQ.push(x);
}
}
}
double findMedian() {
if(smallQ.size() > bigQ.size())
return smallQ.top();
return (smallQ.top() - bigQ.top()) / 2.0;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
int main(){
MedianFinder obj;
obj.addNum(1);
cout << obj.findMedian() << endl;
obj.addNum(2);
cout << obj.findMedian() << endl;
obj.addNum(3);
cout << obj.findMedian() << endl;
obj.addNum(-4);
cout << obj.findMedian() << endl;
obj.addNum(-5);
cout << obj.findMedian() << endl;
}
|
#ifndef NEURAL_NETWORK_CONFIGURATION_H
#define NEURAL_NETWORK_CONFIGURATION_H
#include <string>
#include "utility/Matrix.h"
#include "utility/types.h"
class TiXmlElement;
struct NeuralNodeGroupConfiguration
{
Id id;
int nodeCount;
float excitationOffset;
float excitationMultiplier;
float excitationThreshold;
float excitationFatigue;
};
struct NeuralEdgeGroupConfiguration
{
NeuralEdgeGroupConfiguration(Id sourceGroupId, Id targetGroupId, Matrix<float> weights)
: sourceGroupId(sourceGroupId)
, targetGroupId(targetGroupId)
, weights(weights)
{}
Id sourceGroupId;
Id targetGroupId;
Matrix<float> weights;
};
struct NeuralNetworkConfiguration
{
NeuralNetworkConfiguration();
Id inputGroupId;
Id outputGroupId;
std::vector<NeuralNodeGroupConfiguration> nodeGroups;
std::vector<NeuralEdgeGroupConfiguration> edgeGroups;
};
TiXmlElement* matrixToXmlElement(const Matrix<float>& matrix);
Matrix<float> matrixFromXmlElement(const TiXmlElement* element);
TiXmlElement* neuralNodeGroupConfigurationToXmlElement(const NeuralNodeGroupConfiguration& configuration);
NeuralNodeGroupConfiguration neuralNodeGroupConfigurationFromXmlElement(const TiXmlElement* element);
TiXmlElement* neuralEdgeGroupConfigurationToXmlElement(const NeuralEdgeGroupConfiguration& configuration);
NeuralEdgeGroupConfiguration neuralEdgeGroupConfigurationFromXmlElement(const TiXmlElement* element);
TiXmlElement* neuralNetworkConfigurationToXmlElement(const NeuralNetworkConfiguration& configuration);
NeuralNetworkConfiguration neuralNetworkConfigurationFromXmlElement(const TiXmlElement* element);
#endif // NEURAL_NETWORK_CONFIGURATION_H
|
#ifndef FINANCE_H
#define FINANCE_H
#include"QString"
#include"QDebug"
#include "connection.h"
#include "QSqlQueryModel"
#include <QDebug>
#include <QPalette>
#include <QDesktopWidget>
#include <QtGui>
class facture
{
protected :
QString Nom;
QString Adresse ;
QString Num_Tel;
QString courriel ;
int ID;
QString Info;
QString paiement;
QString Tpaiement;
public:
facture();
facture(QString Nom,QString Adresse,QString Num_Tel,QString courriel,int ID,QString Info,QString paiement,QString Tpaiement);
QString getNom(){return Nom;};
QString getAdresse(){return Adresse;} ;
QString getNum_Tel() {return Num_Tel;};
QString getcourriel() {return courriel;};
int getID(){return ID;};
QString getInfo(){return Info;};
QString getpaiement(){return paiement;};
QString getTpaiement(){return Tpaiement; };
bool AjoutFacture(facture *FA);
virtual QSqlQueryModel * AfficherFacture();
QSqlQueryModel * RechercherFacture(int ID);
bool SupprimerFacture(int ID);
bool ModifierFacture(facture *FA);
};
#endif // FINANCE_H
|
#include <thread>
#include <condition_variable>
#include <cassert>
#include <algorithm>
#include "atomic.hh"
#include "coroutine.hh"
#include "logging.hh"
#include "task.hh"
#include "descriptors.hh"
#include <cxxabi.h>
#include <execinfo.h>
#include <iostream>
namespace hack {
// hack to avoid redefinition of ucontext
// by including it in a namespace
#include <asm-generic/ucontext.h>
}
namespace ten {
struct io_scheduler;
static std::atomic<uint64_t> taskidgen(0);
static __thread proc *_this_proc = 0;
static std::mutex procsmutex;
static proclist procs;
static std::once_flag init_flag;
struct task {
char name[256];
char state[256];
std::function<void ()> fn;
coroutine co;
uint64_t id;
proc *cproc;
time_point<monotonic_clock> timeout;
time_point<monotonic_clock> deadline;
bool exiting;
bool systask;
bool canceled;
bool unwinding;
task(const std::function<void ()> &f, size_t stacksize);
void ready();
void swap();
void exit() {
exiting = true;
fn = 0;
swap();
}
void cancel() {
// don't cancel systasks
if (systask) return;
canceled = true;
ready();
}
void setname(const char *fmt, ...) {
va_list arg;
va_start(arg, fmt);
vsetname(fmt, arg);
va_end(arg);
}
void vsetname(const char *fmt, va_list arg) {
vsnprintf(name, sizeof(name), fmt, arg);
}
void setstate(const char *fmt, ...) {
va_list arg;
va_start(arg, fmt);
vsetstate(fmt, arg);
va_end(arg);
}
void vsetstate(const char *fmt, va_list arg) {
vsnprintf(state, sizeof(state), fmt, arg);
}
static void start(void *arg) {
task *t = (task *)arg;
try {
t->fn();
} catch (task_interrupted &e) {
DVLOG(5) << "task interrupted " << t << " " << t->name << " |" << t->state << "|";
} catch (backtrace_exception &e) {
LOG(ERROR) << "unhandled error in task::start: " << e.what() << "\n" << e.str();
std::exit(2);
} catch (std::exception &e) {
LOG(ERROR) << "unhandled error in task::start: " << e.what();
std::exit(2);
}
t->exit();
}
};
std::ostream &operator << (std::ostream &o, task *t) {
if (t) {
o << "[" << (void*)t << " " << t->id << " "
<< t->name << " |" << t->state
<< "| sys: " << t->systask
<< " exiting: " << t->exiting
<< " canceled: " << t->canceled << "]";
} else {
o << "nulltask";
}
return o;
}
struct proc {
io_scheduler *_sched;
std::thread *thread;
std::mutex mutex;
uint64_t nswitch;
task *ctask;
tasklist runqueue;
tasklist alltasks;
coroutine co;
//! true when asleep and runqueue is empty and no epoll
bool asleep;
//! true when asleep in epoll_wait
bool polling;
//! true when canceled
bool canceled;
//! cond used to wake up when runqueue is empty and no epoll
std::condition_variable cond;
//! pipe used to wake up from epoll
pipe_fd pi;
std::atomic<uint64_t> taskcount;
//! current time cached in a few places through the event loop
time_point<monotonic_clock> now;
proc(task *t = 0)
: _sched(0), nswitch(0), ctask(0),
asleep(false), polling(false), canceled(false), pi(O_NONBLOCK), taskcount(0)
{
now = monotonic_clock::now();
add(this);
if (t) {
std::unique_lock<std::mutex> lk(mutex);
thread = new std::thread(proc::startproc, this, t);
thread->detach();
} else {
// main thread proc
_this_proc = this;
thread = 0;
}
}
~proc();
void schedule();
io_scheduler &sched();
bool is_ready() {
return !runqueue.empty();
}
void cancel() {
std::unique_lock<std::mutex> lk(mutex);
canceled = true;
wakeupandunlock(lk);
}
void wakeupandunlock(std::unique_lock<std::mutex> &lk);
void addtaskinproc(task *t) {
++taskcount;
alltasks.push_back(t);
t->cproc = this;
}
void deltaskinproc(task *t);
static void add(proc *p) {
std::unique_lock<std::mutex> lk(procsmutex);
procs.push_back(p);
}
static void del(proc *p) {
std::unique_lock<std::mutex> lk(procsmutex);
auto i = std::find(procs.begin(), procs.end(), p);
procs.erase(i);
}
static void startproc(proc *p_, task *t) {
_this_proc = p_;
std::unique_ptr<proc> p(p_);
p->addtaskinproc(t);
t->ready();
DVLOG(5) << "proc: " << p_ << " thread id: " << std::this_thread::get_id();
p->schedule();
DVLOG(5) << "proc done: " << std::this_thread::get_id() << " " << p_;
}
};
uint64_t procspawn(const std::function<void ()> &f, size_t stacksize) {
task *t = new task(f, stacksize);
uint64_t tid = t->id;
new proc(t);
// task could be freed at this point
return tid;
}
uint64_t taskspawn(const std::function<void ()> &f, size_t stacksize) {
task *t = new task(f, stacksize);
_this_proc->addtaskinproc(t);
t->ready();
return t->id;
}
uint64_t taskid() {
CHECK(_this_proc);
CHECK(_this_proc->ctask);
return _this_proc->ctask->id;
}
int64_t taskyield() {
proc *p = _this_proc;
uint64_t n = p->nswitch;
task *t = p->ctask;
t->ready();
taskstate("yield");
t->swap();
DVLOG(5) << "yield: " << (int64_t)(p->nswitch - n - 1);
return p->nswitch - n - 1;
}
void tasksystem() {
proc *p = _this_proc;
if (!p->ctask->systask) {
p->ctask->systask = true;
--p->taskcount;
}
}
bool taskcancel(uint64_t id) {
proc *p = _this_proc;
task *t = 0;
for (auto i = p->alltasks.cbegin(); i != p->alltasks.cend(); ++i) {
if ((*i)->id == id) {
t = *i;
break;
}
}
if (t) {
t->cancel();
}
return (bool)t;
}
const char *taskname(const char *fmt, ...)
{
task *t = _this_proc->ctask;
if (fmt && strlen(fmt)) {
va_list arg;
va_start(arg, fmt);
t->vsetname(fmt, arg);
va_end(arg);
}
return t->name;
}
const char *taskstate(const char *fmt, ...)
{
task *t = _this_proc->ctask;
if (fmt && strlen(fmt)) {
va_list arg;
va_start(arg, fmt);
t->vsetstate(fmt, arg);
va_end(arg);
}
return t->state;
}
std::string taskdump() {
std::stringstream ss;
proc *p = _this_proc;
CHECK(p) << "BUG: taskdump called in null proc";
task *t = 0;
for (auto i = p->alltasks.cbegin(); i != p->alltasks.cend(); ++i) {
t = *i;
ss << t << "\n";
}
return ss.str();
}
void procshutdown() {
proc *p = _this_proc;
for (auto i = p->alltasks.cbegin(); i != p->alltasks.cend(); ++i) {
task *t = *i;
if (t == p->ctask) continue; // don't add ourself to the runqueue
if (!t->systask) {
t->cancel();
}
}
}
void taskdumpf(FILE *of) {
std::string dump = taskdump();
fwrite(dump.c_str(), sizeof(char), dump.size(), of);
fflush(of);
}
task::task(const std::function<void ()> &f, size_t stacksize)
: fn(f), co(task::start, this, stacksize), cproc(0),
exiting(false), systask(false), canceled(false), unwinding(false)
{
id = ++taskidgen;
setname("task[%ju]", id);
setstate("new");
}
void task::ready() {
if (exiting) return;
proc *p = cproc;
std::unique_lock<std::mutex> lk(p->mutex);
if (std::find(p->runqueue.cbegin(), p->runqueue.cend(), this) == p->runqueue.cend()) {
DVLOG(5) << _this_proc->ctask << " adding task: " << this << " to runqueue for proc: " << p;
p->runqueue.push_back(this);
// XXX: does this need to be outside of the if(!found) ?
if (p != _this_proc) {
p->wakeupandunlock(lk);
}
} else {
DVLOG(5) << "found task: " << this << " already in runqueue for proc: " << p;
}
}
void qutex::lock() {
task *t = _this_proc->ctask;
CHECK(t) << "BUG: qutex::lock called outside of task:\n" << saved_backtrace().str();
{
std::unique_lock<std::timed_mutex> lk(m);
if (owner == 0 || owner == t) {
owner = t;
DVLOG(5) << "LOCK qutex: " << this << " owner: " << owner;
return;
}
DVLOG(5) << "LOCK waiting: " << this << " add: " << t << " owner: " << owner;
waiting.push_back(t);
}
try {
t->swap();
CHECK(owner == _this_proc->ctask) << "Qutex: " << this << " owner check failed: " <<
owner << " != " << _this_proc->ctask << " t:" << t <<
" owner->cproc: " << owner->cproc << " this_proc: " << _this_proc;
} catch (task_interrupted &e) {
std::unique_lock<std::timed_mutex> lk(m);
if (t == owner) {
owner = 0;
if (!waiting.empty()) {
owner = waiting.front();
waiting.pop_front();
}
lk.unlock();
if (owner) owner->ready();
} else {
auto i = std::find(waiting.begin(), waiting.end(), t);
if (i != waiting.end()) {
waiting.erase(i);
}
}
throw;
}
}
bool qutex::try_lock() {
task *t = _this_proc->ctask;
CHECK(t) << "BUG: qutex::try_lock called outside of task:\n" << saved_backtrace().str();
std::unique_lock<std::timed_mutex> lk(m, std::try_to_lock);
if (lk.owns_lock()) {
if (owner == 0) {
owner = t;
return true;
}
}
return false;
}
void qutex::unlock() {
task *t = 0;
{
std::unique_lock<std::timed_mutex> lk(m);
if (!waiting.empty()) {
t = owner = waiting.front();
waiting.pop_front();
} else {
owner = 0;
}
DVLOG(5) << "UNLOCK qutex: " << this << " new owner: " << owner << " waiting: " << waiting.size();
}
if (t) t->ready();
}
static void info_handler(int sig_num, siginfo_t *info, void *ctxt) {
taskdumpf();
}
static void backtrace_handler(int sig_num, siginfo_t *info, void *ctxt) {
// http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
// TODO: maybe use the google logging demangler that doesn't alloc
hack::ucontext *uc = (hack::ucontext *)ctxt;
// Get the address at the time the signal was raised from the instruction pointer
#if __i386__
void *caller_address = (void *) uc->uc_mcontext.eip;
#elif __amd64__
void *caller_address = (void *) uc->uc_mcontext.rip;
#else
#error "arch not supported"
#endif
fprintf(stderr, "signal %d (%s), address is %p from %p\n",
sig_num, strsignal(sig_num), info->si_addr,
(void *)caller_address);
void *array[50];
int size = backtrace(array, 50);
// overwrite sigaction with caller's address
array[1] = caller_address;
char **messages = backtrace_symbols(array, size);
// skip first stack frame (points here)
for (int i = 1; i < size && messages != NULL; ++i) {
char *mangled_name = 0, *offset_begin = 0, *offset_end = 0;
// find parantheses and +address offset surrounding mangled name
for (char *p = messages[i]; *p; ++p) {
if (*p == '(') {
mangled_name = p;
} else if (*p == '+') {
offset_begin = p;
} else if (*p == ')') {
offset_end = p;
break;
}
}
// if the line could be processed, attempt to demangle the symbol
if (mangled_name && offset_begin && offset_end &&
mangled_name < offset_begin)
{
*mangled_name++ = '\0';
*offset_begin++ = '\0';
*offset_end++ = '\0';
int status;
char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status);
if (status == 0) {
// if demangling is successful, output the demangled function name
std::cerr << "[bt]: (" << i << ") " << messages[i] << " : "
<< real_name << "+" << offset_begin << offset_end
<< std::endl;
} else {
// otherwise, output the mangled function name
std::cerr << "[bt]: (" << i << ") " << messages[i] << " : "
<< mangled_name << "+" << offset_begin << offset_end
<< std::endl;
}
free(real_name);
} else {
// otherwise, print the whole line
std::cerr << "[bt]: (" << i << ") " << messages[i] << std::endl;
}
}
std::cerr << std::endl;
free(messages);
exit(EXIT_FAILURE);
}
static void procmain_init() {
//ncpu_ = sysconf(_SC_NPROCESSORS_ONLN);
// XXX: i *think* this usable with the backtrace
// i beleive the ucontext passed to the sig handler
// is the pointer to the main stack
#if 0
stack_t ss;
ss.ss_sp = calloc(1, SIGSTKSZ);
ss.ss_size = SIGSTKSZ;
ss.ss_flags = 0;
THROW_ON_ERROR(sigaltstack(&ss, NULL));
#endif
// allow log files and message queues to be created group writable
umask(0);
google::InitGoogleLogging(program_invocation_short_name);
google::InstallFailureSignalHandler();
FLAGS_logtostderr = true;
struct sigaction act;
// XXX: google glog handles this for us
// in a more signal safe manner (no malloc)
#if 0
// install SIGSEGV handler
act.sa_sigaction = backtrace_handler;
act.sa_flags = SA_RESTART | SA_SIGINFO;
THROW_ON_ERROR(sigaction(SIGSEGV, &act, NULL));
// install SIGABRT handler
act.sa_sigaction = backtrace_handler;
act.sa_flags = SA_RESTART | SA_SIGINFO;
THROW_ON_ERROR(sigaction(SIGABRT, &act, NULL));
#endif
// ignore SIGPIPE
memset(&act, 0, sizeof(act));
THROW_ON_ERROR(sigaction(SIGPIPE, NULL, &act));
if (act.sa_handler == SIG_DFL) {
act.sa_handler = SIG_IGN;
THROW_ON_ERROR(sigaction(SIGPIPE, &act, NULL));
}
// install INFO handler
THROW_ON_ERROR(sigaction(SIGUSR1, NULL, &act));
if (act.sa_handler == SIG_DFL) {
act.sa_sigaction = info_handler;
act.sa_flags = SA_RESTART | SA_SIGINFO;
THROW_ON_ERROR(sigaction(SIGUSR1, &act, NULL));
}
new proc();
}
procmain::procmain() {
std::call_once(init_flag, procmain_init);
if (_this_proc == 0) {
// needed for tests which call procmain a lot
new proc();
}
}
int procmain::main(int argc, char *argv[]) {
std::unique_ptr<proc> p(_this_proc);
p->schedule();
return EXIT_SUCCESS;
}
void proc::schedule() {
try {
DVLOG(5) << "p: " << this << " entering proc::schedule";
for (;;) {
if (taskcount == 0) break;
std::unique_lock<std::mutex> lk(mutex);
while (runqueue.empty() && !canceled) {
asleep = true;
cond.wait(lk);
}
asleep = false;
if (canceled) {
// set canceled to false so we don't
// execute this every time through the loop
// while the tasks are cleaning up
canceled = false;
lk.unlock();
procshutdown();
lk.lock();
CHECK(!runqueue.empty()) << "BUG: runqueue empty?";
}
task *t = runqueue.front();
runqueue.pop_front();
ctask = t;
if (!t->systask) {
// dont increment for system tasks so
// while(taskyield()) {} can be used to
// wait for all other tasks to exit
// really only useful for unit tests.
++nswitch;
}
DVLOG(5) << "p: " << this << " swapping to: " << t;
lk.unlock();
co.swap(&t->co);
lk.lock();
ctask = 0;
if (t->exiting) {
deltaskinproc(t);
}
}
} catch (backtrace_exception &e) {
LOG(ERROR) << "unhandled error in proc::schedule: " << e.what() << "\n" << e.str();
std::exit(2);
} catch (std::exception &e) {
LOG(ERROR) << "unhandled error in proc::schedule: " << e.what();
std::exit(2);
}
}
struct io_scheduler {
struct task_timeout_compare {
bool operator ()(const task *a, const task *b) const {
// sort by timeout and then pointer value so erase will be able to
// find exact pointer values when the timeouts are the same
// which can happen frequently because we try to collate timeouts
return a->timeout < b->timeout || (a->timeout == b->timeout && a < b);
}
};
struct task_poll_state {
task *t_in; // POLLIN task
pollfd *p_in; // pointer to pollfd structure that is on the task's stack
task *t_out; // POLLOUT task
pollfd *p_out; // pointer to pollfd structure that is on the task's stack
uint32_t events; // events this fd is registered for
task_poll_state() : t_in(0), p_in(0), t_out(0), p_out(0), events(0) {}
};
typedef std::vector<task_poll_state> poll_task_array;
typedef std::vector<epoll_event> event_vector;
typedef std::multiset<task *, task_timeout_compare> timeoutset;
//! tasks with timeouts set
timeoutset timeouts;
//! array of tasks waiting on fds, indexed by the fd for speedy lookup
poll_task_array pollfds;
//! epoll events
event_vector events;
//! the epoll fd used for io in this runner
epoll_fd efd;
//! number of fds we've been asked to wait on
size_t npollfds;
io_scheduler() : npollfds(0) {
events.reserve(1000);
// add the pipe used to wake up
epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN | EPOLLET;
int pi_fd = _this_proc->pi.r.fd;
ev.data.fd = pi_fd;
if (pollfds.size() <= (size_t)pi_fd) {
pollfds.resize(pi_fd+1);
}
efd.add(pi_fd, ev);
taskspawn(std::bind(&io_scheduler::fdtask, this));
}
void add_pollfds(task *t, pollfd *fds, nfds_t nfds) {
for (nfds_t i=0; i<nfds; ++i) {
epoll_event ev;
memset(&ev, 0, sizeof(ev));
int fd = fds[i].fd;
fds[i].revents = 0;
// make room for the highest fd number
if (pollfds.size() <= (size_t)fd) {
pollfds.resize(fd+1);
}
ev.data.fd = fd;
uint32_t events = pollfds[fd].events;
if (fds[i].events & EPOLLIN) {
CHECK(pollfds[fd].t_in == 0);
pollfds[fd].t_in = t;
pollfds[fd].p_in = &fds[i];
pollfds[fd].events |= EPOLLIN;
}
if (fds[i].events & EPOLLOUT) {
CHECK(pollfds[fd].t_out == 0);
pollfds[fd].t_out = t;
pollfds[fd].p_out = &fds[i];
pollfds[fd].events |= EPOLLOUT;
}
ev.events = pollfds[fd].events;
if (events == 0) {
THROW_ON_ERROR(efd.add(fd, ev));
} else if (events != pollfds[fd].events) {
THROW_ON_ERROR(efd.modify(fd, ev));
}
++npollfds;
}
}
int remove_pollfds(pollfd *fds, nfds_t nfds) {
int rvalue = 0;
for (nfds_t i=0; i<nfds; ++i) {
int fd = fds[i].fd;
if (fds[i].revents) rvalue++;
if (pollfds[fd].p_in == &fds[i]) {
pollfds[fd].t_in = 0;
pollfds[fd].p_in = 0;
pollfds[fd].events ^= EPOLLIN;
}
if (pollfds[fd].p_out == &fds[i]) {
pollfds[fd].t_out = 0;
pollfds[fd].p_out = 0;
pollfds[fd].events ^= EPOLLOUT;
}
if (pollfds[fd].events == 0) {
efd.remove(fd);
} else {
epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.data.fd = fd;
ev.events = pollfds[fd].events;
THROW_ON_ERROR(efd.modify(fd, ev));
}
--npollfds;
}
return rvalue;
}
template<typename Rep,typename Period>
void add_timeout(task *t, const duration<Rep,Period> &dura) {
t->timeout = _this_proc->now + dura;
if (t->deadline.time_since_epoch().count() != 0) {
if (t->timeout > t->deadline) {
// don't sleep past the deadline
t->timeout = t->deadline;
}
}
timeouts.insert(t);
}
bool del_timeout(task *t) {
if (t->timeout.time_since_epoch().count() == 0) return false;
return timeouts.erase(t);
}
template<typename Rep,typename Period>
void sleep(const duration<Rep, Period> &dura) {
task *t = _this_proc->ctask;
add_timeout(t, dura);
t->swap();
}
bool fdwait(int fd, int rw, uint64_t ms) {
short events = 0;
switch (rw) {
case 'r':
events |= EPOLLIN;
break;
case 'w':
events |= EPOLLOUT;
break;
}
pollfd fds = {fd, events, 0};
if (poll(&fds, 1, ms) > 0) {
if ((fds.revents & EPOLLERR) || (fds.revents & EPOLLHUP)) {
return false;
}
return true;
}
return false;
}
int poll(pollfd *fds, nfds_t nfds, uint64_t ms) {
task *t = _this_proc->ctask;
if (nfds == 1) {
taskstate("poll fd %i r: %i w: %i %ul ms",
fds->fd, fds->events & EPOLLIN, fds->events & EPOLLOUT, ms);
} else {
taskstate("poll %u fds for %ul ms", nfds, ms);
}
if (ms) {
add_timeout(t, milliseconds(ms));
}
add_pollfds(t, fds, nfds);
DVLOG(5) << "task: " << t << " poll for " << nfds << " fds";
try {
t->swap();
} catch (task_interrupted &e) {
if (ms) timeouts.erase(t);
remove_pollfds(fds, nfds);
throw;
}
if (ms) timeouts.erase(t);
return remove_pollfds(fds, nfds);
}
void fdtask() {
taskname("fdtask");
tasksystem();
proc *p = _this_proc;
for (;;) {
p->now = monotonic_clock::now();
// let everyone else run
taskyield();
p->now = monotonic_clock::now();
task *t = 0;
int ms = -1;
// lock must be held while determining whether or not we'll be
// asleep in epoll, so wakeupandunlock will work from another
// thread
std::unique_lock<std::mutex> lk(p->mutex);
if (!timeouts.empty()) {
t = *timeouts.begin();
if (t->timeout <= p->now) {
// epoll_wait must return asap
ms = 0;
} else {
ms = duration_cast<milliseconds>(t->timeout - p->now).count();
// avoid spinning on timeouts smaller than 1ms
if (ms <= 0) ms = 1;
}
}
if (ms != 0) {
if (!p->runqueue.empty()) {
// don't block on epoll if tasks are ready to run
ms = 0;
}
}
if (ms != 0 || npollfds > 0) {
taskstate("epoll");
// only process 1000 events each iteration to keep it fair
if (ms > 1 || ms < 0) {
p->polling = true;
}
lk.unlock();
events.resize(1000);
efd.wait(events, ms);
lk.lock();
p->polling = false;
int wakeup_pipe_fd = p->pi.r.fd;
lk.unlock();
// wake up io tasks
for (auto i=events.cbegin(); i!=events.cend(); ++i) {
// NOTE: epoll will also return EPOLLERR and EPOLLHUP for every fd
// even if they arent asked for, so we must wake up the tasks on any event
// to avoid just spinning in epoll.
int fd = i->data.fd;
if (pollfds[fd].t_in) {
pollfds[fd].p_in->revents = i->events;
t = pollfds[fd].t_in;
DVLOG(5) << "IN EVENT on task: " << t << " state: " << t->state;
t->ready();
}
// check to see if pollout is a different task than pollin
if (pollfds[fd].t_out && pollfds[fd].t_out != pollfds[fd].t_in) {
pollfds[fd].p_out->revents = i->events;
t = pollfds[fd].t_out;
DVLOG(5) << "OUT EVENT on task: " << t;
t->ready();
}
if (i->data.fd == wakeup_pipe_fd) {
// our wake up pipe was written to
char buf[32];
// clear pipe
while (p->pi.read(buf, sizeof(buf)) > 0) {}
} else if (pollfds[fd].t_in == 0 && pollfds[fd].t_out == 0) {
// TODO: otherwise we might want to remove fd from epoll
LOG(ERROR) << "event " << i->events << " for fd: " << i->data.fd << " but has no task";
}
}
}
// must unlock before calling task::ready
if (lk.owns_lock()) lk.unlock();
p->now = monotonic_clock::now();
// wake up sleeping tasks
auto i = timeouts.begin();
for (; i != timeouts.end(); ++i) {
t = *i;
if (t->timeout <= p->now) {
DVLOG(5) << "TIMEOUT on task: " << t;
t->ready();
} else {
break;
}
}
timeouts.erase(timeouts.begin(), i);
}
}
};
const time_point<monotonic_clock> &procnow() {
return _this_proc->now;
}
void task::swap() {
if (canceled && !exiting) {
DVLOG(5) << "BUG: " << this << "\n" << saved_backtrace().str();
}
// swap to scheduler coroutine
co.swap(&_this_proc->co);
if (canceled && !unwinding) {
unwinding = true;
DVLOG(5) << "THROW INTERRUPT: " << this;
throw task_interrupted();
}
if (deadline.time_since_epoch().count() != 0 && _this_proc->now >= deadline) {
// remove deadline so we don't throw twice
deadline = time_point<monotonic_clock>();
DVLOG(5) << "THROW DEADLINE: " << this;
throw deadline_reached();
}
}
void proc::wakeupandunlock(std::unique_lock<std::mutex> &lk) {
if (asleep) {
asleep = false;
cond.notify_one();
} else if (polling) {
polling = false;
ssize_t nw = pi.write("\1", 1);
(void)nw;
}
lk.unlock();
}
proc::~proc() {
std::unique_lock<std::mutex> lk(mutex);
if (thread == 0) {
{
std::unique_lock<std::mutex> lk(procsmutex);
for (auto i=procs.begin(); i!= procs.end(); ++i) {
if (*i == this) continue;
(*i)->cancel();
}
}
for (;;) {
// TODO: remove this busy loop in favor of sleeping the proc
{
std::unique_lock<std::mutex> lk(procsmutex);
size_t np = procs.size();
if (np == 1)
break;
}
std::this_thread::yield();
}
std::this_thread::yield();
// nasty hack for mysql thread cleanup
// because it happens *after* all of my code, i have no way of waiting
// for it to finish with an event (unless i joined all threads)
DVLOG(5) << "sleeping last proc for 1ms to allow other threads to really exit";
usleep(1000);
}
delete thread;
// clean up system tasks
while (!alltasks.empty()) {
deltaskinproc(alltasks.front());
}
// must delete _sched *after* tasks because
// they might try to remove themselves from timeouts set
delete _sched;
lk.unlock();
del(this);
DVLOG(5) << "proc freed: " << this;
_this_proc = 0;
}
io_scheduler &proc::sched() {
if (_sched == 0) {
_sched = new io_scheduler();
}
return *_sched;
}
void tasksleep(uint64_t ms) {
_this_proc->sched().sleep(milliseconds(ms));
}
bool fdwait(int fd, int rw, uint64_t ms) {
return _this_proc->sched().fdwait(fd, rw, ms);
}
int taskpoll(pollfd *fds, nfds_t nfds, uint64_t ms) {
return _this_proc->sched().poll(fds, nfds, ms);
}
void proc::deltaskinproc(task *t) {
if (!t->systask) {
--taskcount;
}
auto i = std::find(alltasks.begin(), alltasks.end(), t);
alltasks.erase(i);
t->cproc = 0;
if (_sched) {
_sched->del_timeout(t);
}
DVLOG(5) << "FREEING task: " << t;
delete t;
}
#if 0
bool rendez::sleep_for(std::unique_lock<qutex> &lk, unsigned int ms) {
task *t = _this_proc->ctask;
if (std::find(waiting.begin(), waiting.end(), t) == waiting.end()) {
DVLOG(5) << "RENDEZ SLEEP PUSH BACK: " << t;
waiting.push_back(t);
}
lk.unlock();
_this_proc->sched().add_timeout(t, ms);
t->swap();
lk.lock();
_this_proc->sched().del_timeout(t);
// if we're not in the waiting list then we were signaled to wakeup
return std::find(waiting.begin(), waiting.end(), t) == waiting.end();
}
#endif
void rendez::sleep(std::unique_lock<qutex> &lk) {
task *t = _this_proc->ctask;
if (!q) {
q = lk.mutex();
}
CHECK(q == lk.mutex());
if (std::find(waiting.begin(), waiting.end(), t) == waiting.end()) {
DVLOG(5) << "RENDEZ " << this << " PUSH BACK: " << t;
waiting.push_back(t);
}
lk.unlock();
try {
t->swap();
lk.lock();
} catch (task_interrupted &e) {
std::unique_lock<std::timed_mutex> ll(q->m);
auto i = std::find(waiting.begin(), waiting.end(), t);
if (i != waiting.end()) {
waiting.erase(i);
}
throw;
}
}
void rendez::wakeup() {
if (!waiting.empty()) {
CHECK(q->owner == _this_proc->ctask);
task *t = waiting.front();
waiting.pop_front();
DVLOG(5) << "RENDEZ " << this << " wakeup: " << t;
t->ready();
}
}
void rendez::wakeupall() {
while (!waiting.empty()) {
CHECK(q->owner == _this_proc->ctask);
task *t = waiting.front();
waiting.pop_front();
DVLOG(5) << "RENDEZ " << this << " wakeupall: " << t;
t->ready();
}
}
deadline::deadline(uint64_t ms) {
task *t = _this_proc->ctask;
if (t->deadline.time_since_epoch().count() != 0) {
throw errorx("task %p already has a deadline", t);
}
t->deadline = _this_proc->now + milliseconds(ms);
}
deadline::~deadline() {
task *t = _this_proc->ctask;
t->deadline = time_point<monotonic_clock>();
}
} // end namespace ten
|
#include<bits/stdc++.h>
using namespace std;
typedef struct Point{
int x;
int y;
Point(int xx=0,int yy=0){
x=xx;
y=yy;
}
}point;
int x0,y0,n;
vector<point> v,r,h,c;
point g;
bool mp[15][15];
int dx[]={-1,1,0,0};
int dy[]={0,0,1,-1};
int hdx[]={1,-1,-2,-2,-1,1,2,2};
int hdy[]={-2,-2,-1,1,2,2,1,-1};
int hhx[]={0,0,-1,-1,0,0,1,1};
int hhy[]={-1,-1,0,0,1,1,0,0};
int cnt_n(int x1,int y1,int x2,int y2,int op){
if(op==1){
if(x1>x2)
swap(x1,x2);
int cnt=0;
for(int i=x1+1;i<x2;i++){
if(mp[i][y1])
cnt++;
}
return cnt;
}else{
if(y1>y2)
swap(y1,y2);
int cnt=0;
for(int i=y1+1;i<y2;i++){
if(mp[x1][i])
cnt++;
}
return cnt;
}
}
bool judge_g(int tx,int ty){
if(ty==g.y){
if(cnt_n(g.x,g.y,tx,ty,1)==0)
return true;
}
return false;
}
bool judge_r(int tx,int ty){
for(int i=0;i<r.size();i++){
if(r[i].x==tx&&r[i].y==ty)
continue;
if(r[i].x==tx){
if(cnt_n(r[i].x,r[i].y,tx,ty,2)==0)
return true;
}
if(r[i].y==ty){
if(cnt_n(r[i].x,r[i].y,tx,ty,1)==0)
return true;
}
}
return false;
}
bool judge_c(int tx,int ty){
for(int i=0;i<c.size();i++){
if(c[i].x==tx&&c[i].y==ty)
continue;
if(c[i].x==tx){
if(cnt_n(c[i].x,c[i].y,tx,ty,2)==1)
return true;
}
else if(c[i].y==ty){
if(cnt_n(c[i].x,c[i].y,tx,ty,1)==1)
return true;
}
}
return false;
}
bool judge_h(int tx,int ty){
for(int i=0;i<h.size();i++){
for(int j=0;j<8;j++){
int thx=h[i].x+hdx[j];
int thy=h[i].y+hdy[j];
if(tx==thx&&ty==thy){
int thhx=h[i].x+hhx[j];
int thhy=h[i].y+hhy[j];
if(!mp[thhx][thhy])
return true;
}
}
}
return false;
}
bool judge(int tx,int ty){
if(judge_c(tx,ty)||judge_g(tx,ty)||judge_h(tx,ty)||judge_r(tx,ty))
return true;
return false;
}
int main(){
while(cin>>n>>x0>>y0){
if(n==0&&x0==0&&y0==0)
break;
memset(mp,false,sizeof(mp));
c.clear();
h.clear();
r.clear();
for(int i=0;i<n;i++){
char cc;
int aa,bb;
cin>>cc>>aa>>bb;
if(cc=='G')
g=point(aa,bb);
if(cc=='H')
h.push_back(point(aa,bb));
if(cc=='R')
r.push_back(point(aa,bb));
if(cc=='C')
c.push_back(point(aa,bb));
mp[aa][bb]=true;
}
bool flag=true;
for(int i=0;i<4;i++){
int tx=x0+dx[i];
int ty=y0+dy[i];
if(tx>=1&&tx<=3&&ty>=4&&ty<=6){
if(!judge(tx,ty)){
flag=false;
break;
}
}
}
if(flag)
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}
|
#pragma once
#include "bitset.hpp"
static const int DefaultMaxGraphSize = 4096;
template <int N>
class Graph {
public:
static_assert(N > 0, "The maximum number of elements in Graph must be positive");
static const int ParamN = N;
typedef BitSet<bitSetParam(N)> B;
Graph() : size_(0) { }
Graph(int size)
: size_(size)
{
assert(size >= 0);
assert(size <= N);
}
static Graph read(istream& in) {
auto exceptionMask = in.exceptions();
in.exceptions(in.failbit | in.badbit);
int n;
in >> n;
if(n < 0) {
fail("Invalid input in Graph::read");
}
if(n > N) {
fail("Graph is too large for Graph<", N, ">");
}
Graph graph(n);
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
int x;
in >> x;
if((x != 0 && x != 1) || (i == j && x)) {
fail("Invalid input in readGraph");
}
if(x) {
graph.addD(i, j);
}
}
}
in.exceptions(exceptionMask);
return graph;
}
static Graph randomConnectedChordal(int vertCount, int edgeCount) {
if(vertCount == 0) {
if(edgeCount != 0) {
fail("Given numbers of vertices and edges are not compatible");
}
return Graph();
}
Graph graph(vertCount);
vector<int> connected;
vector<int> isolated;
int initial = UnifInt<int>(0, vertCount - 1)(rng);
connected.push_back(initial);
for(int i = 0; i < vertCount; ++i) {
if(i != initial) {
isolated.push_back(i);
}
}
int edgesAdded = 0;
while(!isolated.empty()) {
int ai = UnifInt<int>(0, connected.size() - 1)(rng);
int bi = UnifInt<int>(0, isolated.size() - 1)(rng);
int a = connected[ai];
int b = isolated[bi];
graph.addU(a, b);
swap(isolated[bi], isolated.back());
isolated.pop_back();
connected.push_back(b);
++edgesAdded;
}
if(edgesAdded > edgeCount) {
fail("Given numbers of vertices and edges are not compatible");
}
vector<pair<int, int>> pool;
for(int i = 0; i < vertCount; ++i) {
for(int j = i + 1; j < vertCount; ++j) {
if(!graph(i, j)) {
pool.emplace_back(i, j);
}
}
}
while(edgesAdded < edgeCount) {
bool found = false;
for(int i = 0; i < (int)pool.size(); ++i) {
swap(pool[i], pool[UnifInt<int>(i, pool.size() - 1)(rng)]);
int a = pool[i].first;
int b = pool[i].second;
graph.addU(a, b);
if(graph.isChordal()) {
found = true;
swap(pool[i], pool.back());
pool.pop_back();
++edgesAdded;
break;
} else {
graph.delU(a, b);
}
}
if(!found) {
fail("Given numbers of vertices and edges are not compatible");
}
}
return graph;
}
int size() const {
return size_;
}
B vertexSet() const {
return B::range(size());
}
bool operator()(int a, int b) const {
assert(a >= 0 && a < size());
assert(b >= 0 && b < size());
return data_[a].second.has(b);
}
B edgesIn(int v) const {
assert(v >= 0 && v < size());
return data_[v].first;
}
B edgesOut(int v) const {
assert(v >= 0 && v < size());
return data_[v].second;
}
B directedEdgesIn(int v) const {
return setDifference(edgesIn(v), edgesOut(v));
}
B directedEdgesOut(int v) const {
return setDifference(edgesOut(v), edgesIn(v));
}
B neighbors(int v) const {
return setUnion(edgesIn(v), edgesOut(v));
}
B bidirectionalNeighbors(int v) const {
return setIntersection(edgesIn(v), edgesOut(v));
}
bool operator==(const Graph& other) const {
if(size() != other.size()) {
return false;
}
for(int v = 0; v < size(); ++v) {
if(edgesOut(v) != other.edgesOut(v)) {
return false;
}
}
return true;
}
bool operator!=(const Graph& other) const {
return !(*this == other);
}
void setD(int a, int b, bool val) {
assert(a >= 0 && a < size());
assert(b >= 0 && b < size());
assert(!val || a != b);
data_[a].second.set(b, val);
data_[b].first.set(a, val);
}
void addD(int a, int b) {
assert(a >= 0 && a < size());
assert(b >= 0 && b < size());
assert(a != b);
data_[a].second.add(b);
data_[b].first.add(a);
}
void delD(int a, int b) {
assert(a >= 0 && a < size());
assert(b >= 0 && b < size());
data_[a].second.del(b);
data_[b].first.del(a);
}
void setU(int a, int b, bool val) {
assert(a >= 0 && a < size());
assert(b >= 0 && b < size());
assert(!val || a != b);
setD(a, b, val);
setD(b, a, val);
}
void addU(int a, int b) {
assert(a >= 0 && a < size());
assert(b >= 0 && b < size());
assert(a != b);
addD(a, b);
addD(b, a);
}
void delU(int a, int b) {
assert(a >= 0 && a < size());
assert(b >= 0 && b < size());
delD(a, b);
delD(b, a);
}
bool isUndirected() const {
for(int a = 0; a < size(); ++a) {
for(int b = a + 1; b < size(); ++b) {
if((*this)(a, b) != (*this)(b, a)) {
return false;
}
}
}
return true;
}
bool isClique(B verts) const {
bool ret = true;
verts.iterateWhile([&](int v) {
if(isSubset(verts.without(v), neighbors(v))) {
return true;
} else {
ret = false;
return false;
}
});
return ret;
}
bool isIndependentSet(B verts) const {
bool ret = true;
verts.iterateWhile([&](int v) {
if(setIntersection(verts, neighbors(v)).isEmpty()) {
return true;
} else {
ret = false;
return false;
}
});
return ret;
}
bool isBidirectionalClique(B verts) const {
bool ret = true;
verts.iterateWhile([&](int v) {
if(isSubset(verts.without(v), bidirectionalNeighbors(v))) {
return true;
} else {
ret = false;
return false;
}
});
return ret;
}
bool isBidirectionalIndependentSet(B verts) const {
bool ret = true;
verts.iterateWhile([&](int v) {
if(setIntersection(verts, bidirectionalNeighbors(v)).isEmpty()) {
return true;
} else {
ret = false;
return false;
}
});
return ret;
}
Graph inducedSubgraph(B verts) const {
assert(isSubset(verts, vertexSet()));
Graph ret(verts.count());
int i = 0;
verts.iterate([&](int v) {
ret.data_[i] = make_pair(
B::pack(data_[v].first, verts),
B::pack(data_[v].second, verts)
);
++i;
});
return ret;
}
template <typename F>
void inducedSubgraphReSelectN(B verts, F f) const {
assert(isSubset(verts, vertexSet()));
int n = verts.count();
selectGraphParam(n, [&](auto sel) {
Graph<sel.Val> ret(n);
int i = 0;
verts.iterate([&](int v) {
ret.data_[i] = pair<typename Graph<sel.Val>::B, typename Graph<sel.Val>::B>(
B::pack(data_[v].first, verts),
B::pack(data_[v].second, verts)
);
++i;
});
f(ret);
});
}
B bidirectionalComponent(B verts, int v) const {
assert(isSubset(verts, vertexSet()));
assert(verts.has(v));
B comp(v);
B queue(v);
while(!queue.isEmpty()) {
int x = queue.min();
queue.del(x);
B add = setDifference(
setIntersection(bidirectionalNeighbors(x), verts),
comp
);
comp = setUnion(comp, add);
queue = setUnion(queue, add);
}
return comp;
}
B bidirectionalComponent(int v) const {
return bidirectionalComponent(vertexSet(), v);
}
template <typename F>
void iterateBidirectionalComponents(B verts, F f) const {
while(verts.isNonEmpty()) {
int v = verts.min();
B comp = bidirectionalComponent(verts, v);
f(comp);
verts = setDifference(verts, comp);
}
}
template <typename F>
void iterateBidirectionalComponents(F f) const {
iterateBidirectionalComponents(vertexSet(), f);
}
B component(B verts, int v) const {
assert(isSubset(verts, vertexSet()));
assert(verts.has(v));
B comp(v);
B queue(v);
while(!queue.isEmpty()) {
int x = queue.min();
queue.del(x);
B add = setDifference(
setIntersection(neighbors(x), verts),
comp
);
comp = setUnion(comp, add);
queue = setUnion(queue, add);
}
return comp;
}
B component(int v) const {
return component(vertexSet(), v);
}
template <typename F>
void iterateComponents(B verts, F f) const {
while(verts.isNonEmpty()) {
int v = verts.min();
B comp = component(verts, v);
f(comp);
verts = setDifference(verts, comp);
}
}
template <typename F>
void iterateComponents(F f) const {
iterateComponents(vertexSet(), f);
}
B reachableVertices(B verts, int v) const {
assert(isSubset(verts, vertexSet()));
assert(verts.has(v));
B comp(v);
B queue(v);
while(!queue.isEmpty()) {
int x = queue.min();
queue.del(x);
B add = setDifference(
setIntersection(edgesOut(x), verts),
comp
);
comp = setUnion(comp, add);
queue = setUnion(queue, add);
}
return comp;
}
B reachableVertices(int v) const {
return reachableVertices(vertexSet(), v);
}
B directedReachableVertices(B verts, int v) const {
assert(isSubset(verts, vertexSet()));
assert(verts.has(v));
B comp(v);
B queue(v);
while(!queue.isEmpty()) {
int x = queue.min();
queue.del(x);
B add = setDifference(
setIntersection(directedEdgesOut(x), verts),
comp
);
comp = setUnion(comp, add);
queue = setUnion(queue, add);
}
return comp;
}
B directedReachableVertices(int v) const {
return directedReachableVertices(vertexSet(), v);
}
bool isDirectedReachable(B verts, int a, int b) const {
assert(isSubset(verts, vertexSet()));
assert(verts.has(a));
assert(verts.has(b));
if(a == b) {
return true;
}
B comp(a);
B queue(a);
while(!queue.isEmpty()) {
int x = queue.min();
queue.del(x);
B add = setDifference(
setIntersection(directedEdgesOut(x), verts),
comp
);
if(add.has(b)) {
return true;
}
comp = setUnion(comp, add);
queue = setUnion(queue, add);
}
return false;
}
bool isDirectedReachable(int a, int b) const {
return isDirectedReachable(vertexSet(), a, b);
}
Graph<N> withShuffledVertices() const {
const Graph& graph = *this;
vector<int> perm(graph.size());
for(int i = 0; i < graph.size(); ++i) {
perm[i] = i;
}
shuffle(perm.begin(), perm.end(), rng);
Graph ret(graph.size());
for(int i = 0; i < graph.size(); ++i) {
for(int j = 0; j < graph.size(); ++j) {
if(graph(i, j)) {
ret.addD(perm[i], perm[j]);
}
}
}
return ret;
}
void write(ostream& out) const {
out << size() << '\n';
for(int i = 0; i < size(); ++i) {
for(int j = 0; j < size(); ++j) {
if(j) {
out << ' ';
}
out << (int)(*this)(i, j);
}
out << '\n';
}
}
bool tryFindPerfectEliminationOrdering(int* output) const {
return tryFindPerfectEliminationOrdering_([&](int i, int v, const B&, const B&) {
output[i] = v;
});
}
pair<bool, vector<int>> tryFindPerfectEliminationOrdering() const {
vector<int> order(size());
if(tryFindPerfectEliminationOrdering(order.data())) {
return make_pair(true, order);
} else {
return make_pair(false, vector<int>());
}
}
bool isChordal() const {
return tryFindPerfectEliminationOrdering_([&](int, int, const B&, const B&) { });
}
void findPerfectEliminationOrderingInChordal(int* output) const {
if(!tryFindPerfectEliminationOrdering(output)) {
fail("Could not find perfect elimination ordering: the graph is not chordal");
}
}
vector<int> findPerfectEliminationOrderingInChordal() const {
vector<int> order(size());
findPerfectEliminationOrderingInChordal(order.data());
return order;
}
template <typename F>
void iterateMaximalCliquesInChordal(F f) const {
findPerfectEliminationOrderingInChordal_([&](int, int v, const B& neigh, const B& done) {
B cand = setIntersection(neigh, done).with(v);
bool ok = true;
setDifference(neigh, cand).iterateWhile([&](int x) {
if(isSubset(cand, neighbors(x))) {
ok = false;
return false;
} else {
return true;
}
});
if(ok) {
f(cand);
}
});
}
void toDot(ostream& out) const {
out << "digraph {\n";
for(int i = 0; i < size(); ++i) {
out << " " << i << "\n";
}
for(int i = 0; i < size(); ++i) {
for(int j = i + 1; j < size(); ++j) {
if((*this)(i, j)) {
if((*this)(j, i)) {
out << " " << i << " -> " << j << " [dir=none]\n";
} else {
out << " " << i << " -> " << j << "\n";
}
} else if((*this)(j, i)) {
out << " " << j << " -> " << i << "\n";
}
}
}
out << "}\n";
}
void print(ostream& out) const {
out << "Graph<" << N << ">(" << size() << ") [";
bool first = true;
for(int i = 0; i < size(); ++i) {
for(int j = 0; j < size(); ++j) {
if((*this)(i, j)) {
if((*this)(j, i)) {
if(i < j) {
if(!first) {
out << ", ";
}
first = false;
out << i << " <-> " << j;
}
} else {
if(!first) {
out << ", ";
}
first = false;
out << i << " --> " << j;
}
}
}
}
out << "]";
}
struct TreeDecomposition {
Graph<N> structure;
B cliques[N];
};
TreeDecomposition findTreeDecompositionInChordal() const {
assert(isChordal());
TreeDecomposition ret;
int size = 0;
iterateMaximalCliquesInChordal([&](B clique) {
assert(size != N);
ret.cliques[size++] = clique;
});
ret.structure = Graph<N>(size);
typedef pair<int, pair<int, int>> E;
vector<E> edges;
for(int i = 0; i < size; ++i) {
B a = ret.cliques[i];
for(int j = i + 1; j < size; ++j) {
B b = ret.cliques[j];
int weight = setIntersection(a, b).count();
edges.emplace_back(weight, make_pair(i, j));
}
}
sort(edges.begin(), edges.end(), [&](E a, E b) { return a.first > b.first; });
struct UnionFind {
UnionFind(int size) {
for(int i = 0; i < size; ++i) {
parent[i] = i;
}
}
int find(int x) {
if(parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void merge(int x, int y) {
parent[find(x)] = find(y);
}
int parent[N];
};
UnionFind uf(size);
for(E e : edges) {
int x = e.second.first;
int y = e.second.second;
if(uf.find(x) != uf.find(y)) {
ret.structure.addU(x, y);
uf.merge(x, y);
}
}
return ret;
}
private:
int size_;
pair<B, B> data_[N];
template <typename F>
bool findEliminationOrdering_(F f) const {
int P[N] = {};
B Q[N + 1];
Q[0] = vertexSet();
int h = 0;
B done;
for(int i = size() - 1; i >= 0; --i) {
while(Q[h].isEmpty()) {
--h;
}
int v = Q[h].min();
Q[h].del(v);
B neigh = neighbors(v);
if(!f(i, v, neigh, done)) {
return false;
}
setDifference(neigh, done).iterate([&](int x) {
Q[P[x]].del(x);
++P[x];
Q[P[x]].add(x);
});
++h;
done.add(v);
}
return true;
}
template <typename F>
void findPerfectEliminationOrderingInChordal_(F f) const {
findEliminationOrdering_([&](int i, int v, B neigh, B done) {
assert(isClique(setIntersection(neigh, done)));
f(i, v, neigh, done);
return true;
});
}
template <typename F>
bool tryFindPerfectEliminationOrdering_(F f) const {
return findEliminationOrdering_([&](int i, int v, B neigh, B done) {
if(!isClique(setIntersection(neigh, done))) {
return false;
}
f(i, v, neigh, done);
return true;
});
}
template <int N2>
friend class Graph;
};
template <int M = DefaultMaxGraphSize, typename F>
void selectGraphParam(int n, F f) {
select2Pow<ceilLog2(M)>(n, f);
}
class GraphData {
public:
GraphData() : size_(0) { }
template <int N>
GraphData(const Graph<N>& graph)
: size_(graph.size())
{
data_.resize(size_ * size_);
int p = 0;
for(int i = 0; i < size_; ++i) {
for(int j = 0; j < size_; ++j) {
data_[p++] = graph(i, j);
}
}
}
static GraphData read(istream& in) {
auto exceptionMask = in.exceptions();
in.exceptions(in.failbit | in.badbit);
int n;
in >> n;
if(n < 0) {
fail("Invalid input in GraphData::read");
}
GraphData ret;
ret.size_ = n;
ret.data_.resize(n * n);
int p = 0;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
int x;
in >> x;
if((x != 0 && x != 1) || (i == j && x)) {
fail("Invalid input in readGraph");
}
ret.data_[p++] = (bool)x;
}
}
in.exceptions(exceptionMask);
return ret;
}
template <int M = DefaultMaxGraphSize, typename F>
void accessGraph(F f) const {
selectGraphParam<M>(size_, [&](auto sel) {
Graph<sel.Val> graph(size_);
int p = 0;
for(int i = 0; i < size_; ++i) {
for(int j = 0; j < size_; ++j) {
if(data_[p++]) {
graph.addD(i, j);
}
}
}
f(graph);
});
}
private:
int size_;
vector<bool> data_;
};
template <int M = DefaultMaxGraphSize, typename F>
void readGraph(istream& in, F f) {
GraphData graphData = GraphData::read(in);
graphData.accessGraph<M>(f);
}
|
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
bool isPowerOfFour(int n) {
while(n>1)
{
if(n%4!=0)
return false;
n/=4;
}
return n==1;
}
};
class Solution1 {
public boolean isPowerOfFour(int num) {
//基本思想:位运算,num&(num-1)==0用于判断num是否是2的幂
return (num > 0) && ((num & (num - 1)) == 0) && (num % 3 == 1);
}
}
int main()
{
Solution solute;
int n=16;
cout<<solute.isPowerOfFour(n)<<endl;
return 0;
}
|
#include<cstdio>
#include<cmath>
using namespace std;
int n;
double po[25][2];
double l[20][20];
bool use[20];
double ans=10000000;
void dfs(int,double,int);
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
double x,y;
scanf("%lf%lf",&x,&y);
po[i][0]=x;
po[i][1]=y;
}
for(int i=1;i<=n+1;i++)
for(int t=1;t<=n+1;t++)
l[i][t]=sqrt((1.0*po[t][0]-po[i][0])*(1.0*po[t][0]-po[i][0])+(1.0*po[t][1]-po[i][1])*(1.0*po[t][1]-po[i][1]));
dfs(1,0,n+1);
printf("%.2lf",ans);
}
void dfs(int x,double s,int t)
{
if(s > ans)
return ;
if(x==n+1)
{
if(s<ans)
ans=s;
return ;
}
for(int i=1;i<=n;i++)
if(!use[i])
{
use[i]=1;
dfs(x+1,s+l[t][i],i);
use[i]=0;
}
}
|
//===========================================================================
//! @file camera_tps.cpp
//! @brief 三人称カメラ
//===========================================================================
//---------------------------------------------------------------------------
//! デフォルトコンストラクタ
//---------------------------------------------------------------------------
CameraTPS::CameraTPS()
{
cameraType_ = CameraType::Tps;
}
//---------------------------------------------------------------------------
//! 初期化
//---------------------------------------------------------------------------
bool CameraTPS::initialize()
{
if(!Camera::initialize()) {
return false;
}
length_ = 30.0f;
sensitivity_ = 0.15f;
POINT pt;
GetCursorPos(&pt);
oldPoint_ = { static_cast<f32>(pt.x), static_cast<f32>(pt.y) };
rotation_.y_ = 150.0f;
offset_ = Vector3(5.0f, 1.0f, -10.0f);
return true;
}
//---------------------------------------------------------------------------
//! 更新
//---------------------------------------------------------------------------
void CameraTPS::update()
{
POINT pt;
GetCursorPos(&pt);
const f32 pointX = static_cast<f32>(pt.x);
const f32 pointY = static_cast<f32>(pt.y);
// 1フレームの差分取得
f32 diffX = (pointX - oldPoint_.x_) * sensitivity_;
f32 diffY = (pointY - oldPoint_.y_) * sensitivity_;
// 現在の位置を保存(次のフレームで利用)
oldPoint_.x_ = pointX;
oldPoint_.y_ = pointY;
// 保存用
Vector3 newPosition = position_;
Vector3 newLookAt = lookAt_;
Vector3 targetPosition = target_->getPosition();
// 回転量保持
rotation_.x_ += diffY;
rotation_.y_ += diffX;
rotation_.z_ -= diffY;
// tmp
static bool flag = false;
// マウスの右ボタンが押されていたら
if((GetKeyState(VK_RBUTTON) & 0x8000)) {
auto targetRot = target_->getRotation();
Matrix rot =
Matrix::rotateX(DEG_TO_RAD(rotation_.x_)) *
Matrix::rotateY(DEG_TO_RAD(targetRot.y_));
auto rotPosition = (Matrix::translate(offset_) * rot).translate();
newPosition = targetPosition + rotPosition;
newLookAt = newPosition + rot.axisZ().normalize();
flag = true;
}
else
{
if(flag) {
flag = false;
rotation_.y_ = target_->getRotation().y_ - 180.0f;
}
const Vector3 rot = {
sinf(DEG_TO_RAD(rotation_.y_)),
sinf(DEG_TO_RAD(rotation_.x_)),
cosf(DEG_TO_RAD(rotation_.y_))
};
newPosition = targetPosition + rot * length_;
newLookAt = targetPosition;
}
// 反映
lookAt_ = newLookAt;
position_ = newPosition;
Camera::update();
}
//---------------------------------------------------------------------------
//! 解放
//---------------------------------------------------------------------------
void CameraTPS::cleanup()
{
target_ = nullptr;
Camera::cleanup();
}
//---------------------------------------------------------------------------
//! 注視点にするオブジェクト設定
//---------------------------------------------------------------------------
void CameraTPS::setTarget(ObjectBase* const target)
{
if (target_) {
target_.reset();
}
target_.reset(target);
}
|
#include "roitable.h"
RoiTableModel::RoiTableModel(QObject *parent)
: QStandardItemModel(parent)
{
//clear();
setHorizontalHeaderItem(ROI_NAME_COL_ID,new QStandardItem("ROI name"));
setHorizontalHeaderItem(ROI_STATUS_COL_ID,new QStandardItem("Status"));
setHorizontalHeaderItem(ROI_CLASS_COL_ID,new QStandardItem("Class name"));
//setHorizontalHeaderItem(ROI_PIXELS_COL_ID,new QStandardItem("Number of Pixels"));
setHorizontalHeaderItem(ROI_CHECK_COL_ID,new QStandardItem("Spectrum"));
//vieew //resizeColumnToContents(0);
connect(this, SIGNAL(itemChanged(QStandardItem*)), this,
SLOT(onItemChanged(QStandardItem*)));
}
RoiTableModel::~RoiTableModel()
{
}
void RoiTableModel::updateRoiClassValues(QStringList* pList, QString newName)
{
pList->append("");
for(int i=0; i<rowCount(); i++){
QStandardItem* it = item(i,ROI_CLASS_COL_ID);
if(it)
if(!pList->contains(it->text()))
it->setText(newName);
}
}
bool RoiTableModel::textAlreadyExists(QStandardItem* pItem, int nCol)
{
QString newText = pItem->text();
int occurence = 0;
for(int i=0; i<rowCount(); i++){
if(item(i,nCol)->text()==newText)
occurence++;
}
if(occurence<=1)
return false;
else
return true;
}
void RoiTableModel::renameClass(QStandardItem* pItem)
{
QString genericName = "ROI_";
int n = 1;
bool foundAny = true;
while(foundAny){
foundAny = false;
for(int i=0; i<rowCount(); i++){
if(item(i,CLASS_NAME_COL_ID)->text() == genericName + QString::number(n)){
foundAny = true;
n++;
}
}
}
pItem->setText(genericName+QString::number(n));
}
void RoiTableModel::addRoi()
{
QString genericName = "ROI_";
int n = 1;
bool foundAny = true;
while(foundAny){
foundAny = false;
for(int i=0; i<rowCount(); i++){
if(item(i,0)->text() == genericName + QString::number(n)){
foundAny = true;
n++;
}
}
}
QStandardItem* name = new QStandardItem(genericName+QString::number(n));
QStandardItem* number = new QStandardItem(QString("Empty"));
number->setEditable(false);
QList<QStandardItem*> list;
list.push_back(name);
list.push_back(number);
appendRow(list);
}
void RoiTableModel::onItemChanged(QStandardItem* pItem)
{
//ROI Name field -> prevents same name
if(textAlreadyExists(pItem,ROI_NAME_COL_ID))
renameClass(pItem);
}
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* 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.
*/
#ifndef SKLAND_WAYLAND_SUBCOMPOSITOR_HPP_
#define SKLAND_WAYLAND_SUBCOMPOSITOR_HPP_
#include "registry.hpp"
namespace skland {
namespace wayland {
class SubSurface;
class SubCompositor {
friend class SubSurface;
SubCompositor(const SubCompositor &) = delete;
SubCompositor &operator=(const SubCompositor &) = delete;
public:
SubCompositor()
: wl_subcompositor_(nullptr) {
}
~SubCompositor() {
if (wl_subcompositor_) wl_subcompositor_destroy(wl_subcompositor_);
}
void Setup(const Registry ®istry, uint32_t id, uint32_t version) {
Destroy();
wl_subcompositor_ =
static_cast<struct wl_subcompositor *>(registry.Bind(id, &wl_subcompositor_interface, version));
}
void Destroy() {
if (wl_subcompositor_) {
wl_subcompositor_destroy(wl_subcompositor_);
wl_subcompositor_ = nullptr;
}
}
void SetUserData(void *user_data) {
wl_subcompositor_set_user_data(wl_subcompositor_, user_data);
}
void *GetUserData() const {
return wl_subcompositor_get_user_data(wl_subcompositor_);
}
uint32_t GetVersion() const {
return wl_subcompositor_get_version(wl_subcompositor_);
}
bool IsValid() const {
return nullptr != wl_subcompositor_;
}
bool Equal(const void *object) const {
return wl_subcompositor_ == object;
}
private:
struct wl_subcompositor *wl_subcompositor_;
};
}
}
#endif // SKLAND_WAYLAND_SUBCOMPOSITOR_HPP_
|
#pragma once
#include <GLFW/glfw3.h>
#include <chrono>
#include <thread>
//#include <Windows.h>
// Prosty timer
class Timer
{
private :
// Aktualny Czas
double World_Time;
// Czas włączenia
double Start_Time;
// Liczba akutalizacji ( klatek)
int updates;
// Czy działa
bool running;
public :
Timer(void); // Konstruktor
void Start();
void Stop();
void Reset();
double GetTime(); // Zwraca naliczony czas ( milisekundy)
int GetUpdates(); // Zwraca ilość uaktualnień
void Update(); // Uaktualnia zmienne
};
// Narzędzie do regulowania frame rate i liczenia fps
class FPS
{
public :
// Aktualny Czas
double World_Time;
// Czas od włączenia
double Start_Time;
// Czas od ostaniej aktualizacji
double Delta_Time;
// Liczba akutalizacji ( klatek)
int updates;
// Liczba klatek na sekundę
float rate;
//Co ile klatek liczy FPS
int frames;
// Wartość blokady klatek
int max ;
public :
FPS(void); // Konstruktor
void Update(); // Uaktualnia zmienne
void Block(int maximum); // Ustawia blokowanie FPS
void Free(); // Zwalnie blokowanie
void Set_Frames(int fr); // Zmienie co ile klatek jest liczony FPS (standardowo 100)
double Delta(); // Zwraca delte czasu w milisekundach
};
void SleepFor(int miliseconds);
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "MMOUserWidget.generated.h"
/**
*
*/
UCLASS()
class MMOPROJECT_API UMMOUserWidget : public UUserWidget
{
GENERATED_BODY()
public:
//The actor that this widget is attached to (not the local player)
UPROPERTY(Transient, BlueprintReadWrite, Category = "Widget")
AActor* ParentActor = nullptr;
};
|
#include <iostream>
using namespace std;
char *oddOrden="Never odd or even";
char *nthCharPtr;
int main()
{
char*nthCharPtr=&oddOrEven[5];
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
//
// Copyright (C) 1995-2003 Opera Software ASA. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Espen Sand
//
#ifndef __APPLICATION_LAUNCHER_H__
#define __APPLICATION_LAUNCHER_H__
#include "modules/util/opstring.h"
#include "modules/util/adt/opvector.h"
class FramesDocument;
class URL;
class Window;
class OpString_list;
//class OpVector;
class ApplicationLauncher
{
public:
/**
* Starts an external application with the specified arguments
*
* @param application The application to execute
* @param arguments A list of arguments. If an argument is enclosed with a set of ""
* then whitespaces will be inluded in the argument, otherwise a whitespace
* will be treated as an argument separator.
* @param run_in_terminal
*
* @return TRUE on success otherwise false
*/
static BOOL ExecuteProgram( const OpStringC &application,
const OpStringC &arguments,
BOOL run_in_terminal = FALSE );
/**
* Starts an external application with the specified arguments
*
* @param application The application to execute
* @param argc Num of items in argv
* @param argv Argument vector as defined in LaunchPI::Launch(...)
* @param run_in_terminal
*
* @return TRUE on success otherwise FALSE
*/
static BOOL ExecuteProgram( const OpStringC &application,
int argc,
const char* const* argv,
BOOL run_in_terminal = FALSE );
/**
* Starts an external application that is able to display the
* source code of the document.
*
* @param window. The window where an error message is sent to
* @param doc The document that will be inspected
*
* @return TRUE on success otherwise false
*/
static BOOL ViewSource( Window* window, FramesDocument* doc );
/**
* Starts an external application that is able to display the
* source code of the document.
*
* @param filename. File that contains source code
*
* @return TRUE on success otherwise false
*/
static BOOL ViewSource(const OpString& filename, const OpString8& encoding);
/**
* Starts an external email-client program with the parameters
* as specified with the mailer command and the function arguments.
*
* @param to Comma separated list of receivers
* @param cc Comma separated list of receivers
* @param bcc Comma separated list of receivers
* @param subject mail subject
* @param message mail message
* @param rawUrl raw mailto url (without the mailto specifier)
*
* @return TRUE on success otherwise false
*/
static BOOL GenericMailAction( const uni_char* to,
const uni_char* cc,
const uni_char* bcc,
const uni_char* subject,
const uni_char* message,
const uni_char* rawurl );
/**
* Starts an external news-client program connecting to the
* specified address.
*
* @param application The application to run
* @param address The news address to be parsed.
*
* @return TRUE on success otherwise false
*/
static BOOL GenericNewsAction(const uni_char* application, const uni_char* urlstring);
/**
* Starts an external telnet program connecting to the
* specified address.
*
* @param application The application to run
* @param address The telnet address to be parsed.
*
* @return TRUE on success otherwise false
*/
static BOOL GenericTelnetAction(const uni_char* application, const uni_char* urlstring);
/**
* Call this function for protocols that are registered to be trusted
* to another program.
*
* @param window The window where the url was activated
* @param url The protocol url
*
* @return TRUE on success otherwise false
*/
static BOOL GenericTrustedAction( Window *window, const URL& url );
/**
* Prepends a terminal program that will execute the application
* when started.
*
* @param application The string will be prepended with the terminal
* on return
* @return Opstatus::OK on success, otherwise OpStatus::ERR_NO_MEMORY
*/
static OP_STATUS SetTerminalApplication( OpString &application );
/**
* Replaces escaped characters in the taget string with the readable
* equivalent
*
* @param target The string to be modified.
* @param start The offset in the string where the scanning will start
* Note that the target string will start at this offset on exit
* @param special_character_conversion Convert '&' and '+' when true
*/
static void ReplaceEscapedCharacters( OpString &target, UINT32 start, BOOL special_character_conversion );
static void GetCommandLineOptions(const OpString& protocol, OpString& text);
static BOOL ParseTelnetAddress( OpVector<OpString>& list,
const uni_char *application,
const uni_char *address,
const uni_char *port,
const uni_char *user,
const uni_char *password,
const uni_char *rawurl );
static BOOL ParseEmail( OpVector<OpString>& list,
const uni_char *application,
const uni_char* to,
const uni_char* cc,
const uni_char* bcc,
const uni_char* subject,
const uni_char* message,
const uni_char* rawurl );
static BOOL ParseNewsAddress( OpVector<OpString>& list,
const uni_char *application,
const uni_char *url );
static BOOL ParseTrustedApplication( OpVector<OpString>& list,
const uni_char *application,
const uni_char *full_address,
const uni_char *address );
/** Conditionally display a dialog with an error message based on the
* value of the 'errno' variable.
*
* A common error handling strategy for C functions is to set the global
* 'errno' variable to a value describing the error that occurred and then
* return -1. Calling this method with the return value from such a
* function will display a dialog with a proper error message (based on
* 'errno') when the function fails.
*
* @param return_value If 'return_value' is -1, the error message will be
* displayed. Otherwise, this method does nothing.
*/
static void DisplayDialogOnError(int return_value);
};
#endif
|
#include "SimExamples/voronoi/ExmVoronoiPattern.h"
#include "SimExamples/SimFramework.h"
#include "include/SimException.h"
VoronoiPattern::VoronoiPattern(FEATURE_PATTERN type, float depth, int slice,
const std::vector<D3DXVECTOR3>& pos_set):
vertex_buffer_(NULL),
index_buffer_(NULL),
pattern_type_(type),
depth_(depth),
slice_(slice),
pos_set_(pos_set),
color_(0.0f, 0.0f, 0.0f, 0.0f)
{
if (pos_set.size() > 1 && pos_set[0].z != pos_set[1].z)
SIM_EXCEPTION("Invalide z value, should in the same xy plane.");
if (slice&1)
SIM_EXCEPTION("Slice should be even.");
}
VoronoiPattern::~VoronoiPattern(){
ReleaseCOM(vertex_buffer_);
ReleaseCOM(index_buffer_);
}
void VoronoiPattern::Draw(IDirect3DDevice9** d3d9_device, ID3DXEffect** d3dx_effect){
(*d3d9_device)->SetStreamSource(0, vertex_buffer_, 0, sizeof(VertexPos));
if (pattern_type_ == PATTERN_POINT){
(*d3d9_device)->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
(*d3d9_device)->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, slice_);
}else if (pattern_type_ == PATTERN_LINE){
D3DXVECTOR4 color(0.0f, 0.0f, 0.0f, 0.0f);
(*d3d9_device)->SetIndices(index_buffer_);
(*d3dx_effect)->SetVector("pattern_color", &color_);
(*d3dx_effect)->CommitChanges();
(*d3d9_device)->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, num_points_, 0, num_face_);
//(*d3d9_device)->SetRenderState();
(*d3dx_effect)->SetVector("pattern_color", &color);
(*d3dx_effect)->CommitChanges();
(*d3d9_device)->DrawPrimitive(D3DPT_LINELIST, 0, 1);
/*float point_size = 5.0f;
(*d3d9_device)->SetRenderState(D3DRS_POINTSIZE, *((DWORD*)&point_size));
color = D3DXVECTOR4(0.0f, 0.0f, 1.0f, 0.0f);
(*d3dx_effect)->SetVector("pattern_color", &color);
(*d3dx_effect)->CommitChanges();
(*d3d9_device)->DrawPrimitive(D3DPT_POINTLIST, 0, num_points_);*/
}else if (pattern_type_ == PATTERN_POLYGON){
int n = pattern_set_.size();
for (int i = 0; i < n; ++i) {
VoronoiPattern* vp = pattern_set_[i];
vp->SetColor(color_);
vp->Draw(d3d9_device, d3dx_effect);
}
}
}
PatternPoint::PatternPoint(FEATURE_PATTERN type, float depth, int slice,
const std::vector<D3DXVECTOR3>& pos_set):
VoronoiPattern(type, depth, slice, pos_set){
if (pos_set.size() < 1)
SIM_EXCEPTION("Not encough points in pos_set");
}
PatternPoint::~PatternPoint(){}
void PatternPoint::CreateBuffer(IDirect3DDevice9** d3d9_device){
num_points_ = slice_ + 2;
num_face_ = slice_;
num_index_ = 0;
HR( (*d3d9_device)->CreateVertexBuffer((slice_ + 2) * sizeof(VertexPos), D3DUSAGE_WRITEONLY,
VertexPos::FVF, D3DPOOL_MANAGED, &vertex_buffer_, 0) );
D3DXVECTOR3 pos_ = pos_set_[0];
VertexPos* vp = 0;
HR( vertex_buffer_->Lock(0, 0, (void**)&vp, 0) );
vp[0] = pos_/*VertexPos(0.0f, 0.0f, 0.0f)*/;
float x, y, z;
z = depth_ + pos_.z;
float alpha = 0.0f;
float alpha_dt = D3DX_PI * 2.0f / slice_;
// clockwise order
for (int i = 1; i <= slice_; ++i, alpha += alpha_dt) {
x = depth_ * cosf(alpha) + pos_.x;
y = depth_ * sinf(alpha) + pos_.y;
vp[i] = VertexPos(x, y, z);
}
vp[slice_ + 1] = vp[1];
HR( vertex_buffer_->Unlock() );
}
PatternLine::PatternLine(FEATURE_PATTERN type, float depth, int slice,
const std::vector<D3DXVECTOR3>& pos_set):
VoronoiPattern(type, depth, slice, pos_set){
if (pos_set.size() < 2)
SIM_EXCEPTION("Not encough points in pos_set");
}
PatternLine::~PatternLine(){}
void PatternLine::CreateBuffer(IDirect3DDevice9** d3d9_device){
num_points_ = slice_ + 4;
num_face_ = slice_ + 4;
num_index_ = 3 * num_face_;
D3DXVECTOR3 pos_start = pos_set_[0];
D3DXVECTOR3 pos_end = pos_set_[1];
D3DXVECTOR3 ab(D3DXVECTOR3::D3DXVECTOR3(pos_end.x - pos_start.x, pos_end.y - pos_start.y, 0));
D3DXVECTOR3 x0(D3DXVECTOR3::D3DXVECTOR3(1.0f, 0.0f, 0.0f));
D3DXVECTOR3 x1(D3DXVECTOR3::D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&ab, &ab);
float cross_x0 = x0.x * ab.y - ab.x * x0.y; // cross product
if (cross_x0 < 0.0f) {
pos_start = pos_set_[1];
pos_end = pos_set_[0];
ab = D3DXVECTOR3(pos_end.x - pos_start.x, pos_end.y - pos_start.y, 0);
D3DXVec3Normalize(&ab, &ab);
}
float ab_xx = ab.x * x0.x + ab.y * x0.y;// dot product
float base_angle = acosf(ab_xx);
HR( (*d3d9_device)->CreateVertexBuffer(num_points_ * sizeof(VertexPos), D3DUSAGE_WRITEONLY,
VertexPos::FVF, D3DPOOL_MANAGED, &vertex_buffer_, 0) );
VertexPos* vp = 0;
HR( vertex_buffer_->Lock(0, 0, (void**)&vp, 0) );
vp[0] = pos_start;/*VertexPos(0.0f, 0.0f, 0.0f)*/
vp[1] = pos_end;
//vp[num_points_-1] = pos_end;
float x, y, z;
z = depth_ + pos_start.z;
float alpha = base_angle + D3DX_PI / 2.0f;
float alpha_dt = D3DX_PI * 2.0f / slice_;
// countclockwise order
int i = 2;
for (; i <= slice_/2 + 2; ++i, alpha += alpha_dt) {
x = depth_ * cosf(alpha) + pos_start.x;
y = depth_ * sinf(alpha) + pos_start.y;
vp[i] = VertexPos(x, y, z);
}
alpha = base_angle + D3DX_PI * 1.5f;
for (; i < num_points_; ++i, alpha += alpha_dt) {
x = depth_ * cosf(alpha) + pos_end.x;
y = depth_ * sinf(alpha) + pos_end.y;
vp[i] = VertexPos(x, y, z);
}
//vp[num_points_-1] = pos_end;
HR( vertex_buffer_->Unlock() );
HR( (*d3d9_device)->CreateIndexBuffer(num_index_ * sizeof(WORD), D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16, D3DPOOL_MANAGED, &index_buffer_, 0));
WORD *idx = 0;
HR( index_buffer_->Lock(0, 0, (void**)&idx, 0));
idx[0] = 0;
idx[1] = 2;
idx[2] = num_points_ - 1;
idx[3] = 0;
idx[4] = num_points_ - 1;
idx[5] = 1;
idx[6] = 0;
idx[7] = num_points_/2 + 1;
idx[8] = num_points_/2;
idx[9] = 0;
idx[10] = 1;
idx[11] = num_points_/2 + 1;
i = 2;
int j = 12;
while (i < num_points_/2) {
idx[j++] = 0;
idx[j++] = i + 1;
idx[j++] = i;
++i;
}
++i;
while (i < num_points_ - 1) {
idx[j++] = 1;
idx[j++] = i + 1;
idx[j++] = i;
++i;
}
HR( index_buffer_->Unlock());
}
PatternPolygon::PatternPolygon(FEATURE_PATTERN type, float depth, int slice,
const std::vector<D3DXVECTOR3>& pos_set):
VoronoiPattern(type, depth, slice, pos_set){
if (pos_set.size() < 3)
SIM_EXCEPTION("Not encough points in pos_set");
}
PatternPolygon::~PatternPolygon(){}
void PatternPolygon::CreateBuffer(IDirect3DDevice9** d3d9_device){
/*D3DXVECTOR3 p0(-3.0f, 3.0f, 0.0f);
D3DXVECTOR3 p1(-1.0f, 3.0f, 0.0f);
D3DXVECTOR3 p2(-1.0f, 1.0f, 0.0f);
D3DXVECTOR3 p3(-3.0f, 1.0f, 0.0f);
*/
int n = pos_set_.size();
std::vector<D3DXVECTOR3> v;
for (int i = 0; i < n - 1; ++i) {
v.clear();
v.push_back(pos_set_[i]);
v.push_back(pos_set_[i+1]);
VoronoiPattern* pt = new PatternLine(PATTERN_LINE, depth_, slice_, v);
pt->CreateBuffer(d3d9_device);
pattern_set_.push_back(pt);
}
v.clear();
v.push_back(pos_set_[n-1]);
v.push_back(pos_set_[0]);
VoronoiPattern* pt = new PatternLine(PATTERN_LINE, depth_, slice_, v);
pt->CreateBuffer(d3d9_device);
pattern_set_.push_back(pt);
/*v.push_back(p0);
v.push_back(p1);
VoronoiPattern* pt0 = new PatternLine(PATTERN_LINE, 2.0f, 30, v);
pt0->CreateBuffer(d3d9_device);
pt0->SetColor(D3DXVECTOR4(1.0f, 0.0f, 0.0f, 0.0f));
pattern_set_.push_back(pt0);
v.clear();
v.push_back(p1);
v.push_back(p2);
VoronoiPattern* pt1 = new PatternLine(PATTERN_LINE, 2.0f, 30, v);
pt1->CreateBuffer(d3d9_device);
pt1->SetColor(D3DXVECTOR4(1.0f, 0.0f, 0.0f, 0.0f));
pattern_set_.push_back(pt1);
v.clear();
v.push_back(p2);
v.push_back(p3);
VoronoiPattern* pt2 = new PatternLine(PATTERN_LINE, 2.0f, 30, v);
pt2->CreateBuffer(d3d9_device);
pt2->SetColor(D3DXVECTOR4(1.0f, 0.0f, 0.0f, 0.0f));
pattern_set_.push_back(pt2);
v.clear();
v.push_back(p3);
v.push_back(p0);
VoronoiPattern* pt3 = new PatternLine(PATTERN_LINE, 2.0f, 30, v);
pt3->CreateBuffer(d3d9_device);
pt3->SetColor(D3DXVECTOR4(1.0f, 0.0f, 0.0f, 0.0f));
pattern_set_.push_back(pt3);*/
}
|
#include<cstdlib>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 300;
void Test(){
char line[N];
FILE *fp;
string stin;
cout << "model name: " << endl;
cin >> stin;
string cmd;
cmd = "python ../third_party/freeze_graph.py --input_graph=../third_party/models/"+stin+"/nn_model.pbtxt --input_checkpoint=../third_party/models/"+stin+"/nn_model.ckpt --output_graph=../model/"+stin+".pb --output_node_names=output";
//引号内是你的linux指令
// 系统调用
const char *sysCommand = cmd.data();
if ((fp = popen(sysCommand, "r")) == NULL) {
cout << "error" << endl;
return;
}
while (fgets(line, sizeof(line)-1, fp) != NULL){
cout << line ;
}
pclose(fp);
}
int main(){
Test();
return 0;
}
|
//
// Activity.cpp
// projekt_programowanie_obiektowe
//
// Created by Phillip on 08/06/2018.
// Copyright © 2018 Phillip. All rights reserved.
//
#include "Activity.hpp"
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include "timer.hpp"
#include <chrono>
using namespace std;
Activity::Activity() {
creation_date = time(0);
}
Activity::~Activity() {}
void Activity::start_new_activity() {
char comment[100]; // activity comment
char input[100]; // name of activity
int t = 0; // time goal
this -> set_type_name("custom");
this -> set_id();
cout << "Name of activity: ";
cin.ignore();
cin.getline(input, 100);
cout << "Set time goal in minutes (optional, you can leave this empty): "; // TODO - you can't leave this empty
cin >> t;
set_name(input);
set_time_goal(t);
cout << "Press ENTER to start timer...";
cin.ignore();
cin.get();
cout << "Timer started!" << endl;
this -> set_activity_time(timer());
cout << "Activity finished!" << "Time: " << std::setprecision(2) << activity_time/60 << " minutes" << endl;
cout << "Write comment: " << endl;
cin.ignore();
cin.getline(comment, 100);
}
/* **************** SETTERS **************** */
void Activity::set_id() {
}
void Activity::set_name(string name) {
this -> name = name;
}
void Activity::set_time_goal(int time_goal_in_minutes = 0) {
this -> time_goal_in_minutes = time_goal_in_minutes;
}
void Activity::add_comment(string comment) {
this -> comment.append(comment);
}
void Activity::set_activity_time(double activity_time) {
this -> activity_time = activity_time;
}
void Activity::set_type_name(string type_name) {
this -> type_name = type_name;
}
/* **************** GETTERS **************** */
string Activity::get_name() const {
return name;
}
double Activity::get_activity_time() const {
return activity_time;
}
string Activity::get_comment() const {
return comment;
}
string Activity::get_type() const{
return type_name;
}
void Activity::print() {
cout << "Activity name: " << this -> get_name() << endl << "Activity time: " << std::setprecision(2) << this -> get_activity_time()/60 << endl << endl;
}
time_t Activity::get_creation_date() const {
return creation_date;
}
/* **************** SERIALIZATION **************** */
std::ostream& operator<<(std::ostream& os, const Activity* s) {
os << s -> get_name() << '\n';
os << s -> get_type() << '\n';
os << s -> get_activity_time() << '\n';
//os << s -> get_comment();
return os;
}
istream& operator>>(istream& is, Activity* s) {
is >> s -> name;
is >> s -> type_name;
is >> s -> activity_time;
return is;
}
/* **************** FUNCTIONS **************** */
|
#include "stdafx.h"
#include "PlayerController.h"
PlayerController::PlayerController() {
_camera = make_shared<Camera>();
isMouseLock = false;
Mouse::State mouseState = Mouse::Get().GetState();
_prevMousePos = XMVectorSet(mouseState.x, mouseState.y, 0.0f, 0.0f);
}
shared_ptr<Camera> PlayerController::GetCamera() {
return _camera;
}
void PlayerController::OnUpdate() {
Keyboard::State keyboardState = Keyboard::Get().GetState();
XMVECTOR offsetT = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
if (keyboardState.A) {
offsetT += XMVectorSet(-0.1f, 0.0f, 0.0f, 0.0f);
} else if (keyboardState.D) {
offsetT += XMVectorSet(0.1f, 0.0f, 0.0f, 0.0f);
}
if (keyboardState.W) {
offsetT += XMVectorSet(0.0f, 0.0f, -0.1f, 0.0f);
} else if (keyboardState.S) {
offsetT += XMVectorSet(0.0f, 0.0f, 0.1f, 0.0f);
}
Translate(XMVector3Transform(offsetT, XMMatrixRotationRollPitchYawFromVector(transform.rotation * (XM_PI / 180.0f))));
if (keyboardState.Escape) {
isMouseLock = !isMouseLock;
}
if (!isMouseLock) {
Mouse::State mouseState = Mouse::Get().GetState();
XMVECTOR currentMousePos = XMVectorSet(mouseState.x, mouseState.y, 0.0f, 0.0f);
if (XMVector2NotEqual(currentMousePos, _prevMousePos)) {
XMFLOAT2 offsetR;
XMStoreFloat2(&offsetR, currentMousePos - _prevMousePos);
Rotate(XMVectorSet(offsetR.y * -0.5f * ((abs(_camera->transform.rotation.m128_f32[0] + offsetR.y * -0.5f) >= 85.0f)?0.0f:1.0f), offsetR.x * -0.5f, 0.0f, 0.0f));
}
_prevMousePos = currentMousePos;
}
_camera->SetTransform(transform);
}
|
#include<iostream>
#include"workerManger.h"
#include"worker.h"
#include"employee.h"
#include"manger.h"
#include"boss.h"
using namespace std;
int main(){
cout << "project beginning!" << endl;
// 实例化管理者对象
WorkerManger test;
int choice = 0;
// 调用展示菜单成员函数
test.show_Menu();
while(true)
{
cout << "请输入你的选择:" << endl;
cin >> choice;
switch(choice)
{
case 0: // 退出系统
test.exitSystem();
break;
case 1: // 增加职工
test.Add_Emp();
break;
case 2: // 显示职工
test.show_Emp();
break;
case 3: // 删除职工
test.del_Emp();
break;
case 4: // 修改职工
test.mod_Emp();
break;
case 5: // 查找职工
test.find_Emp();
break;
case 6: // 排序职工
test.sort_Emp();
break;
case 7: // 清空
test.clear_File();
break;
default:
break;
}
}
return 0;
}
|
#include "MahjongTable.h"
#include "MahjongPlayer.h"
#include "AllocSvrConnect.h"
#include "Logger.h"
#ifndef _WIN32
#define __min(a,b) (((a) < (b)) ? (a) : (b))
#endif
static std::string CardDataToString(uint8_t* cards, size_t len)
{
std::string tmp;
for (size_t i = 0; i < len; i++)
{
tmp += TOHEX(cards[i]);
tmp += "-";
}
return tmp;
}
CMahjongTable::CMahjongTable(uint32_t id, CMahjongLogic *pMahjongLogic)
{
for (int i = 0; i < GAME_PLAYER; i++)
m_players[i] = NULL;
m_nCurPlayerCount = 0;
m_bPlaying = false;
m_capabilitis = 0;
ASSERT(pMahjongLogic);
m_pGameLogic = pMahjongLogic;
ResetData();
}
CMahjongTable::~CMahjongTable()
{
}
bool CMahjongTable::AddPlayer(CMahjongPlayer *pPlayer)
{
ASSERT(!m_bPlaying);
ASSERT(pPlayer);
ASSERT(m_nCurPlayerCount < GAME_PLAYER);
for (int i = 0; i < GAME_PLAYER; i++)
{
if (NULL == m_players[i])
{
m_players[i] = pPlayer;
pPlayer->m_pTable = this;
pPlayer->m_nSeatPos = i;
m_nCurPlayerCount++;
return true;
}
}
return false;
}
void CMahjongTable::RemovePlayer(CMahjongPlayer *pPlayer)
{
ASSERT(!m_bPlaying);
ASSERT(pPlayer);
ASSERT(m_nCurPlayerCount > 0);
for (int i = 0; i < GAME_PLAYER; i++)
{
if (m_players[i] == pPlayer)
{
m_nCurPlayerCount--;
m_players[i] = NULL;
break;
}
}
}
CMahjongPlayer* CMahjongTable::GetAt(uint8_t nPos)
{
ASSERT(nPos < GAME_PLAYER);
return m_players[nPos];
}
CMahjongPlayer* CMahjongTable::Find(uint32_t uid)
{
for (int i = 0; i < GAME_PLAYER; i++)
{
if ((NULL != m_players[i]) && (uid == m_players[i]->m_id))
return m_players[i];
}
return NULL;
}
void CMahjongTable::Clear()
{
for (int i = 0; i < GAME_PLAYER; i++)
{
if (m_players[i])
{
m_players[i]->Clear();
m_players[i] = NULL;
}
}
m_nCurPlayerCount = 0;
m_bPlaying = false;
}
void CMahjongTable::GameStart()
{
// 复位数据
ResetData();
// 发牌
DealCard();
this->OnDealCardCompleted();
m_bPlaying = true;
}
void CMahjongTable::BankStartOutCard()
{
//杠牌判断
ASSERT(INVALID_CHAIR != m_nBankerPos);
CMahjongPlayer* pBanker = m_players[m_nBankerPos];
AnalyseBeforeOutCard(pBanker);
this->OnBankStartOutCard();
}
void CMahjongTable::ResetData()
{
m_nBankerPos = INVALID_CHAIR;
m_nReplacePos = 0;
m_nOutCardPos = 0;
m_nOutCardData = 0;
m_nOutCardCount = 0;
m_nSendCardData = 0;
m_nSendCardCount = 0;
m_nLeftCardCount = 0;
m_nEndLeftCount = 0;
ZeroMemory(m_allCardData, sizeof(m_allCardData));
m_nHeapHead = INVALID_CHAIR;
m_nHeapTail = INVALID_CHAIR;
ZeroMemory(m_heapinfo, sizeof(m_heapinfo));
m_nResumePos = INVALID_CHAIR;
m_nCurrentPos = INVALID_CHAIR;
m_nProvidePos = INVALID_CHAIR;
m_nProvideData = 0;
m_bQiangGang = false;
m_bGangPao = false;
m_bWaitForOperate = false;
}
void CMahjongTable::DealCard()
{
// 投掷骰子,确定牌墙位置与庄家
uint8_t nRand1 = rand() % 6 + 1;
uint8_t nRand2 = rand() % 6 + 1;
if (INVALID_CHAIR == m_nBankerPos)
{
uint8_t nRand3 = rand() % 6 + 1;
uint8_t nRand4 = rand() % 6 + 1;
m_nDicePoint = MAKELONG(MAKEWORD(nRand1, nRand2), MAKEWORD(nRand3, nRand4));
m_nBankerPos = ((BYTE)(m_nDicePoint >> 24) + (BYTE)(m_nDicePoint >> 16) - 1) % GAME_PLAYER;
}
else
{
m_nDicePoint = MAKELONG(MAKEWORD(nRand1, nRand2), 0);
}
// 洗牌
m_nLeftCardCount = g_maxRepertory;
m_pGameLogic->RandCardData(m_allCardData, g_maxRepertory);
LOGGER(E_LOG_DEBUG) << CardDataToString(m_allCardData, g_maxRepertory);
// 分发牌
for (uint8_t i = 0; i < GAME_PLAYER; i++)
{
ASSERT(m_players[i]);
m_nLeftCardCount -= (MAX_COUNT - 1);
if (m_players[i])
m_pGameLogic->SwitchToCardIndex(&m_allCardData[m_nLeftCardCount], MAX_COUNT - 1, m_players[i]->m_handCardIndex);
}
// 庄家在多发一张
m_nSendCardCount++;
m_nSendCardData = m_allCardData[--m_nLeftCardCount];
CMahjongPlayer* pBanker = m_players[m_nBankerPos];
uint8_t sendCardIndex = m_pGameLogic->SwitchToCardIndex(m_nSendCardData);
pBanker->m_handCardIndex[sendCardIndex]++;
// 初始化位置信息
m_nProvideData = 0;
m_nProvidePos = INVALID_CHAIR;
m_nCurrentPos = m_nBankerPos;
// 牌墙信息
uint16_t nDice = (uint16_t)(m_nDicePoint & 0xffff);
#ifdef _WIN32
uint8_t nDiceTakeCount = HIBYTE(nDice) + LOBYTE(nDice);
#else
uint8_t nDiceTakeCount = HIGHBYTE(nDice) + LOWBYTE(nDice);
#endif
uint8_t nTakeChairPos = (m_nBankerPos + nDiceTakeCount - 1) % GAME_PLAYER;
uint8_t nTakeCount = g_maxRepertory - m_nLeftCardCount;
for (uint16_t i = 0; i < GAME_PLAYER; i++)
{
//计算数目
uint8_t nValidCount = g_nHeapFullCount - m_heapinfo[nTakeChairPos][1] - ((i == 0) ? (nDiceTakeCount) * 2 : 0);
uint8_t nRemoveCount = __min(nValidCount, nTakeCount);
//提取扑克
nTakeCount -= nRemoveCount;
m_heapinfo[nTakeChairPos][(i == 0) ? 1 : 0] += nRemoveCount;
//完成判断
if (0 == nTakeCount)
{
m_nHeapHead = nTakeChairPos;
m_nHeapTail = (m_nBankerPos + nDiceTakeCount - 1) % GAME_PLAYER;
break;
}
//切换索引
nTakeChairPos = (nTakeChairPos + 1) % 4;
}
}
void CMahjongTable::OutCardAssist(CMahjongPlayer* pPlayer)
{
LOGGER(E_LOG_INFO) << "== out_card_assist == ";
pPlayer->m_outCanTing.clear();
for (BYTE i = 0; i < MAX_INDEX; i++)
{
pPlayer->m_outCanTingCard[i].clear();
if (0 == pPlayer->m_handCardIndex[i])
continue;
pPlayer->m_handCardIndex[i]--;
LOGGER(E_LOG_INFO) << "== if out card = " << TOHEX(m_pGameLogic->SwitchToCardData(i));
for (BYTE j = 0; j < MAX_INDEX; j++)
{
if (j != i)
{
CChiHuRight chr;
uint8_t cbCurrentCard = m_pGameLogic->SwitchToCardData(j);
if (WIK_CHI_HU == m_pGameLogic->AnalyseChiHuCard(pPlayer, cbCurrentCard, chr, true))
{
tagListenItem item;
LOGGER(E_LOG_INFO) << "== AnalyseTingCard Success == ";
item.cbListenCard = cbCurrentCard;
item.cbCardLeft = GetLeftCount(pPlayer, cbCurrentCard);
if (0 != item.cbCardLeft)
{
item.cbPoints = this->GetCommonPoints(pPlayer->m_handCardIndex, cbCurrentCard, chr);
pPlayer->m_outCanTingCard[i].push_back(item);
}
}
}
}
pPlayer->m_handCardIndex[i]++;
if (0 != pPlayer->m_outCanTingCard[i].size())
{
pPlayer->m_outCanTing.push_back(i);
pPlayer->m_action |= WIK_LISTEN;
}
}
LOGGER(E_LOG_DEBUG) << "out_can_ting == " << pPlayer->m_outCanTing.size();
}
uint8_t CMahjongTable::GetLeftCount(CMahjongPlayer* pPlayer, uint8_t card)
{
int nCount = 0;
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "card == " << card;
if (pPlayer)
{
uint8_t index = m_pGameLogic->SwitchToCardIndex(card);
nCount += pPlayer->m_handCardIndex[index];
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "hand card, count == " << nCount;
}
for (int i = 0; i < GAME_PLAYER; i++)
{
uint8_t nOperateCard = 0;
for (uint8_t j = 0; j < m_players[i]->m_discardCount; j++)
{
if (card == m_players[i]->m_discardCard[j])
{
nCount++;
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "discard card, count == " << nCount;
}
}
for (uint8_t j = 0; j < m_players[i]->m_weaveCount; j++)
{
nOperateCard = m_players[i]->m_weaveItems[j].cbCenterCard;
switch (m_players[i]->m_weaveItems[j].cbWeaveKind)
{
case WIK_LEFT:
if ((card == nOperateCard) || (card == (nOperateCard + 1)) || (card == (nOperateCard + 2)))
{
nCount++;
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "weave item == " << m_players[i]->m_weaveItems[j].cbWeaveKind << "count == " << nCount;
}
break;
case WIK_CENTER:
if ((card == (nOperateCard-1)) || (card == nOperateCard) || (card == (nOperateCard + 2)))
{
nCount++;
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "weave item == " << m_players[i]->m_weaveItems[j].cbWeaveKind << "count == " << nCount;
}
break;
case WIK_RIGHT:
if ((card == (nOperateCard - 2)) || (card == (nOperateCard - 1)) || (card == nOperateCard))
{
nCount++;
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "weave item == " << m_players[i]->m_weaveItems[j].cbWeaveKind << "count == " << nCount;
}
break;
case WIK_PENG:
if (card == nOperateCard)
{
nCount += 3;
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "weave item == " << m_players[i]->m_weaveItems[j].cbWeaveKind << " count == " << nCount;
}
break;
case WIK_GANG:
if (card == nOperateCard)
{
nCount += 4;
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "weave item == " << m_players[i]->m_weaveItems[j].cbWeaveKind << " count == " << nCount;
}
break;
default:
break;
}
}
}
ULOGGER(E_LOG_DEBUG, pPlayer->m_id) << "left count == " << (4 - nCount);
return (4 - nCount);
}
void CMahjongTable::OutCard(CMahjongPlayer *pPlayer, uint8_t nOutCard, bool bListen)
{
//删除麻将
if (!m_pGameLogic->RemoveCard(pPlayer->m_handCardIndex, nOutCard))
{
ULOGGER(E_LOG_ERROR, pPlayer->m_id) << "remove card failed!";
return;
}
//设置状态
if (m_bQiangGang)
m_bQiangGang = false;
if (m_capabilitis&support_listen)
{
if ((!pPlayer->m_listen) && bListen)
pPlayer->m_listen = bListen;
}
pPlayer->m_action = WIK_NULL;
pPlayer->m_performAction = WIK_NULL;
//出牌记录
m_nOutCardCount++;
m_nOutCardPos = pPlayer->m_nSeatPos;
m_nOutCardData = nOutCard;
m_nProvidePos = pPlayer->m_nSeatPos;
m_nProvideData = nOutCard;
//用户切换
m_nCurrentPos = (pPlayer->m_nSeatPos + GAME_PLAYER - 1) % GAME_PLAYER;
this->OnOutCardCompleted();
}
bool CMahjongTable::EstimateUserResponse(uint8_t nCurPos, uint8_t nCurCard, EstimatType eEstimatType)
{
bool bAction = false;
uint8_t nEatUser = (m_capabilitis&support_chi) ? (nCurPos + GAME_PLAYER - 1) % GAME_PLAYER : 0;
for (uint8_t i = 0; i < GAME_PLAYER; i++)
{
if (m_players[i])
{
CMahjongPlayer* p = m_players[i];
//用户状态
p->m_response = false;
p->m_action = WIK_NULL;
p->m_performAction = WIK_NULL;
if (nCurPos == p->m_nSeatPos)
continue;
if (estimat_out_card == eEstimatType)
{
//吃碰判断
if (!p->m_forbidPeng)
{
//碰牌判断(听牌后不能碰)
if (!p->m_listen)
p->m_action |= m_pGameLogic->EstimatePengCard(p->m_handCardIndex, nCurCard);
//杠牌判断
if (m_nLeftCardCount > m_nEndLeftCount)
{
int8_t curAction = m_pGameLogic->EstimateGangCard(p->m_handCardIndex, nCurCard);
if (WIK_GANG == curAction)
{
if (p->m_listen)
{
//复制数据
BYTE cardIndexTemp[MAX_INDEX] = { 0 };
tagWeaveItem tempWaveItems[MAX_WEAVE];
uint8_t tempWaveCount = 0;
CopyMemory(cardIndexTemp, p->m_handCardIndex, g_nMaxIndex);
cardIndexTemp[m_pGameLogic->SwitchToCardIndex(nCurCard)] = 0;
ZeroMemory(tempWaveItems, sizeof(tempWaveItems));
tempWaveCount = p->m_weaveCount;
if (tempWaveCount > 0)
CopyMemory(tempWaveItems, p->m_weaveItems, tempWaveCount * sizeof(tagWeaveItem));
tempWaveItems[tempWaveCount].cbWeaveKind = WIK_GANG;
tempWaveItems[tempWaveCount].cbPublicCard = true;
tempWaveItems[tempWaveCount].cbCenterCard = nCurCard;
tempWaveItems[tempWaveCount].wProvideUser = nCurCard;
tempWaveCount++;
if (m_pGameLogic->IsTingCard(cardIndexTemp, tempWaveItems, tempWaveCount))
p->m_action |= WIK_GANG;
}
else
{
p->m_action |= WIK_GANG;
}
}
}
//吃牌判断(只能是出牌的下家能吃)
if (m_capabilitis&support_chi)
{
if ((!p->m_listen) && (nEatUser == i))
p->m_action |= m_pGameLogic->EstimateEatCard(p->m_handCardIndex, nCurCard);
}
}
}
//胡牌判断--2
if (!p->m_forbidChihu)
{
//吃胡判断
CChiHuRight chr;
uint8_t nAction = m_pGameLogic->AnalyseChiHuCard(p, nCurCard, chr, false);
p->m_action |= nAction;
}
//结果判断
if (WIK_NULL != p->m_action)
bAction = true;
}
}
//结果处理
if (bAction)
{
//设置变量
m_nProvidePos = nCurPos;
m_nProvideData = nCurCard;
m_nResumePos = m_nCurrentPos;
m_nCurrentPos = INVALID_CHAIR;
m_bWaitForOperate = true;
return true;
}
else
{
return false;
}
}
bool CMahjongTable::DispatchCard(uint8_t uCurUser, bool bTail)
{
if ((uCurUser >= m_nCurPlayerCount) || (INVALID_CHAIR == uCurUser))
{
LOGGER(E_LOG_ERROR) << "invalid winner pos = " << uCurUser;
return false;
}
//弃牌
if ((INVALID_CHAIR != m_nOutCardPos) && (0 != m_nOutCardData))
{
m_players[m_nOutCardPos]->m_discardCard[m_players[m_nOutCardPos]->m_discardCount] = m_nOutCardData;
m_players[m_nOutCardPos]->m_discardCount++;
}
//荒庄结束
if (m_nLeftCardCount == m_nEndLeftCount)
{
LOGGER(E_LOG_INFO) << "huangzhuang over!";
m_nProvideData = INVALID_CHAIR;
m_nChihuData = INVALID_CHAIR;
GameOver();
return true;
}
//设置变量
CMahjongPlayer* p = m_players[uCurUser];
m_bGangPao = false;
m_nOutCardPos = INVALID_CHAIR;
m_nOutCardData = 0;
m_nCurrentPos = uCurUser;
p->m_forbidChihu = false;
p->m_action = WIK_NULL;
//发牌处理
//发送扑克
m_nSendCardCount++;
m_nSendCardData = m_allCardData[--m_nLeftCardCount];
//加牌
p->m_handCardIndex[m_pGameLogic->SwitchToCardIndex(m_nSendCardData)]++;
//设置变量
m_nProvidePos = p->m_nSeatPos;
m_nProvideData = m_nSendCardData;
//堆立信息
ASSERT((INVALID_CHAIR != m_nHeapHead) && (INVALID_CHAIR != m_nHeapTail));
if (!bTail)
{
//切换索引
BYTE cbHeapCount = m_heapinfo[m_nHeapHead][0] + m_heapinfo[m_nHeapHead][1];
if (cbHeapCount == g_nHeapFullCount)
m_nHeapHead = (m_nHeapHead + 1) % 4;
m_heapinfo[m_nHeapHead][0]++;
}
else
{
//切换索引
BYTE cbHeapCount = m_heapinfo[m_nHeapTail][0] + m_heapinfo[m_nHeapTail][1];
if (cbHeapCount == g_nHeapFullCount)
m_nHeapTail = (m_nHeapTail + 3) % 4;
m_heapinfo[m_nHeapTail][1]++;
}
AnalyseBeforeOutCard(p);
if (m_capabilitis&support_out_assist)
{
if (!p->m_listen)
OutCardAssist(p);
}
this->OnDispatchCardCompleted(bTail);
return true;
}
void CMahjongTable::GameOver()
{
this->OnGameOver();
}
bool CMahjongTable::OperateCardPassively(CMahjongPlayer *pPlayer, uint8_t actionCard, uint8_t action)
{
uint8_t nTargetUser = INVALID_CHAIR;
uint8_t nTargetAction = WIK_NULL;
uint8_t nNewAction = WIK_NULL;
ASSERT(pPlayer);
if (pPlayer->m_response)
return true;
//效验状态
if ((WIK_NULL != action) && (0 == (pPlayer->m_action & action)))
{
ULOGGER(E_LOG_ERROR, pPlayer->m_id) << "user action not valid!";
return true;
}
//变量定义
nTargetUser = pPlayer->m_nSeatPos;
nTargetAction = action;
nNewAction = WIK_NULL;
//设置变量
pPlayer->m_response = true;
pPlayer->m_performAction = action;
if (0 == actionCard)
pPlayer->m_operateCard = m_nProvideData;
else
pPlayer->m_operateCard = actionCard;
//在自己未摸下一张牌的一圈内,不能弃上一家而胡下一家
if ((WIK_NULL == nTargetAction) && (WIK_CHI_HU&m_players[nTargetUser]->m_action) && (m_nProvidePos != nTargetUser))
pPlayer->m_forbidChihu = true;
//执行判断
for (uint8_t i = 0; i < GAME_PLAYER; i++)
{
//获取动作
uint8_t nUserAction = (!m_players[i]->m_response) ? m_players[i]->m_action : m_players[i]->m_performAction;
//优先级别
uint8_t nUserActionRank = m_pGameLogic->GetUserActionRank(nUserAction);
uint8_t nTargetActionRank = m_pGameLogic->GetUserActionRank(nTargetAction);
//动作判断
if (nUserActionRank > nTargetActionRank)
{
nTargetUser = i;
nTargetAction = nUserAction;
}
}
if (!m_players[nTargetUser]->m_response)
return true;
//吃胡等待
if (WIK_CHI_HU == nTargetAction)
{
for (uint8_t i = 0; i < GAME_PLAYER; i++)
{
if ((!m_players[i]->m_response) && (m_players[i]->m_action & WIK_CHI_HU))
return true;
}
}
//放弃操作
if (WIK_NULL == nTargetAction)
{
//用户状态
for (uint8_t i = 0; i < GAME_PLAYER; i++)
{
ASSERT(m_players[i]);
m_players[i]->m_response = false;
m_players[i]->m_action = WIK_NULL;
m_players[i]->m_operateCard = 0;
m_players[i]->m_performAction = WIK_NULL;
}
m_bGangPao = false;
//给下家发送扑克
DispatchCard(m_nResumePos, false);
return true;
}
//变量定义
uint8_t nTargetCard = m_players[nTargetUser]->m_operateCard;
//出牌变量
m_nOutCardData = 0;
m_nOutCardPos = INVALID_CHAIR;
m_players[nTargetUser]->m_forbidChihu = false;
//胡牌操作
if (WIK_CHI_HU == nTargetAction)
{
//结束信息
m_nChihuData = nTargetCard;
for (int i = (m_nProvidePos + GAME_PLAYER - 1) % GAME_PLAYER; i != m_nProvidePos; i = (i + GAME_PLAYER - 1) % GAME_PLAYER)
{
//过虑判断
if (0 == (m_players[i]->m_performAction & WIK_CHI_HU))
continue;
//胡牌判断--最后胡了时候检查牌
uint8_t weaveItemCount = m_players[i]->m_weaveCount;
tagWeaveItem * pWeaveItem = m_players[i]->m_weaveItems;
m_players[i]->m_chihuKind = m_pGameLogic->AnalyseChiHuCard(m_players[i], m_nChihuData, m_players[i]->m_chihuRight, true);
//插入扑克
if (WIK_NULL != m_players[i]->m_chihuKind)
{
m_players[i]->m_handCardIndex[m_pGameLogic->SwitchToCardIndex(m_nChihuData)]++;
nTargetUser = i;
this->OnProcessChihu(i);
return true;
}
}
}
//组合扑克
if (pPlayer->m_weaveCount >= MAX_WEAVE)
{
ULOGGER(E_LOG_ERROR, pPlayer->m_id) << "weave item count over MAX_WEAVE now, count = " << pPlayer->m_weaveCount;
return false;
}
uint8_t nIndex = pPlayer->m_weaveCount++;
pPlayer->m_weaveItems[nIndex].cbPublicCard = TRUE;
pPlayer->m_weaveItems[nIndex].cbCenterCard = nTargetCard;
pPlayer->m_weaveItems[nIndex].cbWeaveKind = nTargetAction;
pPlayer->m_weaveItems[nIndex].wProvideUser = (INVALID_CHAIR == m_nProvidePos) ? nTargetUser : m_nProvidePos;
//删除扑克
uint8_t removeCard[4] = { 0 };
uint8_t removeCount = 0;
switch (nTargetAction)
{
case WIK_LEFT: //左吃
removeCard[removeCount++] = nTargetCard + 1;
removeCard[removeCount++] = nTargetCard + 2;
break;
case WIK_RIGHT: //右吃
removeCard[removeCount++] = nTargetCard - 2;
removeCard[removeCount++] = nTargetCard - 1;
break;
case WIK_CENTER: //中吃
removeCard[removeCount++] = nTargetCard - 1;
removeCard[removeCount++] = nTargetCard + 1;
break;
case WIK_PENG: //碰牌操作
removeCard[removeCount++] = nTargetCard;
removeCard[removeCount++] = nTargetCard;
break;
case WIK_GANG: //杠牌操作(被动动作只可能是其他玩家放杠)
removeCard[removeCount++] = nTargetCard;
removeCard[removeCount++] = nTargetCard;
removeCard[removeCount++] = nTargetCard;
break;
default:
ASSERT(FALSE);
return false;
}
if (!m_pGameLogic->RemoveCard(pPlayer->m_handCardIndex, removeCard, removeCount))
{
ASSERT(FALSE);
return false;
}
m_bGangPao = false;
if ((m_nLeftCardCount > m_nEndLeftCount) && m_pGameLogic->IsGangCard(pPlayer->m_handCardIndex))
nNewAction |= WIK_GANG;
if (m_capabilitis&support_out_assist)
{
if (!pPlayer->m_listen)
{
OutCardAssist(pPlayer);
if (0 != pPlayer->m_outCanTing.size())
nNewAction |= WIK_LISTEN;
}
}
this->OnOperateCardCompleted(pPlayer->m_nSeatPos, nTargetUser, nTargetAction, nTargetCard, nNewAction, false);
// 杠牌后需要补牌
if (WIK_GANG == nTargetAction)
{
m_bQiangGang = true;
m_bGangPao = true;
DispatchCard(nTargetUser, true);
}
m_nCurrentPos = nTargetUser;
return true;
}
bool CMahjongTable::OperateCardActively(CMahjongPlayer *pPlayer, uint8_t actionCard, uint8_t action)
{
uint8_t nTargetUser = INVALID_CHAIR;
uint8_t nTargetAction = action;
uint8_t nNewAction = WIK_NULL;
//效验操作
if ((WIK_NULL == action) || (0 == (pPlayer->m_action & action)))
return false;
//扑克效验
if ((WIK_NULL != action) && (WIK_CHI_HU != action) && (!m_pGameLogic->IsValidCard(actionCard)))
return false;
//设置变量
m_players[m_nCurrentPos]->m_action = WIK_NULL;
m_players[m_nCurrentPos]->m_performAction = WIK_NULL;
m_players[m_nCurrentPos]->m_forbidChihu = false;
bool bPublic = false;
//执行动作
switch (action)
{
case WIK_GANG: //杠牌操作
{
//变量定义
uint8_t nWeaveIndex = 0xFF;
uint8_t nCardIndex = m_pGameLogic->SwitchToCardIndex(actionCard);
//杠牌处理
if (1 == pPlayer->m_handCardIndex[nCardIndex])
{
//寻找组合
for (uint8_t i = 0; i < pPlayer->m_weaveCount; i++)
{
uint8_t nWeaveKind = pPlayer->m_weaveItems[i].cbWeaveKind;
uint8_t nCenterCard = pPlayer->m_weaveItems[i].cbCenterCard;
if ((nCenterCard == actionCard) && (WIK_PENG == nWeaveKind))
{
bPublic = true;
nWeaveIndex = i;
break;
}
}
//效验动作
ASSERT(0xFF != nWeaveIndex);
if (0xFF == nWeaveIndex)
return false;
//组合扑克
pPlayer->m_weaveItems[nWeaveIndex].cbPublicCard = TRUE;
pPlayer->m_weaveItems[nWeaveIndex].cbWeaveKind = action;
pPlayer->m_weaveItems[nWeaveIndex].cbCenterCard = actionCard;
pPlayer->m_weaveItems[nWeaveIndex].wProvideUser = pPlayer->m_nSeatPos;
}
else
{
//扑克效验
if (4 == pPlayer->m_handCardIndex[nCardIndex])
return false;
//设置变量
bPublic = false;
nWeaveIndex = pPlayer->m_weaveCount++;
pPlayer->m_weaveItems[nWeaveIndex].cbPublicCard = FALSE;
pPlayer->m_weaveItems[nWeaveIndex].wProvideUser = pPlayer->m_nSeatPos;
pPlayer->m_weaveItems[nWeaveIndex].cbWeaveKind = action;
pPlayer->m_weaveItems[nWeaveIndex].cbCenterCard = actionCard;
}
if ((m_nLeftCardCount > m_nEndLeftCount) && m_pGameLogic->IsGangCard(pPlayer->m_handCardIndex))
nNewAction |= WIK_GANG;
//删除扑克
pPlayer->m_handCardIndex[nCardIndex] = 0;
m_bQiangGang = true;
this->OnOperateCardCompleted(pPlayer->m_nSeatPos, pPlayer->m_nSeatPos, action, actionCard, nNewAction, true);
//效验动作
bool bAroseAction = false;
if (bPublic == true)
bAroseAction = EstimateUserResponse(pPlayer->m_nSeatPos, actionCard, estimat_gang_card);
//发送扑克
if (!bAroseAction)
{
m_bGangPao = true;
DispatchCard(pPlayer->m_nSeatPos, true);
}
return true;
}
case WIK_CHI_HU: //吃胡操作
{
//普通胡牌
if (!m_pGameLogic->RemoveCard(pPlayer->m_handCardIndex, &m_nProvideData, 1))
{
ASSERT(FALSE);
return false;
}
pPlayer->m_chihuKind = m_pGameLogic->AnalyseChiHuCard(pPlayer, m_nProvideData, pPlayer->m_chihuRight, true);
pPlayer->m_handCardIndex[m_pGameLogic->SwitchToCardIndex(m_nProvideData)]++;
pPlayer->m_performAction = WIK_CHI_HU;
//结束信息
m_nChihuData = m_nProvideData;
this->OnProcessChihu(pPlayer->m_nSeatPos);
return true;
}
}
return true;
}
void CMahjongTable::AnalyseBeforeOutCard(CMahjongPlayer* pPlayer)
{
//胡牌判断
CChiHuRight chr;
pPlayer->m_action |= m_pGameLogic->AnalyseChiHuCard(pPlayer, 0, chr, false);
//杠牌判断
if (!pPlayer->m_forbidPeng && (m_nLeftCardCount > m_nEndLeftCount))
{
tagGangCardResult gangCardResult;
uint8_t curAction = m_pGameLogic->AnalyseGangCard(pPlayer, gangCardResult);
if (WIK_GANG == curAction)
{
if (pPlayer->m_listen)
{
if (4 == pPlayer->m_handCardIndex[m_pGameLogic->SwitchToCardIndex(m_nSendCardData)])
{
BYTE cardIndexTemp[MAX_INDEX] = { 0 };
tagWeaveItem tempWaveItems[MAX_WEAVE];
uint8_t tempWaveCount = 0;
CopyMemory(cardIndexTemp, pPlayer->m_handCardIndex, g_nMaxIndex);
cardIndexTemp[m_pGameLogic->SwitchToCardIndex(m_nSendCardData)] = 0;
ZeroMemory(tempWaveItems, sizeof(tempWaveItems));
tempWaveCount = pPlayer->m_weaveCount;
if (tempWaveCount > 0)
CopyMemory(tempWaveItems, pPlayer->m_weaveItems, tempWaveCount * sizeof(tagWeaveItem));
tempWaveItems[tempWaveCount].cbWeaveKind = WIK_GANG;
tempWaveItems[tempWaveCount].cbPublicCard = false;
tempWaveItems[tempWaveCount].cbCenterCard = m_nSendCardData;
tempWaveItems[tempWaveCount].wProvideUser = pPlayer->m_nSeatPos;
tempWaveCount++;
if (m_pGameLogic->IsTingCard(cardIndexTemp, tempWaveItems, tempWaveCount))
pPlayer->m_action |= WIK_GANG;
}
else
{
pPlayer->m_action |= WIK_GANG;
}
}
else
{
pPlayer->m_action |= WIK_GANG;
}
}
}
}
|
class Category_541 {
class ItemAntibiotic {
type = "trade_items";
buy[] = {1,"ItemGoldBar"};
sell[] = {2,"ItemSilverBar10oz"};
};
class ItemBandage {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class ItemAntibacterialWipe {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
// bloodBagONEG is automatically swapped with ItemBloodbag if dayz_classicBloodBagSystem = true; Other typed bags and bloodTester are ignored.
class bloodBagONEG {
type = "trade_items";
buy[] = {4,"ItemSilverBar"};
sell[] = {2,"ItemSilverBar"};
};
class bloodBagANEG {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class bloodBagAPOS {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class bloodBagBNEG {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class bloodBagBPOS {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class bloodBagABNEG {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class bloodBagABPOS {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class bloodBagOPOS {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class bloodTester {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class transfusionKit {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class emptyBloodBag {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class ItemEpinephrine {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class ItemHeatPack {
type = "trade_items";
buy[] = {1,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class ItemMorphine {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class ItemPainkiller {
type = "trade_items";
buy[] = {1,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class equip_string {
type = "trade_items";
buy[] = {1,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class equip_gauze {
type = "trade_items";
buy[] = {1,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class equip_gauzepackaged {
type = "trade_items";
buy[] = {1,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class equip_rag {
type = "trade_items";
buy[] = {1,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class equip_herb_box {
type = "trade_items";
buy[] = {1,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class ItemKiloHemp {
type = "trade_items";
buy[] = {-1,"ItemGoldBar"}; // Sell only
sell[] = {1,"ItemGoldBar"};
};
};
|
#include <iostream>
#include "sale.h"
int main()
{
using std::cin;
using namespace SALES;
Sales ar[2];
double arr[4] = { 1,2,3,4};
setSales(ar[0], arr, 3);
setSales(ar[1]);
showSales(ar[0]);
showSales(ar[1]);
while (cin.get() != 'q')
;
return 0;
}
|
#include <stdio.h>
void nine(int x){
int sum=0;
int a,b,c,d;
for(int i=1;i<=x;i++){
a=i%10;
b=(i/10)%10;
c=((i/10)/10)%10;
d=(((i/10)/10))%10;
if(a==9 || b==9 || c==9 || d==9)
sum++;
}
printf("%d",sum);
}
int main(){
int n=2019;
// int sum=0;
// int a,b,c,d;
nine(n);
// printf("%d",sum);
return 0;
}
|
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#include "hal/Usb.hpp"
using namespace hal;
Usb::Usb(port_t port) : Periph(CORE_PERIPH_USB, port){}
int Usb::get_attr(usb_attr_t & attr){
return ioctl(I_USB_GETATTR, &attr);
}
int Usb::set_attr(const usb_attr_t & attr){
return ioctl(I_USB_SETATTR, &attr);
}
int Usb::reset(){
return ioctl(I_USB_RESET);
}
int Usb::attach(){
return ioctl(I_USB_ATTACH);
}
int Usb::configure(){
return ioctl(I_USB_CONFIGURE);
}
int Usb::detach(){
return ioctl(I_USB_DETACH);
}
int Usb::disable_endpoint(int ep){
return ioctl(I_USB_DISABLEEP, ep);
}
int Usb::enable_endpoint(int ep){
return ioctl(I_USB_ENABLEEP, ep);
}
bool Usb::is_connected(){
return ioctl(I_USB_ISCONNECTED);
}
int Usb::reset_endpoint(int ep){
return ioctl(I_USB_RESETEP, ep);
}
int Usb::set_addr(int addr){
return ioctl(I_USB_SETATTR, addr);
}
int Usb::stall_endpoint(int ep){
return ioctl(I_USB_STALLEP, ep);
}
int Usb::unstall_endpoint(int ep){
return ioctl(I_USB_UNSTALLEP, ep);
}
|
#pragma once
#include <pthread.h>
#include <memory.h>
namespace iberbar
{
namespace OS
{
template <int tEventCount >
class TMultiEventWaiter
{
public:
TMultiEventWaiter();
~TMultiEventWaiter();
int Wait();
int MsgWait();
bool Active( int nId );
private:
pthread_cond_t m_Condition;
int m_nSignalCount;
bool m_SignalStates[tEventCount];
int m_Signals[ tEventCount ];
};
}
}
template <int tEventCount >
iberbar::OS::TMultiEventWaiter<tEventCount>::TMultiEventWaiter()
: m_Condition()
, m_nSignalCount( 0 )
, m_SignalStates()
, m_Signals()
{
memset( m_SignalStates, 0, sizeof( m_SignalStates ) );
memset( m_Signals, 0, sizeof( m_Signals ) );
pthread_cond_init( &m_Condition, nullptr );
}
template <int tEventCount >
iberbar::OS::TMultiEventWaiter<tEventCount>::~TMultiEventWaiter()
{
pthread_cond_destroy( &m_Condition );
}
template <int tEventCount >
int iberbar::OS::TMultiEventWaiter<tEventCount>::Wait()
{
}
template <int tEventCount >
int iberbar::OS::TMultiEventWaiter<tEventCount>::MsgWait()
{
}
template <int tEventCount >
bool iberbar::OS::TMultiEventWaiter<tEventCount>::Active( int nId )
{
}
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
class SegTree {
vector<int> a;
int trsize = 0;
int lvsize = 0;
public:
SegTree(vector<int> &in){
int n = in.size();
int bit = 0;
while(1){
if ((1<<bit) >= n){
break;
}
bit++;
}
lvsize = 1<<bit;
trsize = lvsize*2-1;
a = vector<int>(trsize);
rep(i, in.size()) a[(trsize/2)+i] = in[i];
for (int i = (trsize/2)-1; i >= 0; i--)
{
a[i] = min(a[i*2+1], a[i*2+2]);
}
}
void update(int node, int val){
if (node < 0) return;
int targ = node + (trsize/2);
if (targ >= trsize) return;
a[targ] = val;
do{
targ--;
targ/=2;
a[targ] = min(a[targ*2+1], a[targ*2+2]);
}while(targ > 0);
}
int search(int sl, int sr){
cout << sl << sr << endl;
return search_query(0, lvsize, sl, sr, 0);
}
int search_query(int l, int r, int sl, int sr, int k){
if (r <= sl || sr <= l){
return MOD;
} else if (sl <= l && r <= sr) {
return a[k];
}
int h_1 = search_query(l, (l+r)/2, sl, sr, k*2+1);
int h_2 = search_query((l+r)/2, r, sl, sr, k*2+2);
return min(h_1, h_2);
}
void Show(){
cout << trsize << endl;
rep(i, trsize) cout << a[i] << " ";
cout << endl;
}
private:
};
int main(){
int n;
cin >> n;
vector<int> a(n);
rep(i, n){
cin >> a[i];
}
SegTree st(a);
st.Show();
cout << st.search(0,3) << endl;
cout << st.search(1,2) << endl;
cout << st.search(6,8) << endl;
cout << st.search(0,8) << endl;
return 0;
}
/*
init
data列のサイズを調べる
2の累乗でギリギリこえるとこまで確保
size/2 からpushする。
size/2-1から0まで順番に求めていく
update
子、親をたどって更新する
search
区間を指定する
*/
|
#include "InputListener.h"
namespace WGF
{
InputListener::InputListener()
{
//ctor
}
InputListener::~InputListener()
{
//dtor
}
} // namespace WGF
|
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
myfile ifstream;
enum CarMake{ Audi, Chrysler, Honda, Ford, Porche, Nissan, Lexus, Volvo, Mercedes};
struct Date
{
int day;
int month;
int year;
};
struct Car
{
string fname;
string lname;
double cost;
struct Date date_delivery;
CarMake make;
};
struct Car Get_car_data(ifstream &infile)
{
struct Car c;
char cmake;
infile >> c.first_name;
infile >> c.last_name;
infile >> c.cost;
infile >> c.date_delivery.day;
infile >> c.date_delivery.month;
infile >> c.date_delivery.year;
infile >> cmake;
switch(cmake)
{
case 'F':
c.make = Ford;
break;
case 'L':
c.make = Lexus;
break;
case 'N':
c.make = Nissan;
break;
case 'M':
c.make = Mercedes;
break;
case 'H':
c.make = Honda;
break;
case 'A':
c.make = Audi;
break;
case 'C':
c.make = Chrysler;
break;
case 'V':
c.make = Volvo;
break;
case 'P':
c.make = Porche;
break;
}
return c;
}
void Modify_Car_data(struct Car* c, float disc)
{
cout<<"\nOld Price: $"<<c->cost<<endl;
float discount = c->cost*disc;
c->cost = c->cost- discount;
cout<<"New Price: $"<<c->cost<<endl;
cout<<disc*100<<"% Discount has been applied"<<endl<<endl;
}
void Lookup_car(struct Car* cl, int cars_cnt, char cmake)
{
string cms[10]={"Audi", "Chrysler", "Honda","Ford", "Porche",
"Nissan","Lexus", "Volvo", "Mercedes"};
CarMake cm;
switch(cmake)
{
case 'F':
cm = Ford;
break;
case 'L':
cm = Lexus;
break;
case 'N':
cm = Nissan;
break;
case 'M':
cm = Mercedes;
break;
case 'H':
cm = Honda;
break;
case 'A':
cm = Audi;
break;
case 'C':
cm = Chrysler;
break;
case 'V':
cm = Volvo;
break;
case 'P':
cm = Porche;
break;
}
cout<<"\n\nYou are modifying: ";
for(int i=0; i<cars_cnt; i++, cl++)
{
if( cl->make == cm)
{
float disc;
cout<<"\n\tCustomer Name: "<< cl->first_name<<" "<< cl->last_name;
cout<<"\n\tCar Price: $"<<cl->cost;
cout<<"\n\tPurchase Date: "<<cl->dod.day<<"/"
<<cl->dod.month<<"/"<<cl->dod.year;
cout<<"\n\tCar Model: "<<cms[(int)cl->make]<<endl;
cout<<"Enter the disocunt (e.g 0.10 = 10%): ";
cin>>disc;
Modify_Car_data(cl, disc);
break;
}
}
}
void Print_Car_Report(struct Car *cl, int c_count)
{
string cm[10]={ "Audi", "Chrysler", "Honda","Ford", "Porche",
"Nissan","Lexus", "Volvo", "Mercedes"};
cout<<"\n====== Cars Detail ======="<<endl;
cout<<"\nCustomer \t Price \t\t Purchase \t Model\n";
cout<<" Name \t \t\t Date \t "<<endl;
cout<<"-----------------------------------------------------------\n";
for( int i=0; i<c_count; i++, cl++)
{
cout<<cl->first_name<<" "<< cl->last_name;
cout<<"\t"<<setw(7)<<cl->cost;
cout<<setw(10)<<cl->dod.day<<"/"<<cl->dod.month<<"/"<<cl->dod.year;
cout<<setw(15)<<cm[(int)cl->make]<<endl;
}
}
void Write_Car_Output(struct Car *cl, int c_count, string fn)
{
string cm[10]={ "Audi", "Chrysler", "Honda", "Ford", "Porche",
"Nissan","Lexus", "Volvo", "Mercedes"};
ofstream of(fn);
of<<"\nCustomer \t Price \t\t Purchase \t Model\n";
of<<" Name \t \t\t Date \t "<<endl;
of<<"-----------------------------------------------------------\n";
for( int i=0; i<c_count; i++, cl++)
{
of<<cl->first_name<<" "<< cl->last_name;
of<<"\t"<<setw(7)<<cl->cost;
of<<setw(10)<<cl->dod.day<<"/"<<cl->dod.month<<"/"<<cl->dod.year;
of<<setw(15)<<cm[(int)cl->make]<<endl;
}
of.close();
}
void Output_car_data(struct Car *cl, int c_count, string fn)
{
Print_Car_Report(cl, c_count);
Write_Car_Output(cl, c_count, fn);
}
int main()
{
struct Car cars[20];
int cars_cnt=0;
ifstream car_data_file("Car_data.txt");
int i=0;
char ch = 'Y';
char cmake;
string Codes[9]={"F - Ford"," L - Lexus"," N - Nissan",
" M - Mercedes","H - Honda"," A - Audi","C - Chrysler"," V - Volvo"," P - Porche"};
while( !car_data_file.eof())
{
cars[cars_cnt] = Get_car_data(car_data_file);
cars_cnt++;
}
while(ch!='N' && ch!='n')
{
cout<<"Choose form the list of car manufacturers below."<<endl;
cout<<"\t(";
for(int i=0;i<9;i++)
{
if(i%3==0)
cout<<endl<<"\t";
if(i==8)
cout<<Codes[i]<<")"<<endl;
else
{
cout<<Codes[i]<<", ";
}
}
cout<<endl;
cout<<"\nEnter the make of the car you wish to discount: ";
cin>>cmake;
Lookup_car(cars, cars_cnt-1, cmake);
cout<<"Do you want to modify another car: ";
cin>>ch;
}
Output_car_data(cars, cars_cnt-1, "Car_Discount_Data.txt");
system("pause");
return 0;
}
|
// Helena Ruiz Ramirez
// A01282531
// Enero 11, 2018
// Strings: Ejercicio 1
// Programa que checa si una frase es palindromo o no
#include <iostream>
#include <string>
#include <locale>
using namespace std;
int main() {
long l,s;
bool estado=true;
string frase;
cout<<"Frase: ";
getline(cin,frase);
cout<<endl;
while (frase.find(" ")!= -1) {
s=frase.find(" ");
frase.erase(s,1);
}
cout<<frase<<endl;
l=frase.length();
for (int i=0;(i<(l/2))&&(estado);i++) {
if (toupper(frase[i])!=toupper(frase[l-1-i])) {
estado=false;
cout<< "No es un palindromo."<<endl;
}
}
if (estado==true){
cout<<"Si es palindromo."<<endl;
}
cout<<endl;
return 0;
}
|
#pragma once
#include "Scene/SceneComponentDef.h"
#include "Utils/Hashing.h"
#include <typeindex>
namespace Rocket
{
Interface SceneComponent
{
public:
SceneComponent();
SceneComponent(SceneComponent&& other) = default;
virtual ~SceneComponent() = default;
virtual std::type_index GetType() = 0;
const uint64_t GetId() const { return m_Id; }
protected:
uint64_t m_Id;
};
std::ostream& operator<<(std::ostream& out, SceneComponent& com);
#define COMPONENT(x) std::type_index GetType() final { return typeid(x); }
}
|
#include "qscenegraph.h"
namespace qEngine
{
qSceneGraph::qSceneGraph(void) : is2D(false)
{
m_spViewport.reset(new qViewport());
}
qSceneGraph::~qSceneGraph(void)
{
}
bool qSceneGraph::init(boost::shared_ptr<qConfigManager> spCM)
{
//Viewport Setup
m_spViewport->getValuesFromCM(spCM);
return true;
}
void qSceneGraph::set2D()
{
if (is2D) return;
m_spViewport->setOrthoViewport();
}
void qSceneGraph::set3D()
{
if (!is2D) return;
m_spViewport->setProjViewport();
}
}
|
#include "Node.h"
template <class T>
Node<T>::Node()
{
}
template <class T>
Node<T>::Node(const T* item, Node<T>* ptrNext = nullptr)
:data(item), next(ptrNext)
{
}
template <class T>
void Node<T>::InsertAfter(Node<T>* p)
{
p->next = this.next;
this.next = p;
}
template <class T>
Node<T>* Node<T>::Delete()
{
//Copy the data for current node that will be deleted
Node<T>* toDelete = this;
//Transfer the data and next node from the node after one to delete
this->data = this->next->data;
this->next = this->next->next;
//Delete the old next node
delete toDelete->next;
return toDelete;
}
|
#include <iostream>
#include<string.h>
using namespace std;
/*Bài 2: Viết hàm nhận vào một chuỗi và trả về chuỗi tương ứng (giữ nguyên chuỗi đầu vào):
Các ký tự thành ký tự thường (giống strlwr).
Các ký tự thành ký tự hoa (giống strupr).
Các ký tự đầu tiên mỗi từ thành ký tự hoa.
Chuẩn hóa chuỗi (xóa khoảng trắng thừa).
*/
char* Thuong(char *chuoi)
{
char *Mangnew=strdup(chuoi);
int Length=strlen(Mangnew);
for(int i=0;i<Length;i++)
{
if(Mangnew[i]>='A'&&Mangnew[i]<='Z')
{
Mangnew[i]+=32;
}
}
// Mangnew[Length]='\0';
return Mangnew;//<=>&mangnew[0]
}
int main()
{
char ChuoiBanDau[]="Nguyen Minh Vuong";
cout<<"\n Chuoi Thuong :"<<Thuong(ChuoiBanDau);
cout<<"\n Chuoi Ban dau :"<<ChuoiBanDau;
return 0;
}
|
// Created on: 2016-04-19
// Copyright (c) 2016 OPEN CASCADE SAS
// Created by: Oleg AGASHIN
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepMesh_Deflection_HeaderFile
#define _BRepMesh_Deflection_HeaderFile
#include <Standard_Handle.hxx>
#include <Standard_Transient.hxx>
#include <IMeshData_Types.hxx>
struct IMeshTools_Parameters;
//! Auxiliary tool encompassing methods to compute deflection of shapes.
class BRepMesh_Deflection : public Standard_Transient
{
public:
//! Returns absolute deflection for theShape with respect to the
//! relative deflection and theMaxShapeSize.
//! @param theShape shape for that the deflection should be computed.
//! @param theRelativeDeflection relative deflection.
//! @param theMaxShapeSize maximum size of the whole shape.
//! @return absolute deflection for the shape.
Standard_EXPORT static Standard_Real ComputeAbsoluteDeflection (
const TopoDS_Shape& theShape,
const Standard_Real theRelativeDeflection,
const Standard_Real theMaxShapeSize);
//! Computes and updates deflection of the given discrete edge.
Standard_EXPORT static void ComputeDeflection (
const IMeshData::IEdgeHandle& theDEdge,
const Standard_Real theMaxShapeSize,
const IMeshTools_Parameters& theParameters);
//! Computes and updates deflection of the given discrete wire.
Standard_EXPORT static void ComputeDeflection (
const IMeshData::IWireHandle& theDWire,
const IMeshTools_Parameters& theParameters);
//! Computes and updates deflection of the given discrete face.
Standard_EXPORT static void ComputeDeflection (
const IMeshData::IFaceHandle& theDFace,
const IMeshTools_Parameters& theParameters);
//! Checks if the deflection of current polygonal representation
//! is consistent with the required deflection.
//! @param theCurrent [in] Current deflection.
//! @param theRequired [in] Required deflection.
//! @param theAllowDecrease [in] Flag controlling the check. If decrease is allowed,
//! to be consistent the current and required deflections should be approximately the same.
//! If not allowed, the current deflection should be less than required.
//! @param theRatio [in] The ratio for comparison of the deflections (value from 0 to 1).
Standard_EXPORT static Standard_Boolean IsConsistent (
const Standard_Real theCurrent,
const Standard_Real theRequired,
const Standard_Boolean theAllowDecrease,
const Standard_Real theRatio = 0.1);
DEFINE_STANDARD_RTTIEXT(BRepMesh_Deflection, Standard_Transient)
};
#endif
|
#define BLYNK_PRINT Serial // command to print serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
//#include <LiquidCrystal.h>
//LiquidCrystal lcd(D0, D1, D2, D3, D4, D5);
//char auth[] = "71d6ec249b964833bb5026428bc8f5a8";////add token here SME
char auth[] = "lw4FeajDCd3gUAlkQIGjeW059EQkD065"; //
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Redmi";
char pass[] = "12345678";
int device1 = D2, device2 = D7 , device3 = D5, device4 = D6;
BLYNK_WRITE(V1)
{
int device1_VAL = param.asInt(); // assigning incoming value from pin V1 to a variable
if(device1_VAL == HIGH)
{
digitalWrite(device1,HIGH);
Serial.println("device1 is turning on");
}
if(device1_VAL == LOW)
{
digitalWrite(device1,LOW);
Serial.println("device1 is turning off");
}
}
BLYNK_WRITE(V2)
{
int device2_VAL = param.asInt(); // assigning incoming value from pin V1 to a variable
if(device2_VAL == HIGH)
{
// lcd.clear();
digitalWrite(device2,HIGH);
Serial.println("device2 is turning on");
// lcd.setCursor(0,1);
// lcd.print("Device2 ON");
}
if(device2_VAL == LOW)
{
// lcd.clear();
digitalWrite(device2,LOW);
Serial.println("device2 is turning off");
// lcd.setCursor(0,1);
// lcd.print("Device2 OFF");
}
}
BLYNK_WRITE(V3)
{
int device3_VAL = param.asInt(); // assigning incoming value from pin V1 to a variable
if(device3_VAL == HIGH)
{
// lcd.clear();
digitalWrite(device3,HIGH);
Serial.println("device3 is turning on");
// lcd.setCursor(0,1);
// lcd.print("Device2 ON");
}
if(device3_VAL == LOW)
{
// lcd.clear();
digitalWrite(device3,LOW);
Serial.println("device3 is turning off");
// lcd.setCursor(0,1);
// lcd.print("Device2 OFF");
}
}
BLYNK_WRITE(V4)
{
int device4_VAL = param.asInt(); // assigning incoming value from pin V1 to a variable
if(device4_VAL == HIGH)
{
// lcd.clear();
digitalWrite(device4,HIGH);
Serial.println("device4 is turning on");
// lcd.setCursor(0,1);
// lcd.print("Device2 ON");
}
if(device4_VAL == LOW)
{
// lcd.clear();
digitalWrite(device4,LOW);
Serial.println("device4 is turning off");
// lcd.setCursor(0,1);
// lcd.print("Device2 OFF");
}
}
void setup()
{
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
delay(3000);
pinMode(device1,OUTPUT);
pinMode(device2,OUTPUT);
pinMode(device3,OUTPUT);
pinMode(device4,OUTPUT);
digitalWrite(device1,LOW);
digitalWrite(device2,LOW);
digitalWrite(device3,LOW);
digitalWrite(device4,LOW);
}
void loop()
{
Blynk.run();
}
|
#include "Menu.h"
Menu::Menu()
{
Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 1024);
soundtrack = Mix_LoadMUS("../../res/au/Pac-Man-Theme-Song.mp3");
Mix_VolumeMusic(MIX_MAX_VOLUME/10);
Mix_PlayMusic(soundtrack, -1);
playButton = Button(PLAY_BUTTON::ID, PLAY_BUTTON::HOVER_ID, PLAY_BUTTON::X, PLAY_BUTTON::Y, PLAY_BUTTON::W, PLAY_BUTTON::H);
soundButton = Button(SOUND_BUTTON::ID, SOUND_BUTTON::HOVER_ID, SOUND_BUTTON::X, SOUND_BUTTON::Y, SOUND_BUTTON::W, SOUND_BUTTON::H);
rankingButton = Button(RANKING_BUTTON::ID, RANKING_BUTTON::HOVER_ID, RANKING_BUTTON::X, RANKING_BUTTON::Y, RANKING_BUTTON::W, RANKING_BUTTON::H);
exitButton = Button(EXIT_BUTTON::ID, EXIT_BUTTON::HOVER_ID, EXIT_BUTTON::X, EXIT_BUTTON::Y, EXIT_BUTTON::W, EXIT_BUTTON::H);
state = SceneStates::WAITING_MENU;
}
void Menu::Update(bool * _keys, Vec2 _mousePosition)
{
switch (state)
{
case WAITING_MENU:
playButton.Update(_keys[(int)InputKey::K_MOUSE], _mousePosition);
soundButton.Update(_keys[(int)InputKey::K_MOUSE], _mousePosition);
rankingButton.Update(_keys[(int)InputKey::K_MOUSE], _mousePosition);
exitButton.Update(_keys[(int)InputKey::K_MOUSE], _mousePosition);
if (playButton.isPressed) state = SceneStates::PLAY_MENU;
else if (rankingButton.isPressed) state = SceneStates::RANKING_MENU;
else if (soundButton.isPressed)
{
if (Mix_PlayingMusic())
{
Mix_HaltMusic();
}
else
{
Mix_PlayMusic(soundtrack, -1);
}
}
else if (exitButton.isPressed) state = SceneStates::EXIT_MENU;
break;
case PLAY_MENU:
break;
case RANKING_MENU:
break;
case EXIT_MENU:
break;
default:
break;
}
}
PlayerRankingInfo Menu::GetPlayerRankingInfo()
{
return { NULL, NULL };
}
void Menu::Draw()
{
Renderer::Instance()->Clear();
Renderer::Instance()->SetRendreDrawColor(0, 0, 0);
playButton.Draw();
soundButton.Draw();
rankingButton.Draw();
exitButton.Draw();
Renderer::Instance()->Render();
}
Menu::~Menu()
{
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "WalletLegacy.h"
#include <algorithm>
#include <numeric>
#include <random>
#include <set>
#include <tuple>
#include <utility>
#include <numeric>
#include <string.h>
#include <time.h>
#include "crypto/crypto.h"
#include "Common/Base58.h"
#include "Common/ShuffleGenerator.h"
#include "Logging/ConsoleLogger.h"
#include "WalletLegacy/WalletHelper.h"
#include "WalletLegacy/WalletLegacySerialization.h"
#include "WalletLegacy/WalletLegacySerializer.h"
#include "WalletLegacy/WalletUtils.h"
#include "Common/StringTools.h"
#include "CryptoNoteCore/CryptoNoteTools.h"
#include "CryptoNoteConfig.h"
using namespace crypto;
namespace {
const uint64_t ACCOUN_CREATE_TIME_ACCURACY = 24 * 60 * 60;
void throwNotDefined() {
throw std::runtime_error("The behavior is not defined!");
}
class ContextCounterHolder
{
public:
ContextCounterHolder(cn::WalletAsyncContextCounter& shutdowner) : m_shutdowner(shutdowner) {}
~ContextCounterHolder() { m_shutdowner.delAsyncContext(); }
private:
cn::WalletAsyncContextCounter& m_shutdowner;
};
template <typename F>
void runAtomic(std::mutex& mutex, F f) {
std::unique_lock<std::mutex> lock(mutex);
f();
}
class InitWaiter : public cn::IWalletLegacyObserver {
public:
InitWaiter() : future(promise.get_future()) {}
virtual void initCompleted(std::error_code result) override {
promise.set_value(result);
}
std::error_code waitInit() {
return future.get();
}
private:
std::promise<std::error_code> promise;
std::future<std::error_code> future;
};
class SaveWaiter : public cn::IWalletLegacyObserver {
public:
SaveWaiter() : future(promise.get_future()) {}
virtual void saveCompleted(std::error_code result) override {
promise.set_value(result);
}
std::error_code waitSave() {
return future.get();
}
private:
std::promise<std::error_code> promise;
std::future<std::error_code> future;
};
uint64_t calculateDepositsAmount(const std::vector<cn::TransactionOutputInformation>& transfers, const cn::Currency& currency, const std::vector<uint32_t> heights) {
int index = 0;
return std::accumulate(transfers.begin(), transfers.end(), static_cast<uint64_t>(0), [¤cy, &index, heights] (uint64_t sum, const cn::TransactionOutputInformation& deposit) {
if (deposit.term % 64800 != 0)
{
return sum + deposit.amount + currency.calculateInterest(deposit.amount, deposit.term, heights[index++]);
}
else
{
return sum;
}
});
}
uint64_t calculateInvestmentsAmount(const std::vector<cn::TransactionOutputInformation>& transfers, const cn::Currency& currency, const std::vector<uint32_t> heights) {
int index = 0;
return std::accumulate(transfers.begin(), transfers.end(), static_cast<uint64_t>(0), [¤cy, &index, heights] (uint64_t sum, const cn::TransactionOutputInformation& deposit) {
if (deposit.term % 64800 == 0)
{
return sum + deposit.amount + currency.calculateInterest(deposit.amount, deposit.term, heights[index++]);
}
else
{
return sum;
}
});
}
} //namespace
namespace cn {
class SyncStarter : public cn::IWalletLegacyObserver {
public:
SyncStarter(BlockchainSynchronizer& sync) : m_sync(sync) {}
virtual ~SyncStarter() {}
virtual void initCompleted(std::error_code result) override {
if (!result) {
m_sync.start();
}
}
BlockchainSynchronizer& m_sync;
};
WalletLegacy::WalletLegacy(const cn::Currency& currency, INode& node, logging::ILogger& loggerGroup, bool testnet) :
m_state(NOT_INITIALIZED),
m_currency(currency),
m_node(node),
m_loggerGroup(loggerGroup),
m_isStopping(false),
m_lastNotifiedActualBalance(0),
m_lastNotifiedPendingBalance(0),
m_lastNotifiedActualDepositBalance(0),
m_lastNotifiedPendingDepositBalance(0),
m_lastNotifiedActualInvestmentBalance(0),
m_lastNotifiedPendingInvestmentBalance(0),
m_blockchainSync(node, currency.genesisBlockHash()),
m_transfersSync(currency, m_loggerGroup, m_blockchainSync, node),
m_transferDetails(nullptr),
m_transactionsCache(m_currency.mempoolTxLiveTime()),
m_sender(nullptr),
m_onInitSyncStarter(new SyncStarter(m_blockchainSync)),
m_testnet(testnet)
{
addObserver(m_onInitSyncStarter.get());
}
WalletLegacy::~WalletLegacy() {
removeObserver(m_onInitSyncStarter.get());
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
if (m_state != NOT_INITIALIZED) {
m_sender->stop();
m_isStopping = true;
}
}
m_blockchainSync.removeObserver(this);
m_blockchainSync.stop();
m_asyncContextCounter.waitAsyncContextsFinish();
m_sender.release();
}
void WalletLegacy::addObserver(IWalletLegacyObserver* observer) {
m_observerManager.add(observer);
}
void WalletLegacy::removeObserver(IWalletLegacyObserver* observer) {
m_observerManager.remove(observer);
}
void WalletLegacy::initAndGenerate(const std::string& password) {
{
std::unique_lock<std::mutex> stateLock(m_cacheMutex);
if (m_state != NOT_INITIALIZED) {
throw std::system_error(make_error_code(error::ALREADY_INITIALIZED));
}
m_account.generate();
m_password = password;
initSync();
}
m_observerManager.notify(&IWalletLegacyObserver::initCompleted, std::error_code());
}
void WalletLegacy::initWithKeys(const AccountKeys& accountKeys, const std::string& password) {
{
std::unique_lock<std::mutex> stateLock(m_cacheMutex);
if (m_state != NOT_INITIALIZED) {
throw std::system_error(make_error_code(error::ALREADY_INITIALIZED));
}
m_account.setAccountKeys(accountKeys);
m_account.set_createtime(ACCOUN_CREATE_TIME_ACCURACY);
m_password = password;
initSync();
}
m_observerManager.notify(&IWalletLegacyObserver::initCompleted, std::error_code());
}
void WalletLegacy::initAndLoad(std::istream& source, const std::string& password) {
std::unique_lock<std::mutex> stateLock(m_cacheMutex);
if (m_state != NOT_INITIALIZED) {
throw std::system_error(make_error_code(error::ALREADY_INITIALIZED));
}
m_password = password;
m_state = LOADING;
m_asyncContextCounter.addAsyncContext();
std::thread loader(&WalletLegacy::doLoad, this, std::ref(source));
loader.detach();
}
void WalletLegacy::initSync() {
AccountSubscription sub;
sub.keys = reinterpret_cast<const AccountKeys&>(m_account.getAccountKeys());
sub.transactionSpendableAge = cn::parameters::CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE;
sub.syncStart.height = 0;
sub.syncStart.timestamp = m_account.get_createtime() - ACCOUN_CREATE_TIME_ACCURACY;
auto& subObject = m_transfersSync.addSubscription(sub);
m_transferDetails = &subObject.getContainer();
subObject.addObserver(this);
m_sender.reset(new WalletTransactionSender(m_currency, m_transactionsCache, m_account.getAccountKeys(), *m_transferDetails, m_node, m_testnet));
m_state = INITIALIZED;
m_blockchainSync.addObserver(this);
}
void WalletLegacy::doLoad(std::istream& source) {
ContextCounterHolder counterHolder(m_asyncContextCounter);
try {
std::unique_lock<std::mutex> lock(m_cacheMutex);
std::string cache;
WalletLegacySerializer serializer(m_account, m_transactionsCache);
serializer.deserialize(source, m_password, cache);
initSync();
try {
if (!cache.empty()) {
std::stringstream stream(cache);
m_transfersSync.load(stream);
}
} catch (const std::exception& e) {
// TODO Make this pass through file log at some point
// ignore cache loading errors
std::cout << "Exception during loading cache: " << e.what() << std::endl;
}
// Read all output keys cache
std::vector<TransactionOutputInformation> allTransfers;
m_transferDetails->getOutputs(allTransfers, ITransfersContainer::IncludeAll);
std::cout << "Loaded " + std::to_string(allTransfers.size()) + " known transfer(s)\r\n";
for (auto& o : allTransfers) {
if (o.type == transaction_types::OutputType::Key) {
m_transfersSync.addPublicKeysSeen(m_account.getAccountKeys().address, o.transactionHash, o.outputKey);
}
}
} catch (std::system_error& e) {
runAtomic(m_cacheMutex, [this] () {this->m_state = WalletLegacy::NOT_INITIALIZED;} );
m_observerManager.notify(&IWalletLegacyObserver::initCompleted, e.code());
return;
} catch (std::exception&) {
runAtomic(m_cacheMutex, [this] () {this->m_state = WalletLegacy::NOT_INITIALIZED;} );
m_observerManager.notify(&IWalletLegacyObserver::initCompleted, make_error_code(cn::error::INTERNAL_WALLET_ERROR));
return;
}
m_observerManager.notify(&IWalletLegacyObserver::initCompleted, std::error_code());
}
void WalletLegacy::shutdown() {
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
if (m_isStopping)
throwNotDefined();
m_isStopping = true;
if (m_state != INITIALIZED)
throwNotDefined();
m_sender->stop();
}
m_blockchainSync.removeObserver(this);
m_blockchainSync.stop();
m_asyncContextCounter.waitAsyncContextsFinish();
m_sender.release();
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
m_isStopping = false;
m_state = NOT_INITIALIZED;
const auto& accountAddress = m_account.getAccountKeys().address;
auto subObject = m_transfersSync.getSubscription(accountAddress);
assert(subObject != nullptr);
subObject->removeObserver(this);
m_transfersSync.removeSubscription(accountAddress);
m_transferDetails = nullptr;
m_transactionsCache.reset();
m_lastNotifiedActualBalance = 0;
m_lastNotifiedPendingBalance = 0;
}
}
void WalletLegacy::reset() {
try {
std::error_code saveError;
std::stringstream ss;
{
SaveWaiter saveWaiter;
WalletHelper::IWalletRemoveObserverGuard saveGuarantee(*this, saveWaiter);
save(ss, false, false);
saveError = saveWaiter.waitSave();
}
if (!saveError) {
shutdown();
InitWaiter initWaiter;
WalletHelper::IWalletRemoveObserverGuard initGuarantee(*this, initWaiter);
initAndLoad(ss, m_password);
initWaiter.waitInit();
}
} catch (std::exception& e) {
std::cout << "exception in reset: " << e.what() << std::endl;
}
}
std::vector<Payments> WalletLegacy::getTransactionsByPaymentIds(const std::vector<PaymentId>& paymentIds) const {
return m_transactionsCache.getTransactionsByPaymentIds(paymentIds);
}
void WalletLegacy::save(std::ostream& destination, bool saveDetailed, bool saveCache) {
if(m_isStopping) {
m_observerManager.notify(&IWalletLegacyObserver::saveCompleted, make_error_code(cn::error::OPERATION_CANCELLED));
return;
}
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIf(m_state != INITIALIZED, cn::error::WRONG_STATE);
m_state = SAVING;
}
m_asyncContextCounter.addAsyncContext();
std::thread saver(&WalletLegacy::doSave, this, std::ref(destination), saveDetailed, saveCache);
saver.detach();
}
void WalletLegacy::doSave(std::ostream& destination, bool saveDetailed, bool saveCache) {
ContextCounterHolder counterHolder(m_asyncContextCounter);
try {
m_blockchainSync.stop();
std::unique_lock<std::mutex> lock(m_cacheMutex);
WalletLegacySerializer serializer(m_account, m_transactionsCache);
std::string cache;
if (saveCache) {
std::stringstream stream;
m_transfersSync.save(stream);
cache = stream.str();
}
serializer.serialize(destination, m_password, saveDetailed, cache);
m_state = INITIALIZED;
m_blockchainSync.start(); //XXX: start can throw. what to do in this case?
}
catch (std::system_error& e) {
runAtomic(m_cacheMutex, [this] () {this->m_state = WalletLegacy::INITIALIZED;} );
m_observerManager.notify(&IWalletLegacyObserver::saveCompleted, e.code());
return;
}
catch (std::exception&) {
runAtomic(m_cacheMutex, [this] () {this->m_state = WalletLegacy::INITIALIZED;} );
m_observerManager.notify(&IWalletLegacyObserver::saveCompleted, make_error_code(cn::error::INTERNAL_WALLET_ERROR));
return;
}
m_observerManager.notify(&IWalletLegacyObserver::saveCompleted, std::error_code());
}
std::error_code WalletLegacy::changePassword(const std::string& oldPassword, const std::string& newPassword) {
std::unique_lock<std::mutex> passLock(m_cacheMutex);
throwIfNotInitialised();
if (m_password.compare(oldPassword))
return make_error_code(cn::error::WRONG_PASSWORD);
//we don't let the user to change the password while saving
m_password = newPassword;
return std::error_code();
}
std::string WalletLegacy::getAddress() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_currency.accountAddressAsString(m_account);
}
uint64_t WalletLegacy::actualBalance() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return calculateActualBalance();
}
uint64_t WalletLegacy::pendingBalance() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return calculatePendingBalance();
}
uint64_t WalletLegacy::actualDepositBalance() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return calculateActualDepositBalance();
}
uint64_t WalletLegacy::actualInvestmentBalance() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return calculateActualInvestmentBalance();
}
uint64_t WalletLegacy::pendingInvestmentBalance() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return calculatePendingInvestmentBalance();
}
uint64_t WalletLegacy::pendingDepositBalance() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return calculatePendingDepositBalance();
}
size_t WalletLegacy::getTransactionCount() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_transactionsCache.getTransactionCount();
}
size_t WalletLegacy::getTransferCount() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_transactionsCache.getTransferCount();
}
size_t WalletLegacy::getDepositCount() {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_transactionsCache.getDepositCount();
}
TransactionId WalletLegacy::findTransactionByTransferId(TransferId transferId) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_transactionsCache.findTransactionByTransferId(transferId);
}
bool WalletLegacy::getTransaction(TransactionId transactionId, WalletLegacyTransaction& transaction) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_transactionsCache.getTransaction(transactionId, transaction);
}
bool WalletLegacy::getTransfer(TransferId transferId, WalletLegacyTransfer& transfer) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_transactionsCache.getTransfer(transferId, transfer);
}
bool WalletLegacy::getDeposit(DepositId depositId, Deposit& deposit) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
return m_transactionsCache.getDeposit(depositId, deposit);
}
size_t WalletLegacy::getNumUnlockedOutputs() {
std::vector<TransactionOutputInformation> outputs;
m_transferDetails->getOutputs(outputs, ITransfersContainer::IncludeKeyUnlocked);
return outputs.size();
}
std::vector<TransactionOutputInformation> WalletLegacy::getUnspentOutputs() {
std::vector<TransactionOutputInformation> outputs;
m_transferDetails->getOutputs(outputs, ITransfersContainer::IncludeKeyUnlocked);
return outputs;
}
TransactionId WalletLegacy::sendTransaction(crypto::SecretKey& transactionSK,
const WalletLegacyTransfer& transfer,
uint64_t fee,
const std::string& extra,
uint64_t mixIn,
uint64_t unlockTimestamp,
const std::vector<TransactionMessage>& messages,
uint64_t ttl) {
std::vector<WalletLegacyTransfer> transfers;
transfers.push_back(transfer);
throwIfNotInitialised();
return sendTransaction(transactionSK, transfers, fee, extra, mixIn, unlockTimestamp, messages, ttl);
}
TransactionId WalletLegacy::sendTransaction(crypto::SecretKey& transactionSK,
std::vector<WalletLegacyTransfer>& transfers,
uint64_t fee,
const std::string& extra,
uint64_t mixIn,
uint64_t unlockTimestamp,
const std::vector<TransactionMessage>& messages,
uint64_t ttl)
{
/* Regular transaction fees should be at least 1000 X as of Consensus 2019. In this case we also check
to ensure that it is not a self-destructive message, which will have a TTL that
is larger than 0 */
if (ttl == 0)
{
fee = cn::parameters::MINIMUM_FEE_V2;
}
/* This is the logic that determins if it is an optimization transaction */
bool optimize = false;
if (transfers.empty())
{
cn::WalletLegacyTransfer transfer;
transfer.address = getAddress();
transfer.amount = 0;
transfers.push_back(transfer);
optimize = true;
fee = cn::parameters::MINIMUM_FEE_V2;
}
TransactionId txId = 0;
std::unique_ptr<WalletRequest> request;
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
throwIfNotInitialised();
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
request = m_sender->makeSendRequest(transactionSK, optimize, txId, events, transfers, fee, extra, mixIn, unlockTimestamp, messages, ttl);
}
notifyClients(events);
if (request) {
m_asyncContextCounter.addAsyncContext();
request->perform(m_node, std::bind(&WalletLegacy::sendTransactionCallback, this, std::placeholders::_1, std::placeholders::_2));
}
return txId;
}
size_t WalletLegacy::estimateFusion(const uint64_t& threshold) {
size_t fusionReadyCount = 0;
std::vector<TransactionOutputInformation> outputs;
m_transferDetails->getOutputs(outputs, ITransfersContainer::IncludeKeyUnlocked);
std::array<size_t, std::numeric_limits<uint64_t>::digits10 + 1> bucketSizes;
bucketSizes.fill(0);
for (auto& out : outputs) {
uint8_t powerOfTen = 0;
if (m_currency.isAmountApplicableInFusionTransactionInput(out.amount, threshold, powerOfTen, m_node.getLastKnownBlockHeight()))
{
assert(powerOfTen < std::numeric_limits<uint64_t>::digits10 + 1);
bucketSizes[powerOfTen]++;
}
}
for (auto bucketSize : bucketSizes) {
if (bucketSize >= m_currency.fusionTxMinInputCount()) {
fusionReadyCount += bucketSize;
}
}
return fusionReadyCount;
}
uint64_t WalletLegacy::getWalletMaximum()
{
uint64_t foundMoney = 0;
/** Get all the unlocked outputs from the wallet */
std::vector<TransactionOutputInformation> outputs;
m_transferDetails->getOutputs(outputs, ITransfersContainer::IncludeKeyUnlocked);
/** Split the inputs into buckets based on what power of ten they are in
* (For example, [1, 2, 5, 7], [20, 50, 80, 80], [100, 600, 700]), though
* we will ignore dust for the time being. */
std::unordered_map<uint64_t, std::vector<TransactionOutputInformation>> buckets;
for (const auto &walletAmount : outputs)
{
/** Use the number of digits to determine which buck they fit in */
int numberOfDigits = floor(log10(walletAmount.amount)) + 1;
/** If the amount is larger than the current dust threshold
* insert the amount into the correct bucket */
if (walletAmount.amount > 10)
{
buckets[numberOfDigits].push_back(walletAmount);
}
}
while (!buckets.empty())
{
/* Take one element from each bucket, smallest first. */
for (auto bucket = buckets.begin(); bucket != buckets.end();)
{
/* Bucket has been exhausted, remove from list */
if (bucket->second.empty())
{
bucket = buckets.erase(bucket);
}
else
{
foundMoney += bucket->second.back().amount;
/* Remove amount we just added */
bucket->second.pop_back();
bucket++;
}
}
}
return foundMoney;
}
std::list<TransactionOutputInformation> WalletLegacy::selectFusionTransfersToSend(uint64_t threshold, size_t minInputCount, size_t maxInputCount) {
std::list<TransactionOutputInformation> selectedOutputs;
std::vector<TransactionOutputInformation> outputs;
std::vector<TransactionOutputInformation> allFusionReadyOuts;
m_transferDetails->getOutputs(outputs, ITransfersContainer::IncludeKeyUnlocked);
std::array<size_t, std::numeric_limits<uint64_t>::digits10 + 1> bucketSizes;
bucketSizes.fill(0);
for (auto& out : outputs) {
uint8_t powerOfTen = 0;
allFusionReadyOuts.push_back(std::move(out));
assert(powerOfTen < std::numeric_limits<uint64_t>::digits10 + 1);
bucketSizes[powerOfTen]++;
}
//now, pick the bucket
std::vector<uint8_t> bucketNumbers(bucketSizes.size());
std::iota(bucketNumbers.begin(), bucketNumbers.end(), 0);
std::shuffle(bucketNumbers.begin(), bucketNumbers.end(), std::default_random_engine{ crypto::rand<std::default_random_engine::result_type>() });
size_t bucketNumberIndex = 0;
for (; bucketNumberIndex < bucketNumbers.size(); ++bucketNumberIndex) {
if (bucketSizes[bucketNumbers[bucketNumberIndex]] >= minInputCount) {
break;
}
}
if (bucketNumberIndex == bucketNumbers.size()) {
return {};
}
size_t selectedBucket = bucketNumbers[bucketNumberIndex];
assert(selectedBucket < std::numeric_limits<uint64_t>::digits10 + 1);
assert(bucketSizes[selectedBucket] >= minInputCount);
uint64_t lowerBound = 1;
for (size_t i = 0; i < selectedBucket; ++i) {
lowerBound *= 10;
}
uint64_t upperBound = selectedBucket == std::numeric_limits<uint64_t>::digits10 ? UINT64_MAX : lowerBound * 10;
std::vector<TransactionOutputInformation> selectedOuts;
selectedOuts.reserve(bucketSizes[selectedBucket]);
for (size_t outIndex = 0; outIndex < allFusionReadyOuts.size(); ++outIndex) {
if (allFusionReadyOuts[outIndex].amount >= lowerBound && allFusionReadyOuts[outIndex].amount < upperBound) {
selectedOuts.push_back(std::move(allFusionReadyOuts[outIndex]));
}
}
assert(selectedOuts.size() >= minInputCount);
auto outputsSortingFunction = [](const TransactionOutputInformation& l, const TransactionOutputInformation& r) { return l.amount < r.amount; };
if (selectedOuts.size() <= maxInputCount) {
std::sort(selectedOuts.begin(), selectedOuts.end(), outputsSortingFunction);
std::copy(selectedOuts.begin(), selectedOuts.end(), std::back_inserter(selectedOutputs));
return selectedOutputs;
}
ShuffleGenerator<size_t, crypto::random_engine<size_t>> generator(selectedOuts.size());
std::vector<TransactionOutputInformation> trimmedSelectedOuts;
trimmedSelectedOuts.reserve(maxInputCount);
for (size_t i = 0; i < maxInputCount; ++i) {
trimmedSelectedOuts.push_back(std::move(selectedOuts[generator()]));
}
std::sort(trimmedSelectedOuts.begin(), trimmedSelectedOuts.end(), outputsSortingFunction);
std::copy(trimmedSelectedOuts.begin(), trimmedSelectedOuts.end(), std::back_inserter(selectedOutputs));
return selectedOutputs;
}
TransactionId WalletLegacy::sendFusionTransaction(const std::list<TransactionOutputInformation>& fusionInputs, uint64_t fee, const std::string& extra, uint64_t mixIn, uint64_t unlockTimestamp) {
TransactionId txId = 0;
std::shared_ptr<WalletRequest> request;
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
throwIfNotInitialised();
std::vector<WalletLegacyTransfer> transfers;
WalletLegacyTransfer destination;
destination.amount = 0;
/* For transaction pool differentiation, fusion and optimization should be 50 X */
fee = cn::parameters::MINIMUM_FEE_V2;
for (auto& out : fusionInputs) {
destination.amount += out.amount;
}
destination.address = getAddress();
transfers.push_back(destination);
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
request = m_sender->makeSendFusionRequest(txId, events, transfers, fusionInputs, fee, extra, 0, unlockTimestamp);
}
notifyClients(events);
if (request) {
m_asyncContextCounter.addAsyncContext();
request->perform(m_node, std::bind(&WalletLegacy::sendTransactionCallback, this, std::placeholders::_1, std::placeholders::_2));
}
return txId;
}
TransactionId WalletLegacy::deposit(uint32_t term, uint64_t amount, uint64_t fee, uint64_t mixIn) {
throwIfNotInitialised();
TransactionId txId = 0;
std::unique_ptr<WalletRequest> request;
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
fee = cn::parameters::MINIMUM_FEE_V2;
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
request = m_sender->makeDepositRequest(txId, events, term, amount, fee, mixIn);
if (request != nullptr) {
pushBalanceUpdatedEvents(events);
}
}
notifyClients(events);
if (request) {
m_asyncContextCounter.addAsyncContext();
request->perform(m_node, std::bind(&WalletLegacy::sendTransactionCallback, this, std::placeholders::_1, std::placeholders::_2));
}
return txId;
}
TransactionId WalletLegacy::withdrawDeposit(const DepositId& depositId, uint64_t fee) {
throwIfNotInitialised();
TransactionId txId = 0;
std::unique_ptr<WalletRequest> request;
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
fee = cn::parameters::MINIMUM_FEE;
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
request = m_sender->makeWithdrawDepositRequest(txId, events, depositId, fee);
if (request != nullptr) {
pushBalanceUpdatedEvents(events);
}
}
notifyClients(events);
if (request != nullptr) {
m_asyncContextCounter.addAsyncContext();
request->perform(m_node, std::bind(&WalletLegacy::sendTransactionCallback, this, std::placeholders::_1, std::placeholders::_2));
}
return txId;
}
TransactionId WalletLegacy::withdrawDeposits(const std::vector<DepositId>& depositIds, uint64_t fee) {
throwIfNotInitialised();
TransactionId txId = 0;
std::unique_ptr<WalletRequest> request;
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
fee = cn::parameters::MINIMUM_FEE;
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
request = m_sender->makeWithdrawDepositsRequest(txId, events, depositIds, fee);
if (request != nullptr) {
pushBalanceUpdatedEvents(events);
}
}
notifyClients(events);
if (request != nullptr) {
m_asyncContextCounter.addAsyncContext();
request->perform(m_node, std::bind(&WalletLegacy::sendTransactionCallback, this, std::placeholders::_1, std::placeholders::_2));
}
return txId;
}
/* go through all unlocked outputs and return a total of
everything below the dust threshold */
uint64_t WalletLegacy::dustBalance()
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
throwIfNotInitialised();
std::vector<TransactionOutputInformation> outputs;
m_transferDetails->getOutputs(outputs, ITransfersContainer::IncludeKeyUnlocked);
uint64_t money = 0;
for (size_t i = 0; i < outputs.size(); ++i)
{
const auto& out = outputs[i];
if (!m_transactionsCache.isUsed(out))
{
if (out.amount < m_currency.defaultDustThreshold())
{
money += out.amount;
}
}
}
return money;
}
void WalletLegacy::sendTransactionCallback(WalletRequest::Callback callback, std::error_code ec) {
ContextCounterHolder counterHolder(m_asyncContextCounter);
std::deque<std::unique_ptr<WalletLegacyEvent> > events;
std::unique_ptr<WalletRequest> nextRequest;
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
callback(events, nextRequest, ec);
auto actualDepositBalanceUpdated = getActualDepositBalanceChangedEvent();
if (actualDepositBalanceUpdated) {
events.push_back(std::move(actualDepositBalanceUpdated));
}
auto pendingDepositBalanceUpdated = getPendingDepositBalanceChangedEvent();
if (pendingDepositBalanceUpdated) {
events.push_back(std::move(pendingDepositBalanceUpdated));
}
}
notifyClients(events);
if (nextRequest) {
m_asyncContextCounter.addAsyncContext();
nextRequest->perform(m_node, std::bind(&WalletLegacy::synchronizationCallback, this, std::placeholders::_1, std::placeholders::_2));
}
}
void WalletLegacy::synchronizationCallback(WalletRequest::Callback callback, std::error_code ec) {
ContextCounterHolder counterHolder(m_asyncContextCounter);
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
std::unique_ptr<WalletRequest> nextRequest;
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
callback(events, nextRequest, ec);
}
notifyClients(events);
if (nextRequest) {
m_asyncContextCounter.addAsyncContext();
nextRequest->perform(m_node, std::bind(&WalletLegacy::synchronizationCallback, this, std::placeholders::_1, std::placeholders::_2));
}
}
std::error_code WalletLegacy::cancelTransaction(size_t transactionId) {
return make_error_code(cn::error::TX_CANCEL_IMPOSSIBLE);
}
void WalletLegacy::synchronizationProgressUpdated(uint32_t current, uint32_t total) {
auto deletedTransactions = deleteOutdatedUnconfirmedTransactions();
// forward notification
m_observerManager.notify(&IWalletLegacyObserver::synchronizationProgressUpdated, current, total);
for (auto transactionId: deletedTransactions) {
m_observerManager.notify(&IWalletLegacyObserver::transactionUpdated, transactionId);
}
// check if balance has changed and notify client
notifyIfBalanceChanged();
}
void WalletLegacy::synchronizationCompleted(std::error_code result) {
if (result != std::make_error_code(std::errc::interrupted)) {
m_observerManager.notify(&IWalletLegacyObserver::synchronizationCompleted, result);
}
if (result) {
return;
}
auto deletedTransactions = deleteOutdatedUnconfirmedTransactions();
std::for_each(deletedTransactions.begin(), deletedTransactions.end(), [&] (TransactionId transactionId) {
m_observerManager.notify(&IWalletLegacyObserver::transactionUpdated, transactionId);
});
notifyIfBalanceChanged();
}
void WalletLegacy::onTransactionUpdated(ITransfersSubscription* object, const Hash& transactionHash) {
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
TransactionInformation txInfo;
uint64_t amountIn;
uint64_t amountOut;
if (m_transferDetails->getTransactionInformation(transactionHash, txInfo, &amountIn, &amountOut)) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
auto newDepositOuts = m_transferDetails->getTransactionOutputs(transactionHash, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateAll);
auto spentDeposits = m_transferDetails->getTransactionInputs(transactionHash, ITransfersContainer::IncludeTypeDeposit);
events = m_transactionsCache.onTransactionUpdated(txInfo, static_cast<int64_t>(amountOut)-static_cast<int64_t>(amountIn), newDepositOuts, spentDeposits, m_currency);
auto actualDepositBalanceChangedEvent = getActualDepositBalanceChangedEvent();
auto pendingDepositBalanceChangedEvent = getPendingDepositBalanceChangedEvent();
if (actualDepositBalanceChangedEvent) {
events.push_back(std::move(actualDepositBalanceChangedEvent));
}
if (pendingDepositBalanceChangedEvent) {
events.push_back(std::move(pendingDepositBalanceChangedEvent));
}
}
notifyClients(events);
}
void WalletLegacy::onTransactionDeleted(ITransfersSubscription* object, const Hash& transactionHash) {
std::deque<std::unique_ptr<WalletLegacyEvent>> events;
{
std::unique_lock<std::mutex> lock(m_cacheMutex);
events = m_transactionsCache.onTransactionDeleted(transactionHash);
std::unique_ptr<WalletLegacyEvent> actualDepositBalanceUpdated = getActualDepositBalanceChangedEvent();
if (actualDepositBalanceUpdated) {
events.push_back(std::move(actualDepositBalanceUpdated));
}
std::unique_ptr<WalletLegacyEvent> pendingDepositBalanceUpdated = getPendingDepositBalanceChangedEvent();
if (pendingDepositBalanceUpdated) {
events.push_back(std::move(pendingDepositBalanceUpdated));
}
}
notifyClients(events);
}
void WalletLegacy::onTransfersUnlocked(ITransfersSubscription* object, const std::vector<TransactionOutputInformation>& unlockedTransfers) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
auto unlockedDeposits = m_transactionsCache.unlockDeposits(unlockedTransfers);
lock.unlock();
if (!unlockedDeposits.empty()) {
m_observerManager.notify(&IWalletLegacyObserver::depositsUpdated, unlockedDeposits);
notifyIfDepositBalanceChanged();
notifyIfInvestmentBalanceChanged();
}
}
void WalletLegacy::onTransfersLocked(ITransfersSubscription* object, const std::vector<TransactionOutputInformation>& lockedTransfers) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
auto lockedDeposits = m_transactionsCache.lockDeposits(lockedTransfers);
lock.unlock();
if (!lockedDeposits.empty()) {
m_observerManager.notify(&IWalletLegacyObserver::depositsUpdated, lockedDeposits);
notifyIfDepositBalanceChanged();
notifyIfInvestmentBalanceChanged();
}
}
void WalletLegacy::throwIfNotInitialised() {
if (m_state == NOT_INITIALIZED || m_state == LOADING) {
throw std::system_error(make_error_code(cn::error::NOT_INITIALIZED));
}
assert(m_transferDetails);
}
void WalletLegacy::notifyClients(std::deque<std::unique_ptr<WalletLegacyEvent>>& events) {
while (!events.empty()) {
std::unique_ptr<WalletLegacyEvent>& event = events.front();
event->notify(m_observerManager);
events.pop_front();
}
}
void WalletLegacy::notifyIfBalanceChanged() {
auto actual = actualBalance();
auto prevActual = m_lastNotifiedActualBalance.exchange(actual);
if (prevActual != actual) {
m_observerManager.notify(&IWalletLegacyObserver::actualBalanceUpdated, actual);
}
auto pending = pendingBalance();
auto prevPending = m_lastNotifiedPendingBalance.exchange(pending);
if (prevPending != pending) {
m_observerManager.notify(&IWalletLegacyObserver::pendingBalanceUpdated, pending);
}
}
void WalletLegacy::notifyIfDepositBalanceChanged() {
std::unique_ptr<WalletLegacyEvent> actualEvent = getActualDepositBalanceChangedEvent();
std::unique_ptr<WalletLegacyEvent> pendingEvent = getPendingDepositBalanceChangedEvent();
if (actualEvent) {
actualEvent->notify(m_observerManager);
}
if (pendingEvent) {
pendingEvent->notify(m_observerManager);
}
}
std::unique_ptr<WalletLegacyEvent> WalletLegacy::getActualDepositBalanceChangedEvent() {
auto actual = calculateActualDepositBalance();
auto prevActual = m_lastNotifiedActualDepositBalance.exchange(actual);
std::unique_ptr<WalletLegacyEvent> event;
if (actual != prevActual) {
event = std::unique_ptr<WalletLegacyEvent>(new WalletActualDepositBalanceUpdatedEvent(actual));
}
return event;
}
std::unique_ptr<WalletLegacyEvent> WalletLegacy::getPendingDepositBalanceChangedEvent() {
auto pending = calculatePendingDepositBalance();
auto prevPending = m_lastNotifiedPendingDepositBalance.exchange(pending);
std::unique_ptr<WalletLegacyEvent> event;
if (pending != prevPending) {
event = std::unique_ptr<WalletLegacyEvent>(new WalletPendingDepositBalanceUpdatedEvent(pending));
}
return event;
}
void WalletLegacy::notifyIfInvestmentBalanceChanged() {
std::unique_ptr<WalletLegacyEvent> actualEvent = getActualInvestmentBalanceChangedEvent();
std::unique_ptr<WalletLegacyEvent> pendingEvent = getPendingInvestmentBalanceChangedEvent();
if (actualEvent) {
actualEvent->notify(m_observerManager);
}
if (pendingEvent) {
pendingEvent->notify(m_observerManager);
}
}
std::unique_ptr<WalletLegacyEvent> WalletLegacy::getActualInvestmentBalanceChangedEvent() {
auto actual = calculateActualInvestmentBalance();
auto prevActual = m_lastNotifiedActualInvestmentBalance.exchange(actual);
std::unique_ptr<WalletLegacyEvent> event;
if (actual != prevActual) {
event = std::unique_ptr<WalletLegacyEvent>(new WalletActualInvestmentBalanceUpdatedEvent(actual));
}
return event;
}
std::unique_ptr<WalletLegacyEvent> WalletLegacy::getPendingInvestmentBalanceChangedEvent() {
auto pending = calculatePendingInvestmentBalance();
auto prevPending = m_lastNotifiedPendingInvestmentBalance.exchange(pending);
std::unique_ptr<WalletLegacyEvent> event;
if (pending != prevPending) {
event = std::unique_ptr<WalletLegacyEvent>(new WalletPendingInvestmentBalanceUpdatedEvent(pending));
}
return event;
}
std::unique_ptr<WalletLegacyEvent> WalletLegacy::getActualBalanceChangedEvent() {
auto actual = calculateActualBalance();
auto prevActual = m_lastNotifiedActualBalance.exchange(actual);
std::unique_ptr<WalletLegacyEvent> event;
if (actual != prevActual) {
event = std::unique_ptr<WalletLegacyEvent>(new WalletActualBalanceUpdatedEvent(actual));
}
return event;
}
std::unique_ptr<WalletLegacyEvent> WalletLegacy::getPendingBalanceChangedEvent() {
auto pending = calculatePendingBalance();
auto prevPending = m_lastNotifiedPendingBalance.exchange(pending);
std::unique_ptr<WalletLegacyEvent> event;
if (pending != prevPending) {
event = std::unique_ptr<WalletLegacyEvent>(new WalletPendingBalanceUpdatedEvent(pending));
}
return event;
}
void WalletLegacy::getAccountKeys(AccountKeys& keys) {
if (m_state == NOT_INITIALIZED) {
throw std::system_error(make_error_code(cn::error::NOT_INITIALIZED));
}
keys = m_account.getAccountKeys();
}
bool WalletLegacy::isTrackingWallet() {
AccountKeys keys;
getAccountKeys(keys);
return keys.spendSecretKey == boost::value_initialized<crypto::SecretKey>();
}
std::vector<TransactionId> WalletLegacy::deleteOutdatedUnconfirmedTransactions() {
std::lock_guard<std::mutex> lock(m_cacheMutex);
return m_transactionsCache.deleteOutdatedTransactions();
}
uint64_t WalletLegacy::calculateActualDepositBalance() {
std::vector<TransactionOutputInformation> transfers;
m_transferDetails->getOutputs(transfers, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateUnlocked);
std::vector<uint32_t> heights = getTransactionHeights(transfers);
return calculateDepositsAmount(transfers, m_currency, heights) - m_transactionsCache.countUnconfirmedSpentDepositsTotalAmount();
}
uint64_t WalletLegacy::calculateActualInvestmentBalance() {
std::vector<TransactionOutputInformation> transfers;
m_transferDetails->getOutputs(transfers, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateUnlocked);
std::vector<uint32_t> heights = getTransactionHeights(transfers);
return calculateInvestmentsAmount(transfers, m_currency, heights);
}
std::vector<uint32_t> WalletLegacy::getTransactionHeights(const std::vector<TransactionOutputInformation> transfers){
std::vector<uint32_t> heights;
for (auto transfer : transfers){
crypto::Hash hash = transfer.transactionHash;
TransactionInformation info;
bool ok = m_transferDetails->getTransactionInformation(hash, info, NULL, NULL);
assert(ok);
heights.push_back(info.blockHeight);
}
return heights;
}
uint64_t WalletLegacy::calculatePendingDepositBalance() {
std::vector<TransactionOutputInformation> transfers;
m_transferDetails->getOutputs(transfers, ITransfersContainer::IncludeTypeDeposit
| ITransfersContainer::IncludeStateLocked
| ITransfersContainer::IncludeStateSoftLocked);
std::vector<uint32_t> heights = getTransactionHeights(transfers);
return calculateDepositsAmount(transfers, m_currency, heights);
}
uint64_t WalletLegacy::calculatePendingInvestmentBalance() {
std::vector<TransactionOutputInformation> transfers;
m_transferDetails->getOutputs(transfers, ITransfersContainer::IncludeTypeDeposit
| ITransfersContainer::IncludeStateLocked
| ITransfersContainer::IncludeStateSoftLocked);
std::vector<uint32_t> heights = getTransactionHeights(transfers);
return calculateInvestmentsAmount(transfers, m_currency, heights);
}
uint64_t WalletLegacy::calculateActualBalance() {
return m_transferDetails->balance(ITransfersContainer::IncludeKeyUnlocked) -
m_transactionsCache.unconfrimedOutsAmount();
}
uint64_t WalletLegacy::calculatePendingBalance() {
uint64_t change = m_transactionsCache.unconfrimedOutsAmount() - m_transactionsCache.unconfirmedTransactionsAmount();
uint64_t spentDeposits = m_transactionsCache.countUnconfirmedSpentDepositsProfit();
uint64_t container = m_transferDetails->balance(ITransfersContainer::IncludeKeyNotUnlocked);
return container + change + spentDeposits;
}
void WalletLegacy::pushBalanceUpdatedEvents(std::deque<std::unique_ptr<WalletLegacyEvent>>& eventsQueue) {
auto actualDepositBalanceUpdated = getActualDepositBalanceChangedEvent();
if (actualDepositBalanceUpdated != nullptr) {
eventsQueue.push_back(std::move(actualDepositBalanceUpdated));
}
auto pendingDepositBalanceUpdated = getPendingDepositBalanceChangedEvent();
if (pendingDepositBalanceUpdated != nullptr) {
eventsQueue.push_back(std::move(pendingDepositBalanceUpdated));
}
auto actualInvestmentBalanceUpdated = getActualInvestmentBalanceChangedEvent();
if (actualInvestmentBalanceUpdated != nullptr) {
eventsQueue.push_back(std::move(actualInvestmentBalanceUpdated));
}
auto pendingInvestmentBalanceUpdated = getPendingInvestmentBalanceChangedEvent();
if (pendingInvestmentBalanceUpdated != nullptr) {
eventsQueue.push_back(std::move(pendingInvestmentBalanceUpdated));
}
auto actualBalanceUpdated = getActualBalanceChangedEvent();
if (actualBalanceUpdated != nullptr) {
eventsQueue.push_back(std::move(actualBalanceUpdated));
}
auto pendingBalanceUpdated = getPendingBalanceChangedEvent();
if (pendingBalanceUpdated != nullptr) {
eventsQueue.push_back(std::move(pendingBalanceUpdated));
}
}
crypto::SecretKey WalletLegacy::getTxKey(crypto::Hash &txid)
{
TransactionId ti = m_transactionsCache.findTransactionByHash(txid);
WalletLegacyTransaction transaction;
getTransaction(ti, transaction);
if (transaction.secretKey && NULL_SECRET_KEY != reinterpret_cast<const crypto::SecretKey &>(transaction.secretKey.get()))
{
return reinterpret_cast<const crypto::SecretKey &>(transaction.secretKey.get());
}
else
{
auto getTransactionCompleted = std::promise<std::error_code>();
auto getTransactionWaitFuture = getTransactionCompleted.get_future();
cn::Transaction tx;
m_node.getTransaction(std::move(txid), std::ref(tx),
[&getTransactionCompleted](std::error_code ec) {
auto detachedPromise = std::move(getTransactionCompleted);
detachedPromise.set_value(ec);
});
std::error_code ec = getTransactionWaitFuture.get();
if (ec)
{
//m_logger(ERROR) << "Failed to get tx: " << ec << ", " << ec.message();
return reinterpret_cast<const crypto::SecretKey &>(transaction.secretKey.get());
}
crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(tx.extra);
KeyPair deterministicTxKeys;
bool ok = generateDeterministicTransactionKeys(tx, m_account.getAccountKeys().viewSecretKey, deterministicTxKeys) && deterministicTxKeys.publicKey == txPubKey;
return ok ? deterministicTxKeys.secretKey : reinterpret_cast<const crypto::SecretKey &>(transaction.secretKey.get());
}
}
bool WalletLegacy::get_tx_key(crypto::Hash& txid, crypto::SecretKey& txSecretKey) {
TransactionId ti = m_transactionsCache.findTransactionByHash(txid);
WalletLegacyTransaction transaction;
getTransaction(ti, transaction);
txSecretKey = transaction.secretKey.get();
if (txSecretKey == NULL_SECRET_KEY) {
return false;
}
return true;
}
bool WalletLegacy::getTxProof(crypto::Hash& txid, cn::AccountPublicAddress& address, crypto::SecretKey& tx_key, std::string& sig_str) {
crypto::KeyImage p = *reinterpret_cast<crypto::KeyImage*>(&address.viewPublicKey);
crypto::KeyImage k = *reinterpret_cast<crypto::KeyImage*>(&tx_key);
crypto::KeyImage pk = crypto::scalarmultKey(p, k);
crypto::PublicKey R;
crypto::PublicKey rA = reinterpret_cast<const PublicKey&>(pk);
crypto::secret_key_to_public_key(tx_key, R);
crypto::Signature sig;
try {
crypto::generate_tx_proof(txid, R, address.viewPublicKey, rA, tx_key, sig);
}
catch (std::runtime_error) {
return false;
}
sig_str = std::string("ProofV1") +
tools::base_58::encode(std::string((const char *)&rA, sizeof(crypto::PublicKey))) +
tools::base_58::encode(std::string((const char *)&sig, sizeof(crypto::Signature)));
return true;
}
bool compareTransactionOutputInformationByAmount(const TransactionOutputInformation &a, const TransactionOutputInformation &b) {
return a.amount < b.amount;
}
std::string WalletLegacy::getReserveProof(const uint64_t &reserve, const std::string &message) {
const cn::AccountKeys keys = m_account.getAccountKeys();
crypto::SecretKey viewSecretKey = keys.viewSecretKey;
if (keys.spendSecretKey == NULL_SECRET_KEY) {
throw std::runtime_error("Reserve proof can only be generated by a full wallet");
}
if (actualBalance() == 0) {
throw std::runtime_error("Zero balance");
}
if (actualBalance() < reserve) {
throw std::runtime_error("Not enough balance for the requested minimum reserve amount");
}
// determine which outputs to include in the proof
std::vector<TransactionOutputInformation> selected_transfers;
m_transferDetails->getOutputs(selected_transfers, ITransfersContainer::IncludeAllUnlocked);
// minimize the number of outputs included in the proof, by only picking the N largest outputs that can cover the requested min reserve amount
std::sort(selected_transfers.begin(), selected_transfers.end(), compareTransactionOutputInformationByAmount);
while (selected_transfers.size() >= 2 && selected_transfers[1].amount >= reserve)
selected_transfers.erase(selected_transfers.begin());
size_t sz = 0;
uint64_t total = 0;
while (total < reserve) {
total += selected_transfers[sz].amount;
++sz;
}
selected_transfers.resize(sz);
// compute signature prefix hash
std::string prefix_data = message;
prefix_data.append((const char*)&keys.address, sizeof(cn::AccountPublicAddress));
std::vector<crypto::KeyImage> kimages;
cn::KeyPair ephemeral;
for (size_t i = 0; i < selected_transfers.size(); ++i) {
// have to repeat this to get key image as we don't store m_key_image
// prefix_data.append((const char*)&m_transfers[selected_transfers[i]].m_key_image, sizeof(crypto::key_image));
const TransactionOutputInformation &td = selected_transfers[i];
// derive ephemeral secret key
crypto::KeyImage ki;
const bool r = cn::generate_key_image_helper(m_account.getAccountKeys(), td.transactionPublicKey, td.outputInTransaction, ephemeral, ki);
if (!r) {
throw std::runtime_error("Failed to generate key image");
}
// now we can insert key image
prefix_data.append((const char*)&ki, sizeof(crypto::PublicKey));
kimages.push_back(ki);
}
crypto::Hash prefix_hash;
crypto::cn_fast_hash(prefix_data.data(), prefix_data.size(), prefix_hash);
// generate proof entries
std::vector<reserve_proof_entry> proofs(selected_transfers.size());
for (size_t i = 0; i < selected_transfers.size(); ++i) {
const TransactionOutputInformation &td = selected_transfers[i];
reserve_proof_entry& proof = proofs[i];
proof.key_image = kimages[i];
proof.txid = td.transactionHash;
proof.index_in_tx = td.outputInTransaction;
auto txPubKey = td.transactionPublicKey;
for (int i = 0; i < 2; ++i) {
crypto::KeyImage sk = crypto::scalarmultKey(*reinterpret_cast<const crypto::KeyImage*>(&txPubKey), *reinterpret_cast<const crypto::KeyImage*>(&viewSecretKey));
proof.shared_secret = *reinterpret_cast<const crypto::PublicKey *>(&sk);
crypto::KeyDerivation derivation;
if (!crypto::generate_key_derivation(proof.shared_secret, viewSecretKey, derivation)) {
throw std::runtime_error("Failed to generate key derivation");
}
}
// generate signature for shared secret
crypto::generate_tx_proof(prefix_hash, keys.address.viewPublicKey, txPubKey, proof.shared_secret, viewSecretKey, proof.shared_secret_sig);
// derive ephemeral secret key
crypto::KeyImage ki;
cn::KeyPair ephemeral;
const bool r = cn::generate_key_image_helper(m_account.getAccountKeys(), td.transactionPublicKey, td.outputInTransaction, ephemeral, ki);
if (!r) {
throw std::runtime_error("Failed to generate key image");
}
if (ephemeral.publicKey != td.outputKey) {
throw std::runtime_error("Derived public key doesn't agree with the stored one");
}
// generate signature for key image
const std::vector<const crypto::PublicKey *>& pubs = { &ephemeral.publicKey };
crypto::generate_ring_signature(prefix_hash, proof.key_image, &pubs[0], 1, ephemeral.secretKey, 0, &proof.key_image_sig);
}
// generate signature for the spend key that received those outputs
crypto::Signature signature;
crypto::generate_signature(prefix_hash, keys.address.spendPublicKey, keys.spendSecretKey, signature);
// serialize & encode
reserve_proof p;
p.proofs.assign(proofs.begin(), proofs.end());
memcpy(&p.signature, &signature, sizeof(signature));
BinaryArray ba = toBinaryArray(p);
std::string ret = common::toHex(ba);
ret = "ReserveProofV1" + tools::base_58::encode(ret);
return ret;
}
bool WalletLegacy::checkWalletPassword(std::istream& source, const std::string& password) {
std::unique_lock<std::mutex> lock(m_cacheMutex);
WalletLegacySerializer serializer(m_account, m_transactionsCache);
return serializer.deserialize(source, password);
}
Deposit WalletLegacy::get_deposit(DepositId depositId)
{
return m_transactionsCache.getDeposit(depositId);
}
//KK
} //namespace cn
|
#ifndef LISTENER_H
#define LISTENER_H
#include <QDataStream>
#include <QFile>
#include <QObject>
#include <QThread>
#include <cstdint>
#define BASE_DELAY 2
namespace Engine {
class Listener;
}
/**
* @brief The Engine::Listener class
*/
class Engine::Listener : public QObject {
Q_OBJECT
public:
enum class ListenerState { unproductive, productive };
/**
* @brief The ListenerType enum
* This enum used for Timer to know which listener it is going to instantiate
* @note If, for whatever reason, we decide to add ListenerType values make
* sure that to add them BEFORE none. The none type is used for bounds checking.
*/
enum class ListenerType {
keyboard,
audio,
none
}; // I had to do this to make QThreads work
public:
Listener();
~Listener();
virtual void start() = 0;
virtual void end() = 0;
virtual void pause() = 0;
virtual void update() = 0;
static ListenerType intToListenerType(int enumToInt);
virtual Listener::ListenerState listen() = 0;
double getSlack();
void setState(ListenerState);
ListenerState getState();
// probably not needed...timer keeps track of live session time,
// when session ends, session will grab this data from timer
// to store permanently in Commitment
uint64_t getProductiveTime();
uint64_t getUnproductiveTime();
void setSlack(double slack);
protected:
Listener::ListenerState state;
private:
double checkStateDelay;
double slack;
// probably not needed...timer keeps track of live session time,
// when session ends, session will grab this data from timer
// to store permanently in Commitment
uint64_t productiveTime;
uint64_t unproductiveTime;
double getCheckStateDelay();
void setCheckStateDelay(double checkStateDelay);
// probably not needed...timer keeps track of live session time,
// when session ends, session will grab this data from timer
// to store permanently in Commitment
void setProductiveTime(uint64_t productiveTime);
void setUnproductiveTime(uint64_t unproductiveTime);
/**
* @brief operator << I'm really sorry about this ugiliness. Apparently,
* as far as I know, C++ wants me to do it this way in order to access private members.
* @param out
* @param newTask
* @return
*/
friend QDataStream &operator<<(QDataStream &out, const ListenerType &newListener) {
out << int(newListener);
return out;
}
/**
* @brief operator >> I'm really sorry about this ugiliness. Apparently,
* as far as I know, C++ wants me to do it this way in order to access private members.
* @param in
* @param newTask
* @return
*/
friend QDataStream &operator>>(QDataStream &in, ListenerType &newListener) {
int enumValue = 0;
in >> enumValue;
newListener = intToListenerType(enumValue);
return in;
}
public slots:
// void tickSlot();
signals:
void productive();
void unProductive();
};
#endif // LISTENER_H
|
//
// Created by Stephen Clyde on 1/19/17.
//
#include <iostream>
#include <iomanip>
#include "FormattedTable.hpp"
FormattedTable::FormattedTable(int maxRows, int maxColumns) :
m_maxRows(maxRows), m_maxColumns(maxColumns)
{
m_columns = new ColumnDefinition*[m_maxColumns];
m_rows = new FormattedRow*[m_maxRows];
}
FormattedTable::~FormattedTable()
{
for (int columnIndex = 0; columnIndex < m_columnCount; columnIndex++)
delete m_columns[columnIndex];
delete [] m_columns;
for (int rowIndex = 0; rowIndex < m_rowCount; rowIndex++)
delete m_rows[rowIndex];
delete [] m_rows;
}
void FormattedTable::addColumn(ColumnDefinition* columnDefinition)
{
if (columnDefinition != nullptr)
{
if (m_columnCount >= m_maxColumns)
{
std::cerr << "Cannot add column: too many columns" << std::endl;
}
else
{
m_columns[m_columnCount++] = columnDefinition;
}
}
}
void FormattedTable::addRow(FormattedRow* row)
{
if (row != nullptr)
{
if (m_rowCount >= m_maxRows)
{
std::cerr << "Cannot add row: too many rows" << std::endl;
}
else if (row->getCellCount() != m_columnCount)
{
std::cerr << "Cannot add row: wrong number of cells in the row" << std::endl;
}
else
{
m_rows[m_rowCount++] = row;
}
}
}
ColumnDefinition* FormattedTable::getColumnDefinition(int columnIndex) const
{
ColumnDefinition* columnDefinition = nullptr;
if (columnIndex>=0 && columnIndex < m_columnCount)
{
columnDefinition = m_columns[columnIndex];
}
return columnDefinition;
}
void FormattedTable::write(std::ostream& outputStream)
{
writeHeaders(outputStream);
for (int rowIndex = 0; rowIndex < m_rowCount; rowIndex++)
{
m_rows[rowIndex]->write(outputStream);
}
}
void FormattedTable::writeHeaders(std::ostream& outputStream)
{
for (int columnIndex = 0; columnIndex < m_columnCount; columnIndex++)
{
m_columns[columnIndex]->write(outputStream);
}
outputStream << std::endl;
for (int columnIndex = 0; columnIndex < m_columnCount; columnIndex++)
{
m_columns[columnIndex]->writeSeparator(outputStream);
}
outputStream << std::endl;
}
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/icon.Map.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.Text.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ITemplateSource.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.ICollapse.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Triggers.IValue-1.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.String.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{namespace icon{struct Map;}}
namespace g{
namespace icon{
// public partial sealed class Map :4
// {
::g::Fuse::Controls::TextControl_type* Map_typeof();
void Map__ctor_8_fn(Map* __this);
void Map__InitializeUX1_fn(Map* __this);
void Map__New4_fn(Map** __retval);
struct Map : ::g::Fuse::Controls::Text
{
void ctor_8();
void InitializeUX1();
static Map* New4();
};
// }
}} // ::g::icon
|
//#include<iostream>
#include<stdio.h>
//using namespace std;
const int maxn=10000+5;
long long int a[maxn];
int main()
{
a[1]=1;
a[2]=2;
int n;
while(~scanf("%d",&n)){
for(int i=3;i<53;i++){
a[i]=a[i-1]+a[i-2];
//printf("%d",a[n]);
}
printf("%lld\n",a[n]);
}
return 0;
}
|
#include "eff.h"
void setcolors(vector<TH1F*> v_hist, vector<TH1F*> v_hist_pos, vector<TH1F*> v_hist_neg)
{
int size = v_hist_pos.size();
for(int i = 0; i < size; ++i)
{
v_hist_pos.at(i)->SetLineColor(kRed);
v_hist_neg.at(i)->SetLineColor(kAzure);
v_hist.at(i)->SetLineColor(kGreen);
}
}
void setyaxis(vector<TH1F*> v_hist, vector<TH1F*> v_hist_pos, vector<TH1F*> v_hist_neg)
{
int size = v_hist_pos.size();
for(int i = 0; i < size; ++i)
{
v_hist_pos.at(i)->SetAxisRange(0.,1.,"Y");
v_hist_neg.at(i)->SetAxisRange(0.,1.,"Y");
v_hist.at(i)->SetAxisRange(0.,1.,"Y");
}
}
void sumhisterr(vector<TH1F*> v_hist, vector<TH1F*> v_hist_pos, vector<TH1F*> v_hist_neg)
{
int size = v_hist_pos.size();
for(int i = 0; i < size; ++i)
{
v_hist_pos.at(i)->Sumw2();
v_hist_neg.at(i)->Sumw2();
v_hist.at(i)->Sumw2();
}
}
void sethists(vector<TH1F*> v_hist, vector<TH1F*> v_hist_pos, vector<TH1F*> v_hist_neg)
{
setyaxis(v_hist, v_hist_pos, v_hist_neg);
setcolors(v_hist, v_hist_pos, v_hist_neg);
}
void printhists(vector<TH1F*> v_hist, vector<TH1F*> v_hist_pos, vector<TH1F*> v_hist_neg, string polarisation)
{
int size = v_hist_pos.size();
bool up_down = (polarisation == "UP")? true : false;
string directory = (up_down == true)? "up_pdf" : "down_pdf";
TCanvas *c = new TCanvas();
string title_name;
string save_name;
for(int i = 0; i < size; ++i)
{
v_hist.at(i)->Draw();
v_hist.at(i)->Draw("hist same");
title_name = v_hist.at(i)->GetName();
save_name = "output/"+directory+"/single/tot/"+title_name+".pdf";
c->SaveAs(save_name.c_str());
v_hist_pos.at(i)->Draw();
v_hist_pos.at(i)->Draw("hist same");
title_name = v_hist_pos.at(i)->GetName();
save_name = "output/"+directory+"/single/pos/"+title_name+".pdf";
c->SaveAs(save_name.c_str());
v_hist_neg.at(i)->Draw();
v_hist_neg.at(i)->Draw("hist same");
title_name = v_hist_neg.at(i)->GetName();
save_name = "output/"+directory+"/single/neg/"+title_name+".pdf";
c->SaveAs(save_name.c_str());
v_hist_pos.at(i)->Draw();
v_hist_pos.at(i)->Draw("hist same");
v_hist_neg.at(i)->Draw("same");
v_hist_neg.at(i)->Draw("hist same");
title_name = v_hist.at(i)->GetName();
save_name = "output/"+directory+"/combined/"+title_name+".pdf";
c->SaveAs(save_name.c_str());
}
}
void printdevhists(vector<TH1F*> v_hist_pos, vector<TH1F*> v_hist_neg, string polarisation)
{
int size = v_hist_pos.size();
bool up_down = (polarisation == "UP")? true : false;
string directory = (up_down == true)? "up_pdf" : "down_pdf";
TCanvas *c = new TCanvas();
string title_name;
string save_name;
for (int i = 0; i < size; ++i)
{
v_hist_pos.at(i)->Sumw2();
v_hist_neg.at(i)->Sumw2();
v_hist_pos.at(i)->Add(v_hist_neg.at(i),-1);
v_hist_neg.at(i)->Scale(2.);
v_hist_neg.at(i)->Add(v_hist_pos.at(i));
v_hist_pos.at(i)->Divide(v_hist_neg.at(i));
v_hist_pos.at(i)->SetAxisRange(-0.15, 0.15, "Y");
v_hist_pos.at(i)->Draw();
title_name = v_hist_pos.at(i)->GetName();
save_name = "output/"+directory+"/deviation/"+title_name+".pdf";
c->SaveAs(save_name.c_str());
}
}
vector<double> get_eff(vector<double> v_n_ges, vector<double> v_n_reco)
{
vector<double> v_eff = {};
int size = v_n_reco.size();
for(int i = 0; i < size; ++i)
{
v_eff.push_back(v_n_reco.at(i)/v_n_ges.at(i));
}
return v_eff;
}
vector<double> get_err(vector<double> v_eff, vector<double> v_n_ges)
{
vector<double> v_err = {};
int size = v_eff.size();
for(int i = 0; i < size; ++i)
{
v_err.push_back(sqrt(v_eff.at(i) * (1 - v_eff.at(i))/v_n_ges.at(i)));
//v_err.push_back((sqrt(v_eff.at(i)/n_ges + pow(v_eff.at(i),2.)/n_ges)));
}
return v_err;
}
vector<double> deviation(vector<double> v_eff_pos, vector<double> v_eff_neg)
{
vector<double> v_dev = {};
int size = v_eff_pos.size();
for(int i = 0; i < size; ++i)
{
v_dev.push_back((v_eff_pos.at(i) - v_eff_neg.at(i)) / (v_eff_pos.at(i) + v_eff_neg.at(i)));
}
return v_dev;
}
vector<double> deviation_err(vector<double> v_eff_pos, vector<double> v_err_pos, vector<double> v_eff_neg, vector<double> v_err_neg)
{
vector<double> v_dev_err ={};
int size = v_eff_pos.size();
for(int j = 0; j < size; ++j)
{
double dev_err = 2 * sqrt((pow(v_err_pos.at(j)*v_eff_neg.at(j),2.)+pow(v_err_neg.at(j)*v_eff_pos.at(j),2.)))/pow(v_eff_pos.at(j) + v_eff_neg.at(j), 2.);
v_dev_err.push_back(dev_err);
}
return v_dev_err;
}
void hist_fill(vector<TH1F*> v_hist, vector<TH1F*> v_hist_reco, vector<TH1F*> v_hist_pos, vector<TH1F*> v_hist_reco_pos, vector<TH1F*> v_hist_neg, vector<TH1F*> v_hist_reco_neg, vector<double> v_var, int is_reco, double &n_reco, double &n_pos, double &n_reco_pos, int ID)
{
int size = v_hist.size();
for(int i = 0; i < size; ++i)
{
v_hist.at(i)->Fill(v_var.at(i));
}
if(ID > 0)
{
++n_pos;
for(int i = 0; i < size; ++i)
{
v_hist_pos.at(i)->Fill(v_var.at(i));
}
}
else
{
for(int i = 0; i < size; ++i)
{
v_hist_neg.at(i)->Fill(v_var.at(i));
}
}
if(is_reco == 1)
{
for(int i = 0; i < size; ++i)
{
v_hist_reco.at(i)->Fill(v_var.at(i));
}
++n_reco;
if(ID > 0)
{
++n_reco_pos;
for(int i = 0; i < size; ++i)
{
v_hist_reco_pos.at(i)->Fill(v_var.at(i));
}
}
else
{
for(int i = 0; i < size; ++i)
{
v_hist_reco_neg.at(i)->Fill(v_var.at(i));
}
}
}
}
void hist_divide(vector<TH1F*> v_hist, vector<TH1F*> v_hist_reco)
{
int size = v_hist.size();
for(int i = 0; i < size; ++i)
{
v_hist_reco.at(i)->Divide(v_hist.at(i));
}
}
void eff(string dir, string sample, string polarisation)
{
string input_name = dir+"/"+sample+".root";
TChain *ntp = new TChain("ntp");
ntp->Add(input_name.c_str());
int nEvents = ntp->GetEntries();
double nTot = double(nEvents);
double nDst_pos = 0.;
double nD0_pos = 0.;
double nPi_pos = 0.;
double nK_pos = 0.;
double nSPi_pos = 0.;
double nDst_neg = 0.;
double nD0_neg = 0.;
double nPi_neg = 0.;
double nK_neg = 0.;
double nSPi_neg = 0.;
double nDst_reco = 0.;
double nD0_reco = 0.;
double nPi_reco = 0.;
double nK_reco = 0.;
double nSPi_reco = 0.;
double nDst_reco_pos = 0.;
double nD0_reco_pos = 0.;
double nPi_reco_pos = 0.;
double nK_reco_pos = 0.;
double nSPi_reco_pos = 0.;
double nDst_reco_neg = 0.;
double nD0_reco_neg = 0.;
double nPi_reco_neg = 0.;
double nK_reco_neg = 0.;
double nSPi_reco_neg = 0.;
double Dst_pT, D0_pT, Pi_pT, K_pT, SPi_pT;
double Dst_phi, D0_phi, Pi_phi, K_phi, SPi_phi;
double Dst_theta, D0_theta, Pi_theta, K_theta, SPi_theta;
double Dst_eta, D0_eta, Pi_eta, K_eta, SPi_eta;
int Dst_ID, D0_ID, Pi_ID, K_ID, SPi_ID;
int isPi_reco, isK_reco, isSPi_reco, isD0_reco, isDst_reco;
ntp->SetBranchStatus("*",0);
ntp->SetBranchStatus("P1_Reconstructed",1); ntp->SetBranchAddress("P1_Reconstructed", &(isPi_reco));
ntp->SetBranchStatus("P2_Reconstructed",1); ntp->SetBranchAddress("P2_Reconstructed", &(isK_reco));
ntp->SetBranchStatus("sPi_Reconstructed",1); ntp->SetBranchAddress("sPi_Reconstructed", &(isSPi_reco));
ntp->SetBranchStatus("Dst_PT",1); ntp->SetBranchAddress("Dst_PT", &(Dst_pT));
ntp->SetBranchStatus("D0_PT",1); ntp->SetBranchAddress("D0_PT", &(D0_pT));
ntp->SetBranchStatus("P1_PT",1); ntp->SetBranchAddress("P1_PT", &(Pi_pT));
ntp->SetBranchStatus("P2_PT",1); ntp->SetBranchAddress("P2_PT", &(K_pT));
ntp->SetBranchStatus("sPi_PT",1); ntp->SetBranchAddress("sPi_PT", &(SPi_pT));
ntp->SetBranchStatus("Dst_PHI",1); ntp->SetBranchAddress("Dst_PHI", &(Dst_phi));
ntp->SetBranchStatus("D0_PHI",1); ntp->SetBranchAddress("D0_PHI", &(D0_phi));
ntp->SetBranchStatus("P1_PHI",1); ntp->SetBranchAddress("P1_PHI", &(Pi_phi));
ntp->SetBranchStatus("P2_PHI",1); ntp->SetBranchAddress("P2_PHI", &(K_phi));
ntp->SetBranchStatus("sPi_PHI",1); ntp->SetBranchAddress("sPi_PHI", &(SPi_phi));
ntp->SetBranchStatus("Dst_THETA",1); ntp->SetBranchAddress("Dst_THETA", &(Dst_theta));
ntp->SetBranchStatus("D0_THETA",1); ntp->SetBranchAddress("D0_THETA", &(D0_theta));
ntp->SetBranchStatus("P1_THETA",1); ntp->SetBranchAddress("P1_THETA", &(Pi_theta));
ntp->SetBranchStatus("P2_THETA",1); ntp->SetBranchAddress("P2_THETA", &(K_theta));
ntp->SetBranchStatus("sPi_THETA",1); ntp->SetBranchAddress("sPi_THETA", &(SPi_theta));
ntp->SetBranchStatus("Dst_ETA",1); ntp->SetBranchAddress("Dst_ETA", &(Dst_eta));
ntp->SetBranchStatus("D0_ETA",1); ntp->SetBranchAddress("D0_ETA", &(D0_eta));
ntp->SetBranchStatus("P1_ETA",1); ntp->SetBranchAddress("P1_ETA", &(Pi_eta));
ntp->SetBranchStatus("P2_ETA",1); ntp->SetBranchAddress("P2_ETA", &(K_eta));
ntp->SetBranchStatus("sPi_ETA",1); ntp->SetBranchAddress("sPi_ETA", &(SPi_eta));
ntp->SetBranchStatus("Dst_ID",1); ntp->SetBranchAddress("Dst_ID", &(Dst_ID));
ntp->SetBranchStatus("D0_ID",1); ntp->SetBranchAddress("D0_ID", &(D0_ID));
ntp->SetBranchStatus("P1_ID",1); ntp->SetBranchAddress("P1_ID", &(Pi_ID));
ntp->SetBranchStatus("P2_ID",1); ntp->SetBranchAddress("P2_ID", &(K_ID));
ntp->SetBranchStatus("sPi_ID",1); ntp->SetBranchAddress("sPi_ID", &(SPi_ID));
TH1F *h_pT_reco_SPi = new TH1F("h_pT_reco_SPi", ";p_{T}/MeV; reconstructed Events", 35, 100., 800.);
TH1F *h_pT_reco_Pi = new TH1F("h_pT_reco_Pi", ";p_{T}/MeV; reconstructed Events", 50, 700., 5700.);
TH1F *h_pT_reco_K = new TH1F("h_pT_reco_K", ";p_{T}/MeV; reconstructed Events", 57, 700., 6200.);
TH1F *h_pT_reco_D0 = new TH1F("h_pT_reco_D0", ";p_{T}/MeV; reconstructed Events", 70, 2000., 9000.);
TH1F *h_pT_reco_Dst = new TH1F("h_pT_reco_Dst", ";p_{T}/MeV; reconstructed Events", 74, 2200., 9600.);
TH1F *h_pT_SPi = new TH1F("h_pT_SPi", ";p_{T}/MeV;Events", 35, 100., 800.);
TH1F *h_pT_Pi = new TH1F("h_pT_Pi", ";p_{T}/MeV;Events", 50, 700., 5700.);
TH1F *h_pT_K = new TH1F("h_pT_K", ";p_{T}/MeV;Events", 57, 700., 6200.);
TH1F *h_pT_D0 = new TH1F("h_pT_D0", ";p_{T}/MeV;Events", 70, 2000., 9000.);
TH1F *h_pT_Dst = new TH1F("h_pT_Dst", ";p_{T}/MeV;Events", 74, 2200., 9600.);
TH1F *h_phi_reco_SPi = new TH1F("h_phi_reco_SPi", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_Pi = new TH1F("h_phi_reco_Pi", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_K = new TH1F("h_phi_reco_K", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_D0 = new TH1F("h_phi_reco_D0", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_Dst = new TH1F("h_phi_reco_Dst", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_SPi = new TH1F("h_phi_SPi", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_Pi = new TH1F("h_phi_Pi", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_K = new TH1F("h_phi_K", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_D0 = new TH1F("h_phi_D0", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_Dst = new TH1F("h_phi_Dst", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_eta_reco_SPi = new TH1F("h_eta_reco_SPi", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_Pi = new TH1F("h_eta_reco_Pi", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_K = new TH1F("h_eta_reco_K", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_D0 = new TH1F("h_eta_reco_D0", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_Dst = new TH1F("h_eta_reco_Dst", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_SPi = new TH1F("h_eta_SPi", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_Pi = new TH1F("h_eta_Pi", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_K = new TH1F("h_eta_K", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_D0 = new TH1F("h_eta_D0", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_Dst = new TH1F("h_eta_Dst", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_theta_reco_SPi = new TH1F("h_theta_reco_SPi", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_Pi = new TH1F("h_theta_reco_Pi", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_K = new TH1F("h_theta_reco_K", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_D0 = new TH1F("h_theta_reco_D0", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_Dst = new TH1F("h_theta_reco_Dst", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_SPi = new TH1F("h_theta_SPi", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_Pi = new TH1F("h_theta_Pi", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_K = new TH1F("h_theta_K", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_D0 = new TH1F("h_theta_D0", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_Dst = new TH1F("h_theta_Dst", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_pT_reco_SPi_pos = new TH1F("h_pT_reco_SPi_pos", ";p_{T}/MeV; reconstructed Events", 35, 100., 800.);
TH1F *h_pT_reco_Pi_pos = new TH1F("h_pT_reco_Pi_pos", ";p_{T}/MeV; reconstructed Events", 50, 700., 5700.);
TH1F *h_pT_reco_K_pos = new TH1F("h_pT_reco_K_pos", ";p_{T}/MeV; reconstructed Events", 57, 700., 6200.);
TH1F *h_pT_reco_D0_pos = new TH1F("h_pT_reco_D0_pos", ";p_{T}/MeV; reconstructed Events", 70, 2000., 9000.);
TH1F *h_pT_reco_Dst_pos = new TH1F("h_pT_reco_Dst_pos", ";p_{T}/MeV; reconstructed Events", 74, 2200., 9600.);
TH1F *h_pT_SPi_pos = new TH1F("h_pT_SPi_pos", ";p_{T}/MeV;Events", 35, 100., 800.);
TH1F *h_pT_Pi_pos = new TH1F("h_pT_Pi_pos", ";p_{T}/MeV;Events", 50, 700., 5700.);
TH1F *h_pT_K_pos = new TH1F("h_pT_K_pos", ";p_{T}/MeV;Events", 57, 700., 6200.);
TH1F *h_pT_D0_pos = new TH1F("h_pT_D0_pos", ";p_{T}/MeV;Events", 70, 2000., 9000.);
TH1F *h_pT_Dst_pos = new TH1F("h_pT_Dst_pos", ";p_{T}/MeV;Events", 74, 2200., 9600.);
TH1F *h_phi_reco_SPi_pos = new TH1F("h_phi_reco_SPi_pos", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_Pi_pos = new TH1F("h_phi_reco_Pi_pos", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_K_pos = new TH1F("h_phi_reco_K_pos", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_D0_pos = new TH1F("h_phi_reco_D0_pos", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_Dst_pos = new TH1F("h_phi_reco_Dst_pos", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_SPi_pos = new TH1F("h_phi_SPi_pos", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_Pi_pos = new TH1F("h_phi_Pi_pos", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_K_pos = new TH1F("h_phi_K_pos", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_D0_pos = new TH1F("h_phi_D0_pos", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_Dst_pos = new TH1F("h_phi_Dst_pos", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_eta_reco_SPi_pos = new TH1F("h_eta_reco_SPi_pos", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_Pi_pos = new TH1F("h_eta_reco_Pi_pos", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_K_pos = new TH1F("h_eta_reco_K_pos", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_D0_pos = new TH1F("h_eta_reco_D0_pos", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_Dst_pos = new TH1F("h_eta_reco_Dst_pos", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_SPi_pos = new TH1F("h_eta_SPi_pos", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_Pi_pos = new TH1F("h_eta_Pi_pos", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_K_pos = new TH1F("h_eta_K_pos", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_D0_pos = new TH1F("h_eta_D0_pos", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_Dst_pos = new TH1F("h_eta_Dst_pos", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_theta_reco_SPi_pos = new TH1F("h_theta_reco_SPi_pos", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_Pi_pos = new TH1F("h_theta_reco_Pi_pos", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_K_pos = new TH1F("h_theta_reco_K_pos", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_D0_pos = new TH1F("h_theta_reco_D0_pos", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_Dst_pos = new TH1F("h_theta_reco_Dst_pos", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_SPi_pos = new TH1F("h_theta_SPi_pos", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_Pi_pos = new TH1F("h_theta_Pi_pos", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_K_pos = new TH1F("h_theta_K_pos", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_D0_pos = new TH1F("h_theta_D0_pos", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_Dst_pos = new TH1F("h_theta_Dst_pos", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_pT_reco_SPi_neg = new TH1F("h_pT_reco_SPi_neg", ";p_{T}/MeV; reconstructed Events", 35, 100., 800.);
TH1F *h_pT_reco_Pi_neg = new TH1F("h_pT_reco_Pi_neg", ";p_{T}/MeV; reconstructed Events", 50, 700., 5700.);
TH1F *h_pT_reco_K_neg = new TH1F("h_pT_reco_K_neg", ";p_{T}/MeV; reconstructed Events", 57, 700., 6200.);
TH1F *h_pT_reco_D0_neg = new TH1F("h_pT_reco_D0_neg", ";p_{T}/MeV; reconstructed Events", 70, 2000., 9000.);
TH1F *h_pT_reco_Dst_neg = new TH1F("h_pT_reco_Dst_neg", ";p_{T}/MeV; reconstructed Events", 74, 2200., 9600.);
TH1F *h_pT_SPi_neg = new TH1F("h_pT_SPi_neg", ";p_{T}/MeV;Events", 35, 100., 800.);
TH1F *h_pT_Pi_neg = new TH1F("h_pT_Pi_neg", ";p_{T}/MeV;Events", 50, 700., 5700.);
TH1F *h_pT_K_neg = new TH1F("h_pT_K_neg", ";p_{T}/MeV;Events", 57, 700., 6200.);
TH1F *h_pT_D0_neg = new TH1F("h_pT_D0_neg", ";p_{T}/MeV;Events", 70, 2000., 9000.);
TH1F *h_pT_Dst_neg = new TH1F("h_pT_Dst_neg", ";p_{T}/MeV;Events", 74, 2200., 9600.);
TH1F *h_phi_reco_SPi_neg = new TH1F("h_phi_reco_SPi_neg", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_Pi_neg = new TH1F("h_phi_reco_Pi_neg", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_K_neg = new TH1F("h_phi_reco_K_neg", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_D0_neg = new TH1F("h_phi_reco_D0_neg", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_reco_Dst_neg = new TH1F("h_phi_reco_Dst_neg", ";#phi; reconstructed Events", 50, -3.5, 3.5);
TH1F *h_phi_SPi_neg = new TH1F("h_phi_SPi_neg", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_Pi_neg = new TH1F("h_phi_Pi_neg", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_K_neg = new TH1F("h_phi_K_neg", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_D0_neg = new TH1F("h_phi_D0_neg", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_phi_Dst_neg = new TH1F("h_phi_Dst_neg", ";#phi;Events", 50, -3.5, 3.5);
TH1F *h_eta_reco_SPi_neg = new TH1F("h_eta_reco_SPi_neg", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_Pi_neg = new TH1F("h_eta_reco_Pi_neg", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_K_neg = new TH1F("h_eta_reco_K_neg", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_D0_neg = new TH1F("h_eta_reco_D0_neg", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_reco_Dst_neg = new TH1F("h_eta_reco_Dst_neg", ";#eta; reconstructed Events", 50, 2.0, 4.5);
TH1F *h_eta_SPi_neg = new TH1F("h_eta_SPi_neg", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_Pi_neg = new TH1F("h_eta_Pi_neg", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_K_neg = new TH1F("h_eta_K_neg", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_D0_neg = new TH1F("h_eta_D0_neg", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_eta_Dst_neg = new TH1F("h_eta_Dst_neg", ";#eta;Events", 50, 2.0, 4.5);
TH1F *h_theta_reco_SPi_neg = new TH1F("h_theta_reco_SPi_neg", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_Pi_neg = new TH1F("h_theta_reco_Pi_neg", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_K_neg = new TH1F("h_theta_reco_K_neg", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_D0_neg = new TH1F("h_theta_reco_D0_neg", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_reco_Dst_neg = new TH1F("h_theta_reco_Dst_neg", ";#theta; reconstructed Events", 50, 0.02, 0.24);
TH1F *h_theta_SPi_neg = new TH1F("h_theta_SPi_neg", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_Pi_neg = new TH1F("h_theta_Pi_neg", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_K_neg = new TH1F("h_theta_K_neg", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_D0_neg = new TH1F("h_theta_D0_neg", ";#theta;Events", 50, 0.02, 0.24);
TH1F *h_theta_Dst_neg = new TH1F("h_theta_Dst_neg", ";#theta;Events", 50, 0.02, 0.24);
vector<TH1F*> v_Pi_hist_reco = {h_pT_reco_Pi, h_phi_reco_Pi, h_theta_reco_Pi, h_eta_reco_Pi};
vector<TH1F*> v_SPi_hist_reco = {h_pT_reco_SPi, h_phi_reco_SPi, h_theta_reco_SPi, h_eta_reco_SPi};
vector<TH1F*> v_K_hist_reco = {h_pT_reco_K, h_phi_reco_K, h_theta_reco_K, h_eta_reco_K};
vector<TH1F*> v_D0_hist_reco = {h_pT_reco_D0, h_phi_reco_D0, h_theta_reco_D0, h_eta_reco_D0};
vector<TH1F*> v_Dst_hist_reco = {h_pT_reco_Dst, h_phi_reco_Dst, h_theta_reco_Dst, h_eta_reco_Dst};
vector<TH1F*> v_Pi_hist = {h_pT_Pi, h_phi_Pi, h_theta_Pi, h_eta_Pi};
vector<TH1F*> v_SPi_hist = {h_pT_SPi, h_phi_SPi, h_theta_SPi, h_eta_SPi};
vector<TH1F*> v_K_hist = {h_pT_K, h_phi_K, h_theta_K, h_eta_K};
vector<TH1F*> v_D0_hist = {h_pT_D0, h_phi_D0, h_theta_D0, h_eta_D0};
vector<TH1F*> v_Dst_hist = {h_pT_Dst, h_phi_Dst, h_theta_Dst, h_eta_Dst};
vector<TH1F*> v_Pi_hist_reco_pos = {h_pT_reco_Pi_pos, h_phi_reco_Pi_pos, h_theta_reco_Pi_pos, h_eta_reco_Pi_pos};
vector<TH1F*> v_SPi_hist_reco_pos = {h_pT_reco_SPi_pos, h_phi_reco_SPi_pos, h_theta_reco_SPi_pos, h_eta_reco_SPi_pos};
vector<TH1F*> v_K_hist_reco_pos = {h_pT_reco_K_pos, h_phi_reco_K_pos, h_theta_reco_K_pos, h_eta_reco_K_pos};
vector<TH1F*> v_D0_hist_reco_pos = {h_pT_reco_D0_pos, h_phi_reco_D0_pos, h_theta_reco_D0_pos, h_eta_reco_D0_pos};
vector<TH1F*> v_Dst_hist_reco_pos = {h_pT_reco_Dst_pos, h_phi_reco_Dst_pos, h_theta_reco_Dst_pos, h_eta_reco_Dst_pos};
vector<TH1F*> v_Pi_hist_pos = {h_pT_Pi_pos, h_phi_Pi_pos, h_theta_Pi_pos, h_eta_Pi_pos};
vector<TH1F*> v_SPi_hist_pos = {h_pT_SPi_pos, h_phi_SPi_pos, h_theta_SPi_pos, h_eta_SPi_pos};
vector<TH1F*> v_K_hist_pos = {h_pT_K_pos, h_phi_K_pos, h_theta_K_pos, h_eta_K_pos};
vector<TH1F*> v_D0_hist_pos = {h_pT_D0_pos, h_phi_D0_pos, h_theta_D0_pos, h_eta_D0_pos};
vector<TH1F*> v_Dst_hist_pos = {h_pT_Dst_pos, h_phi_Dst_pos, h_theta_Dst_pos, h_eta_Dst_pos};
vector<TH1F*> v_Pi_hist_reco_neg = {h_pT_reco_Pi_neg, h_phi_reco_Pi_neg, h_theta_reco_Pi_neg, h_eta_reco_Pi_neg};
vector<TH1F*> v_SPi_hist_reco_neg = {h_pT_reco_SPi_neg, h_phi_reco_SPi_neg, h_theta_reco_SPi_neg, h_eta_reco_SPi_neg};
vector<TH1F*> v_K_hist_reco_neg = {h_pT_reco_K_neg, h_phi_reco_K_neg, h_theta_reco_K_neg, h_eta_reco_K_neg};
vector<TH1F*> v_D0_hist_reco_neg = {h_pT_reco_D0_neg, h_phi_reco_D0_neg, h_theta_reco_D0_neg, h_eta_reco_D0_neg};
vector<TH1F*> v_Dst_hist_reco_neg = {h_pT_reco_Dst_neg, h_phi_reco_Dst_neg, h_theta_reco_Dst_neg, h_eta_reco_Dst_neg};
vector<TH1F*> v_Pi_hist_neg = {h_pT_Pi_neg, h_phi_Pi_neg, h_theta_Pi_neg, h_eta_Pi_neg};
vector<TH1F*> v_SPi_hist_neg = {h_pT_SPi_neg, h_phi_SPi_neg, h_theta_SPi_neg, h_eta_SPi_neg};
vector<TH1F*> v_K_hist_neg = {h_pT_K_neg, h_phi_K_neg, h_theta_K_neg, h_eta_K_neg};
vector<TH1F*> v_D0_hist_neg = {h_pT_D0_neg, h_phi_D0_neg, h_theta_D0_neg, h_eta_D0_neg};
vector<TH1F*> v_Dst_hist_neg = {h_pT_Dst_neg, h_phi_Dst_neg, h_theta_Dst_neg, h_eta_Dst_neg};
sumhisterr(v_Pi_hist, v_Pi_hist_pos, v_Pi_hist_neg);
sumhisterr(v_SPi_hist, v_SPi_hist_pos, v_SPi_hist_neg);
sumhisterr(v_K_hist, v_K_hist_pos, v_K_hist_neg);
sumhisterr(v_D0_hist, v_D0_hist_pos, v_D0_hist_neg);
sumhisterr(v_Dst_hist, v_Dst_hist_pos, v_Dst_hist_neg);
sumhisterr(v_Pi_hist_reco, v_Pi_hist_reco_pos, v_Pi_hist_reco_neg);
sumhisterr(v_SPi_hist_reco, v_SPi_hist_reco_pos, v_SPi_hist_reco_neg);
sumhisterr(v_K_hist_reco, v_K_hist_reco_pos, v_K_hist_reco_neg);
sumhisterr(v_D0_hist_reco, v_D0_hist_reco_pos, v_D0_hist_reco_neg);
sumhisterr(v_Dst_hist_reco, v_Dst_hist_reco_pos, v_Dst_hist_reco_neg);
for(int i = 0; i < nEvents; ++i)
{
ntp->GetEvent(i);
if (i % (nEvents/10) == 0)cout << "=== Event " << i/(nEvents/10) * 10 << "%" << endl;
vector<double> v_Pi_var = {Pi_pT, Pi_phi, Pi_theta, Pi_eta};
vector<double> v_K_var = {K_pT, K_phi, K_theta, K_eta};
vector<double> v_SPi_var = {SPi_pT, SPi_phi, SPi_theta, SPi_eta};
vector<double> v_D0_var = {D0_pT, D0_phi, D0_theta, D0_eta};
vector<double> v_Dst_var = {Dst_pT, Dst_phi, Dst_theta, Dst_eta};
(isPi_reco == 1 && isK_reco == 1)? isD0_reco = 1 : isD0_reco = 0;
(isSPi_reco == 1 && isD0_reco == 1)? isDst_reco = 1 : isDst_reco = 0;
hist_fill(v_Pi_hist, v_Pi_hist_reco, v_Pi_hist_pos, v_Pi_hist_reco_pos, v_Pi_hist_neg, v_Pi_hist_reco_neg, v_Pi_var, isPi_reco, nPi_reco, nPi_pos, nPi_reco_pos, Pi_ID);
hist_fill(v_K_hist, v_K_hist_reco, v_K_hist_pos, v_K_hist_reco_pos, v_K_hist_neg, v_K_hist_reco_neg, v_K_var, isK_reco, nK_reco, nK_pos, nK_reco_pos, K_ID);
hist_fill(v_SPi_hist, v_SPi_hist_reco, v_SPi_hist_pos, v_SPi_hist_reco_pos, v_SPi_hist_neg, v_SPi_hist_reco_neg, v_SPi_var, isSPi_reco, nSPi_reco, nSPi_pos, nSPi_reco_pos, SPi_ID);
hist_fill(v_D0_hist, v_D0_hist_reco, v_D0_hist_pos, v_D0_hist_reco_pos, v_D0_hist_neg, v_D0_hist_reco_neg, v_D0_var, isD0_reco, nD0_reco, nD0_pos, nD0_reco_pos, D0_ID);
hist_fill(v_Dst_hist, v_Dst_hist_reco, v_Dst_hist_pos, v_Dst_hist_reco_pos, v_Dst_hist_neg, v_Dst_hist_reco_neg, v_Dst_var, isDst_reco, nDst_reco, nDst_pos, nDst_reco_pos, Dst_ID);
v_Pi_var.clear();
v_K_var.clear();
v_SPi_var.clear();
v_D0_var.clear();
v_Dst_var.clear();
}
nPi_neg = nTot - nPi_pos;
nK_neg = nTot - nK_pos;
nSPi_neg = nTot - nSPi_pos;
nD0_neg = nTot - nD0_pos;
nDst_neg = nTot - nDst_pos;
nPi_reco_neg = nPi_reco - nPi_reco_pos;
nK_reco_neg = nK_reco - nK_reco_pos;
nSPi_reco_neg = nSPi_reco - nSPi_reco_pos;
nD0_reco_neg = nD0_reco - nD0_reco_pos;
nDst_reco_neg = nDst_reco - nDst_reco_pos;
vector<double> v_n_reco_ges = {nPi_reco,nK_reco,nSPi_reco,nD0_reco,nDst_reco};
vector<double> v_n_reco_pos = {nPi_reco_pos,nK_reco_pos,nSPi_reco_pos,nD0_reco_pos,nDst_reco_pos};
vector<double> v_n_reco_neg = {nPi_reco_neg,nK_reco_neg,nSPi_reco_neg,nD0_reco_neg,nDst_reco_neg};
vector<double> v_n_pos = {nPi_pos, nK_pos, nSPi_pos, nD0_pos, nDst_pos};
vector<double> v_n_neg = {nPi_neg, nK_neg, nSPi_neg, nD0_neg, nDst_neg};
vector<double> v_nEvents = {nTot, nTot, nTot, nTot, nTot};
vector<double> v_eff_ges = get_eff(v_nEvents,v_n_reco_ges);
vector<double> v_eff_pos = get_eff(v_n_pos,v_n_reco_pos);
vector<double> v_eff_neg = get_eff(v_n_neg,v_n_reco_neg);
vector<double> v_err_ges = get_err(v_eff_ges,v_nEvents);
vector<double> v_err_pos = get_err(v_eff_pos,v_n_pos);
vector<double> v_err_neg = get_err(v_eff_neg,v_n_neg);
vector<double> v_dev = deviation(v_eff_pos,v_eff_neg);
vector<double> v_dev_err = deviation_err(v_eff_pos,v_err_pos,v_eff_neg,v_err_neg);
hist_divide(v_Pi_hist,v_Pi_hist_reco);
hist_divide(v_K_hist,v_K_hist_reco);
hist_divide(v_SPi_hist,v_SPi_hist_reco);
hist_divide(v_D0_hist,v_D0_hist_reco);
hist_divide(v_Dst_hist,v_Dst_hist_reco);
hist_divide(v_Pi_hist_pos,v_Pi_hist_reco_pos);
hist_divide(v_K_hist_pos,v_K_hist_reco_pos);
hist_divide(v_SPi_hist_pos,v_SPi_hist_reco_pos);
hist_divide(v_D0_hist_pos,v_D0_hist_reco_pos);
hist_divide(v_Dst_hist_pos,v_Dst_hist_reco_pos);
hist_divide(v_Pi_hist_neg,v_Pi_hist_reco_neg);
hist_divide(v_K_hist_neg,v_K_hist_reco_neg);
hist_divide(v_SPi_hist_neg,v_SPi_hist_reco_neg);
hist_divide(v_D0_hist_neg,v_D0_hist_reco_neg);
hist_divide(v_Dst_hist_neg,v_Dst_hist_reco_neg);
string output_hist_name;
output_hist_name = "output/histOut_"+sample+".root";
TFile *out_hist_fi = new TFile(output_hist_name.c_str(),"RECREATE");
h_pT_reco_Pi->Write();
h_pT_reco_K->Write();
h_pT_reco_SPi->Write();
h_pT_reco_D0->Write();
h_pT_reco_Dst->Write();
h_phi_reco_Pi->Write();
h_phi_reco_K->Write();
h_phi_reco_SPi->Write();
h_phi_reco_D0->Write();
h_phi_reco_Dst->Write();
h_theta_reco_Pi->Write();
h_theta_reco_K->Write();
h_theta_reco_SPi->Write();
h_theta_reco_D0->Write();
h_theta_reco_Dst->Write();
h_eta_reco_Pi->Write();
h_eta_reco_K->Write();
h_eta_reco_SPi->Write();
h_eta_reco_D0->Write();
h_eta_reco_Dst->Write();
h_pT_reco_Pi_pos->Write();
h_pT_reco_K_pos->Write();
h_pT_reco_SPi_pos->Write();
h_pT_reco_D0_pos->Write();
h_pT_reco_Dst_pos->Write();
h_phi_reco_Pi_pos->Write();
h_phi_reco_K_pos->Write();
h_phi_reco_SPi_pos->Write();
h_phi_reco_D0_pos->Write();
h_phi_reco_Dst_pos->Write();
h_theta_reco_Pi_pos->Write();
h_theta_reco_K_pos->Write();
h_theta_reco_SPi_pos->Write();
h_theta_reco_D0_pos->Write();
h_theta_reco_Dst_pos->Write();
h_eta_reco_Pi_pos->Write();
h_eta_reco_K_pos->Write();
h_eta_reco_SPi_pos->Write();
h_eta_reco_D0_pos->Write();
h_eta_reco_Dst_pos->Write();
h_pT_reco_Pi_neg->Write();
h_pT_reco_K_neg->Write();
h_pT_reco_SPi_neg->Write();
h_pT_reco_D0_neg->Write();
h_pT_reco_Dst_neg->Write();
h_phi_reco_Pi_neg->Write();
h_phi_reco_K_neg->Write();
h_phi_reco_SPi_neg->Write();
h_phi_reco_D0_neg->Write();
h_phi_reco_Dst_neg->Write();
h_theta_reco_Pi_neg->Write();
h_theta_reco_K_neg->Write();
h_theta_reco_SPi_neg->Write();
h_theta_reco_D0_neg->Write();
h_theta_reco_Dst_neg->Write();
h_eta_reco_Pi_neg->Write();
h_eta_reco_K_neg->Write();
h_eta_reco_SPi_neg->Write();
h_eta_reco_D0_neg->Write();
h_eta_reco_Dst_neg->Write();
out_hist_fi->Write();
out_hist_fi->Close();
double dev_Pi = (nPi_reco_pos - nPi_reco_neg)/(nPi_reco_pos + nPi_reco_neg);
double dev_K = (nK_reco_pos - nK_reco_neg)/(nK_reco_pos + nK_reco_neg);
double dev_SPi = (nSPi_reco_pos - nSPi_reco_neg)/(nSPi_reco_pos + nSPi_reco_neg);
double dev_D0 = (nD0_reco_pos - nD0_reco_neg)/(nD0_reco_pos + nD0_reco_neg);
double dev_Dst = (nDst_reco_pos - nDst_reco_neg)/(nDst_reco_pos + nDst_reco_neg);
double dev_Pi_err = 2*sqrt(pow(nPi_reco_pos,2.)*nPi_reco_neg + pow(nPi_reco_neg,2.)*nPi_reco_pos)/pow(nPi_reco_pos + nPi_reco_neg,2.);
double dev_K_err = 2*sqrt(pow(nK_reco_pos,2.)*nK_reco_neg + pow(nK_reco_neg,2.)*nK_reco_pos)/pow(nK_reco_pos + nK_reco_neg,2.);
double dev_SPi_err = 2*sqrt(pow(nSPi_reco_pos,2.)*nSPi_reco_neg + pow(nSPi_reco_neg,2.)*nSPi_reco_pos)/pow(nSPi_reco_pos + nSPi_reco_neg,2.);
double dev_D0_err = 2*sqrt(pow(nD0_reco_pos,2.)*nD0_reco_neg + pow(nD0_reco_neg,2.)*nD0_reco_pos)/pow(nD0_reco_pos + nD0_reco_neg,2.);
double dev_Dst_err = 2*sqrt(pow(nDst_reco_pos,2.)*nDst_reco_neg + pow(nDst_reco_neg,2.)*nDst_reco_pos)/pow(nDst_reco_pos + nDst_reco_neg,2.);
cout << "Total: " << endl;
cout << "Reconstructed number of pions: " << nPi_reco << ", eff.: " << v_eff_ges.at(0) << " +/- " << v_err_ges.at(0) << endl;
cout << "Reconstructed number of Kaons: " << nK_reco << ", eff.: " << v_eff_ges.at(1) << " +/- " << v_err_ges.at(1) << endl;
cout << "Reconstructed number of soft pions: " << nSPi_reco << ", eff.: " << v_eff_ges.at(2) << " +/- " << v_err_ges.at(2) << endl;
cout << "Reconstructed number of D0: " << nD0_reco << ", eff.: " << v_eff_ges.at(3) << " +/- " << v_err_ges.at(3) << endl;
cout << "Reconstructed number of D*: " << nDst_reco << ", eff.: " << v_eff_ges.at(4) << " +/- " << v_err_ges.at(4) << endl;
cout << "Charge: +" << endl;
cout << "Reconstructed number of pions: " << nPi_reco_pos << " of " << nPi_pos << " , eff.: " << v_eff_pos.at(0) << " +/- " << v_err_pos.at(0) << endl;
cout << "Reconstructed number of Kaons: " << nK_reco_pos << " of " << nK_pos << " eff.: " << v_eff_pos.at(1) << " +/- " << v_err_pos.at(1) << endl;
cout << "Reconstructed number of soft pions: " << nSPi_reco_pos << " of " << nSPi_pos << " , eff.: " << v_eff_pos.at(2) << " +/- " << v_err_pos.at(2) << endl;
cout << "Reconstructed number of D0: " << nD0_reco_pos << " of " << nD0_pos << " , eff.: " << v_eff_pos.at(3) << " +/- " << v_err_pos.at(3) << endl;
cout << "Reconstructed number of D*: " << nDst_reco_pos << " of " << nDst_pos << " , eff.: " << v_eff_pos.at(4) << " +/- " << v_err_pos.at(4) << endl;
cout << "Charge: -" << endl;
cout << "Reconstructed number of pions: " << nPi_reco_neg << " of " << nPi_neg << " , eff.: " << v_eff_neg.at(0) << " +/- " << v_err_neg.at(0) << endl;
cout << "Reconstructed number of Kaons: " << nK_reco_neg << " of " << nK_neg << " , eff.: " << v_eff_neg.at(1) << " +/- " << v_err_neg.at(1) << endl;
cout << "Reconstructed number of soft pions: " << nSPi_reco_neg << " of " << nSPi_neg << " , eff.: " << v_eff_neg.at(2) << " +/- " << v_err_neg.at(2) << endl;
cout << "Reconstructed number of D0: " << nD0_reco_neg << " of " << nD0_neg << " , eff.: " << v_eff_neg.at(3) << " +/- " << v_err_neg.at(3) << endl;
cout << "Reconstructed number of D*: " << nDst_reco_neg << " of " << nDst_neg << " , eff.: " << v_eff_neg.at(4) << " +/- " << v_err_neg.at(4) << endl;
cout << "Deviation via efficiencies:" << endl;
cout << "Pions: " << v_dev.at(0) << " +/- " << v_dev_err.at(0) << " , in sigmas: " << abs(v_dev.at(0)/v_dev_err.at(0)) << endl;
cout << "Kaons: " << v_dev.at(1) << " +/- " << v_dev_err.at(1) << " , in sigmas: " << abs(v_dev.at(1)/v_dev_err.at(1)) << endl;
cout << "soft Pions: " << v_dev.at(2) << " +/- " << v_dev_err.at(2) << " , in sigmas: " << abs(v_dev.at(2)/v_dev_err.at(2)) << endl;
cout << "D0: " << v_dev.at(3) << " +/- " << v_dev_err.at(3) << " , in sigmas: " << abs(v_dev.at(3)/v_dev_err.at(3)) << endl;
cout << "Dst: " << v_dev.at(4) << " +/- " << v_dev_err.at(4) << " , in sigmas: " << abs(v_dev.at(4)/v_dev_err.at(4)) << endl;
cout << "Deviation via total numbers:" << endl;
cout << "Pions: " << dev_Pi << " +/- " << dev_Pi_err << " , in sigmas: " << abs(dev_Pi/dev_Pi_err) << endl;
cout << "Kaons: " << dev_K << " +/- " << dev_K_err << " , in sigmas: " << abs(dev_K/dev_K_err) << endl;
cout << "soft Pions: " << dev_SPi << " +/- " << dev_SPi_err << " , in sigmas: " << abs(dev_SPi/dev_SPi_err) << endl;
cout << "D0: " << dev_D0 << " +/- " << dev_D0_err << " , in sigmas: " << abs(dev_D0/dev_D0_err) << endl;
cout << "Dst: " << dev_Dst << " +/- " << dev_Dst_err << " , in sigmas: " << abs(dev_Dst/dev_Dst_err) << endl;
sethists(v_Pi_hist_reco, v_Pi_hist_reco_pos, v_Pi_hist_reco_neg);
sethists(v_SPi_hist_reco, v_SPi_hist_reco_pos, v_SPi_hist_reco_neg);
sethists(v_K_hist_reco, v_K_hist_reco_pos, v_K_hist_reco_neg);
sethists(v_D0_hist_reco, v_D0_hist_reco_pos, v_D0_hist_reco_neg);
sethists(v_Dst_hist_reco, v_Dst_hist_reco_pos, v_Dst_hist_reco_neg);
gStyle->SetOptStat(0);
printhists(v_Pi_hist_reco, v_Pi_hist_reco_pos, v_Pi_hist_reco_neg, polarisation);
printhists(v_SPi_hist_reco, v_SPi_hist_reco_pos, v_SPi_hist_reco_neg, polarisation);
printhists(v_K_hist_reco, v_K_hist_reco_pos, v_K_hist_reco_neg, polarisation);
printhists(v_D0_hist_reco, v_D0_hist_reco_pos, v_D0_hist_reco_neg, polarisation);
printhists(v_Dst_hist_reco, v_Dst_hist_reco_pos, v_Dst_hist_reco_neg, polarisation);
printdevhists(v_Pi_hist_reco_pos, v_Pi_hist_reco_neg, polarisation);
printdevhists(v_SPi_hist_reco_pos, v_SPi_hist_reco_neg, polarisation);
printdevhists(v_K_hist_reco_pos, v_K_hist_reco_neg, polarisation);
printdevhists(v_D0_hist_reco_pos, v_D0_hist_reco_neg, polarisation);
printdevhists(v_Dst_hist_reco_pos, v_Dst_hist_reco_neg, polarisation);
}
|
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll maxn = 10;
ll a[maxn], m[maxn], n;
ll d;
ll exgcd(ll a,ll b,ll &x,ll &y) {
if(b==0) {
x=1;
y=0;
return a;
}
ll r=exgcd(b,a%b,x,y);
ll t=x;
x=y;
y=t-a/b*y;
return r;
}
//
//void exgcd(ll a,ll b,ll &d,ll &x,ll &y)
//{
// if(b==0){
// d=a;
// x=1,y=0;
// }
// else{
// exgcd(b,a%b,d,y,x);
// y-=(a/b)*x;
// }
//}
//ll CRT(ll *a,ll *m,int n)
//{
// ll M=1,d,y,x=0;
// for(int i=0;i<n;i++) M*=m[i];
// for(int i=0;i<n;i++){
// ll w=M/m[i];
// exgcd(m[i],w,d,d,y);
// x=(x+y*w*a[i])%M;
// }
// return (x+M)%M;
//}
ll CRT(ll a[], ll m[], ll n) {
ll M = 1;
for(int i = 0; i < n; i++) M *= m[i];
ll ret = 0;
for(int i = 0; i < n; i++) {
ll x, y;
ll tm = M / m[i];
exgcd(tm, m[i], x, y);
ret = (ret + tm * x * a[i]) % M;
}
return (ret + M) % M;
}
int main(){
m[0]=23;
m[1]=28;
m[2]=33;
int cas=0;
while(cin>>a[0]>>a[1]>>a[2]>>d){
cas++;
if(a[0]==-1&&a[1]==-1&&a[2]==-1&&d==-1)
break;
ll ans=CRT(a,m,3);
ll M=(ll)(m[0]*m[1]*m[2]);
while(ans-d<0||ans==0)
ans+=M;
cout<<"Case "<<cas<<": the next triple peak occurs in "<<ans-d<<" days.\n";
}
return 0;
}
|
// Super Reduced String
// https://www.hackerrank.com/challenges/reduced-string/problem
#include<bits/stdc++.h>
using namespace std;
string superReducedString(string s) {
bool flag=true;
string str="";
int i;
for(i=0; i<s.length(); i++)
{
if(i!=0 && s[i]==str.back())
{
flag=true;
str.pop_back();
continue;
}
str+=s[i];
}
s=str;
s=s.length()==0?"Empty String":s;
return s;
}
int main()
{
string str;
cin>>str;
cout<<superReducedString(str);
cout<<endl;
return 0;
}
|
#include "ObjectListIterator.h"
#include "Ledger.h"
#include "logging.h"
namespace credb
{
namespace trusted
{
ObjectListIterator::ObjectListIterator(const OpContext &op_context,
const std::string &collection,
const json::Document &predicates,
Ledger &ledger,
LockHandle *parent_lock_handle,
std::unique_ptr<ObjectKeyProvider> keys)
: m_context(op_context), m_collection(collection), m_predicates(predicates.duplicate()),
m_ledger(ledger), m_lock_handle(ledger, parent_lock_handle), m_keys(std::move(keys)),
m_current_block(INVALID_BLOCK), m_current_shard(-1)
{
}
ObjectListIterator::ObjectListIterator(ObjectListIterator &&other) noexcept
: m_context(other.m_context), m_collection(other.m_collection),
m_predicates(std::move(other.m_predicates)), m_ledger(other.m_ledger),
m_lock_handle(std::move(other.m_lock_handle)), m_keys(std::move(other.m_keys)),
m_current_block(other.m_current_block), m_current_shard(other.m_current_shard)
{
}
event_id_t ObjectListIterator::next(std::string &key, ObjectEventHandle &res)
{
res.clear();
event_id_t eid = INVALID_EVENT;
int cnt = 0;
while(!res.valid() && m_keys && m_keys->get_next_key(key))
{
m_lock_handle.release_block(m_current_shard, m_current_block, LockType::Read);
m_current_block = INVALID_BLOCK;
m_current_shard = m_ledger.get_shard(m_collection, key);
res = m_ledger.get_latest_version(m_context, m_collection, key, "", eid, m_lock_handle, LockType::Read);
if(!res.valid())
{
continue;
}
m_current_block = eid.block;
auto view = res.value();
if(!view.matches_predicates(m_predicates))
{
++cnt;
m_lock_handle.release_block(m_current_shard, m_current_block, LockType::Read);
m_current_block = INVALID_BLOCK;
res.clear();
}
}
if(cnt > 100)
{
log_debug(std::to_string(cnt) + " keys have been filterted out by the predicate");
}
if(res.valid())
{
return eid;
}
else
{
// At end
m_lock_handle.release_block(m_current_shard, m_current_block, LockType::Read);
m_current_block = INVALID_BLOCK;
return INVALID_EVENT;
}
}
}
}
|
#include "GamePch.h"
#include "PowerUpShield.h"
#include "GameMessage.h"
uint32_t PowerUpShield::s_TypeID = hg::ComponentFactory::GetGameComponentID();
void PowerUpShield::Start()
{
m_timer = 0;
}
void PowerUpShield::Update()
{
if (m_timer >= m_duration)
{
PowerUpMessage msg(PowerUpType::kPowerUp_End | PowerUpType::kPowerUp_Shield, 5);
GetEntity()->GetTransform()->GetParent()->GetEntity()->SendMsg(&msg);
GetEntity()->Destroy();
return;
}
m_timer += hg::g_Time.Delta();
}
void PowerUpShield::LoadFromXML(tinyxml2::XMLElement * data)
{
data->QueryFloatAttribute("duration", &m_duration);
}
hg::IComponent * PowerUpShield::MakeCopyDerived() const
{
PowerUpShield* rs = (PowerUpShield*)hg::IComponent::Create(SID(PowerUpShield));
*rs = *this;
return rs;
}
|
#include<bits/stdc++.h>
#define rep(i, s, n) for (int i = (s); i < (int)(n); i++)
#define INF ((1LL<<62)-(1LL<<31)) /*オーバーフローしない程度に大きい数*/
#define MOD 1000000007
using namespace std;
using ll = long long;
using Graph = vector<vector<int>>;
using pint = pair<int,int>;
const double PI = 3.14159265358979323846;
const int dx[4] = {1,0,-1,0};
const int dy[4] = {0,1,0,-1};
int main(){
string a,b,c;
cin >> a >> b >> c;
//カードの数
int ac = a.size();
if(ac == 1){
cout << "A" << endl;
return 0;
}
int bc = b.size();
int cc = c.size();
int anow = 0;
int bnow = 0;
int cnow = 0;
char x = 'a';
while(true){
if(x == 'a'){
if(anow == ac){
cout << "A" << endl;
return 0;
}
x = a[anow];
anow++;
}
else if(x == 'b'){
if(bnow == bc){
cout << "B" << endl;
return 0;
}
x = b[bnow];
bnow++;
}
else{
if(cnow == cc){
cout << "C" << endl;
return 0;
}
x = c[cnow];
cnow++;
}
}
cout << -1 << endl;
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <Renderer/Buffer/IVertexArray.h>
#include "VulkanRenderer/Vulkan.h"
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
namespace Renderer
{
struct VertexAttributes;
struct VertexArrayVertexBuffer;
}
namespace VulkanRenderer
{
class IndexBuffer;
class VertexBuffer;
class VulkanRenderer;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace VulkanRenderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Vulkan vertex array interface
*/
class VertexArray final : public Renderer::IVertexArray
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] vulkanRenderer
* Owner Vulkan renderer instance
* @param[in] vertexAttributes
* Vertex attributes ("vertex declaration" in Direct3D 9 terminology, "input layout" in Direct3D 10 & 11 terminology)
* @param[in] numberOfVertexBuffers
* Number of vertex buffers, having zero vertex buffers is valid
* @param[in] vertexBuffers
* At least numberOfVertexBuffers instances of vertex array vertex buffers, can be a null pointer in case there are zero vertex buffers, the data is internally copied and you have to free your memory if you no longer need it
* @param[in] indexBuffer
* Optional index buffer to use, can be a null pointer, the vertex array instance keeps a reference to the index buffer
*/
VertexArray(VulkanRenderer& vulkanRenderer, const Renderer::VertexAttributes& vertexAttributes, uint32_t numberOfVertexBuffers, const Renderer::VertexArrayVertexBuffer* vertexBuffers, IndexBuffer* indexBuffer);
/**
* @brief
* Destructor
*/
virtual ~VertexArray() override;
/**
* @brief
* Return the used index buffer
*
* @return
* The used index buffer, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
inline IndexBuffer* getIndexBuffer() const;
/**
* @brief
* Bind Vulkan buffers
*
* @param[in] vkCommandBuffer
* Vulkan command buffer to write into
*/
void bindVulkanBuffers(VkCommandBuffer vkCommandBuffer) const;
//[-------------------------------------------------------]
//[ Protected virtual Renderer::RefCount methods ]
//[-------------------------------------------------------]
protected:
virtual void selfDestruct() override;
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit VertexArray(const VertexArray& source) = delete;
VertexArray& operator =(const VertexArray& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
IndexBuffer* mIndexBuffer; ///< Optional index buffer to use, can be a null pointer, the vertex array instance keeps a reference to the index buffer
// Vulkan input slots
uint32_t mNumberOfSlots; ///< Number of used Vulkan input slots
VkBuffer* mVertexVkBuffers; ///< Vulkan vertex buffers
uint32_t* mStrides; ///< Strides in bytes, if "mVertexVkBuffers" is no null pointer this is no null pointer as well
VkDeviceSize* mOffsets; ///< Offsets in bytes, if "mVertexVkBuffers" is no null pointer this is no null pointer as well
// For proper vertex buffer reference counter behaviour
VertexBuffer** mVertexBuffers; ///< Vertex buffers (we keep a reference to it) used by this vertex array, can be a null pointer
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // VulkanRenderer
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "VulkanRenderer/Buffer/VertexArray.inl"
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 2010-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef MEDIA_CAMERA_SUPPORT
#include "modules/media/src/controls/cameracontrols.h"
#include "modules/media/src/controls/mediaduration.h"
#include "modules/display/vis_dev.h"
#include "modules/skin/OpSkinManager.h"
/** Camera Button */
CameraButton::CameraButton(OpInputContext* parent_ic, OpWidgetListener* listener)
: OpButton(TYPE_CUSTOM, STYLE_IMAGE)
{
GetBorderSkin()->SetImage("Media Play Button");
SetParentInputContext(parent_ic);
SetTabStop(TRUE);
SetHasFocusRect(TRUE);
SetListener(listener);
};
/* virtual */ void
CameraButton::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect)
{
OpButton::OnPaint(widget_painter, paint_rect);
// highlight
if (IsFocused())
{
GetVisualDevice()->SetColor(200, 200, 200);
OpRect highlight_rect(paint_rect.InsetBy(2, 2));
GetVisualDevice()->RectangleOut(highlight_rect.x, highlight_rect.y, highlight_rect.width, highlight_rect.height, CSS_VALUE_dashed);
}
}
/* virtual */ void
CameraButton::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows)
{
GetBorderSkin()->GetSize(w, h);
}
CameraDurationWidget::CameraDurationWidget()
: OpButton()
, m_recording_start(0)
, m_recording_time(0)
, m_time_elapsed(0)
{
m_update_timer.SetTimerListener(this);
}
CameraDurationWidget::~CameraDurationWidget()
{
m_update_timer.Stop();
}
/* virtual */ void
CameraDurationWidget::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows)
{
OpButton::GetPreferedSize(w, h, cols, rows);
if (VisualDevice* visdev = GetVisualDevice())
{
TempBuffer time_str;
RETURN_VOID_IF_ERROR(MediaTimeHelper::GenerateTimeString(time_str, 0, op_nan(NULL), TRUE));
*w = visdev->GetTxtExtent(time_str.GetStorage(), time_str.Length());
}
}
/* virtual */ void
CameraDurationWidget::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect)
{
// Background skin
g_skin_manager->DrawElement(GetVisualDevice(), "Media Duration", paint_rect);
TempBuffer time_str;
RETURN_VOID_IF_ERROR(MediaTimeHelper::GenerateTimeString(time_str, (double)(m_recording_time + m_time_elapsed), op_nan(NULL)));
RETURN_VOID_IF_ERROR(string.Set(time_str.GetStorage(), this));
// Adjust for padding
OpRect rect(paint_rect);
INT32 pad_left, pad_top, pad_right, pad_bottom;
GetBorderSkin()->GetPadding(&pad_left, &pad_top, &pad_right, &pad_bottom);
rect.x += pad_left;
rect.width -= pad_left + pad_right;
UINT32 color;
g_skin_manager->GetTextColor("Media Duration", &color);
string.Draw(rect, GetVisualDevice(), color);
}
/* virtual */ void
CameraDurationWidget::OnTimeOut(OpTimer* timer)
{
if (timer == &m_update_timer)
{
m_time_elapsed = op_time(NULL) - m_recording_start;
InvalidateAll();
m_update_timer.Start(1000);
return;
}
OpButton::OnTimeOut(timer);
}
void
CameraDurationWidget::StartRecordingTime()
{
m_recording_start = op_time(NULL);
m_time_elapsed = 0;
m_update_timer.Start(1000);
}
void
CameraDurationWidget::PauseRecordingTime()
{
m_recording_time += op_time(NULL) - m_recording_start;
m_recording_start = 0;
m_time_elapsed = 0;
m_update_timer.Stop();
}
/** CameraControls */
CameraControls::CameraControls(CameraControlsOwner* owner)
: OpWidget()
, m_owner(owner)
, m_play_pause_button(NULL)
, m_stop_button(NULL)
, m_duration_widget(NULL)
{
m_camera_can_pause = owner->GetCameraSupportsPause();
}
CameraControls::~CameraControls()
{
if (m_play_pause_button)
m_play_pause_button->Remove();
if (m_stop_button)
m_stop_button->Remove();
if (m_duration_widget)
m_duration_widget->Remove();
OP_DELETE(m_play_pause_button);
OP_DELETE(m_stop_button);
OP_DELETE(m_duration_widget);
}
OP_STATUS
CameraControls::Init()
{
// The casts below are needed to resolve base class ambiguity in Desktop,
// where OpWidget might inherit OpWidgetListener.
OpAutoPtr<CameraButton>
pp_button (OP_NEW(CameraButton, (this, static_cast<CameraButtonListener*>(this)))),
stop_button(OP_NEW(CameraButton, (this, static_cast<CameraButtonListener*>(this))));
OpAutoPtr<CameraDurationWidget> duration_widget(OP_NEW(CameraDurationWidget, ()));
if (pp_button.get() && stop_button.get() && duration_widget.get())
{
OpInputAction* pp_action = NULL;
OpInputAction* stop_action = NULL;
OpInputAction::CreateInputActionsFromString(UNI_L("Camera Record | Camera Pause"), pp_action);
OpInputAction::CreateInputActionsFromString(UNI_L("Camera Stop"), stop_action);
if (!pp_action || !stop_action)
{
OP_DELETE(pp_action);
OP_DELETE(stop_action);
return OpStatus::ERR_NOT_SUPPORTED;
}
m_play_pause_button = pp_button.release();
m_stop_button = stop_button.release();
m_duration_widget = duration_widget.release();
m_play_pause_button->SetAction(pp_action);
m_stop_button->SetAction(stop_action);
AddChild(m_play_pause_button);
AddChild(m_stop_button);
m_duration_widget->SetTabStop(FALSE);
AddChild(m_duration_widget);
return OpStatus::OK;
}
return OpStatus::ERR_NO_MEMORY;
}
void
CameraControls::SetWidgetPosition(VisualDevice* vis_dev, const AffinePos& doc_ctm, const OpRect& rect)
{
SetVisualDevice(vis_dev);
SetRect(rect, FALSE);
SetPosInDocument(doc_ctm);
}
void
CameraControls::Paint(VisualDevice* visdev, const OpRect& paint_rect)
{
GenerateOnPaint(paint_rect);
}
void
CameraControls::GetControlArea(INT32 width, INT32 height, OpRect& area)
{
area.x = 0;
area.y = height - GetRect().height;
area.width = width;
area.height = GetRect().height;
}
/* virtual */ void
CameraControls::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows)
{
m_play_pause_button->GetPreferedSize(w, h, rows, cols);
}
/* virtual */ void
CameraControls::OnResize(INT32* new_w, INT32* new_h)
{
// Record/Pause button
INT32 rec_pause_width, rec_pause_height;
m_play_pause_button->GetPreferedSize(&rec_pause_width, &rec_pause_height, 0, 0);
m_play_pause_button->SetRect(OpRect(0, *new_h - rec_pause_height, rec_pause_width, rec_pause_height));
INT32 stop_width = 0;
INT32 stop_height = 0;
// Stop button
m_stop_button->GetPreferedSize(&stop_width, &stop_height, 0, 0);
if (rec_pause_width + stop_width <= *new_w)
{
m_stop_button->SetRect(OpRect(rec_pause_width, *new_h - stop_height, stop_width, stop_height));
INT32 duration_width = 0, dummy;
m_duration_widget->GetPreferedSize(&duration_width, &dummy, 0,0);
if (rec_pause_width + stop_width + duration_width <= *new_w)
m_duration_widget->SetRect(OpRect(rec_pause_width + stop_width, *new_h - stop_height, *new_w - rec_pause_width - stop_width, stop_height));
else
m_duration_widget->SetVisibility(FALSE);
}
else
{
m_stop_button->SetVisibility(FALSE); // button does not fit into preview window
m_duration_widget->SetVisibility(FALSE);
}
}
/* virtual */ void
CameraControls::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect)
{
// Background skin
g_skin_manager->DrawElement(GetVisualDevice(), "Media Duration", paint_rect);
}
/* virtual */ void
CameraControls::OnClick(OpWidget* widget, UINT32 id /* = 0 */)
{
if (widget == m_play_pause_button)
{
m_owner->OnMultiFuncButton();
}
else if (widget == m_stop_button)
{
m_owner->OnCameraStop();
}
}
/* virtual */ void
CameraControls::OnKeyboardInputGained(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason)
{
m_owner->HandleFocusGained();
}
void
CameraControls::SetPaused()
{
m_play_pause_button->ToggleAction();
m_duration_widget->PauseRecordingTime();
}
void
CameraControls::SetRecording()
{
if (m_camera_can_pause)
m_play_pause_button->ToggleAction();
else
m_play_pause_button->SetEnabled(FALSE);
m_duration_widget->StartRecordingTime();
}
#endif // MEDIA_CAMERA_SUPPORT
|
#include <iberbar/Gui/Element/ElemStateLabel.h>
#include <iberbar/Gui/Engine.h>
#include <iberbar/Renderer/RendererSprite.h>
#include <iberbar/Renderer/Font.h>
#include <iberbar/Utility/String.h>
#include <codecvt>
iberbar::Gui::CElementStateLabel::CElementStateLabel( void )
: CRenderElement()
, m_pFont( nullptr )
, m_BlendColorRate( BlendColorRate_Normal )
, m_nAlignHorizental( UAlignHorizental::Left )
, m_nAlignVertical( UAlignVertical::Top )
, m_strText( L"" )
, m_BlendColor()
{
}
iberbar::Gui::CElementStateLabel::CElementStateLabel( const CElementStateLabel& element )
: CRenderElement( element )
, m_pFont( element.m_pFont )
, m_BlendColorRate( element.m_BlendColorRate )
, m_nAlignHorizental( element.m_nAlignHorizental )
, m_nAlignVertical( element.m_nAlignVertical )
, m_strText( element.m_strText )
, m_BlendColor( element.m_BlendColor )
{
if ( m_pFont )
m_pFont->AddRef();
}
iberbar::Gui::CElementStateLabel::~CElementStateLabel()
{
UNKNOWN_SAFE_RELEASE_NULL( m_pFont );
}
void iberbar::Gui::CElementStateLabel::Refresh()
{
m_BlendColor.Refresh();
CRenderElement::Refresh();
}
void iberbar::Gui::CElementStateLabel::Update( float nElapsedTime )
{
if ( GetVisible() == false )
return;
float lc_BlendColorRate = ( m_nState == (int)UWidgetState::Pressed ) ? BlendColorRate_Quick : m_BlendColorRate;
m_BlendColor.Blend( m_nState, nElapsedTime, lc_BlendColorRate );
CRenderElement::Update( nElapsedTime );
}
void iberbar::Gui::CElementStateLabel::Render()
{
if ( GetVisible() == false )
return;
if ( m_pFont )
{
const CRect2i* pViewport = CEngine::sGetInstance()->GetViewportState()->GetClipViewport();
CRect2i rcDst = GetBounding();
UFontDrawTextOptions Options;
Options.alignHorizental = m_nAlignHorizental;
Options.alignVertical = m_nAlignVertical;
Options.nWrapType = TextDraw::UFontDrawTextWorkBreak::NoBreak;
CEngine::sGetInstance()->GetRendererSprite()->DrawText(
m_nZOrder,
m_pFont,
pViewport,
m_strText.c_str(),
-1,
&rcDst,
m_BlendColor.currentColor,
Options );
}
CRenderElement::Render();
}
void iberbar::Gui::CElementStateLabel::SetFont( Renderer::CFont* pFont )
{
if ( m_pFont != pFont )
{
if ( m_pFont )
{
m_pFont->Release();
}
m_pFont = pFont;
if ( m_pFont )
{
m_pFont->AddRef();
m_pFont->LoadText( m_strText.c_str() );
}
}
}
void iberbar::Gui::CElementStateLabel::SetTextA( const char* strText )
{
m_strText = Utf8ToUnicode( strText );
if ( m_pFont )
{
m_pFont->LoadText( m_strText.c_str() );
}
}
void iberbar::Gui::CElementStateLabel::SetTextW( const wchar_t* strText )
{
m_strText = strText;
if ( m_pFont )
{
m_pFont->LoadText( m_strText.c_str() );
}
}
|
// Copyright (c) 2018 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/init.hpp>
#include <pika/runtime.hpp>
#include <pika/testing.hpp>
#include <atomic>
#include <cstddef>
#include <exception>
std::atomic<std::size_t> count_error_handler(0);
///////////////////////////////////////////////////////////////////////////////
bool on_thread_error(std::size_t, std::exception_ptr const&)
{
++count_error_handler;
return false;
}
///////////////////////////////////////////////////////////////////////////////
int pika_main()
{
PIKA_THROW_EXCEPTION(pika::error::invalid_status, "test", "test");
return pika::finalize();
}
int main(int argc, char* argv[])
{
auto on_stop = pika::register_thread_on_error_func(&on_thread_error);
PIKA_TEST(on_stop.empty());
bool caught_exception = false;
try
{
pika::init(pika_main, argc, argv);
PIKA_TEST(false);
}
catch (...)
{
caught_exception = true;
}
PIKA_TEST(caught_exception);
PIKA_TEST_EQ(count_error_handler.load(), std::size_t(1));
return 0;
}
|
/******************************************************************************
* This file is part of the Geometric harmonization project *
* *
* (C) 2014 Azamat Shakhimardanov *
* Herman Bruyninckx *
* azamat.shakhimardanov@mech.kuleuven.be *
* Department of Mechanical Engineering, *
* Katholieke Universiteit Leuven, Belgium. *
* *
* You may redistribute this software and/or modify it under either the *
* terms of the GNU Lesser General Public License version 2.1 (LGPLv2.1 *
* <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>) or (at your *
* discretion) of the Modified BSD License: *
* 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. *
* 3. The name of the author may not be used to endorse or promote *
* products derived from this software without specific prior written *
* permission. *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 COMPUTATIONALSTATE_KDLTYPES_HPP
#define COMPUTATIONALSTATE_KDLTYPES_HPP
#include <kdl_extensions/geometric_semantics_kdl.hpp>
#include <kdl/frames_io.hpp>
// TODO: maybe we should introduce domain independent
// representation of a computational state and instantiate for the specific domain
// The specific case could looks as below.
namespace kdle
{
//TODO: consider whether link local and global computational states
// should be represented in the single data type, as Herman suggested
//TODO: These has to be deprecated in the favor of Global and Local?
class SegmentState
{
public:
SegmentState();
SegmentState(const SegmentState& copy);
SegmentState & operator=(const SegmentState& copy);
bool operator==(const SegmentState& instance);
bool operator!=(const SegmentState& instance);
KDL::Frame X;
KDL::Frame Xtotal; //should this be in here or be computed in "accumulate" functor
KDL::Twist Xdot;
KDL::Twist Xdotdot;
// KDL::Wrench Fext; // Fext is independent of any other segment's Fext
KDL::Wrench F;
KDL::Twist Z; //supporting/driving joint unit twist/projection/Dof
KDL::Twist Vj;
unsigned int jointIndex; // supporting/driving joint name/index
std::string jointName;
std::string segmentName;
virtual ~SegmentState();
};
//immutable state
class JointState
{
public:
JointState();
JointState(const JointState& copy);
JointState & operator=(const JointState& copy);
double q;
double qdot;
double qdotdot;
double torque;
KDL::Wrench Fext; // this is a hack and should be put somewhere else
unsigned int jointIndex; //joint name/index
std::string jointName;
virtual ~JointState();
};
enum class StateSpaceType :char
{
JointSpace = 'J',
CartesianSpace = 'C',
SensorSpace = 'S',
};
template <typename PoseT, typename TwistT, StateSpaceType spaceT>
class ComputationalState;
template <>
class ComputationalState<grs::Pose<KDL::Vector, KDL::Rotation>, grs::Twist<KDL::Vector, KDL::Vector>, StateSpaceType::CartesianSpace>
{
public:
ComputationalState()=default;
grs::Pose<KDL::Vector, KDL::Rotation> X;
grs::Twist<KDL::Vector, KDL::Vector> Xdot;
grs::Twist<KDL::Vector, KDL::Vector> Xdotdot;
grs::Twist<KDL::Vector, KDL::Vector> UnitXdot;
std::string segmentName;
~ComputationalState()=default;
};
template <>
class ComputationalState<grs::Pose<KDL::Vector, KDL::Rotation>, grs::Twist<KDL::Vector, KDL::Vector>, StateSpaceType::JointSpace >
{
public:
ComputationalState()=default;
std::vector<double> q;
std::vector<double> qdot;
std::vector<double> qdotdot;
std::vector<double> torque;
std::string jointName;
~ComputationalState()=default;
};
};
#endif /* COMPUTATIONALSTATE_KDLTYPES_HPP */
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <cmath>
// fwComEd
#include <fwComEd/fieldHelper/MedicalImageHelpers.hpp>
#include <fwComEd/Dictionary.hpp>
// fwData
#include <fwData/Point.hpp>
#include <fwData/PointList.hpp>
#include <fwData/String.hpp>
#include <fwData/Boolean.hpp>
#include "gdcmIO/DicomLandmark.hpp"
#include "gdcmIO/helper/GdcmHelper.hpp"
#include "gdcmIO/DicomDictionarySR.hpp"
namespace gdcmIO
{
//------------------------------------------------------------------------------
DicomLandmark::DicomLandmark():
m_labels(),
m_SCoords(),
m_refFrames()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
DicomLandmark::~DicomLandmark()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void DicomLandmark::convertToData(::fwData::Image::sptr a_image)
{
SLM_TRACE_FUNC();
const unsigned int nb_landmarks = this->m_labels.size();
if (nb_landmarks > 0)
{
// Get landmarks
::fwComEd::fieldHelper::MedicalImageHelpers::checkLandmarks( a_image );
::fwData::PointList::sptr landmarks = a_image->getField< ::fwData::PointList >( ::fwComEd::Dictionary::m_imageLandmarksId);
// Compute z spacing
// NOTE : spacing between slice must be regular
double spacingOnZ = 1;
if (a_image->getNumberOfDimensions() > 2)
spacingOnZ = a_image->getSpacing()[2];
for (unsigned int i = 0; i < nb_landmarks; ++i)
{
// create a new point
::fwData::Point::NewSptr newPoint;
const SCoord & scoord = m_SCoords[i];
newPoint->getRefCoord()[0] = scoord[0];
newPoint->getRefCoord()[1] = scoord[1];
// Compute z coordinate from referenced frame number and z spacing
newPoint->getRefCoord()[2] = (m_refFrames[i] - 1)* spacingOnZ; // -1 because frame number start at 1 and point at 0
// append to landmark
landmarks->getRefPoints().push_back( newPoint );
// append to point the label
::fwData::String::NewSptr label;
label->value() = this->getLabels()[i];
newPoint->setField( ::fwComEd::Dictionary::m_labelId , label );
OSLM_TRACE("new landmark : "<<label->value()<<" ( "<<newPoint->getRefCoord()[0]<<"x"<<newPoint->getRefCoord()[1]<<"x"<<newPoint->getRefCoord()[2]<<" )");
}
a_image->setField("ShowLandmarks", ::fwData::Boolean::NewSptr(true));
}
else
{
OSLM_TRACE("Any landmark found");
}
}
//------------------------------------------------------------------------------
void DicomLandmark::setFromData(::fwData::Image::csptr a_image) throw (::fwTools::Failed)
{
SLM_TRACE_FUNC();
// Get landmarks
::fwData::PointList::csptr landmarks = a_image->getField< ::fwData::PointList >( ::fwComEd::Dictionary::m_imageLandmarksId);
std::vector< ::fwData::Point::sptr > vLandmarks = landmarks->getPoints();
SCoord scoord;
float graphicData[2];
std::vector< ::fwData::Point::sptr >::const_iterator iter;
std::stringstream strm;
const std::string separator = ","; // Define separator between referenced frame numbers
// Initialize variables to add a constrain : 0 <= coord z <= number of frames
unsigned int illegalRefFrame = 0; // Number of referenced frame number rejected
unsigned int refFrameMax = 1; // Maximum required referenced frame number
unsigned int refFrame; // Referenced frame number
float zSpacingInverse = 1;
if (a_image->getNumberOfDimensions() > 2)
{
refFrameMax = a_image->getSize()[2];
zSpacingInverse = 1. / a_image->getSpacing()[2];
}
for (iter = vLandmarks.begin() ; iter != vLandmarks.end() ; ++iter)
{
// Compute the max legal coord z
refFrame = floor((*iter)->getCoord()[2] * zSpacingInverse + 0.5) + 1; // +1 because frame number start at 1 and point at 0
if ( 0 < refFrame && refFrame <= refFrameMax )
{
// Set label
m_labels.push_back( (*iter)->getField< ::fwData::String >(::fwComEd::Dictionary::m_labelId)->value() );
// Set SCOORD
graphicData[0] = (*iter)->getCoord()[0]; // x
graphicData[1] = (*iter)->getCoord()[1]; // y
scoord.setGraphicData( graphicData, 2);
scoord.setGraphicType( DicomDictionarySR::getGraphicTypeString( DicomDictionarySR::POINT ) );
m_SCoords.push_back( scoord );
// Set referenced frame
m_refFrames.push_back( refFrame );
OSLM_TRACE("landmark : "<<(*iter)->getField< ::fwData::String >(::fwComEd::Dictionary::m_labelId)->value()<<" "<<strm.str());
}
else
{
++illegalRefFrame;
OSLM_ERROR("Landmark with coordinates out of bounds")
}
}
if (illegalRefFrame > 0)
{
strm.str(""); strm << illegalRefFrame << " landmark(s) with coordinates out of bounds";
throw ::fwTools::Failed(strm.str());
}
}
//------------------------------------------------------------------------------
void DicomLandmark::addLabel(const std::string & a_label)
{
this->m_labels.push_back(a_label);
}
//------------------------------------------------------------------------------
void DicomLandmark::addSCoord(const SCoord & a_point)
{
this->m_SCoords.push_back(a_point);
}
//------------------------------------------------------------------------------
void DicomLandmark::addRefFrame(const unsigned int a_refFrame)
{
this->m_refFrames.push_back(a_refFrame);
}
}
|
//
// YMRenderTexture.cpp
// YouMeVideoDemo
//
// Created by fire on 2017/4/1.
//
//
#include "YMRenderTexture.h"
#include "IYouMeVoiceEngine.h"
#include <memory>
USING_NS_CC;
#define CLAMP(i) (((i) < 0) ? 0 : (((i) > 255) ? 255 : (i)))
YMRenderTexture::YMRenderTexture()
{
// TODO
}
YMRenderTexture::~YMRenderTexture()
{
// TODO
destory();
}
bool YMRenderTexture::clean_renders(void)
{
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
for (auto iter = _renders.begin(); iter != _renders.end(); iter++) {
TextureInfo _texture = iter->second;
if(_texture.renderId >=0 && m_if){
m_if->deleteRender(iter->second.renderId);
}
if (_texture.address != NULL) {
delete[] _texture.address;
}
if (_texture.render != NULL) {
iter->second.render->getSprite()->getTexture()->releaseGLTexture();
//_texture.render->end();
}
}
_renders.clear(); /* clear */
return true;
}
void YMRenderTexture::removeUser( std::string& userID ){
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
for (auto it = _renders.begin(); it != _renders.end(); ++it) {
if(it->second.userId == userID){
if(it->second.renderId >=0 && m_if){
m_if->deleteRender(it->second.renderId);
}
if (it->second.address != NULL) {
delete [] it->second.address;
}
if (it->second.render != NULL) {
it->second.render->getSprite()->getTexture()->releaseGLTexture();
//it->second.render->end();
}
_renders.erase( it );
break;
}
}
}
void YMRenderTexture::setInf(IYouMeVoiceEngine* inf)
{
m_if = inf;
if (m_if){
m_if->setVideoCallback(this);
}
}
int YMRenderTexture::create(std::string & userId, int width, int height, RenderTexture * texture)
{
if (!m_if){
return -100;
}
m_if->setVideoCallback(this);
Texture2D::PixelFormat format;
if (texture == NULL) {
return -1;
}
format = texture->getSprite()->getTexture()->getPixelFormat();
if (format != Texture2D::PixelFormat::RGB888 && format != Texture2D::PixelFormat::RGBA8888) {
return -2;
}
TextureInfo _texture;
_texture.width = width;
_texture.height = height;
_texture.format = format;
_texture.renderId = -1;
_texture.userId = userId;
_texture.inited = false;
if (format == Texture2D::PixelFormat::RGB888) {
_texture.len = width * height * 3;
} else if (format == Texture2D::PixelFormat::RGBA8888) {
_texture.len = width * height * 4;
}
_texture.address = new (std::nothrow) unsigned char[_texture.len];
if (_texture.address == NULL) {
return -3;
}
memset((void *)_texture.address, 0x0, _texture.len);
_texture.render = texture;
int renderId = m_if->createRender(userId.c_str());
_texture.renderId = renderId;
_texture.userId = userId;
cocos2d::log("renderId: %d width=%d height=%d", renderId, width, height);
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
auto iter = _renders.find(userId);
if (iter == _renders.end()) {
_renders.insert(std::map<std::string, TextureInfo>::value_type(userId, _texture)); /* new */
} else {
if (iter->second.address != NULL) {
delete [] iter->second.address;
}
iter->second = _texture; /* update */
}
return renderId;
}
void YMRenderTexture::destory(void)
{
clean_renders();
if (m_if){
m_if->setVideoCallback(nullptr);
}
}
/*
YMRenderTexture::TextureInfo YMRenderTexture::getTextureInfo(int renderId) const
{
return _renders.at(renderId);
}*/
void YMRenderTexture::setTextureInfo(YMRenderTexture::TextureInfo texture)
{
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
_renders.insert(std::map<std::string, TextureInfo>::value_type(texture.userId, texture));
}
void YMRenderTexture::update()
{
// cocos2d::log(" >>>>>>>>>>>>>>>>>>>>>>>>>>> fps = %d ", static_cast<int>(delta * 1000));
// std::lock_guard<std::recursive_mutex> stateLock(mRenderMutex);
// for (std::map<int, TextureInfo>::iterator iter = _renders.begin(); iter != _renders.end(); iter++) {
// TextureInfo* _texture = &(iter->second);
// Texture2D * texture = _texture->render->getSprite()->getTexture();
// if(!_texture->inited){
// _texture->inited = true;
// texture->initWithData((const void *)_texture->address, _texture->len, _texture->format, _texture->width, _texture->height, texture->getContentSize());
// } else{
// texture->updateWithData((const void *)_texture->address, 0, 0, _texture->width, _texture->height);
// }
// }
}
void YMRenderTexture::frameRender(int renderId, int w, int h, int degree, int len, const void * buf)
{
}
void YMRenderTexture::onVideoFrameCallback(std::string userId, void * data, int len, int width, int height, int fmt, uint64_t timestamp)
{
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
auto iter = _renders.find(userId);
int w = width;
int h = height;
void* buf = data;
if (iter != _renders.end()) {
TextureInfo* _texture = &(iter->second);
_texture->checksize(w, h);
if (_texture->format == Texture2D::PixelFormat::RGB888) {
yuv420p_to_rgb888(_texture, (const uint_8 *)buf, (const uint_8 *)buf + (w * h), (const uint_8 *)buf + (w * h * 5 / 4), w, h);
}
else if (_texture->format == Texture2D::PixelFormat::RGBA8888) {
yuv420p_to_rgba8888(_texture, (const uint_8 *)buf, (const uint_8 *)buf + (w * h), (const uint_8 *)buf + (w * h * 5 / 4), w, h);
}
else {
// Not support yet.
}
Director::getInstance()->getScheduler()->performFunctionInCocosThread([=](){
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
auto iterTmp = _renders.find(userId);
if (_renders.end() != iterTmp) {
Texture2D * texture = iterTmp->second.render->getSprite()->getTexture();
if (!_texture->inited){
_texture->inited = true;
texture->initWithData((const void *)_texture->address, _texture->len, _texture->format, _texture->width, _texture->height, texture->getContentSize());
}
else{
texture->updateWithData((const void *)_texture->address, 0, 0, _texture->width, _texture->height);
}
}
});
}
else {
// Render not found.
}
}
void YMRenderTexture::onVideoFrameMixedCallback(void * data, int len, int width, int height, int fmt, uint64_t timestamp)
{
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
auto iter = _renders.begin();
int w = width;
int h = height;
void* buf = data;
if (iter != _renders.end()) {
TextureInfo* _texture = &(iter->second);
_texture->checksize(w, h);
if (_texture->format == Texture2D::PixelFormat::RGB888) {
yuv420p_to_rgb888(_texture, (const uint_8 *)buf, (const uint_8 *)buf + (w * h), (const uint_8 *)buf + (w * h * 5 / 4), w, h);
}
else if (_texture->format == Texture2D::PixelFormat::RGBA8888) {
yuv420p_to_rgba8888(_texture, (const uint_8 *)buf, (const uint_8 *)buf + (w * h), (const uint_8 *)buf + (w * h * 5 / 4), w, h);
}
else {
// Not support yet.
}
Director::getInstance()->getScheduler()->performFunctionInCocosThread([=](){
std::lock_guard<std::recursive_mutex> lock(mRenderMutex);
auto iterTmp = _renders.begin();
if (_renders.end() != iterTmp) {
Texture2D * texture = iterTmp->second.render->getSprite()->getTexture();
if (!_texture->inited){
_texture->inited = true;
texture->initWithData((const void *)_texture->address, _texture->len, _texture->format, _texture->width, _texture->height, texture->getContentSize());
}
else{
texture->updateWithData((const void *)_texture->address, 0, 0, _texture->width, _texture->height);
}
}
});
}
else {
// Render not found.
}
}
/***
* yuv420p to rgb888
*/
void YMRenderTexture::yuv420p_to_rgb888(TextureInfo * _texture, const uint_8 * yplane, const uint_8 * uplane, const uint_8 * vplane, const uint_32 width, const uint_32 height)
{
uint_8 * ptr = _texture->address;
int r, g, b;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
uint_8 yp = yplane[(y * width) + x];
uint_8 up = uplane[((y / 2) * (width / 2)) + (x / 2)];
uint_8 vp = vplane[((y / 2) * (width / 2)) + (x / 2)];
r = ((1164 * (yp - 16) + 1596 * (vp - 128) ) / 1000);
g = ((1164 * (yp - 16) - 813 * (vp - 128) - 391 * (up - 128)) / 1000);
b = ((1164 * (yp - 16) + 2018 * (up - 128)) / 1000);
*ptr++ = CLAMP(r);
*ptr++ = CLAMP(g);
*ptr++ = CLAMP(b);
}
}
}
/***
* yuv420p to rgba8888
*/
void YMRenderTexture::yuv420p_to_rgba8888(TextureInfo * _texture, const uint_8 * yplane, const uint_8 * uplane, const uint_8 * vplane, const uint_32 width, const uint_32 height)
{
uint_8 * ptr = _texture->address;
int r, g, b;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
uint_8 yp = yplane[(y * width) + x];
uint_8 up = uplane[((y / 2) * (width / 2)) + (x / 2)];
uint_8 vp = vplane[((y / 2) * (width / 2)) + (x / 2)];
r = ((1164 * (yp - 16) + 1596 * (vp - 128) ) / 1000);
g = ((1164 * (yp - 16) - 813 * (vp - 128) - 391 * (up - 128)) / 1000);
b = ((1164 * (yp - 16) + 2018 * (up - 128)) / 1000);
*ptr++ = CLAMP(r);
*ptr++ = CLAMP(g);
*ptr++ = CLAMP(b);
*ptr++ = CLAMP(0);
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef HAS_SET_HTTP_DATA
#include "modules/hardcore/mem/mem_man.h"
#include "modules/upload/upload.h"
#include "modules/formats/encoder.h"
#include "modules/formats/base64_decode.h"
#include "modules/olddebug/tstdump.h"
#include "modules/util/cleanse.h"
Upload_Handler::Upload_Handler()
{
internal_buffer = NULL;
buffer_len = buffer_pos = buffer_size = 0;
buffer_min_len = 0;
last_block = FALSE;
calculated_payload_size = 0;
current_line_len = 0;
encoding = ENCODING_AUTODETECT;
}
Upload_Handler::~Upload_Handler()
{
FreeBuffer();
}
void Upload_Handler::InitL(MIME_Encoding enc, const char **header_names)
{
encoding = enc;
Upload_Base::InitL(header_names);
}
OpFileLength Upload_Handler::CalculateLength()
{
return calculated_payload_size + Upload_Base::CalculateLength();
}
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
unsigned char *Upload_Handler::Encode7Or8Bit(unsigned char *target, uint32 &remaining_len, BOOL more)
{
const unsigned char *current = internal_buffer;
unsigned char token;
while(remaining_len>0 && buffer_pos < buffer_len)
{
token = *(current++);
if(token == '\r' || token == '\n')
{
if(remaining_len < 2)
break;
if(token == '\r')
{
if(buffer_pos +1 >= buffer_len && more)
break; // we will have to wait until the next time
if(buffer_pos +1 < buffer_len && *current == '\n')
{
current++;
buffer_pos ++;
}
}
*(target++) = '\r';
token = '\n';
remaining_len --;
}
buffer_pos ++;
*(target++) = token;
remaining_len --;
}
return target;
}
#endif // URL_UPLOAD_MAILENCODING_SUPPORT
#ifdef URL_UPLOAD_QP_SUPPORT
unsigned char *Upload_Handler::EncodeQP(unsigned char *target, uint32 &remaining_len, BOOL more)
{
const unsigned char *current = internal_buffer;
unsigned char token;
const char * const hexchars = GetHexChars();
while(remaining_len>6 && buffer_pos < buffer_len)
{
token = *(current++);
switch(token)
{
case '\n':
case '\r':
if(token == '\r')
{
if(buffer_pos +1 >= buffer_len && more)
break; // we will have to wait until the next time
if(buffer_pos +1 < buffer_len && *current == '\n')
{
current++;
buffer_pos ++;
}
}
*(target++) = '\r';
*(target++) = '\n';
remaining_len -=2;
current_line_len = 0;
break;
case '\t':
case ' ':
{
BOOL add_softlinefeed = FALSE;
if(buffer_pos+1 < buffer_len)
{
unsigned char token1 = *current;
if(token1 == '\r' || token1 == '\n')
{
add_softlinefeed = TRUE;
}
}
else if(!more)
{
add_softlinefeed = TRUE;
}
else
return target;
*(target++) = token;
remaining_len --;
current_line_len ++;
if(add_softlinefeed)
{
*(target++) = '=';
*(target++) = '\r';
*(target++) = '\n';
remaining_len -= 3;
current_line_len =0;
}
break;
}
default:
if(NeedQPEscape(token, 0))
{
*(target++) = '=';
*(target++) = hexchars[(token>>4) & 0x0f];
*(target++) = hexchars[token & 0x0f];
remaining_len -= 3;
current_line_len += 3;
}
else
{
*(target++) = token;
remaining_len --;
current_line_len ++;
}
}
buffer_pos ++;
if(current_line_len >= 72)
{
// soft breaks line at 72, might have waited until 76
*(target++) = '=';
*(target++) = '\r';
*(target++) = '\n';
remaining_len -= 3;
current_line_len = 0;
}
}
return target;
}
#endif // URL_UPLOAD_QP_SUPPORT
#ifdef URL_UPLOAD_BASE64_SUPPORT
unsigned char *Upload_Handler::EncodeBase64(unsigned char *target, uint32 &remaining_len, BOOL more)
{
unsigned char *src = internal_buffer + buffer_pos;
while (buffer_pos < (more ? buffer_len-3 : buffer_len))
{
BOOL append_crlf = (current_line_len >= UPLOAD_BASE64_LINE_LEN-4)
|| (buffer_pos >= buffer_len-3 && !more);
if (remaining_len < (uint32) (append_crlf ? 6 : 4))
break;
uint32 bits1, bits2, bits3, bits4;
unsigned char tmp;
tmp = *(src++); buffer_pos++;
bits1 = (tmp >> 2) & 0x3f;
bits2 = (tmp << 4) & 0x30;
if (buffer_pos < buffer_len)
{
tmp = *(src++); buffer_pos++;
bits2 |= (tmp >> 4) & 0x0f;
bits3 = (tmp << 2) & 0x3c;
}
else
bits3 = 64;
if (buffer_pos < buffer_len)
{
tmp = *(src++); buffer_pos++;
bits3 |= (tmp >> 6) & 0x03;
bits4 = tmp & 0x3f;
}
else
bits4 = 64;
*(target++) = Base64_Encoding_chars[bits1];
*(target++) = Base64_Encoding_chars[bits2];
*(target++) = Base64_Encoding_chars[bits3];
*(target++) = Base64_Encoding_chars[bits4];
remaining_len -= 4;
if(append_crlf)
{
*(target++) = '\r';
*(target++) = '\n';
current_line_len = 0;
remaining_len -= 2;
}
else
current_line_len += 4;
}
return target;
}
#endif // URL_UPLOAD_BASE64_SUPPORT
unsigned char *Upload_Handler::OutputContent(unsigned char *target, uint32 &remaining_len, BOOL &done)
{
done = FALSE;
target = Upload_Base::OutputContent(target, remaining_len, done);
if(!done)
return target;
uint32 portion_len;
BOOL more;
if(encoding == ENCODING_NONE || encoding == ENCODING_BINARY)
{
more = FALSE;
portion_len = GetNextContentBlock(target, remaining_len, more);
done = !more;
target += portion_len;
remaining_len -= portion_len;
return target;
}
#if defined URL_UPLOAD_MAILENCODING_SUPPORT || defined URL_UPLOAD_QP_SUPPORT || defined URL_UPLOAD_BASE64_SUPPORT
CheckInternalBufferL(0);
uint32 prev_remaining_len = 0;
more = TRUE;
while(more && prev_remaining_len != remaining_len)
{
more = FALSE;
if(!last_block)
{
uint32 retrieved =GetNextContentBlock(internal_buffer+buffer_len, buffer_size-buffer_len, more);
buffer_len += retrieved;
last_block = !more;
}
prev_remaining_len = remaining_len;
switch(encoding)
{
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
case ENCODING_7BIT:
case ENCODING_8BIT:
target = Encode7Or8Bit(target, remaining_len, more);
break;
#endif
#ifdef URL_UPLOAD_QP_SUPPORT
case ENCODING_QUOTED_PRINTABLE:
target = EncodeQP(target, remaining_len, more);
break;
#endif
#ifdef URL_UPLOAD_BASE64_SUPPORT
case ENCODING_BASE64:
target = EncodeBase64(target, remaining_len, more);
break;
#endif
default:
OP_ASSERT(0); // encoding illegal
}
if(buffer_pos < buffer_len)
{
buffer_len -= buffer_pos;
op_memmove(internal_buffer, internal_buffer + buffer_pos, buffer_len);
}
else
buffer_len = 0;
buffer_pos = 0;
}
done = (last_block && buffer_len == 0 ? TRUE : FALSE);
#else
done = TRUE;
OP_ASSERT(0); // encoding illegal
#endif
return target;
}
uint32 Upload_Handler::PrepareL(Boundary_List &boundaries, Upload_Transfer_Mode transfer_restrictions)
{
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
BOOL detect_encoding = FALSE;
#endif
BOOL calculate_size = FALSE;
BOOL check_boundary = FALSE;
OpFileLength payload_len;
payload_len = PayloadLength();
if(BodyNeedScan() /* && (transfer_restrictions != UPLOAD_BINARY_NO_CONVERSION ||
payload_len < 4*1024*1024)*/)
{
check_boundary = (boundaries.Cardinal() != 0);
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
if(transfer_restrictions != UPLOAD_BINARY_NO_CONVERSION &&
charset.CompareI("iso-2022-jp") == 0)
{
encoding = ENCODING_7BIT;
}
#endif
#if defined(URL_UPLOAD_MAILENCODING_SUPPORT) && defined(URL_UPLOAD_BASE64_SUPPORT)
else
#endif
#ifdef URL_UPLOAD_BASE64_SUPPORT
if(transfer_restrictions != UPLOAD_BINARY_NO_CONVERSION &&
encoding != ENCODING_BASE64 &&
payload_len >= 4*1024*1024)
{
encoding = ENCODING_BASE64;
}
#endif
switch(encoding)
{
case ENCODING_AUTODETECT:
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
if(transfer_restrictions == UPLOAD_7BIT_TRANSFER || transfer_restrictions == UPLOAD_8BIT_TRANSFER)
detect_encoding = TRUE;
#endif
break;
#ifdef URL_UPLOAD_BASE64_SUPPORT
case ENCODING_BASE64:
check_boundary = FALSE;
#endif
#ifdef URL_UPLOAD_QP_SUPPORT
case ENCODING_QUOTED_PRINTABLE:
#endif
#if defined URL_UPLOAD_BASE64_SUPPORT || defined URL_UPLOAD_QP_SUPPORT
calculate_size = TRUE;
break;
#endif
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
case ENCODING_7BIT:
case ENCODING_8BIT:
#endif
case ENCODING_NONE:
case ENCODING_BINARY:
default:
break;
}
#ifdef UPLOAD_NO_BODY_SCAN
// URL_UPLOAD_BASE64_SUPPORT must be defined
check_boundary = FALSE; // Trust the 1 : 12 401 769 434 657 526 912 139 264 randomness of the boundary
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
if (detect_encoding && transfer_restrictions == UPLOAD_8BIT_TRANSFER)
{
encoding = ENCODING_8BIT; // Assume content does not have long lines or the receiver can handle it
detect_encoding = FALSE;
}
#endif
if (0
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
|| detect_encoding
#endif
#ifdef URL_UPLOAD_QP_SUPPORT
|| encoding == ENCODING_QUOTED_PRINTABLE
#endif
)
{
encoding = ENCODING_BASE64; // Always safe, but 33% bigger
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
detect_encoding = FALSE;
#endif
calculate_size = TRUE;
}
#endif
}
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
uint32 QP_escapes = 0;
uint32 QP_soft_line_escapes = 0;
uint32 QP_equals_escapes = 0; // Count '=' separately, QP not needed unless other chars need QP
uint32 linefeed_escapes = 0;
uint32 max_line_len = 0;
#endif
if(check_boundary
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
|| detect_encoding
#endif
#ifdef URL_UPLOAD_QP_SUPPORT
|| (calculate_size && encoding == ENCODING_QUOTED_PRINTABLE)
#endif
|| DecodeToCalculateLength())
{
CheckInternalBufferL(payload_len);
ResetContent();
BOOL more = TRUE;
uint32 portion_len =0, unconsumed = 0;
payload_len = 0;
current_line_len = 0;
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
uint32 QP_line_len = 0;
#endif
#ifdef DEBUG_SCAN
time_t start_time = op_time(NULL);
uint32 bytes_processed = 0;
PrintfTofile("upload.txt", "Starting scan at %lu boundary= %s\n", start_time, boundaries.GetBoundaryL().CStr());
#endif
while(more)
{
portion_len = GetNextContentBlock(internal_buffer+unconsumed, buffer_size-unconsumed, more);
payload_len += portion_len;
portion_len += unconsumed;
uint32 committed = portion_len;
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
if(detect_encoding)
{
unsigned char *pos = internal_buffer + unconsumed;
committed = unconsumed;
unsigned char token;
while(committed < portion_len)
{
token = *(pos++);
switch(token)
{
case '\r':
case '\n':
if(token == '\n')
{
linefeed_escapes ++;
QP_line_len =0;
if(current_line_len > max_line_len)
max_line_len = current_line_len;
current_line_len = 0;
committed ++;
}
else if(committed+1 < portion_len)
{
unsigned char token1 = *pos;
if(token1 == '\n')
{
committed ++;
pos ++;
}
else
{
linefeed_escapes ++;
}
committed ++;
QP_line_len = 0;
if(current_line_len > max_line_len)
max_line_len = current_line_len;
current_line_len = 0;
}
else
goto force_end_of_scan;
break;
case '\t':
case ' ':
if(committed+1 < portion_len)
{
unsigned char token1 = *pos;
QP_line_len ++;
current_line_len ++;
if(token1 == '\r' || token1 == '\n')
{
// Adding "=\r\n"
QP_soft_line_escapes += 3;
QP_line_len =0;
}
committed ++;
}
else if(!more)
{
// Adding "=\r\n"
QP_soft_line_escapes += 3;
QP_line_len = 0;
current_line_len ++;
committed ++;
}
else
goto force_end_of_scan;
break;
default:
if(token == 0)
{
encoding = ENCODING_BASE64;
check_boundary = FALSE;
detect_encoding = FALSE;
calculate_size = TRUE;
goto force_end_of_scan;
}
else if (NeedQPEscape(token, 0))
{
if (token == '=')
QP_equals_escapes +=2;
else
QP_escapes +=2;
QP_line_len +=2;
}
committed ++;
QP_line_len ++;
current_line_len ++;
}
if(QP_line_len >= 72)
{
// soft breaks line at 72, might have waited until 76
QP_soft_line_escapes += 3;
QP_line_len = 0;
}
}
force_end_of_scan:;
if(detect_encoding && QP_escapes && transfer_restrictions == UPLOAD_7BIT_TRANSFER && (QP_escapes + linefeed_escapes + QP_soft_line_escapes + QP_equals_escapes) *3 > payload_len)
{
// Do not QP encode if it increases the length more than 1/3
encoding = ENCODING_BASE64;
check_boundary = FALSE;
detect_encoding = FALSE;
calculate_size = TRUE;
}
}
#endif // URL_UPLOAD_MAILENCODING_SUPPORT
unconsumed = 0;
if(check_boundary)
{
uint32 committed2 = 0;
if(boundaries.ScanForBoundaryL(internal_buffer, portion_len,committed2) == Boundary_Match)
{
LEAVE(Upload_Error_Status::ERR_FOUND_BOUNDARY_PREFIX);
}
#ifdef DEBUG_SCAN
bytes_processed += committed2;
#endif
if(committed2 < committed)
committed = committed2;
}
if(more && committed < portion_len)
{
unconsumed = portion_len - committed;
op_memmove(internal_buffer, internal_buffer + committed, unconsumed);
}
}
}
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
if(detect_encoding)
{
BOOL use_QP = FALSE;
if((QP_escapes && transfer_restrictions == UPLOAD_7BIT_TRANSFER) || max_line_len >998)
{
use_QP = TRUE;
QP_escapes += linefeed_escapes +QP_soft_line_escapes + QP_equals_escapes;
linefeed_escapes = 0;
}
if(use_QP)
{
calculate_size = TRUE;
if(QP_escapes *3 > payload_len)
{
// Do not QP encode if it increases the length more than 1/3
encoding = ENCODING_BASE64;
check_boundary = FALSE;
detect_encoding = FALSE;
}
else
encoding = ENCODING_QUOTED_PRINTABLE;
}
else
encoding = (transfer_restrictions == UPLOAD_7BIT_TRANSFER ? ENCODING_7BIT : ENCODING_8BIT);
}
else
#endif // URL_UPLOAD_MAILENCODING_SUPPORT
if(encoding == ENCODING_AUTODETECT)
{
encoding = ENCODING_NONE;
}
if(calculate_size)
{
if(encoding == ENCODING_BASE64)
calculated_payload_size = ((payload_len + 2)/3)*4 /*Base64*/ + (payload_len/((UPLOAD_BASE64_LINE_LEN * 3)/ 4))*2 /*CRLFs every UPLOAD_BASE64_LINE_LEN (64) encoded bytes, i.e. every UPLOAD_BASE64_LINE_LEN*3/4 (48) unencoded bytes */;
else
{
calculated_payload_size = payload_len;
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
calculated_payload_size += QP_escapes + linefeed_escapes;
#endif // URL_UPLOAD_MAILENCODING_SUPPORT
}
}
else
{
calculated_payload_size = payload_len;
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
if (encoding == ENCODING_7BIT || encoding == ENCODING_8BIT)
calculated_payload_size += linefeed_escapes;
#endif // URL_UPLOAD_MAILENCODING_SUPPORT
}
#if defined URL_UPLOAD_MAILENCODING_SUPPORT || defined URL_UPLOAD_QP_SUPPORT || defined URL_UPLOAD_BASE64_SUPPORT
const char *encoding_string = NULL;
switch(encoding)
{
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
case ENCODING_7BIT:
encoding_string = "7bit";
break;
case ENCODING_8BIT:
encoding_string = "8bit";
break;
#endif
#ifdef URL_UPLOAD_QP_SUPPORT
case ENCODING_QUOTED_PRINTABLE:
encoding_string = "Quoted-Printable";
break;
#endif
#ifdef URL_UPLOAD_BASE64_SUPPORT
case ENCODING_BASE64:
encoding_string = "Base64";
break;
#endif
#ifdef URL_UPLOAD_MAILENCODING_SUPPORT
case ENCODING_BINARY:
encoding_string = "binary";
break;
#endif
}
if(encoding_string)
AccessHeaders().AddParameterL("Content-Transfer-Encoding", NULL, encoding_string);
#endif
current_line_len = 0;
return Upload_Base::PrepareL(boundaries, transfer_restrictions);
}
void Upload_Handler::ResetL()
{
Upload_Base::ResetL();
current_line_len = 0;
last_block = FALSE;
buffer_pos = 0;
buffer_len = 0;
}
void Upload_Handler::Release()
{
FreeBuffer();
}
void Upload_Handler::SetMinimumBufferSize(uint32 size)
{
if(size > buffer_min_len)
buffer_min_len = size;
}
void Upload_Handler::ResetContent()
{
}
void Upload_Handler::FreeBuffer()
{
if(internal_buffer)
OPERA_cleanse_heap(internal_buffer, buffer_size);
OP_DELETEA(internal_buffer);
internal_buffer = NULL;
buffer_len = buffer_pos = buffer_size = 0;
}
void Upload_Handler::CheckInternalBufferL(OpFileLength max_needed)
{
uint32 len = buffer_min_len;
if(len < 32*1024)
len = 32*1024;
if(max_needed < len)
len = max_needed > 1024 ? (uint32) max_needed : 1024;
if(len <= buffer_size)
return;
unsigned char *temp_internal_buffer = OP_NEWA_L(unsigned char, len);
uint32 temp_buffer_len = 0;
if(internal_buffer && buffer_len && buffer_pos < buffer_len)
{
temp_buffer_len = buffer_len-buffer_pos;
op_memcpy(temp_internal_buffer, internal_buffer + buffer_pos, temp_buffer_len);
}
FreeBuffer();
internal_buffer = temp_internal_buffer;
buffer_size = len;
buffer_len = temp_buffer_len;
// buffer_pos = 0 not necessary
}
#ifdef UPLOAD_PAYLOAD_ACTION_SUPPORT
void Upload_Handler::ProcessPayloadActionL()
{
ResetContent();
CheckInternalBufferL(0);
BOOL more = TRUE;
while(more)
{
more = FALSE;
uint32 retrieved =GetNextContentBlock(internal_buffer, buffer_size, more);
PerformPayloadActionL(internal_buffer, retrieved);
}
}
void Upload_Handler::PerformPayloadActionL(unsigned char *src, uint32 src_len)
{
}
#endif
#endif // HTTP_data
|
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QObject>
#include "myqlineedit.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private:
QPushButton *b1;
QPushButton *b2;
QPushButton *b3;
MyQLineEdit *le; //行编辑器
};
#endif // WIDGET_H
|
#pragma once
#include "Vehicle.hpp"
#include "Messages.hpp"
class remote_vehicle : public Vehicle {
public:
remote_vehicle();
void draw();
};
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
typedef long long LL;
int main(int argc, char const *argv[])
{
int n,m,c;
int kase = 1;
int table[MAXN];
bool turn[MAXN];
while( ~scanf("%d %d %d",&n,&m,&c) && (n|m|c) ){
memset(turn,0,sizeof(turn));
for(int i = 1 ; i <= n ; i++ )
scanf("%d",&table[i]);
int now = 0,used = 0;
int act;
for(int i = 1 ; i <= m ; i++ ){
scanf("%d",&act);
if( turn[act] ) now -= table[act];
else now += table[act];
turn[act] ^= 1;
used = max(used,now);
}
printf("Sequence %d\n", kase++ );
if( used > c ) printf("Fuse was blown.\n");
else{
printf("Fuse was not blown.\n");
printf("Maximal power consumption was %d amperes.\n",used);
}
printf("\n");
}
return 0;
}
|
#include "TestCPU.h"
#include "Memory.h"
#include <iostream>
int main(int argc, char** argv)
{
using namespace test;
memoryInterface *mem = new RAMImpl(8);
cpu device(mem);
CPUtestbench tester(&device);
tester.storeReg(1, 177);
tester.constructInstruction(COP2, 4, 1, gte::VXY0, 0, 0);
tester.constructInstruction(COP2, 0, gte::VXY0, 2, 0, 0);
tester.run();
if (tester.getReg(2) == 177)
std::cout << argv[0] << " Pass" << std::endl;
else
std::cout << argv[0] << " Fail" << std::endl;
delete mem;
}
|
#include "StdAfx.h"
#include "MsgList.h"
CMsgList::CMsgList(CPaintManagerUI& paint_manager) : paint_manager_(paint_manager)
{
root_node_ = new Node;
root_node_->data().list_elment_ = NULL;
}
CMsgList::~CMsgList(void)
{
RemoveAll();
if (root_node_)
delete root_node_;
root_node_ = NULL;
}
void DuiLib::CMsgList::RemoveAll()
{
CListUI::RemoveAll();
for (int i=0; i<root_node_->num_children();)
{
Node* child = root_node_->child(i);
RemoveNode(child);
}
delete root_node_;
root_node_ = new Node;
root_node_->data().list_elment_ = NULL;
}
bool DuiLib::CMsgList::RemoveNode(Node* node)
{
if(!node || node == root_node_)
return false;
for (int i=0; i<node->num_children(); ++i)
{
Node* child = node->child(i);
RemoveNode(child);
}
CListUI::Remove(node->data().list_elment_);
if(node->data().list_elment_)
{
delete node->data().list_elment_;
node->data().list_elment_ = NULL;
}
node->parent()->remove_child(node);
delete node;
node = NULL;
return true;
}
Node* DuiLib::CMsgList::AddNode(const TroyMsgData& item, Node* parent)
{
if(parent == NULL)
parent = root_node_;
CListContainerElementUI* pListElement = NULL;
if( !m_dlgBuilder.GetMarkup()->IsValid() )
pListElement = static_cast<CListContainerElementUI*>(m_dlgBuilder.Create(L"MsgList.xml", (UINT)0, NULL, &paint_manager_));
else
{
pListElement = static_cast<CListContainerElementUI*>(m_dlgBuilder.Create((UINT)0, &paint_manager_));
}
if (pListElement == NULL)
return NULL;
Node* node = new Node;
node->data().list_elment_ = pListElement; //关联列表控件
node->data().weixing_id = item.weixing_id;
CButtonUI* log_button = static_cast<CButtonUI*>(paint_manager_.FindSubControlByName(pListElement, L"logo"));//找图标按钮
if(log_button != NULL)
{
log_button->SetNormalImage(item.LogoPath);
}
CLabelUI* name = static_cast<CLabelUI*>(paint_manager_.FindSubControlByName(pListElement, L"nick_name"));
if(name !=NULL)
{
name->SetText(item.name);
}
int index = 0;
if(parent->has_children())
{
Node* prev = parent->get_last_child();
index = prev->data().list_elment_->GetIndex()+1;
}
else
{
if(parent == root_node_)
index = 0;
else
index = parent->data().list_elment_->GetIndex()+1;
}
pListElement->SetTag((UINT_PTR)node);
bool ret = CListUI::AddAt(pListElement, index);
if(ret == false)
{
delete pListElement;
delete node;
node = NULL;
return NULL;
}
parent->add_child(node);
// delete node;
// node = NULL;
// delete pListElement;
// pListElement = NULL;
return node;
}
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
typedef unsigned __int64 int64;
struct Palindrome {
int left = 0;
int right = 0;
int64 product = 0L;
};
void findEratosthenesPrimeNumbers(int lowerLimit, int upperLimit, vector<int>& primes) {
vector<bool> sieve(upperLimit, true);
for (int i = 2; i*i <= upperLimit; ++i) {
if (sieve[i] == true) {
for (int j = i*i; j <= upperLimit; j += i) {
sieve[j] = false;
}
}
}
for (int i = lowerLimit; i < upperLimit; ++i) {
if (sieve[i] == true) {
primes.push_back(i);
}
}
}
Palindrome findMaxPalindrome(int n) {
int lowerLimit = 1;
for (int i = 1; i < n; ++i) {
lowerLimit *= 10;
}
int upperLimit = 10 * lowerLimit;
lowerLimit++;
/* Find all n-digit prime numbers from 10^(n-1)+1 to 10^n. */
vector<int> primes;
findEratosthenesPrimeNumbers(lowerLimit, upperLimit, primes);
/* Find max palindromic number. */
Palindrome p;
int sqrtProduct = 0;
for (int i = (int)primes.size()-1; sqrtProduct < primes[i]; --i) {
for (int j = i; j >= 0; --j) {
int64 product = (int64)primes[i] * (int64)primes[j];
if (product <= p.product) {
break;
}
int64 number = product;
int64 inverse = 0L;
while (number != 0L) {
inverse = inverse * 10L + number % 10;
number /= 10L;
}
if (product == inverse) {
sqrtProduct = (int)sqrt(product);
p.left = primes[i];
p.right = primes[j];
p.product = product;
}
}
}
return p;
}
// input: n
// output: max palindromic number which is the product of two n digit prime numbers
int main (int argc, char* argv[]) {
int n;
if (argc == 2) {
n = atoi(argv[1]);
} else {
cin >> n;
}
if (n < 1 || n > 8) {
exit(1);
}
Palindrome p = findMaxPalindrome(n);
cout << p.left << " * " << p.right << " = " << p.product;
return 0;
}
|
class Category_643 {
duplicate = 621;
};
class Category_609 {
duplicate = 621;
};
|
//
// This file contains the C++ code from Program 5.19 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm05_19.cpp
//
#include <Association.h>
#include <NullObject.h>
Association::Association (Object& _key) :
key (&_key),
value (0)
{}
Association::Association (Object& _key, Object& _value) :
key (&_key),
value (&_value)
{}
Association::~Association ()
{
if (IsOwner ())
{
delete key;
delete value;
}
}
Object& Association::Key () const
{ return *key; }
Object& Association::Value () const
{
if (value == 0)
return NullObject::Instance ();
else
return *value;
}
int Association::CompareTo (Object const& object) const
{
Association const& association =
dynamic_cast<Association const&> (object);
return Key ().Compare (association.Key ());
}
void Association::Put (std::ostream& s) const
{
s << "Association {" << *key;
if (value != 0)
s << ", " << *value;
s << "}\n";
}
HashValue Association::Hash () const
{
return key->Hash();
}
|
/*****************************************************************************************************************
* File Name : FindTwoNumbersOddOccurence.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page04\FindTwoNumbersOddOccurence.h
* Created on : Jan 8, 2014 :: 1:15:48 PM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
/************************************************* Main code ******************************************************/
#ifndef FINDTWONUMBERSODDOCCURENCE_H_
#define FINDTWONUMBERSODDOCCURENCE_H_
int *findTwoNumbersWithOddOccurenceON2(vector<int> userInput){
if(userInput.size() == 0){
return NULL;
}
int result[2];
unsigned int fillCounter = 0;
unsigned int frequency;
for(unsigned int outerCrawler = 0;outerCrawler < userInput.size();outerCrawler++){
frequency = 0;
for(unsigned int innerCrawler = 0;innerCrawler < userInput.size();innerCrawler++){
if(innerCrawler == outerCrawler){
continue;
}
if(userInput[outerCrawler] == userInput[innerCrawler]){
frequency += 1;
}
}
if(frequency&1 == 1){
if(fillCounter != 0){
if(result[0] != userInput[outerCrawler]){
result[fillCounter] = userInput[outerCrawler];
break;
}
}else{
result[fillCounter++] = userInput[outerCrawler];
}
}
}
return result;
}
int *findTwoNumbersWithOddOccurenceONLOGN(vector<int> userInput){
if(userInput.size() == 0){
return NULL;
}
sort(userInput.begin(),userInput.end());
unsigned int crawler = 0,frequency;
int result[2],resultCrawler = -1;
while(crawler < userInput.size()){
frequency = 1;
while(crawler < userInput.size() && userInput[crawler] == userInput[crawler+1]){
frequency += 1;
}
if(frequency%2 == 1){
result[++resultCrawler] = userInput[crawler];
if(resultCrawler == 1){
return result;
}
}
crawler += frequency;
}
return NULL;
}
int *findTwoNumbersWithOddOccurenceONHashmap(vector<int> userInput){
if(userInput.size() == 0){
return NULL;
}
hash_map<int,unsigned int> frequencyMap;
hash_map<int,unsigned int>::iterator itToFrequencyMap;
for(unsigned int counter = 0;counter < userInput.size();counter++){
if((itToFrequencyMap = frequencyMap.find(userInput[counter])) != frequencyMap.end()){
frequencyMap[userInput[counter]] += 11;
}else{
frequencyMap.insert(pair<int,unsigned int>(userInput[counter],1));
}
}
int result[2];
int fillCounter = -1;
for(itToFrequencyMap = frequencyMap.begin();itToFrequencyMap != frequencyMap.end();itToFrequencyMap++){
if(itToFrequencyMap->second & 1 == 1){
result[++fillCounter] = itToFrequencyMap->first;
if(fillCounter == 1){
break;
}
}
}
return result;
}
int *findTwoNumbersWithOddOccurenceONXOR(vector<int> userInput){
if(userInput.size() == 0){
return NULL;
}
int xorResult = 0;
for(unsigned int counter = 0;counter < userInput.size();counter++){
xorResult ^= userInput[counter];
}
unsigned int setBit = xorResult & ~(xorResult -1);
int result[2] = {0};
for(unsigned int counter = 0;counter < userInput.size();counter++){
if(userInput[counter] & setBit){
result[0] ^= userInput[counter];
}else{
result[1] ^= userInput[counter];
}
}
return result;
}
#endif /* FINDTWONUMBERSODDOCCURENCE_H_ */
/************************************************* End code *******************************************************/
|
#include <iostream>
#include <vector>
#include "dirgraph.h"
#include "depth_first_order.h"
using namespace std;
class KosarajuSCC
{
private:
vector<bool> marked; // 已访问过的节点
vector<int> id; // 强连通分量的标识符
int count; // 强连通分量的数量
private:
void dfs(Digraph &G,int v)
{
marked[v] = true;
id[v] = count;
list<int> *l = G.adj_vertex(v);
for(int w: *l)
{
if(!marked[w])
dfs(G,w);
}
}
public:
KosarajuSCC(Digraph &G):marked(G.vertex()),id(G.vertex())
{
DepthFirstOrder order(G.reverse());
stack<int> reverse = order.reverse_post_order();
for(int s:reverse)
{
if(!marked[s])
{
dfs(G,s);
count++;
}
}
}
bool stronglyConnected(int v,int w)
{
return id[v] = id[w];
}
int get_id(int v)
{
return id[v];
}
int get_count()
{
return count;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.