<commit_before>#include "stdafx.h"
#include "SteamVRDemoRuleManager.h"

#include <string.h>
#include <sstream>
#include <log4cplus\log4cplus.h>
#include "util\l4util.h"

const char *IGNORE_LIST_SECTION = "IgnoreList";

enum RuleMessage {
	RM_UNKNOWN = -1,
	RM_ACTIVATE = HCBT_ACTIVATE,
	RM_CREATE = HCBT_CREATEWND
};
enum RuleAction {
	RA_UNKNOWN = -1,
	RA_MAX = SW_MAXIMIZE,
	RA_MIN = SW_MINIMIZE,
	RA_HIDE = SW_HIDE
};

SteamVRDemoRuleManager::TokenMap SteamVRDemoRuleManager::s_ruleMessageTokenMap = {
	{HCBT_ACTIVATE, "ACTIVATE"},
	{HCBT_CREATEWND, "CREATE"}
};

SteamVRDemoRuleManager::TokenMap SteamVRDemoRuleManager::s_ruleActionTokenMap = {
	{SW_MAXIMIZE, "MAX"},
	{SW_MINIMIZE, "MIN"},
	{SW_HIDE, "HIDE"},
	{WM_CLOSE, "CLOSE"},
	{SteamVRDemoRuleManager::RA_FULL, "FULL"}
};

SteamVRDemoRuleManager::RuleItemList SteamVRDemoRuleManager::s_ruleItemList;
SteamVRDemoRuleManager::NameList SteamVRDemoRuleManager::s_ignoredProcessNameList;

bool SteamVRDemoRuleManager::ifIgnore(const std::string &processName)
{
	bool result = false;

	for (NameList::const_iterator it = SteamVRDemoRuleManager::s_ignoredProcessNameList.begin(); it != SteamVRDemoRuleManager::s_ignoredProcessNameList.end(); ++it) {
		if (0 == _stricmp(processName.c_str(), it->c_str())) {
			result = true;
			break;
		}
	}
	return result;
}

void SteamVRDemoRuleManager::performFullScreenAction(HWND wnd)
{
	HWND desktopWindow = GetDesktopWindow();
	RECT desktopRect, windowRect;
	log4cplus::Logger logger = log4cplus::Logger::getInstance("SERVER");

	GetWindowRect(desktopWindow, &desktopRect);
	GetWindowRect(wnd, &windowRect);

	LOG4CPLUS_DEBUG(logger, "Desktop width: " << desktopRect.right << ", height: " << desktopRect.bottom);
	LOG4CPLUS_DEBUG(logger, "Window width: " << windowRect.right - windowRect.left << ", height: " << desktopRect.bottom - desktopRect.top);

	if (windowRect.left > desktopRect.left ||
		windowRect.right < desktopRect.right ||
		windowRect.top < desktopRect.top ||
		windowRect.bottom < desktopRect.bottom) {
		LOG4CPLUS_DEBUG(logger, "Window is not full screen size, toggole it");
		// TODO: check why it desn't work with Unreal 4 games(it works with Unity games)
		PostMessageA(wnd, WM_SYSKEYDOWN, VK_RETURN, 1 << 29 | 0x001C0001);
		PostMessageA(wnd, WM_SYSCHAR, 13, 1 << 29 | 0x001C0001);
	}
}

void SteamVRDemoRuleManager::handleMessage(int message, HWND wnd)
{
	char className[MAX_PATH];
	RuleAction action = RA_UNKNOWN;

	log4cplus::Logger logger = log4cplus::Logger::getInstance("SERVER");
	DWORD processId = GetCurrentProcessId();
	std::string processName = l4util::getCurrentProcessName();

	if (SteamVRDemoRuleManager::ifIgnore(processName)) {
		return;
	}

	RealGetWindowClassA(wnd, className, MAX_PATH);
	for (RuleItemList::const_iterator it = SteamVRDemoRuleManager::s_ruleItemList.begin(); it != SteamVRDemoRuleManager::s_ruleItemList.end(); ++it) {
		if (it->m_className == className && it->m_message == message) {
			action = it->m_action;
		}
	}
	LOG4CPLUS_INFO(logger, "[" << SteamVRDemoRuleManager::s_ruleMessageTokenMap[message] << "] ID=" << processId << ", name=" << processName << ", Class=" << className << std::endl);

	if (RA_UNKNOWN != action) {
		switch (action) {
		case RA_FULL:
			performFullScreenAction(wnd);
			break;
		case RA_CLOSE:
			PostMessage(wnd, WM_CLOSE, 0, 0);
			break;
		default:
			// show window commands
			ShowWindow(wnd, action);
			break;
		}
	}
}

int SteamVRDemoRuleManager::parseValue(const std::string &token, const TokenMap &tokenMap)
{
	int result = UNKNOWN_TOKEN;
	std::string trimmedToken = (token);

	for (TokenMap::const_iterator it = tokenMap.begin(); it != tokenMap.end(); ++it) {
		if (0 == _stricmp(it->second.c_str(), trimmedToken.c_str())) {
			result = it->first;
			break;
		}
	}
	return result;
}

bool SteamVRDemoRuleManager::parseIgnoreListSection(const std::string &filePath) {
	bool result = false;
	char buf[1024] = "";
	DWORD p = 0, ret = GetPrivateProfileSectionA(IGNORE_LIST_SECTION, buf, sizeof(buf), filePath.c_str());
	std::ostringstream line;
	while (p < ret) {
		line << buf[p];
		if ('\0' == buf[p]) {
			l4util::StringPair keyValue;
			if (l4util::parseProperty(line.str(), keyValue)) {
				s_ignoredProcessNameList.push_back(keyValue.second);
			}
			line.str("");
			line.clear();
		}
		p++;
	}
	return result;
}

bool SteamVRDemoRuleManager::parseRuleSection(const std::string &sectionName, const std::string &filePath, RuleItem &ruleItem) {
	bool result = true;
	char value[MAX_PATH];

	// TODO: refactor it with GetPrivateProfileSection
	result &= (0 < GetPrivateProfileStringA(sectionName.c_str(), "ClassName", "", value, sizeof(value), filePath.c_str()));
	ruleItem.m_className = value;

	result &= (0 < GetPrivateProfileStringA(sectionName.c_str(), "Message", "", value, sizeof(value), filePath.c_str()));
	ruleItem.m_message = (RuleMessage)parseValue(value, SteamVRDemoRuleManager::s_ruleMessageTokenMap);

	result &= (0 < GetPrivateProfileStringA(sectionName.c_str(), "Action", "", value, sizeof(value), filePath.c_str()));
	ruleItem.m_action = (RuleAction)parseValue(value, SteamVRDemoRuleManager::s_ruleActionTokenMap);

	return result;
}

bool SteamVRDemoRuleManager::init(const char *configFilePath)
{
	bool result = true;
	char buf[1024];
	DWORD p = 0, ret = GetPrivateProfileSectionNamesA(buf, sizeof(buf), configFilePath);
	if (0 < ret) {
		std::ostringstream sectionName;
		while (p < ret) {
			sectionName << buf[p];
			if ('\0' == buf[p]) {
				if (0 == _stricmp(IGNORE_LIST_SECTION, sectionName.str().c_str())) {
					parseIgnoreListSection(configFilePath);
				}
				else {
					RuleItem ruleItem;
					if (parseRuleSection(sectionName.str(), configFilePath, ruleItem)) {
						SteamVRDemoRuleManager::s_ruleItemList.push_back(ruleItem);
					}
					else {
						// TODO: log it as a warning
					}
				}
				sectionName.str("");
				sectionName.clear();
			}
			p++;
		}
	}
	else {
		result = false;
	}
	return result;
}

<commit_msg>Fix full screen action with Unreal games<commit_after>#include "stdafx.h"
#include "SteamVRDemoRuleManager.h"

#include <string.h>
#include <sstream>
#include <log4cplus\log4cplus.h>
#include "util\l4util.h"

const char *IGNORE_LIST_SECTION = "IgnoreList";

enum RuleMessage {
	RM_UNKNOWN = -1,
	RM_ACTIVATE = HCBT_ACTIVATE,
	RM_CREATE = HCBT_CREATEWND
};
enum RuleAction {
	RA_UNKNOWN = -1,
	RA_MAX = SW_MAXIMIZE,
	RA_MIN = SW_MINIMIZE,
	RA_HIDE = SW_HIDE
};

SteamVRDemoRuleManager::TokenMap SteamVRDemoRuleManager::s_ruleMessageTokenMap = {
	{HCBT_ACTIVATE, "ACTIVATE"},
	{HCBT_CREATEWND, "CREATE"}
};

SteamVRDemoRuleManager::TokenMap SteamVRDemoRuleManager::s_ruleActionTokenMap = {
	{SW_MAXIMIZE, "MAX"},
	{SW_MINIMIZE, "MIN"},
	{SW_HIDE, "HIDE"},
	{WM_CLOSE, "CLOSE"},
	{SteamVRDemoRuleManager::RA_FULL, "FULL"}
};

SteamVRDemoRuleManager::RuleItemList SteamVRDemoRuleManager::s_ruleItemList;
SteamVRDemoRuleManager::NameList SteamVRDemoRuleManager::s_ignoredProcessNameList;

bool SteamVRDemoRuleManager::ifIgnore(const std::string &processName)
{
	bool result = false;

	for (NameList::const_iterator it = SteamVRDemoRuleManager::s_ignoredProcessNameList.begin(); it != SteamVRDemoRuleManager::s_ignoredProcessNameList.end(); ++it) {
		if (0 == _stricmp(processName.c_str(), it->c_str())) {
			result = true;
			break;
		}
	}
	return result;
}

void SteamVRDemoRuleManager::performFullScreenAction(HWND wnd)
{
	HWND desktopWindow = GetDesktopWindow();
	RECT desktopRect, windowRect;
	log4cplus::Logger logger = log4cplus::Logger::getInstance("SERVER");

	GetWindowRect(desktopWindow, &desktopRect);
	GetWindowRect(wnd, &windowRect);

	LOG4CPLUS_DEBUG(logger, "Desktop width: " << desktopRect.right << ", height: " << desktopRect.bottom);
	LOG4CPLUS_DEBUG(logger, "Window width: " << windowRect.right - windowRect.left << ", height: " << desktopRect.bottom - desktopRect.top);

	if (windowRect.left > desktopRect.left ||
		windowRect.right < desktopRect.right ||
		windowRect.top < desktopRect.top ||
		windowRect.bottom < desktopRect.bottom) {
		LOG4CPLUS_DEBUG(logger, "Window is not full screen size, toggole it");
		PostMessageA(wnd, WM_KEYDOWN, VK_MENU, 0);				// Post WM_KEYDOWN for Unreal games
		// TODO: check if char code or repeat is necessary
		PostMessageA(wnd, WM_SYSKEYDOWN, VK_RETURN, 1 << 29 | 0x001C0001);  // ALT down | char code = 1C | repeat = 1
		PostMessageA(wnd, WM_KEYUP, VK_MENU, 0);				// Post WM_KEYUP for Unreal games
	}
}

void SteamVRDemoRuleManager::handleMessage(int message, HWND wnd)
{
	char className[MAX_PATH];
	RuleAction action = RA_UNKNOWN;

	log4cplus::Logger logger = log4cplus::Logger::getInstance("SERVER");
	DWORD processId = GetCurrentProcessId();
	std::string processName = l4util::getCurrentProcessName();

	if (SteamVRDemoRuleManager::ifIgnore(processName)) {
		return;
	}

	RealGetWindowClassA(wnd, className, MAX_PATH);
	for (RuleItemList::const_iterator it = SteamVRDemoRuleManager::s_ruleItemList.begin(); it != SteamVRDemoRuleManager::s_ruleItemList.end(); ++it) {
		if (it->m_className == className && it->m_message == message) {
			action = it->m_action;
		}
	}
	LOG4CPLUS_INFO(logger, "[" << SteamVRDemoRuleManager::s_ruleMessageTokenMap[message] << "] ID=" << processId << ", name=" << processName << ", Class=" << className << std::endl);

	if (RA_UNKNOWN != action) {
		switch (action) {
		case RA_FULL:
			performFullScreenAction(wnd);
			break;
		case RA_CLOSE:
			PostMessage(wnd, WM_CLOSE, 0, 0);
			break;
		default:
			// show window commands
			ShowWindow(wnd, action);
			break;
		}
	}
}

int SteamVRDemoRuleManager::parseValue(const std::string &token, const TokenMap &tokenMap)
{
	int result = UNKNOWN_TOKEN;
	std::string trimmedToken = (token);

	for (TokenMap::const_iterator it = tokenMap.begin(); it != tokenMap.end(); ++it) {
		if (0 == _stricmp(it->second.c_str(), trimmedToken.c_str())) {
			result = it->first;
			break;
		}
	}
	return result;
}

bool SteamVRDemoRuleManager::parseIgnoreListSection(const std::string &filePath) {
	bool result = false;
	char buf[1024] = "";
	DWORD p = 0, ret = GetPrivateProfileSectionA(IGNORE_LIST_SECTION, buf, sizeof(buf), filePath.c_str());
	std::ostringstream line;
	while (p < ret) {
		line << buf[p];
		if ('\0' == buf[p]) {
			l4util::StringPair keyValue;
			if (l4util::parseProperty(line.str(), keyValue)) {
				s_ignoredProcessNameList.push_back(keyValue.second);
			}
			line.str("");
			line.clear();
		}
		p++;
	}
	return result;
}

bool SteamVRDemoRuleManager::parseRuleSection(const std::string &sectionName, const std::string &filePath, RuleItem &ruleItem) {
	bool result = true;
	char value[MAX_PATH];

	// TODO: refactor it with GetPrivateProfileSection
	result &= (0 < GetPrivateProfileStringA(sectionName.c_str(), "ClassName", "", value, sizeof(value), filePath.c_str()));
	ruleItem.m_className = value;

	result &= (0 < GetPrivateProfileStringA(sectionName.c_str(), "Message", "", value, sizeof(value), filePath.c_str()));
	ruleItem.m_message = (RuleMessage)parseValue(value, SteamVRDemoRuleManager::s_ruleMessageTokenMap);

	result &= (0 < GetPrivateProfileStringA(sectionName.c_str(), "Action", "", value, sizeof(value), filePath.c_str()));
	ruleItem.m_action = (RuleAction)parseValue(value, SteamVRDemoRuleManager::s_ruleActionTokenMap);

	return result;
}

bool SteamVRDemoRuleManager::init(const char *configFilePath)
{
	bool result = true;
	char buf[1024];
	DWORD p = 0, ret = GetPrivateProfileSectionNamesA(buf, sizeof(buf), configFilePath);
	if (0 < ret) {
		std::ostringstream sectionName;
		while (p < ret) {
			sectionName << buf[p];
			if ('\0' == buf[p]) {
				if (0 == _stricmp(IGNORE_LIST_SECTION, sectionName.str().c_str())) {
					parseIgnoreListSection(configFilePath);
				}
				else {
					RuleItem ruleItem;
					if (parseRuleSection(sectionName.str(), configFilePath, ruleItem)) {
						SteamVRDemoRuleManager::s_ruleItemList.push_back(ruleItem);
					}
					else {
						// TODO: log it as a warning
					}
				}
				sectionName.str("");
				sectionName.clear();
			}
			p++;
		}
	}
	else {
		result = false;
	}
	return result;
}

<|endoftext|>


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

#include "qnetworkconfiguration.h"

#include "qnetworkconfiguration_p.h"

QT_BEGIN_NAMESPACE

/*!
    \class QNetworkConfiguration

    \brief The QNetworkConfiguration class provides an abstraction of one or more access point configurations.

    \since 4.7

    \inmodule QtNetwork
    \ingroup bearer

    QNetworkConfiguration encapsulates a single access point or service network.
    In most cases a single access point configuration can be mapped to one network
    interface. However a single network interface may not always map to only one
    access point configuration. Multiple configurations for the same
    network device may enable multiple access points. An example
    device that could exhibit such a configuration might be a
    Smartphone which allows the user to manage multiple WLAN
    configurations while the device itself has only one WLAN network device.

    The QNetworkConfiguration also supports the concept of service networks.
    This concept allows the grouping of multiple access point configurations
    into one entity. Such a group is called service network and can be
    beneficial in cases whereby a network session to a
    particular destination network is required (e.g. a company network).
    When using a service network the user doesn't usually care which one of the
    connectivity options is chosen (e.g. corporate WLAN or VPN via GPRS)
    as long as he can reach the company's target server. Depending
    on the current position and time some of the access points that make
    up the service network may not even be available. Furthermore
    automated access point roaming can be enabled which enables the device
    to change the network interface configuration dynamically while maintaining
    the applications connection to the target network. It allows adaption
    to the changing environment and may enable optimization with regards to
    cost, speed or other network parameters.

    Special configurations of type UserChoice provide a placeholder configuration which is
    resolved to an actual network configuration by the platform when a
    \l {QNetworkSession}{session} is \l {QNetworkSession::open()}{opened}. Not all platforms
    support the concept of a user choice configuration.

    \section1 Configuration states

    The list of available configurations can be obtained via
    QNetworkConfigurationManager::allConfigurations(). A configuration can have
    multiple states. The \l Defined configuration state indicates that the configuration
    is stored on the device. However the configuration is not yet ready to be activated
    as e.g. a WLAN may not be available at the current time.

    The \l Discovered state implies that the configuration is \l Defined and
    the outside conditions are such that the configuration can be used immediately
    to open a new network session. An example of such an outside condition may be
    that the Ethernet cable is actually connected to the device or that the WLAN
    with the specified SSID is in range.

    The \l Active state implies that the configuration is \l Discovered. A configuration
    in this state is currently being used by an application. The underlying network
    interface has a valid IP configuration and can transfer IP packets between the
    device and the target network.

    The \l Undefined state indicates that the system has knowledge of possible target
    networks but cannot actually use that knowledge to connect to it. An example
    for such a state could be an encrypted WLAN that has been discovered
    but the user hasn't actually saved a configuration including the required password
    which would allow the device to connect to it.

    Depending on the type of configuration some states are transient in nature. A GPRS/UMTS
    connection may almost always be \l Discovered if the GSM/UMTS network is available.
    However if the GSM/UMTS network looses the connection the associated configuration may change its state
    from \l Discovered to \l Defined as well. A similar use case might be triggered by
    WLAN availability. QNetworkConfigurationManager::updateConfigurations() can be used to
    manually trigger updates of states. Note that some platforms do not require such updates
    as they implicitly change the state once it has been discovered. If the state of a
    configuration changes all related QNetworkConfiguration instances change their state automatically.

    \sa QNetworkSession, QNetworkConfigurationManager
*/

/*!
    \enum QNetworkConfiguration::Type

    This enum describes the type of configuration.

    \value InternetAccessPoint  The configuration specifies the details for a single access point.
                                Note that configurations of type InternetAccessPoint may be part
                                of other QNetworkConfigurations of type ServiceNetwork.
    \value ServiceNetwork       The configuration is based on a group of QNetworkConfigurations of
                                type InternetAccessPoint. All group members can reach the same
                                target network. This type of configuration is a mandatory
                                requirement for roaming enabled network sessions. On some
                                platforms this form of configuration may also be called Service
                                Network Access Point (SNAP).
    \value UserChoice           The configuration is a placeholder which will be resolved to an
                                actual configuration by the platform when a session is opened. Depending
                                on the platform the selection may generate a popup dialog asking the user
                                for his preferred choice.
    \value Invalid              The configuration is invalid.
*/

/*!
    \enum QNetworkConfiguration::StateFlag

    Specifies the configuration states.

    \value Undefined    This state is used for transient configurations such as newly discovered
                        WLANs for which the user has not actually created a configuration yet.
    \value Defined      Defined configurations are known to the system but are not immediately
                        usable (e.g. a configured WLAN is not within range or the Ethernet cable
                        is currently not plugged into the machine).
    \value Discovered   A discovered configuration can be immediately used to create a new
                        QNetworkSession. An example of a discovered configuration could be a WLAN
                        which is within in range. If the device moves out of range the discovered
                        flag is dropped. A second example is a GPRS configuration which generally
                        remains discovered for as long as the phone has network coverage. A
                        configuration that has this state is also in state
                        QNetworkConfiguration::Defined. If the configuration is a service network
                        this flag is set if at least one of the underlying access points
                        configurations has the Discovered state.
    \value Active       The configuration is currently used by an open network session
                        (see \l QNetworkSession::isOpen()). However this does not mean that the
                        current process is the entity that created the open session. It merely
                        indicates that if a new QNetworkSession were to be constructed based on
                        this configuration \l QNetworkSession::state() would return
                        \l QNetworkSession::Connected. This state implies the
                        QNetworkConfiguration::Discovered state.
*/

/*!
    \enum QNetworkConfiguration::Purpose

    Specifies the purpose of the configuration.

    \value UnknownPurpose           The configuration doesn't specify any purpose. This is the default value.
    \value PublicPurpose            The configuration can be used for general purpose internet access.
    \value PrivatePurpose           The configuration is suitable to access a private network such as an office Intranet.
    \value ServiceSpecificPurpose   The configuration can be used for operator specific services (e.g.
                                    receiving MMS messages or content streaming).
*/

/*!
    Constructs an invalid configuration object.

    \sa isValid()
*/
QNetworkConfiguration::QNetworkConfiguration()
    : d(0)
{
}

/*!
    Creates a copy of the QNetworkConfiguration object contained in \a other.
*/
QNetworkConfiguration::QNetworkConfiguration(const QNetworkConfiguration& other)
    : d(other.d)
{
}

/*!
    Copies the content of the QNetworkConfiguration object contained in \a other into this one.
*/
QNetworkConfiguration& QNetworkConfiguration::operator=(const QNetworkConfiguration& other)
{
    d = other.d;
    return *this;
}

/*!
    Frees the resources associated with the QNetworkConfiguration object.
*/
QNetworkConfiguration::~QNetworkConfiguration()
{
}

/*!
    Returns true, if this configuration is the same as the \a other
    configuration given; otherwise returns false.
*/
bool QNetworkConfiguration::operator==(const QNetworkConfiguration& other) const
{
    if (!d)
        return !other.d;

    if (!other.d)
        return false;

    return (d == other.d);
}

/*!
    \fn bool QNetworkConfiguration::operator!=(const QNetworkConfiguration& other) const

    Returns true if this configuration is not the same as the \a other
    configuration given; otherwise returns false.
*/

/*!
    Returns the user visible name of this configuration.

    The name may either be the name of the underlying access point or the
    name for service network that this configuration represents.
*/
QString QNetworkConfiguration::name() const
{
    return d ? d->name : QString();
}

/*!
    Returns the unique and platform specific identifier for this network configuration;
    otherwise an empty string.
*/
QString QNetworkConfiguration::identifier() const
{
    return d ? d->id : QString();
}

/*!
    Returns the type of the configuration.

    A configuration can represent a single access point configuration or
    a set of access point configurations. Such a set is called service network.
    A configuration that is based on a service network can potentially support
    roaming of network sessions.
*/
QNetworkConfiguration::Type QNetworkConfiguration::type() const
{
    return d ? d->type : QNetworkConfiguration::Invalid;
}

/*!
    Returns true if this QNetworkConfiguration object is valid.
    A configuration may become invalid if the user deletes the configuration or
    the configuration was default-constructed.

    The addition and removal of configurations can be monitored via the
    QNetworkConfigurationManager.

    \sa QNetworkConfigurationManager
*/
bool QNetworkConfiguration::isValid() const
{
    return d ? d->isValid : false;
}

/*!
    Returns the current state of the configuration.
*/
QNetworkConfiguration::StateFlags QNetworkConfiguration::state() const
{
    return d ? d->state : QNetworkConfiguration::Undefined;
}

/*!
    Returns the purpose of this configuration.

    The purpose field may be used to programmatically determine the
    purpose of a configuration. Such information is usually part of the
    access point or service network meta data.
*/
QNetworkConfiguration::Purpose QNetworkConfiguration::purpose() const
{
    return d ? d->purpose : QNetworkConfiguration::UnknownPurpose;
}

/*!
    Returns true if this configuration supports roaming; otherwise false.
*/
bool QNetworkConfiguration::isRoamingAvailable() const
{
    return d ? d->roamingSupported : false;
}

/*!
    Returns all sub configurations of this network configuration.
    Only network configurations of type \l ServiceNetwork can have children. Otherwise
    this function returns an empty list.
*/
QList<QNetworkConfiguration> QNetworkConfiguration::children() const
{
    QList<QNetworkConfiguration> results;
    if (type() != QNetworkConfiguration::ServiceNetwork || !isValid() )
        return results;

    QMutableListIterator<QNetworkConfigurationPrivatePointer> iter(d->serviceNetworkMembers);
    while(iter.hasNext()) {
        QNetworkConfigurationPrivatePointer p = iter.next();
        //if we have an invalid member get rid of it -> was deleted earlier on
        if (!p->isValid)
            iter.remove();

        QNetworkConfiguration item;
        item.d = p;
        results << item;
    }

    return results;
}

/*!
    Returns the type of bearer. The string is not translated and
    therefore can not be shown to the user. The subsequent table presents the currently known
    bearer types:

    \table
        \header
            \o Value
            \o Description
        \row
            \o Unknown
            \o The session is based on an unknown or unspecified bearer type.
        \row
            \o Ethernet
            \o The session is based on Ethernet.
        \row
            \o WLAN
            \o The session is based on Wireless LAN.
        \row
            \o 2G
            \o The session uses CSD, GPRS, HSCSD, EDGE or cdmaOne.
        \row
            \o CDMA2000
            \o The session uses CDMA.
        \row
            \o WCDMA
            \o The session uses W-CDMA/UMTS.
        \row
            \o HSPA
            \o The session uses High Speed Packet Access.
        \row
            \o Bluetooth
            \o The session uses Bluetooth.
        \row
            \o WiMAX
            \o The session uses WiMAX.
    \endtable

    This function returns an empty string if this is an invalid configuration,
    a network configuration of type \l QNetworkConfiguration::ServiceNetwork or
    \l QNetworkConfiguration::UserChoice.
*/
QString QNetworkConfiguration::bearerName() const
{
    if (!isValid())
        return QString();

    return d->bearerName();
}

QT_END_NAMESPACE

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

#include "qnetworkconfiguration.h"

#include "qnetworkconfiguration_p.h"

QT_BEGIN_NAMESPACE

/*!
    \class QNetworkConfiguration

    \brief The QNetworkConfiguration class provides an abstraction of one or more access point configurations.

    \since 4.7

    \inmodule QtNetwork
    \ingroup bearer

    QNetworkConfiguration encapsulates a single access point or service network.
    In most cases a single access point configuration can be mapped to one network
    interface. However a single network interface may not always map to only one
    access point configuration. Multiple configurations for the same
    network device may enable multiple access points. An example
    device that could exhibit such a configuration might be a
    Smartphone which allows the user to manage multiple WLAN
    configurations while the device itself has only one WLAN network device.

    The QNetworkConfiguration also supports the concept of service networks.
    This concept allows the grouping of multiple access point configurations
    into one entity. Such a group is called service network and can be
    beneficial in cases whereby a network session to a
    particular destination network is required (e.g. a company network).
    When using a service network the user doesn't usually care which one of the
    connectivity options is chosen (e.g. corporate WLAN or VPN via GPRS)
    as long as he can reach the company's target server. Depending
    on the current position and time some of the access points that make
    up the service network may not even be available. Furthermore
    automated access point roaming can be enabled which enables the device
    to change the network interface configuration dynamically while maintaining
    the applications connection to the target network. It allows adaption
    to the changing environment and may enable optimization with regards to
    cost, speed or other network parameters.

    Special configurations of type UserChoice provide a placeholder configuration which is
    resolved to an actual network configuration by the platform when a
    \l {QNetworkSession}{session} is \l {QNetworkSession::open()}{opened}. Not all platforms
    support the concept of a user choice configuration.

    \section1 Configuration states

    The list of available configurations can be obtained via
    QNetworkConfigurationManager::allConfigurations(). A configuration can have
    multiple states. The \l Defined configuration state indicates that the configuration
    is stored on the device. However the configuration is not yet ready to be activated
    as e.g. a WLAN may not be available at the current time.

    The \l Discovered state implies that the configuration is \l Defined and
    the outside conditions are such that the configuration can be used immediately
    to open a new network session. An example of such an outside condition may be
    that the Ethernet cable is actually connected to the device or that the WLAN
    with the specified SSID is in range.

    The \l Active state implies that the configuration is \l Discovered. A configuration
    in this state is currently being used by an application. The underlying network
    interface has a valid IP configuration and can transfer IP packets between the
    device and the target network.

    The \l Undefined state indicates that the system has knowledge of possible target
    networks but cannot actually use that knowledge to connect to it. An example
    for such a state could be an encrypted WLAN that has been discovered
    but the user hasn't actually saved a configuration including the required password
    which would allow the device to connect to it.

    Depending on the type of configuration some states are transient in nature. A GPRS/UMTS
    connection may almost always be \l Discovered if the GSM/UMTS network is available.
    However if the GSM/UMTS network looses the connection the associated configuration may change its state
    from \l Discovered to \l Defined as well. A similar use case might be triggered by
    WLAN availability. QNetworkConfigurationManager::updateConfigurations() can be used to
    manually trigger updates of states. Note that some platforms do not require such updates
    as they implicitly change the state once it has been discovered. If the state of a
    configuration changes all related QNetworkConfiguration instances change their state automatically.

    \sa QNetworkSession, QNetworkConfigurationManager
*/

/*!
    \enum QNetworkConfiguration::Type

    This enum describes the type of configuration.

    \value InternetAccessPoint  The configuration specifies the details for a single access point.
                                Note that configurations of type InternetAccessPoint may be part
                                of other QNetworkConfigurations of type ServiceNetwork.
    \value ServiceNetwork       The configuration is based on a group of QNetworkConfigurations of
                                type InternetAccessPoint. All group members can reach the same
                                target network. This type of configuration is a mandatory
                                requirement for roaming enabled network sessions. On some
                                platforms this form of configuration may also be called Service
                                Network Access Point (SNAP).
    \value UserChoice           The configuration is a placeholder which will be resolved to an
                                actual configuration by the platform when a session is opened. Depending
                                on the platform the selection may generate a popup dialog asking the user
                                for his preferred choice.
    \value Invalid              The configuration is invalid.
*/

/*!
    \enum QNetworkConfiguration::StateFlag

    Specifies the configuration states.

    \value Undefined    This state is used for transient configurations such as newly discovered
                        WLANs for which the user has not actually created a configuration yet.
    \value Defined      Defined configurations are known to the system but are not immediately
                        usable (e.g. a configured WLAN is not within range or the Ethernet cable
                        is currently not plugged into the machine).
    \value Discovered   A discovered configuration can be immediately used to create a new
                        QNetworkSession. An example of a discovered configuration could be a WLAN
                        which is within in range. If the device moves out of range the discovered
                        flag is dropped. A second example is a GPRS configuration which generally
                        remains discovered for as long as the device has network coverage. A
                        configuration that has this state is also in state
                        QNetworkConfiguration::Defined. If the configuration is a service network
                        this flag is set if at least one of the underlying access points
                        configurations has the Discovered state.
    \value Active       The configuration is currently used by an open network session
                        (see \l QNetworkSession::isOpen()). However this does not mean that the
                        current process is the entity that created the open session. It merely
                        indicates that if a new QNetworkSession were to be constructed based on
                        this configuration \l QNetworkSession::state() would return
                        \l QNetworkSession::Connected. This state implies the
                        QNetworkConfiguration::Discovered state.
*/

/*!
    \enum QNetworkConfiguration::Purpose

    Specifies the purpose of the configuration.

    \value UnknownPurpose           The configuration doesn't specify any purpose. This is the default value.
    \value PublicPurpose            The configuration can be used for general purpose internet access.
    \value PrivatePurpose           The configuration is suitable to access a private network such as an office Intranet.
    \value ServiceSpecificPurpose   The configuration can be used for operator specific services (e.g.
                                    receiving MMS messages or content streaming).
*/

/*!
    Constructs an invalid configuration object.

    \sa isValid()
*/
QNetworkConfiguration::QNetworkConfiguration()
    : d(0)
{
}

/*!
    Creates a copy of the QNetworkConfiguration object contained in \a other.
*/
QNetworkConfiguration::QNetworkConfiguration(const QNetworkConfiguration& other)
    : d(other.d)
{
}

/*!
    Copies the content of the QNetworkConfiguration object contained in \a other into this one.
*/
QNetworkConfiguration& QNetworkConfiguration::operator=(const QNetworkConfiguration& other)
{
    d = other.d;
    return *this;
}

/*!
    Frees the resources associated with the QNetworkConfiguration object.
*/
QNetworkConfiguration::~QNetworkConfiguration()
{
}

/*!
    Returns true, if this configuration is the same as the \a other
    configuration given; otherwise returns false.
*/
bool QNetworkConfiguration::operator==(const QNetworkConfiguration& other) const
{
    if (!d)
        return !other.d;

    if (!other.d)
        return false;

    return (d == other.d);
}

/*!
    \fn bool QNetworkConfiguration::operator!=(const QNetworkConfiguration& other) const

    Returns true if this configuration is not the same as the \a other
    configuration given; otherwise returns false.
*/

/*!
    Returns the user visible name of this configuration.

    The name may either be the name of the underlying access point or the
    name for service network that this configuration represents.
*/
QString QNetworkConfiguration::name() const
{
    return d ? d->name : QString();
}

/*!
    Returns the unique and platform specific identifier for this network configuration;
    otherwise an empty string.
*/
QString QNetworkConfiguration::identifier() const
{
    return d ? d->id : QString();
}

/*!
    Returns the type of the configuration.

    A configuration can represent a single access point configuration or
    a set of access point configurations. Such a set is called service network.
    A configuration that is based on a service network can potentially support
    roaming of network sessions.
*/
QNetworkConfiguration::Type QNetworkConfiguration::type() const
{
    return d ? d->type : QNetworkConfiguration::Invalid;
}

/*!
    Returns true if this QNetworkConfiguration object is valid.
    A configuration may become invalid if the user deletes the configuration or
    the configuration was default-constructed.

    The addition and removal of configurations can be monitored via the
    QNetworkConfigurationManager.

    \sa QNetworkConfigurationManager
*/
bool QNetworkConfiguration::isValid() const
{
    return d ? d->isValid : false;
}

/*!
    Returns the current state of the configuration.
*/
QNetworkConfiguration::StateFlags QNetworkConfiguration::state() const
{
    return d ? d->state : QNetworkConfiguration::Undefined;
}

/*!
    Returns the purpose of this configuration.

    The purpose field may be used to programmatically determine the
    purpose of a configuration. Such information is usually part of the
    access point or service network meta data.
*/
QNetworkConfiguration::Purpose QNetworkConfiguration::purpose() const
{
    return d ? d->purpose : QNetworkConfiguration::UnknownPurpose;
}

/*!
    Returns true if this configuration supports roaming; otherwise false.
*/
bool QNetworkConfiguration::isRoamingAvailable() const
{
    return d ? d->roamingSupported : false;
}

/*!
    Returns all sub configurations of this network configuration.
    Only network configurations of type \l ServiceNetwork can have children. Otherwise
    this function returns an empty list.
*/
QList<QNetworkConfiguration> QNetworkConfiguration::children() const
{
    QList<QNetworkConfiguration> results;
    if (type() != QNetworkConfiguration::ServiceNetwork || !isValid() )
        return results;

    QMutableListIterator<QNetworkConfigurationPrivatePointer> iter(d->serviceNetworkMembers);
    while(iter.hasNext()) {
        QNetworkConfigurationPrivatePointer p = iter.next();
        //if we have an invalid member get rid of it -> was deleted earlier on
        if (!p->isValid)
            iter.remove();

        QNetworkConfiguration item;
        item.d = p;
        results << item;
    }

    return results;
}

/*!
    Returns the type of bearer. The string is not translated and
    therefore can not be shown to the user. The subsequent table presents the currently known
    bearer types:

    \table
        \header
            \o Value
            \o Description
        \row
            \o Unknown
            \o The session is based on an unknown or unspecified bearer type.
        \row
            \o Ethernet
            \o The session is based on Ethernet.
        \row
            \o WLAN
            \o The session is based on Wireless LAN.
        \row
            \o 2G
            \o The session uses CSD, GPRS, HSCSD, EDGE or cdmaOne.
        \row
            \o CDMA2000
            \o The session uses CDMA.
        \row
            \o WCDMA
            \o The session uses W-CDMA/UMTS.
        \row
            \o HSPA
            \o The session uses High Speed Packet Access.
        \row
            \o Bluetooth
            \o The session uses Bluetooth.
        \row
            \o WiMAX
            \o The session uses WiMAX.
    \endtable

    This function returns an empty string if this is an invalid configuration,
    a network configuration of type \l QNetworkConfiguration::ServiceNetwork or
    \l QNetworkConfiguration::UserChoice.
*/
QString QNetworkConfiguration::bearerName() const
{
    if (!isValid())
        return QString();

    return d->bearerName();
}

QT_END_NAMESPACE

<|endoftext|>


<commit_before>/**
 * feed_the_dog.cpp - an msp430g2xxx specific watchdog timer example
 *
 * msp430-size msp430g2553in20_release/feed_the_dog.elf
 *  text     data      bss      dec      hex  filename
 *   416        0        6      422      1a6  msp430g2553in20_release/feed_the_dog.elf
 */

#include <fabooh.h>
#include <main.h>
#include <serial.h>

volatile unsigned int count = 0;
sw_serial_t<9600, CPU::frequency, TX_PIN, NO_PIN> Serial;

inline void setup(void)
{
  Serial.begin();

  /* ADC */
  P1_5::PSEL();
  ADC10CTL0 &= ~ENC;
  ADC10CTL1 = INCH_5 | ADC10DIV_3 ;
  ADC10CTL0 = SREF_0 | ADC10SHT_3 | ADC10ON;
  ADC10AE0 |= BIT5;

  /* Timer1 A0*/
  TA1CCR0 = (CPU::frequency*.010 )/8;     // Count overflow frequency ~10ms
  TA1CTL = TASSEL_2 | ID_3 | MC_1;        // SMCLK / 8  upmode
  TA1CCTL0 = CCIE;

  __enable_interrupt();
  WDTCTL = WDTPW | WDTCNTCL;              // Enable WDT
  Serial << "\r\nreset...\n";
}

void loop()
{
  unsigned sample;

  LPM0;
  WDTCTL = WDTPW | WDTCNTCL;

  if (count > 100) {                      // ~1 Second
    count = 1;
    __delay_cycles(128);                  // let the pins settle
    ADC10CTL0 |= ENC | ADC10SC;           // Sampling and conversion start
    while (ADC10CTL1 & ADC10BUSY) {       // sleep and wait for completion
      asm("nop");
    }
    sample = ADC10MEM;

    Serial << sample << "    \r";
  }
}

__attribute__( (interrupt(TIMER1_A0_VECTOR)) )
void TIMER1_A0_ISR(void)
{
  LPM0_EXIT;
  count++;
}

<commit_msg>make example more low power<commit_after>/**
 * feed_the_dog.cpp - an msp430g2xxx specific watchdog timer example
 *
 * msp430-size msp430g2553in20_release/feed_the_dog.elf
 *   text     data      bss      dec      hex  filename
 *    432        0        6      438      1b6  msp430g2553in20_release/feed_the_dog.elf
 */

#include <fabooh.h>
#include <main.h>
#include <serial.h>

volatile unsigned int count = 0;
sw_serial_t<9600, CPU::frequency, TX_PIN, NO_PIN> Serial;

inline void setup(void)
{
  Serial.begin();

  /* ADC */
  P1_5::PSEL();
  ADC10CTL0 &= ~ENC;
  ADC10CTL1 = INCH_5 | ADC10DIV_3 ;
  ADC10CTL0 = SREF_0 | ADC10SHT_3 | ADC10ON;
  ADC10AE0 |= BIT5;

  /* Timer1 A0*/
  TA1CCR0 = (CPU::frequency*.010 )/8;     // Count overflow frequency ~10ms
  TA1CTL = TASSEL_2 | ID_3 | MC_1;        // SMCLK / 8  upmode
  TA1CCTL0 = CCIE;

  __enable_interrupt();
  WDTCTL = WDTPW | WDTCNTCL;              // Enable WDT
  Serial << "\r\nreset...\n";
}

void loop()
{
  unsigned sample;

  LPM0;
  WDTCTL = WDTPW | WDTCNTCL;

  if (count > 100) {                      // ~1 Second
    count = 1;
    __delay_cycles(128);                  // Let the pins settle
    ADC10CTL0 |= ENC | ADC10SC;           // Sampling and conversion start
    while(ADC10CTL1 & ADC10BUSY) {
      LPM0;                               // Sleep until ADC done
    }
    sample = ADC10MEM;

    Serial << sample << "    \r";
  }
}

__attribute__( (interrupt(TIMER1_A0_VECTOR)) )
void TIMER1_A0_ISR(void)
{
  count++;

  if ( !(ADC10CTL1 & ADC10BUSY) ) {
  	LPM0_EXIT;
  }
}

__attribute__( (interrupt(ADC10_VECTOR)) )
void ADC10_ISR(void)
{
  LPM0_EXIT;
}

<|endoftext|>


<commit_before>//
//  From NumpySrc/numpy/core/src/multiarray/compiled_base.c

/** @brief find index of a sorted array such that arr[i] <= key < arr[i + 1].
 *
 * If an starting index guess is in-range, the array values around this
 * index are first checked.  This allows for repeated calls for well-ordered
 * keys (a very common case) to use the previous index as a very good guess.
 *
 * If the guess value is not useful, bisection of the array is used to
 * find the index.  If there is no such index, the return values are:
 *     key < arr[0] -- -1
 *     key == arr[len - 1] -- len - 1
 *     key > arr[len - 1] -- len
 * The array is assumed contiguous and sorted in ascending order.
 *
 * @param key key value.
 * @param arr contiguous sorted array to be searched.
 * @param len length of the array.
 * @param guess initial guess of index
 * @return index
 */
#include "pythonic/numpy/isnan.hpp"
#include "pythonic/utils/functor.hpp"

#define LIKELY_IN_CACHE_SIZE 8
PYTHONIC_NS_BEGIN

template <typename npy_intp, typename npy_double, class T>
static npy_intp binary_search_with_guess(const npy_double key, const T &arr,
                                         npy_intp len, npy_intp guess)
{
  npy_intp imin = 0;
  npy_intp imax = len;

  /* Handle keys outside of the arr range first */
  if (key > arr[len - 1]) {
    return len;
  } else if (key < arr[0]) {
    return -1;
  }

  /*
   * If len <= 4 use linear search.
   * From above we know key >= arr[0] when we start.
   */
  if (len <= 4) {
    npy_intp i;

    for (i = 1; i < len && key >= arr[i]; ++i)
      ;
    return i - 1;
  }

  if (guess > len - 3) {
    guess = len - 3;
  }
  if (guess < 1) {
    guess = 1;
  }

  /* check most likely values: guess - 1, guess, guess + 1 */
  if (key < arr[guess]) {
    if (key < arr[guess - 1]) {
      imax = guess - 1;
      /* last attempt to restrict search to items in cache */
      if (guess > LIKELY_IN_CACHE_SIZE &&
          key >= arr[guess - LIKELY_IN_CACHE_SIZE]) {
        imin = guess - LIKELY_IN_CACHE_SIZE;
      }
    } else {
      /* key >= arr[guess - 1] */
      return guess - 1;
    }
  } else {
    /* key >= arr[guess] */
    if (key < arr[guess + 1]) {
      return guess;
    } else {
      /* key >= arr[guess + 1] */
      if (key < arr[guess + 2]) {
        return guess + 1;
      } else {
        /* key >= arr[guess + 2] */
        imin = guess + 2;
        /* last attempt to restrict search to items in cache */
        if (guess < len - LIKELY_IN_CACHE_SIZE - 1 &&
            key < arr[guess + LIKELY_IN_CACHE_SIZE]) {
          imax = guess + LIKELY_IN_CACHE_SIZE;
        }
      }
    }
  }

  /* finally, find index by bisection */
  while (imin < imax) {
    const npy_intp imid = imin + ((imax - imin) >> 1);
    if (key >= arr[imid]) {
      imin = imid + 1;
    } else {
      imax = imid;
    }
  }
  return imin - 1;
}
//
//#undef LIKELY_IN_CACHE_SIZE
//
// NPY_NO_EXPORT PyObject *
// arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
//{
//
//    PyObject *fp, *xp, *x;
//    PyObject *left = NULL, *right = NULL;
//    PyArrayObject *afp = NULL, *axp = NULL, *ax = NULL, *af = NULL;
//    npy_intp i, lenx, lenxp;
//    npy_double lval, rval;
//    const npy_double *dy, *dx, *dz;
//    npy_double *dres, *slopes = NULL;
//
//    static char *kwlist[] = {"x", "xp", "fp", "left", "right", NULL};
//
//    NPY_BEGIN_THREADS_DEF;
//
//    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OO:interp", kwlist,
//                                     &x, &xp, &fp, &left, &right)) {
//        return NULL;
//    }
//
//    afp = (PyArrayObject *)PyArray_ContiguousFromAny(fp, NPY_DOUBLE, 1, 1);
//    if (afp == NULL) {
//        return NULL;
//    }
//    axp = (PyArrayObject *)PyArray_ContiguousFromAny(xp, NPY_DOUBLE, 1, 1);
//    if (axp == NULL) {
//        goto fail;
//    }
//    ax = (PyArrayObject *)PyArray_ContiguousFromAny(x, NPY_DOUBLE, 0, 0);
//    if (ax == NULL) {
//        goto fail;
//    }
//    lenxp = PyArray_SIZE(axp);
//    if (lenxp == 0) {
//        PyErr_SetString(PyExc_ValueError,
//                        "array of sample points is empty");
//        goto fail;
//    }
//    if (PyArray_SIZE(afp) != lenxp) {
//        PyErr_SetString(PyExc_ValueError,
//                        "fp and xp are not of the same length.");
//        goto fail;
//    }
//
//    af = (PyArrayObject *)PyArray_SimpleNew(PyArray_NDIM(ax),
//                                            PyArray_DIMS(ax), NPY_DOUBLE);
//    if (af == NULL) {
//        goto fail;
//    }
//    lenx = PyArray_SIZE(ax);
//
//    dy = (const npy_double *)PyArray_DATA(afp);
//    dx = (const npy_double *)PyArray_DATA(axp);
//    dz = (const npy_double *)PyArray_DATA(ax);
//    dres = (npy_double *)PyArray_DATA(af);
//    /* Get left and right fill values. */
//    if ((left == NULL) || (left == Py_None)) {
//        lval = dy[0];
//    }
//    else {
//        lval = PyFloat_AsDouble(left);
//        if (error_converting(lval)) {
//            goto fail;
//        }
//    }
//    if ((right == NULL) || (right == Py_None)) {
//        rval = dy[lenxp - 1];
//    }
//    else {
//        rval = PyFloat_AsDouble(right);
//        if (error_converting(rval)) {
//            goto fail;
//        }
//    }

// xp->dx   fp->dy  x -> dz
// This is the output type, based on the type of T, which can be complex.
template <class T>
using out_type =
    typename std::conditional<types::is_complex<typename T::dtype>::value,
                              std::complex<double>, double>::type;

template <typename npy_intp, typename T5, class T1, class T2, class T3,
          class T4>
void do_interp(const T1 &dz, const T2 &dx, const T3 &dy, T4 &dres,
               npy_intp lenxp, npy_intp lenx, T5 lval, T5 rval)
{
  npy_intp i;
  out_type<T3> *slopes = NULL;
  std::vector<out_type<T3>> slope_vect;
  /* binary_search_with_guess needs at least a 3 item long array */
  if (lenxp == 1) {
    const npy_double xp_val = dx[0];
    const out_type<T3> fp_val = dy[0];

    //        NPY_BEGIN_THREADS_THRESHOLDED(lenx);
    for (i = 0; i < lenx; ++i) {
      const npy_double x_val = dz[i];
      dres[i] = (x_val < xp_val) ? lval : ((x_val > xp_val) ? rval : fp_val);
    }
    //        NPY_END_THREADS;
  } else {
    npy_intp j = 0;

    /* only pre-calculate slopes if there are relatively few of them. */
    if (lenxp <= lenx) {
      slope_vect.resize(lenxp - 1);
      slopes = slope_vect.data();
    }

    //        NPY_BEGIN_THREADS;

    if (slopes != NULL) {
      for (i = 0; i < lenxp - 1; ++i) {
        slopes[i] = (dy[i + 1] - dy[i]) / (dx[i + 1] - dx[i]);
      }
    }

    for (i = 0; i < lenx; ++i) {
      const npy_double x_val = dz[i];

      if (pythonic::numpy::functor::isnan()(x_val)) {
        dres[i] = x_val;
        continue;
      }

      j = binary_search_with_guess(x_val, dx, lenxp, j);
      if (j == -1) {
        dres[i] = lval;
      } else if (j == lenxp) {
        dres[i] = rval;
      } else if (j == lenxp - 1) {
        dres[i] = dy[j];
      } else if (dx[j] == x_val) {
        /* Avoid potential non-finite interpolation */
        dres[i] = dy[j];
      } else {
        const out_type<T3> slope =
            (slopes != NULL) ? slopes[j]
                             : (dy[j + 1] - dy[j]) / (dx[j + 1] - dx[j]);
        dres[i] = slope * (x_val - dx[j]) + dy[j];
      }
    }

    //        NPY_END_THREADS;
  }
}
PYTHONIC_NS_END<commit_msg>Change npy_double -> double<commit_after>//
//  From NumpySrc/numpy/core/src/multiarray/compiled_base.c

/** @brief find index of a sorted array such that arr[i] <= key < arr[i + 1].
 *
 * If an starting index guess is in-range, the array values around this
 * index are first checked.  This allows for repeated calls for well-ordered
 * keys (a very common case) to use the previous index as a very good guess.
 *
 * If the guess value is not useful, bisection of the array is used to
 * find the index.  If there is no such index, the return values are:
 *     key < arr[0] -- -1
 *     key == arr[len - 1] -- len - 1
 *     key > arr[len - 1] -- len
 * The array is assumed contiguous and sorted in ascending order.
 *
 * @param key key value.
 * @param arr contiguous sorted array to be searched.
 * @param len length of the array.
 * @param guess initial guess of index
 * @return index
 */
#include "pythonic/numpy/isnan.hpp"
#include "pythonic/utils/functor.hpp"

#define LIKELY_IN_CACHE_SIZE 8
PYTHONIC_NS_BEGIN

template <typename npy_intp, typename npy_double, class T>
static npy_intp binary_search_with_guess(const npy_double key, const T &arr,
                                         npy_intp len, npy_intp guess)
{
  npy_intp imin = 0;
  npy_intp imax = len;

  /* Handle keys outside of the arr range first */
  if (key > arr[len - 1]) {
    return len;
  } else if (key < arr[0]) {
    return -1;
  }

  /*
   * If len <= 4 use linear search.
   * From above we know key >= arr[0] when we start.
   */
  if (len <= 4) {
    npy_intp i;

    for (i = 1; i < len && key >= arr[i]; ++i)
      ;
    return i - 1;
  }

  if (guess > len - 3) {
    guess = len - 3;
  }
  if (guess < 1) {
    guess = 1;
  }

  /* check most likely values: guess - 1, guess, guess + 1 */
  if (key < arr[guess]) {
    if (key < arr[guess - 1]) {
      imax = guess - 1;
      /* last attempt to restrict search to items in cache */
      if (guess > LIKELY_IN_CACHE_SIZE &&
          key >= arr[guess - LIKELY_IN_CACHE_SIZE]) {
        imin = guess - LIKELY_IN_CACHE_SIZE;
      }
    } else {
      /* key >= arr[guess - 1] */
      return guess - 1;
    }
  } else {
    /* key >= arr[guess] */
    if (key < arr[guess + 1]) {
      return guess;
    } else {
      /* key >= arr[guess + 1] */
      if (key < arr[guess + 2]) {
        return guess + 1;
      } else {
        /* key >= arr[guess + 2] */
        imin = guess + 2;
        /* last attempt to restrict search to items in cache */
        if (guess < len - LIKELY_IN_CACHE_SIZE - 1 &&
            key < arr[guess + LIKELY_IN_CACHE_SIZE]) {
          imax = guess + LIKELY_IN_CACHE_SIZE;
        }
      }
    }
  }

  /* finally, find index by bisection */
  while (imin < imax) {
    const npy_intp imid = imin + ((imax - imin) >> 1);
    if (key >= arr[imid]) {
      imin = imid + 1;
    } else {
      imax = imid;
    }
  }
  return imin - 1;
}
//
//#undef LIKELY_IN_CACHE_SIZE
//
// NPY_NO_EXPORT PyObject *
// arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
//{
//
//    PyObject *fp, *xp, *x;
//    PyObject *left = NULL, *right = NULL;
//    PyArrayObject *afp = NULL, *axp = NULL, *ax = NULL, *af = NULL;
//    npy_intp i, lenx, lenxp;
//    double lval, rval;
//    const double *dy, *dx, *dz;
//    double *dres, *slopes = NULL;
//
//    static char *kwlist[] = {"x", "xp", "fp", "left", "right", NULL};
//
//    NPY_BEGIN_THREADS_DEF;
//
//    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OO:interp", kwlist,
//                                     &x, &xp, &fp, &left, &right)) {
//        return NULL;
//    }
//
//    afp = (PyArrayObject *)PyArray_ContiguousFromAny(fp, double, 1, 1);
//    if (afp == NULL) {
//        return NULL;
//    }
//    axp = (PyArrayObject *)PyArray_ContiguousFromAny(xp, double, 1, 1);
//    if (axp == NULL) {
//        goto fail;
//    }
//    ax = (PyArrayObject *)PyArray_ContiguousFromAny(x, double, 0, 0);
//    if (ax == NULL) {
//        goto fail;
//    }
//    lenxp = PyArray_SIZE(axp);
//    if (lenxp == 0) {
//        PyErr_SetString(PyExc_ValueError,
//                        "array of sample points is empty");
//        goto fail;
//    }
//    if (PyArray_SIZE(afp) != lenxp) {
//        PyErr_SetString(PyExc_ValueError,
//                        "fp and xp are not of the same length.");
//        goto fail;
//    }
//
//    af = (PyArrayObject *)PyArray_SimpleNew(PyArray_NDIM(ax),
//                                            PyArray_DIMS(ax), double);
//    if (af == NULL) {
//        goto fail;
//    }
//    lenx = PyArray_SIZE(ax);
//
//    dy = (const double *)PyArray_DATA(afp);
//    dx = (const double *)PyArray_DATA(axp);
//    dz = (const double *)PyArray_DATA(ax);
//    dres = (double *)PyArray_DATA(af);
//    /* Get left and right fill values. */
//    if ((left == NULL) || (left == Py_None)) {
//        lval = dy[0];
//    }
//    else {
//        lval = PyFloat_AsDouble(left);
//        if (error_converting(lval)) {
//            goto fail;
//        }
//    }
//    if ((right == NULL) || (right == Py_None)) {
//        rval = dy[lenxp - 1];
//    }
//    else {
//        rval = PyFloat_AsDouble(right);
//        if (error_converting(rval)) {
//            goto fail;
//        }
//    }

// xp->dx   fp->dy  x -> dz
// This is the output type, based on the type of T, which can be complex.
template <class T>
using out_type =
    typename std::conditional<types::is_complex<typename T::dtype>::value,
                              std::complex<double>, double>::type;

template <typename npy_intp, typename T5, class T1, class T2, class T3,
          class T4>
void do_interp(const T1 &dz, const T2 &dx, const T3 &dy, T4 &dres,
               npy_intp lenxp, npy_intp lenx, T5 lval, T5 rval)
{
  npy_intp i;
  out_type<T3> *slopes = NULL;
  std::vector<out_type<T3>> slope_vect;
  /* binary_search_with_guess needs at least a 3 item long array */
  if (lenxp == 1) {
    const double xp_val = dx[0];
    const out_type<T3> fp_val = dy[0];

    //        NPY_BEGIN_THREADS_THRESHOLDED(lenx);
    for (i = 0; i < lenx; ++i) {
      const double x_val = dz[i];
      dres[i] = (x_val < xp_val) ? lval : ((x_val > xp_val) ? rval : fp_val);
    }
    //        NPY_END_THREADS;
  } else {
    npy_intp j = 0;

    /* only pre-calculate slopes if there are relatively few of them. */
    if (lenxp <= lenx) {
      slope_vect.resize(lenxp - 1);
      slopes = slope_vect.data();
    }

    //        NPY_BEGIN_THREADS;

    if (slopes != NULL) {
      for (i = 0; i < lenxp - 1; ++i) {
        slopes[i] = (dy[i + 1] - dy[i]) / (dx[i + 1] - dx[i]);
      }
    }

    for (i = 0; i < lenx; ++i) {
      const double x_val = dz[i];

      if (pythonic::numpy::functor::isnan()(x_val)) {
        dres[i] = x_val;
        continue;
      }

      j = binary_search_with_guess(x_val, dx, lenxp, j);
      if (j == -1) {
        dres[i] = lval;
      } else if (j == lenxp) {
        dres[i] = rval;
      } else if (j == lenxp - 1) {
        dres[i] = dy[j];
      } else if (dx[j] == x_val) {
        /* Avoid potential non-finite interpolation */
        dres[i] = dy[j];
      } else {
        const out_type<T3> slope =
            (slopes != NULL) ? slopes[j]
                             : (dy[j + 1] - dy[j]) / (dx[j + 1] - dx[j]);
        dres[i] = slope * (x_val - dx[j]) + dy[j];
      }
    }

    //        NPY_END_THREADS;
  }
}
PYTHONIC_NS_END<|endoftext|>


<commit_before>//----------------------------  rtn_2.cc  ---------------------------
//    rtn_2.cc,v 1.3 2003/06/09 16:00:38 wolf Exp
//    Version:
//
//    Copyright (C) 2003, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  rtn_2.cc  ---------------------------

// rt(2) had some problems with shape functions (tested in rt_7.cc). because
// it is so simple, just run the same test for the RT-Nodal element as well

#include "../tests.h"
#include <base/quadrature_lib.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_accessor.h>
#include <grid/grid_generator.h>
#include <grid/grid_tools.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_values.h>

#include <vector>
#include <fstream>
#include <string>

#define PRECISION 2

template<int dim>
void
plot_shape_functions(const unsigned int degree)
{
  FE_RaviartThomasNodal<dim> fe_rt(degree);
  Triangulation<dim> tr;
  GridGenerator::hyper_cube(tr, 0., 1.);

  DoFHandler<dim> dof(tr);
  typename DoFHandler<dim>::cell_iterator c = dof.begin();
  dof.distribute_dofs(fe_rt);

  QTrapez<1> q_trapez;
  const unsigned int div=10;
  QIterated<dim> q(q_trapez, div);
  FEValues<dim> fe(fe_rt, q, update_values|update_gradients|update_q_points);
  fe.reinit(c);

  Assert (fe.get_fe().n_components() == dim, ExcInternalError());

  for (unsigned int q_point=0; q_point<q.n_quadrature_points; ++q_point)
    {
      if (q_point % QIterated<1>(q_trapez,div).n_quadrature_points == 0)
        deallog << std::endl;

      deallog << fe.quadrature_point(q_point) << " ";

      for (unsigned int i=0;i<fe_rt.dofs_per_cell;++i)
        for (unsigned int c=0; c<fe.get_fe().n_components(); ++c)
          deallog << " " << fe.shape_value_component(i,q_point,c);

      deallog << std::endl;
    }
}

int
main()
{
  std::ofstream logfile ("rtn_2/output");
  logfile.precision (PRECISION);
  logfile.setf(std::ios::fixed);
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  plot_shape_functions<2>(2);

  return 0;
}

<commit_msg>remove assertion<commit_after>//----------------------------  rtn_2.cc  ---------------------------
//    rtn_2.cc,v 1.3 2003/06/09 16:00:38 wolf Exp
//    Version:
//
//    Copyright (C) 2003, 2005, 2006 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  rtn_2.cc  ---------------------------

// rt(2) had some problems with shape functions (tested in rt_7.cc). because
// it is so simple, just run the same test for the RT-Nodal element as well

#include "../tests.h"
#include <base/quadrature_lib.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_accessor.h>
#include <grid/grid_generator.h>
#include <grid/grid_tools.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_values.h>

#include <vector>
#include <fstream>
#include <string>

#define PRECISION 2

template<int dim>
void
plot_shape_functions(const unsigned int degree)
{
  FE_RaviartThomasNodal<dim> fe_rt(degree);
  Triangulation<dim> tr;
  GridGenerator::hyper_cube(tr, 0., 1.);

  DoFHandler<dim> dof(tr);
  typename DoFHandler<dim>::cell_iterator c = dof.begin();
  dof.distribute_dofs(fe_rt);

  QTrapez<1> q_trapez;
  const unsigned int div=10;
  QIterated<dim> q(q_trapez, div);
  FEValues<dim> fe(fe_rt, q, update_values|update_gradients|update_q_points);
  fe.reinit(c);

  for (unsigned int q_point=0; q_point<q.n_quadrature_points; ++q_point)
    {
      if (q_point % QIterated<1>(q_trapez,div).n_quadrature_points == 0)
        deallog << std::endl;

      deallog << fe.quadrature_point(q_point) << " ";

      for (unsigned int i=0;i<fe_rt.dofs_per_cell;++i)
        for (unsigned int c=0; c<fe.get_fe().n_components(); ++c)
          deallog << " " << fe.shape_value_component(i,q_point,c);

      deallog << std::endl;
    }
}

int
main()
{
  std::ofstream logfile ("rtn_2/output");
  logfile.precision (PRECISION);
  logfile.setf(std::ios::fixed);
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  plot_shape_functions<2>(2);

  return 0;
}

<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 **/

#include "query_execution/PolicyEnforcerBase.hpp"

#include <cstddef>
#include <memory>
#include <queue>
#include <unordered_map>
#include <vector>

#include "catalog/CatalogDatabase.hpp"
#include "catalog/CatalogRelation.hpp"
#include "catalog/PartitionScheme.hpp"
#include "query_execution/QueryExecutionMessages.pb.h"
#include "query_execution/QueryExecutionState.hpp"
#include "query_execution/QueryExecutionTypedefs.hpp"
#include "query_execution/QueryManagerBase.hpp"
#include "relational_operators/WorkOrder.hpp"
#include "storage/StorageBlockInfo.hpp"

#include "gflags/gflags.h"
#include "glog/logging.h"

namespace quickstep {

DECLARE_bool(visualize_execution_dag);

DEFINE_bool(profile_and_report_workorder_perf, false,
    "If true, Quickstep will record the exceution time of all the individual "
    "normal work orders and report it at the end of query execution.");

PolicyEnforcerBase::PolicyEnforcerBase(CatalogDatabaseLite *catalog_database)
    : catalog_database_(catalog_database),
      profile_individual_workorders_(FLAGS_profile_and_report_workorder_perf || FLAGS_visualize_execution_dag) {
}

void PolicyEnforcerBase::processMessage(const TaggedMessage &tagged_message) {
  std::size_t query_id;
  QueryManagerBase::dag_node_index op_index;

  switch (tagged_message.message_type()) {
    case kWorkOrderCompleteMessage: {
      serialization::WorkOrderCompletionMessage proto;
      // Note: This proto message contains the time it took to execute the
      // WorkOrder. It can be accessed in this scope.
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));
      decrementNumQueuedWorkOrders(proto);

      if (profile_individual_workorders_) {
        recordTimeForWorkOrder(proto);
      }

      query_id = proto.query_id();
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = proto.operator_index();
      admitted_queries_[query_id]->processWorkOrderCompleteMessage(op_index);
      break;
    }
    case kRebuildWorkOrderCompleteMessage: {
      serialization::WorkOrderCompletionMessage proto;
      // Note: This proto message contains the time it took to execute the
      // rebuild WorkOrder. It can be accessed in this scope.
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));
      decrementNumQueuedWorkOrders(proto);

      query_id = proto.query_id();
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = proto.operator_index();
      admitted_queries_[query_id]->processRebuildWorkOrderCompleteMessage(op_index);
      break;
    }
    case kCatalogRelationNewBlockMessage: {
      serialization::CatalogRelationNewBlockMessage proto;
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));

      const block_id block = proto.block_id();

      CatalogRelation *relation =
          static_cast<CatalogDatabase*>(catalog_database_)->getRelationByIdMutable(proto.relation_id());
      relation->addBlock(block);

      if (proto.has_partition_id()) {
        relation->getPartitionSchemeMutable()->addBlockToPartition(block, proto.partition_id());
      }
      return;
    }
    case kDataPipelineMessage: {
      serialization::DataPipelineMessage proto;
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));
      query_id = proto.query_id();
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = proto.operator_index();
      admitted_queries_[query_id]->processDataPipelineMessage(
          op_index, proto.block_id(), proto.relation_id(), proto.partition_id());
      break;
    }
    case kWorkOrderFeedbackMessage: {
      WorkOrder::FeedbackMessage msg(
          const_cast<void *>(tagged_message.message()),
          tagged_message.message_bytes());
      query_id = msg.header().query_id;
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = msg.header().rel_op_index;
      admitted_queries_[query_id]->processFeedbackMessage(op_index, msg);
      break;
    }
    default:
      LOG(FATAL) << "Unknown message type found in PolicyEnforcer";
  }
  if (admitted_queries_[query_id]->queryStatus(op_index) ==
          QueryManagerBase::QueryStatusCode::kQueryExecuted) {
    onQueryCompletion(admitted_queries_[query_id].get());

    removeQuery(query_id);
    if (!waiting_queries_.empty()) {
      // Admit the earliest waiting query.
      QueryHandle *new_query = waiting_queries_.front();
      waiting_queries_.pop();
      admitQuery(new_query);
    }
  }
}

void PolicyEnforcerBase::removeQuery(const std::size_t query_id) {
  DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());
  if (!admitted_queries_[query_id]->getQueryExecutionState().hasQueryExecutionFinished()) {
    LOG(WARNING) << "Removing query with ID " << query_id
                 << " that hasn't finished its execution";
  }
  admitted_queries_.erase(query_id);
}

bool PolicyEnforcerBase::admitQueries(
    const std::vector<QueryHandle*> &query_handles) {
  for (QueryHandle *curr_query : query_handles) {
    if (!admitQuery(curr_query)) {
      return false;
    }
  }
  return true;
}

void PolicyEnforcerBase::recordTimeForWorkOrder(
    const serialization::WorkOrderCompletionMessage &proto) {
  const std::size_t query_id = proto.query_id();
  std::vector<WorkOrderTimeEntry> &workorder_time_entries
      = workorder_time_recorder_[query_id];
  workorder_time_entries.emplace_back();
  WorkOrderTimeEntry &entry = workorder_time_entries.back();
  entry.worker_id = proto.worker_thread_index(),
  entry.operator_id = proto.operator_index(),
  entry.start_time = proto.execution_start_time(),
  entry.end_time = proto.execution_end_time();
}

}  // namespace quickstep
<commit_msg>Fixed the admitQueries bug.<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 **/

#include "query_execution/PolicyEnforcerBase.hpp"

#include <cstddef>
#include <memory>
#include <queue>
#include <unordered_map>
#include <vector>

#include "catalog/CatalogDatabase.hpp"
#include "catalog/CatalogRelation.hpp"
#include "catalog/PartitionScheme.hpp"
#include "query_execution/QueryExecutionMessages.pb.h"
#include "query_execution/QueryExecutionState.hpp"
#include "query_execution/QueryExecutionTypedefs.hpp"
#include "query_execution/QueryManagerBase.hpp"
#include "relational_operators/WorkOrder.hpp"
#include "storage/StorageBlockInfo.hpp"

#include "gflags/gflags.h"
#include "glog/logging.h"

namespace quickstep {

DECLARE_bool(visualize_execution_dag);

DEFINE_bool(profile_and_report_workorder_perf, false,
    "If true, Quickstep will record the exceution time of all the individual "
    "normal work orders and report it at the end of query execution.");

PolicyEnforcerBase::PolicyEnforcerBase(CatalogDatabaseLite *catalog_database)
    : catalog_database_(catalog_database),
      profile_individual_workorders_(FLAGS_profile_and_report_workorder_perf || FLAGS_visualize_execution_dag) {
}

void PolicyEnforcerBase::processMessage(const TaggedMessage &tagged_message) {
  std::size_t query_id;
  QueryManagerBase::dag_node_index op_index;

  switch (tagged_message.message_type()) {
    case kWorkOrderCompleteMessage: {
      serialization::WorkOrderCompletionMessage proto;
      // Note: This proto message contains the time it took to execute the
      // WorkOrder. It can be accessed in this scope.
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));
      decrementNumQueuedWorkOrders(proto);

      if (profile_individual_workorders_) {
        recordTimeForWorkOrder(proto);
      }

      query_id = proto.query_id();
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = proto.operator_index();
      admitted_queries_[query_id]->processWorkOrderCompleteMessage(op_index);
      break;
    }
    case kRebuildWorkOrderCompleteMessage: {
      serialization::WorkOrderCompletionMessage proto;
      // Note: This proto message contains the time it took to execute the
      // rebuild WorkOrder. It can be accessed in this scope.
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));
      decrementNumQueuedWorkOrders(proto);

      query_id = proto.query_id();
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = proto.operator_index();
      admitted_queries_[query_id]->processRebuildWorkOrderCompleteMessage(op_index);
      break;
    }
    case kCatalogRelationNewBlockMessage: {
      serialization::CatalogRelationNewBlockMessage proto;
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));

      const block_id block = proto.block_id();

      CatalogRelation *relation =
          static_cast<CatalogDatabase*>(catalog_database_)->getRelationByIdMutable(proto.relation_id());
      relation->addBlock(block);

      if (proto.has_partition_id()) {
        relation->getPartitionSchemeMutable()->addBlockToPartition(block, proto.partition_id());
      }
      return;
    }
    case kDataPipelineMessage: {
      serialization::DataPipelineMessage proto;
      CHECK(proto.ParseFromArray(tagged_message.message(),
                                 tagged_message.message_bytes()));
      query_id = proto.query_id();
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = proto.operator_index();
      admitted_queries_[query_id]->processDataPipelineMessage(
          op_index, proto.block_id(), proto.relation_id(), proto.partition_id());
      break;
    }
    case kWorkOrderFeedbackMessage: {
      WorkOrder::FeedbackMessage msg(
          const_cast<void *>(tagged_message.message()),
          tagged_message.message_bytes());
      query_id = msg.header().query_id;
      DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());

      op_index = msg.header().rel_op_index;
      admitted_queries_[query_id]->processFeedbackMessage(op_index, msg);
      break;
    }
    default:
      LOG(FATAL) << "Unknown message type found in PolicyEnforcer";
  }
  if (admitted_queries_[query_id]->queryStatus(op_index) ==
          QueryManagerBase::QueryStatusCode::kQueryExecuted) {
    onQueryCompletion(admitted_queries_[query_id].get());

    removeQuery(query_id);
    if (!waiting_queries_.empty()) {
      // Admit the earliest waiting query.
      QueryHandle *new_query = waiting_queries_.front();
      waiting_queries_.pop();
      admitQuery(new_query);
    }
  }
}

void PolicyEnforcerBase::removeQuery(const std::size_t query_id) {
  DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end());
  if (!admitted_queries_[query_id]->getQueryExecutionState().hasQueryExecutionFinished()) {
    LOG(WARNING) << "Removing query with ID " << query_id
                 << " that hasn't finished its execution";
  }
  admitted_queries_.erase(query_id);
}

bool PolicyEnforcerBase::admitQueries(
    const std::vector<QueryHandle*> &query_handles) {
  bool all_queries_admitted = true;
  for (QueryHandle *curr_query : query_handles) {
    if (all_queries_admitted) {
      all_queries_admitted = admitQuery(curr_query);
    } else {
      waiting_queries_.push(curr_query);
    }
  }
  return all_queries_admitted;
}

void PolicyEnforcerBase::recordTimeForWorkOrder(
    const serialization::WorkOrderCompletionMessage &proto) {
  const std::size_t query_id = proto.query_id();
  std::vector<WorkOrderTimeEntry> &workorder_time_entries
      = workorder_time_recorder_[query_id];
  workorder_time_entries.emplace_back();
  WorkOrderTimeEntry &entry = workorder_time_entries.back();
  entry.worker_id = proto.worker_thread_index(),
  entry.operator_id = proto.operator_index(),
  entry.start_time = proto.execution_start_time(),
  entry.end_time = proto.execution_end_time();
}

}  // namespace quickstep
<|endoftext|>


<commit_before>/*
** -*- coding: utf-8 -*-
**
** File: document_object.cpp
** by Arzaroth Lekva
** arzaroth@arzaroth.com
**
*/

#include <Python.h>
#include <structmember.h>
#include <rapidxml.hpp>
#include <vector>
#include <fstream>
#include <streambuf>
#include <cstring>
#include <cerrno>

#include <common.h>

static void rapidxml_DocumentObject_dealloc(rapidxml_DocumentObject* self) {
  delete self->base.base.document;
  Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}

static int _parse(rapidxml_DocumentObject* self,
                  Py_buffer* text_buff,
                  bool from_file, bool parse_cdata=false) {
  const char* text;
  std::vector<char> text_vector;

  text = static_cast<const char*>(text_buff->buf);
  if (from_file) {
    std::ifstream f(text, std::ios::binary);
    if (f.fail()) {
      PyErr_SetString(rapidxml_RapidXmlError, strerror(errno));
      return 0;
    }
    text_vector = std::vector<char>((std::istreambuf_iterator<char>(f)),
                                    std::istreambuf_iterator<char>());
    text_vector.push_back(0);
    text = &text_vector[0];
  }
  try {
    self->base.base.document->clear();
	if (parse_cdata){
		(self->base.base.document
			->parse<rapidxml::parse_no_utf8 | rapidxml::parse_no_data_nodes>)
				(self->base.base.document->allocate_string(text));

	}else{
		(self->base.base.document
			->parse<rapidxml::parse_declaration_node>)
				(self->base.base.document->allocate_string(text));
	}

  } catch (rapidxml::parse_error &e) {
    PyErr_SetString(rapidxml_RapidXmlError, e.what());
    return 0;
  }
  return 1;
}

static PyObject* rapidxml_DocumentObject_parse(rapidxml_DocumentObject* self,
                                               PyObject* args,
                                               PyObject* kwds) {
  Py_buffer text_buff;
  PyObject* from_file_obj = NULL;
  bool read_cdata = false
  char kw_text[] = "text";
  char kw_from_file[] = "from_file";
  char kw_parse_cdata[] = "parse_cdata";

  static char* kwlist[] = {kw_text, kw_from_file, kw_parse_cdata, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|Op", kwlist,
                                   &text_buff, &from_file_obj, &read_cdata)) {
    return NULL;
  }

  if (!_parse(self, &text_buff,
              (from_file_obj != NULL) && PyObject_IsTrue(from_file_obj), read_cdata)) {
    return NULL;
  }
  Py_INCREF(Py_None);
  return Py_None;
}

static int rapidxml_DocumentObject_init(rapidxml_DocumentObject* self,
                                        PyObject* args,
                                        PyObject* kwds) {
  Py_buffer text_buff = {0};
  PyObject* from_file_obj = NULL;
  char kw_text[] = "text";
  char kw_from_file[] = "from_file";
  char kw_parse_cdata[] = "parse_cdata";

  if (rapidxml_NodeType.tp_init(reinterpret_cast<PyObject*>(self), args, kwds) < 0) {
    return -1;
  }
  static char* kwlist[] = {kw_text, kw_from_file, kw_parse_cdata, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s*Op", kwlist,
                                   &text_buff, &from_file_obj, &read_cdata)) {
    return -1;
  }
  self->base.base.underlying_obj = new rapidxml::xml_document<>();
  self->base.base.document = static_cast<rapidxml::xml_document<>*>(self->base.base.underlying_obj);
  if (text_buff.buf) {
    return _parse(self, &text_buff, (from_file_obj != NULL) && PyObject_IsTrue(from_file_obj), read_cdata) - 1;
  }
  return 0;
}

static PyObject* rapidxml_DocumentObject_allocate_node(rapidxml_DocumentObject* self,
                                                       PyObject* args,
                                                       PyObject* kwds) {
  const char* name;
  Py_buffer name_buff = {0};
  const char* value;
  Py_buffer value_buff = {0};
  char kw_name[] = "name";
  char kw_value[] = "value";
  rapidxml::xml_node<>* node;

  static char* kwlist[] = {kw_name, kw_value, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s*s*", kwlist,
                                   &name_buff, &value_buff)) {
    Py_INCREF(Py_None);
    return Py_None;
  }
  name = static_cast<const char*>(name_buff.buf);
  if (name) {
    name = self->base.base.document->allocate_string(name);
  }
  value = static_cast<const char*>(value_buff.buf);
  if (value) {
    value = self->base.base.document->allocate_string(value);
  }
  node = self->base.base.document->allocate_node(rapidxml::node_element, name, value);
  return _bind_result(reinterpret_cast<rapidxml_BaseObject*>(self),
                      node, &rapidxml_NodeType);
}
#include <iostream>
static PyObject* rapidxml_DocumentObject_allocate_attribute(rapidxml_DocumentObject* self,
                                                            PyObject* args,
                                                            PyObject* kwds) {
  const char* name;
  Py_buffer name_buff = {0};
  const char* value;
  Py_buffer value_buff = {0};
  char kw_name[] = "name";
  char kw_value[] = "value";
  rapidxml::xml_attribute<>* attribute;

  static char* kwlist[] = {kw_name, kw_value, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s*s*", kwlist,
                                   &name_buff, &value_buff)) {
    Py_INCREF(Py_None);
    return Py_None;
  }
  name = static_cast<const char*>(name_buff.buf);
  if (name) {
    name = self->base.base.document->allocate_string(name);
  }
  value = static_cast<const char*>(value_buff.buf);
  if (value) {
    value = self->base.base.document->allocate_string(value);
  }
  attribute = self->base.base.document->allocate_attribute(name, value);
  return _bind_result(reinterpret_cast<rapidxml_BaseObject*>(self),
                      attribute, &rapidxml_AttributeType);
}

static PyMemberDef rapidxml_DocumentObject_members[] = {
  {NULL}
};

static PyMethodDef rapidxml_DocumentObject_methods[] = {
  {"parse", reinterpret_cast<PyCFunction>(rapidxml_DocumentObject_parse),
   METH_VARARGS | METH_KEYWORDS, "parse given xml string, optionally from a file a from_file argument is True"},
  {"allocate_node", reinterpret_cast<PyCFunction>(rapidxml_DocumentObject_allocate_node),
   METH_VARARGS | METH_KEYWORDS, "allocates a new node from the pool, and optionally assigns name and value to it"},
  {"allocate_attribute", reinterpret_cast<PyCFunction>(rapidxml_DocumentObject_allocate_attribute),
   METH_VARARGS | METH_KEYWORDS, "allocates a new attribute from the pool, and optionally assigns name and value to it"},
  {NULL}
};

PyTypeObject rapidxml_DocumentType = {
  PyVarObject_HEAD_INIT(NULL, 0)
  "rapidxml.c_ext.Document",       /* tp_name */
  sizeof(rapidxml_DocumentObject), /* tp_basicsize */
  0,                               /* tp_itemsize */
  reinterpret_cast<destructor>(rapidxml_DocumentObject_dealloc), /* tp_dealloc */
  0,                               /* tp_print */
  0,                               /* tp_getattr */
  0,                               /* tp_setattr */
  0,                               /* tp_reserved */
  0,                               /* tp_repr */
  0,                               /* tp_as_number */
  0,                               /* tp_as_sequence */
  0,                               /* tp_as_mapping */
  0,                               /* tp_hash  */
  0,                               /* tp_call */
  0,                               /* tp_str */
  0,                               /* tp_getattro */
  0,                               /* tp_setattro */
  0,                               /* tp_as_buffer */
  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  "class representing a rapidxml::xml_document", /* tp_doc */
  0,                               /* tp_traverse */
  0,                               /* tp_clear */
  0,                               /* tp_richcompare */
  0,                               /* tp_weaklistoffset */
  0,                               /* tp_iter */
  0,                               /* tp_iternext */
  rapidxml_DocumentObject_methods, /* tp_methods */
  rapidxml_DocumentObject_members, /* tp_members */
  0,                               /* tp_getset */
  0,                               /* tp_base */
  0,                               /* tp_dict */
  0,                               /* tp_descr_get */
  0,                               /* tp_descr_set */
  0,                               /* tp_dictoffset */
  reinterpret_cast<initproc>(rapidxml_DocumentObject_init), /* tp_init */
  0,                               /* tp_alloc */
  0,                               /* tp_new */
  0,                               /* tp_free */
  0,                               /* tp_is_gc */
  0,                               /* tp_bases */
  0,                               /* tp_mro */
  0,                               /* tp_cache */
  0,                               /* tp_subclasses */
  0,                               /* tp_weaklist */
};
<commit_msg>cdata decodoing<commit_after>/*
** -*- coding: utf-8 -*-
**
** File: document_object.cpp
** by Arzaroth Lekva
** arzaroth@arzaroth.com
**
*/

#include <Python.h>
#include <structmember.h>
#include <rapidxml.hpp>
#include <vector>
#include <fstream>
#include <streambuf>
#include <cstring>
#include <cerrno>

#include <common.h>

static void rapidxml_DocumentObject_dealloc(rapidxml_DocumentObject* self) {
  delete self->base.base.document;
  Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}

static int _parse(rapidxml_DocumentObject* self,
                  Py_buffer* text_buff,
                  bool from_file, bool parse_cdata=false) {
  const char* text;
  std::vector<char> text_vector;

  text = static_cast<const char*>(text_buff->buf);
  if (from_file) {
    std::ifstream f(text, std::ios::binary);
    if (f.fail()) {
      PyErr_SetString(rapidxml_RapidXmlError, strerror(errno));
      return 0;
    }
    text_vector = std::vector<char>((std::istreambuf_iterator<char>(f)),
                                    std::istreambuf_iterator<char>());
    text_vector.push_back(0);
    text = &text_vector[0];
  }
  try {
    self->base.base.document->clear();
	if (parse_cdata){
		(self->base.base.document
			->parse<rapidxml::parse_no_utf8 | rapidxml::parse_no_data_nodes>)
				(self->base.base.document->allocate_string(text));

	}else{
		(self->base.base.document
			->parse<rapidxml::parse_declaration_node>)
				(self->base.base.document->allocate_string(text));
	}

  } catch (rapidxml::parse_error &e) {
    PyErr_SetString(rapidxml_RapidXmlError, e.what());
    return 0;
  }
  return 1;
}

static PyObject* rapidxml_DocumentObject_parse(rapidxml_DocumentObject* self,
                                               PyObject* args,
                                               PyObject* kwds) {
  Py_buffer text_buff;
  PyObject* from_file_obj = NULL;
  bool read_cdata = false
  char kw_text[] = "text";
  char kw_from_file[] = "from_file";
  char kw_parse_cdata[] = "parse_cdata";

  static char* kwlist[] = {kw_text, kw_from_file, kw_parse_cdata, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|Op", kwlist,
                                   &text_buff, &from_file_obj, &read_cdata)) {
    return NULL;
  }

  if (!_parse(self, &text_buff,
              (from_file_obj != NULL) && PyObject_IsTrue(from_file_obj), read_cdata)) {
    return NULL;
  }
  Py_INCREF(Py_None);
  return Py_None;
}

static int rapidxml_DocumentObject_init(rapidxml_DocumentObject* self,
                                        PyObject* args,
                                        PyObject* kwds) {
  Py_buffer text_buff = {0};
  PyObject* from_file_obj = NULL;
  bool read_cdata = false
  char kw_text[] = "text";
  char kw_from_file[] = "from_file";
  char kw_parse_cdata[] = "parse_cdata";

  if (rapidxml_NodeType.tp_init(reinterpret_cast<PyObject*>(self), args, kwds) < 0) {
    return -1;
  }
  static char* kwlist[] = {kw_text, kw_from_file, kw_parse_cdata, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s*Op", kwlist,
                                   &text_buff, &from_file_obj, &read_cdata)) {
    return -1;
  }
  self->base.base.underlying_obj = new rapidxml::xml_document<>();
  self->base.base.document = static_cast<rapidxml::xml_document<>*>(self->base.base.underlying_obj);
  if (text_buff.buf) {
    return _parse(self, &text_buff, (from_file_obj != NULL) && PyObject_IsTrue(from_file_obj), read_cdata) - 1;
  }
  return 0;
}

static PyObject* rapidxml_DocumentObject_allocate_node(rapidxml_DocumentObject* self,
                                                       PyObject* args,
                                                       PyObject* kwds) {
  const char* name;
  Py_buffer name_buff = {0};
  const char* value;
  Py_buffer value_buff = {0};
  char kw_name[] = "name";
  char kw_value[] = "value";
  rapidxml::xml_node<>* node;

  static char* kwlist[] = {kw_name, kw_value, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s*s*", kwlist,
                                   &name_buff, &value_buff)) {
    Py_INCREF(Py_None);
    return Py_None;
  }
  name = static_cast<const char*>(name_buff.buf);
  if (name) {
    name = self->base.base.document->allocate_string(name);
  }
  value = static_cast<const char*>(value_buff.buf);
  if (value) {
    value = self->base.base.document->allocate_string(value);
  }
  node = self->base.base.document->allocate_node(rapidxml::node_element, name, value);
  return _bind_result(reinterpret_cast<rapidxml_BaseObject*>(self),
                      node, &rapidxml_NodeType);
}
#include <iostream>
static PyObject* rapidxml_DocumentObject_allocate_attribute(rapidxml_DocumentObject* self,
                                                            PyObject* args,
                                                            PyObject* kwds) {
  const char* name;
  Py_buffer name_buff = {0};
  const char* value;
  Py_buffer value_buff = {0};
  char kw_name[] = "name";
  char kw_value[] = "value";
  rapidxml::xml_attribute<>* attribute;

  static char* kwlist[] = {kw_name, kw_value, NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s*s*", kwlist,
                                   &name_buff, &value_buff)) {
    Py_INCREF(Py_None);
    return Py_None;
  }
  name = static_cast<const char*>(name_buff.buf);
  if (name) {
    name = self->base.base.document->allocate_string(name);
  }
  value = static_cast<const char*>(value_buff.buf);
  if (value) {
    value = self->base.base.document->allocate_string(value);
  }
  attribute = self->base.base.document->allocate_attribute(name, value);
  return _bind_result(reinterpret_cast<rapidxml_BaseObject*>(self),
                      attribute, &rapidxml_AttributeType);
}

static PyMemberDef rapidxml_DocumentObject_members[] = {
  {NULL}
};

static PyMethodDef rapidxml_DocumentObject_methods[] = {
  {"parse", reinterpret_cast<PyCFunction>(rapidxml_DocumentObject_parse),
   METH_VARARGS | METH_KEYWORDS, "parse given xml string, optionally from a file a from_file argument is True"},
  {"allocate_node", reinterpret_cast<PyCFunction>(rapidxml_DocumentObject_allocate_node),
   METH_VARARGS | METH_KEYWORDS, "allocates a new node from the pool, and optionally assigns name and value to it"},
  {"allocate_attribute", reinterpret_cast<PyCFunction>(rapidxml_DocumentObject_allocate_attribute),
   METH_VARARGS | METH_KEYWORDS, "allocates a new attribute from the pool, and optionally assigns name and value to it"},
  {NULL}
};

PyTypeObject rapidxml_DocumentType = {
  PyVarObject_HEAD_INIT(NULL, 0)
  "rapidxml.c_ext.Document",       /* tp_name */
  sizeof(rapidxml_DocumentObject), /* tp_basicsize */
  0,                               /* tp_itemsize */
  reinterpret_cast<destructor>(rapidxml_DocumentObject_dealloc), /* tp_dealloc */
  0,                               /* tp_print */
  0,                               /* tp_getattr */
  0,                               /* tp_setattr */
  0,                               /* tp_reserved */
  0,                               /* tp_repr */
  0,                               /* tp_as_number */
  0,                               /* tp_as_sequence */
  0,                               /* tp_as_mapping */
  0,                               /* tp_hash  */
  0,                               /* tp_call */
  0,                               /* tp_str */
  0,                               /* tp_getattro */
  0,                               /* tp_setattro */
  0,                               /* tp_as_buffer */
  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  "class representing a rapidxml::xml_document", /* tp_doc */
  0,                               /* tp_traverse */
  0,                               /* tp_clear */
  0,                               /* tp_richcompare */
  0,                               /* tp_weaklistoffset */
  0,                               /* tp_iter */
  0,                               /* tp_iternext */
  rapidxml_DocumentObject_methods, /* tp_methods */
  rapidxml_DocumentObject_members, /* tp_members */
  0,                               /* tp_getset */
  0,                               /* tp_base */
  0,                               /* tp_dict */
  0,                               /* tp_descr_get */
  0,                               /* tp_descr_set */
  0,                               /* tp_dictoffset */
  reinterpret_cast<initproc>(rapidxml_DocumentObject_init), /* tp_init */
  0,                               /* tp_alloc */
  0,                               /* tp_new */
  0,                               /* tp_free */
  0,                               /* tp_is_gc */
  0,                               /* tp_bases */
  0,                               /* tp_mro */
  0,                               /* tp_cache */
  0,                               /* tp_subclasses */
  0,                               /* tp_weaklist */
};
<|endoftext|>