<commit_before>/*
 * File:   PolynomialCircuit.cpp
 * Author: ph4r05
 *
 * Created on April 29, 2014, 4:20 PM
 */

#include "PolynomialCircuit.h"
#include "circuit/ICircuit.h"
#include "PolynomialCircuitIO.h"
#include "GAPolyCallbacks.h"
#include "Term.h"
#include <cmath>
#include "XMLProcessor.h"

PolynomialCircuit::PolynomialCircuit() : ICircuit(CIRCUIT_POLYNOMIAL) { }

PolynomialCircuit::~PolynomialCircuit() { }

string PolynomialCircuit::shortDescription() {
    return "polynomial functions in ANF";
}

GAGenome* PolynomialCircuit::createGenome(bool setCallbacks) {
    // Has to compute genome dimensions.
    int numVariables = PolynomialCircuit::getNumVariables();
    int numPolynomials = PolynomialCircuit::getNumPolynomials();
    // Length of one term in terms of POLY_GENOME_ITEM_TYPE.
    unsigned int termSize = Term::getTermSize(numVariables);

    GA2DArrayGenome<POLY_GENOME_ITEM_TYPE>* g = new GA2DArrayGenome<POLY_GENOME_ITEM_TYPE>(
            numPolynomials,
            // 1 (number of terms) + term size * max number of terms
            1 + termSize * pGlobals->settings->polyCircuit.maxNumTerms,
            this->getEvaluator());
    if (setCallbacks){
        setGACallbacks(g);
    }
    return g;
}

GAPopulation* PolynomialCircuit::createPopulation() {
    GAGenome* g = createGenome(true);
    GAPopulation* population = new GAPopulation(*g, pGlobals->settings->ga.popupationSize);
    delete g;
    return population;
}

bool PolynomialCircuit::postProcess(GAGenome& originalGenome, GAGenome& prunnedGenome) {
    return false;
}

int PolynomialCircuit::loadCircuitConfiguration(TiXmlNode* pRoot) {
    // parsing EACIRC/POLYNOMIAL_CIRCUIT
    pGlobals->settings->polyCircuit.numPolynomials                 = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/NUM_POLYNOMIALS").c_str());
    pGlobals->settings->polyCircuit.maxNumTerms                    = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/MAX_NUM_TERMS").c_str());
    pGlobals->settings->polyCircuit.mutateTermStrategy             = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/MUTATE_TERM_STRATEGY").c_str());
    pGlobals->settings->polyCircuit.genomeInitTermCountProbability = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/TERM_COUNT_PROB").c_str());
    pGlobals->settings->polyCircuit.genomeInitTermStopProbability  = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/TERM_VAR_PROB").c_str());
    pGlobals->settings->polyCircuit.mutateAddTermProbability       = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/ADD_TERM_PROB").c_str());
    pGlobals->settings->polyCircuit.mutateAddTermStrategy          = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/ADD_TERM_STRATEGY").c_str());
    pGlobals->settings->polyCircuit.mutateRemoveTermProbability    = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/RM_TERM_PROB").c_str());
    pGlobals->settings->polyCircuit.mutateRemoveTermStrategy       = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/RM_TERM_STRATEGY").c_str());
    pGlobals->settings->polyCircuit.crossoverRandomizePolySelect   = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/CROSSOVER_RANDOMIZE_POLY").c_str()) ? true : false;
    pGlobals->settings->polyCircuit.crossoverTermsProbability      = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/CROSSOVER_TERM_PROB").c_str());

    // Sanity checks
    if (pGlobals->settings->polyCircuit.numPolynomials <= 0
            || pGlobals->settings->polyCircuit.numPolynomials > pGlobals->settings->main.circuitSizeOutput*BITS_IN_UCHAR){
        mainLogger.out(LOGGER_ERROR) << "Number of polynomials not set properly." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.genomeInitTermCountProbability < 0 || pGlobals->settings->polyCircuit.genomeInitTermCountProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Genome initialization term count probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.genomeInitTermStopProbability < 0 || pGlobals->settings->polyCircuit.genomeInitTermStopProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Genome initialization term stop probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.mutateAddTermProbability < 0 || pGlobals->settings->polyCircuit.mutateAddTermProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Mutate add term probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.mutateRemoveTermProbability < 0 || pGlobals->settings->polyCircuit.mutateRemoveTermProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Mutate remove term probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.crossoverTermsProbability < 0 || pGlobals->settings->polyCircuit.crossoverTermsProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Crossover terms probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->ga.replacementSize % 2 == 1) {
        mainLogger.out(LOGGER_ERROR) << "GA/REPLACEMENT_SIZE is odd, polynomials have to use even size of replacement population." << endl;
        return STAT_CONFIG_INCORRECT;
    }

    return STAT_OK;
}
<commit_msg>Added sanity check for polynomials count<commit_after>/*
 * File:   PolynomialCircuit.cpp
 * Author: ph4r05
 *
 * Created on April 29, 2014, 4:20 PM
 */

#include "PolynomialCircuit.h"
#include "circuit/ICircuit.h"
#include "PolynomialCircuitIO.h"
#include "GAPolyCallbacks.h"
#include "Term.h"
#include <cmath>
#include "XMLProcessor.h"

PolynomialCircuit::PolynomialCircuit() : ICircuit(CIRCUIT_POLYNOMIAL) { }

PolynomialCircuit::~PolynomialCircuit() { }

string PolynomialCircuit::shortDescription() {
    return "polynomial functions in ANF";
}

GAGenome* PolynomialCircuit::createGenome(bool setCallbacks) {
    // Has to compute genome dimensions.
    int numVariables = PolynomialCircuit::getNumVariables();
    int numPolynomials = PolynomialCircuit::getNumPolynomials();
    // Length of one term in terms of POLY_GENOME_ITEM_TYPE.
    unsigned int termSize = Term::getTermSize(numVariables);

    GA2DArrayGenome<POLY_GENOME_ITEM_TYPE>* g = new GA2DArrayGenome<POLY_GENOME_ITEM_TYPE>(
            numPolynomials,
            // 1 (number of terms) + term size * max number of terms
            1 + termSize * pGlobals->settings->polyCircuit.maxNumTerms,
            this->getEvaluator());
    if (setCallbacks){
        setGACallbacks(g);
    }
    return g;
}

GAPopulation* PolynomialCircuit::createPopulation() {
    GAGenome* g = createGenome(true);
    GAPopulation* population = new GAPopulation(*g, pGlobals->settings->ga.popupationSize);
    delete g;
    return population;
}

bool PolynomialCircuit::postProcess(GAGenome& originalGenome, GAGenome& prunnedGenome) {
    return false;
}

int PolynomialCircuit::loadCircuitConfiguration(TiXmlNode* pRoot) {
    // parsing EACIRC/POLYNOMIAL_CIRCUIT
    pGlobals->settings->polyCircuit.numPolynomials                 = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/NUM_POLYNOMIALS").c_str());
    pGlobals->settings->polyCircuit.maxNumTerms                    = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/MAX_NUM_TERMS").c_str());
    pGlobals->settings->polyCircuit.mutateTermStrategy             = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/MUTATE_TERM_STRATEGY").c_str());
    pGlobals->settings->polyCircuit.genomeInitTermCountProbability = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/TERM_COUNT_PROB").c_str());
    pGlobals->settings->polyCircuit.genomeInitTermStopProbability  = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/TERM_VAR_PROB").c_str());
    pGlobals->settings->polyCircuit.mutateAddTermProbability       = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/ADD_TERM_PROB").c_str());
    pGlobals->settings->polyCircuit.mutateAddTermStrategy          = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/ADD_TERM_STRATEGY").c_str());
    pGlobals->settings->polyCircuit.mutateRemoveTermProbability    = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/RM_TERM_PROB").c_str());
    pGlobals->settings->polyCircuit.mutateRemoveTermStrategy       = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/RM_TERM_STRATEGY").c_str());
    pGlobals->settings->polyCircuit.crossoverRandomizePolySelect   = atoi(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/CROSSOVER_RANDOMIZE_POLY").c_str()) ? true : false;
    pGlobals->settings->polyCircuit.crossoverTermsProbability      = atof(getXMLElementValue(pRoot,"POLYNOMIAL_CIRCUIT/CROSSOVER_TERM_PROB").c_str());

    // Sanity checks
    if (pGlobals->settings->polyCircuit.numPolynomials <= 0
            || pGlobals->settings->polyCircuit.numPolynomials > pGlobals->settings->main.circuitSizeOutput*BITS_IN_UCHAR) {
        mainLogger.out(LOGGER_ERROR) << "Number of polynomials <= 0 or > 8 * MAIN/CIRCUIT_SIZE_OUTPUT." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->main.evaluatorType != 25
            && pGlobals->settings->polyCircuit.numPolynomials != pGlobals->settings->main.circuitSizeOutput*BITS_IN_UCHAR) {
        mainLogger.out(LOGGER_ERROR) << "Number of polynomials is not 8 * MAIN/CIRCUIT_SIZE_OUTPUT (using evaluator 26 with this polynomials count causes undefined behaviour)." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.genomeInitTermCountProbability < 0 || pGlobals->settings->polyCircuit.genomeInitTermCountProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Genome initialization term count probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.genomeInitTermStopProbability < 0 || pGlobals->settings->polyCircuit.genomeInitTermStopProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Genome initialization term stop probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.mutateAddTermProbability < 0 || pGlobals->settings->polyCircuit.mutateAddTermProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Mutate add term probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.mutateRemoveTermProbability < 0 || pGlobals->settings->polyCircuit.mutateRemoveTermProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Mutate remove term probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->polyCircuit.crossoverTermsProbability < 0 || pGlobals->settings->polyCircuit.crossoverTermsProbability > 1) {
        mainLogger.out(LOGGER_ERROR) << "Crossover terms probability is out of bounds." << endl;
        return STAT_CONFIG_INCORRECT;
    }
    if (pGlobals->settings->ga.replacementSize % 2 == 1) {
        mainLogger.out(LOGGER_ERROR) << "GA/REPLACEMENT_SIZE is odd, polynomials have to use even size of replacement population." << endl;
        return STAT_CONFIG_INCORRECT;
    }

    return STAT_OK;
}
<|endoftext|>


<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "SampleSlide.h"

#include "SkCanvas.h"
#include "SkCommonFlags.h"
#include "SkKey.h"
#include "SkOSFile.h"
#include "SkStream.h"

using namespace sk_app;

SampleSlide::SampleSlide(const SkViewFactory* factory)
    : fViewFactory(factory)
    , fClick(nullptr) {
    SkView* view = (*factory)();
    SampleCode::RequestTitle(view, &fName);
    view->unref();
}

SampleSlide::~SampleSlide() { delete fClick; }

void SampleSlide::draw(SkCanvas* canvas) {
    SkASSERT(fView);
    fView->draw(canvas);
}

void SampleSlide::load(SkScalar winWidth, SkScalar winHeight) {
    fView.reset((*fViewFactory)());
    fView->setVisibleP(true);
    fView->setClipToBounds(false);
    fView->setSize(winWidth, winHeight);
}

void SampleSlide::unload() {
    fView.reset();
}

bool SampleSlide::onChar(SkUnichar c) {
    if (!fView) {
        return false;
    }
    SkEvent evt(gCharEvtName);
    evt.setFast32(c);
    return fView->doQuery(&evt);
}

bool SampleSlide::onMouse(SkScalar x, SkScalar y, Window::InputState state,
                          uint32_t modifiers) {
    // map to SkView modifiers
    unsigned modifierKeys = 0;
    modifierKeys |= (state & Window::kShift_ModifierKey) ? kShift_SkModifierKey : 0;
    modifierKeys |= (state & Window::kControl_ModifierKey) ? kControl_SkModifierKey : 0;
    modifierKeys |= (state & Window::kOption_ModifierKey) ? kOption_SkModifierKey : 0;
    modifierKeys |= (state & Window::kCommand_ModifierKey) ? kCommand_SkModifierKey : 0;

    bool handled = false;
    switch (state) {
        case Window::kDown_InputState: {
            delete fClick;
            fClick = fView->findClickHandler(SkIntToScalar(x), SkIntToScalar(y), modifierKeys);
            if (fClick) {
                SkView::DoClickDown(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kMove_InputState: {
            if (fClick) {
                SkView::DoClickMoved(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kUp_InputState: {
            if (fClick) {
                SkView::DoClickUp(fClick, x, y, modifierKeys);
                delete fClick;
                fClick = nullptr;
                handled = true;
            }
            break;
        }
    }

    return handled;
}
<commit_msg>Roll external/skia c6f7a4ffa..6f3eac9b5 (1 commits)<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "SampleSlide.h"

#include "SkCanvas.h"
#include "SkCommonFlags.h"
#include "SkKey.h"
#include "SkOSFile.h"
#include "SkStream.h"

using namespace sk_app;

SampleSlide::SampleSlide(const SkViewFactory* factory)
    : fViewFactory(factory)
    , fClick(nullptr) {
    SkView* view = (*factory)();
    SampleCode::RequestTitle(view, &fName);
    view->unref();
}

SampleSlide::~SampleSlide() { delete fClick; }

void SampleSlide::draw(SkCanvas* canvas) {
    SkASSERT(fView);
    fView->draw(canvas);
}

void SampleSlide::load(SkScalar winWidth, SkScalar winHeight) {
    fView.reset((*fViewFactory)());
    fView->setVisibleP(true);
    fView->setClipToBounds(false);
    fView->setSize(winWidth, winHeight);
}

void SampleSlide::unload() {
    fView.reset();
}

bool SampleSlide::onChar(SkUnichar c) {
    if (!fView) {
        return false;
    }
    SkEvent evt(gCharEvtName);
    evt.setFast32(c);
    return fView->doQuery(&evt);
}

bool SampleSlide::onMouse(SkScalar x, SkScalar y, Window::InputState state,
                          uint32_t modifiers) {
    // map to SkView modifiers
    unsigned modifierKeys = 0;
    modifierKeys |= (modifiers & Window::kShift_ModifierKey) ? kShift_SkModifierKey : 0;
    modifierKeys |= (modifiers & Window::kControl_ModifierKey) ? kControl_SkModifierKey : 0;
    modifierKeys |= (modifiers & Window::kOption_ModifierKey) ? kOption_SkModifierKey : 0;
    modifierKeys |= (modifiers & Window::kCommand_ModifierKey) ? kCommand_SkModifierKey : 0;

    bool handled = false;
    switch (state) {
        case Window::kDown_InputState: {
            delete fClick;
            fClick = fView->findClickHandler(SkIntToScalar(x), SkIntToScalar(y), modifierKeys);
            if (fClick) {
                SkView::DoClickDown(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kMove_InputState: {
            if (fClick) {
                SkView::DoClickMoved(fClick, x, y, modifierKeys);
                handled = true;
            }
            break;
        }
        case Window::kUp_InputState: {
            if (fClick) {
                SkView::DoClickUp(fClick, x, y, modifierKeys);
                delete fClick;
                fClick = nullptr;
                handled = true;
            }
            break;
        }
    }

    return handled;
}
<|endoftext|>


<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

/* bzflag special common - 1st one */
#include "common.h"

#include <iostream>
#include <string>

#include "WorldEventManager.h"

//-------------------BaseEventData--------------------
BaseEventData::BaseEventData()
{
	eventType = eNullEvent;
}

//-------------------CTFCaptureEventData--------------------
CTFCaptureEventData::CTFCaptureEventData()
{
	eventType = eCaptureEvent;
	teamCAped = -1;
	teamCaping = -1;
	playerCaping = -1;
}

CTFCaptureEventData::~CTFCaptureEventData()
{
}

//-------------------PlayerDieEventData--------------------
PlayerDieEventData::PlayerDieEventData()
{
	eventType = ePlayerDieEvent;
	playerID = -1;
	teamID = -1;
	killerID = -1;
	killerTeamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerDieEventData::~PlayerDieEventData()
{
}

//-------------------PlayerSpawnEventData--------------------
PlayerSpawnEventData::PlayerSpawnEventData()
{
	eventType = ePlayerSpawnEvent;
	playerID = -1;
	teamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerSpawnEventData::~PlayerSpawnEventData()
{
}

//-------------------ZoneEntryExitEventData--------------------
ZoneEntryExitEventData::ZoneEntryExitEventData()
{
	eventType = eZoneEntryEvent;
	playerID = -1;
	teamID = -1;
	zoneID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

ZoneEntryExitEventData::~ZoneEntryExitEventData()
{
}

//-------------------PlayerJoinPartEventData--------------------
PlayerJoinPartEventData::PlayerJoinPartEventData()
{
	eventType = ePlayerJoinEvent;

	playerID = -1;
	teamID = -1;
	time = 0.0;
}

PlayerJoinPartEventData::~PlayerJoinPartEventData()
{
}

//-------------------WorldEventManager--------------------
WorldEventManager::WorldEventManager()
{
}

WorldEventManager::~WorldEventManager()
{
	tmEventMap::iterator teamItr = eventtMap.begin();
	while ( teamItr != eventtMap.end() )
	{
		tmEventTypeList::iterator eventItr = teamItr->second.begin();
		while (eventItr == teamItr->second.end())
		{
			tvEventList::iterator itr = eventItr->second.begin();
			while ( itr != eventItr->second.end() )
			{
				if ((*itr)->autoDelete())
					delete (*itr++);
			}
			eventItr++;
		}
		teamItr++;
	}
}

void WorldEventManager::addEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
	{
		tvEventList newList;
		(*teamEvents)[eventType] = newList;
	}

	teamEvents->find(eventType)->second.push_back(theEvetnt);
}

void WorldEventManager::removeEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
		return;

	tmEventTypeList::iterator eventTypeItr = teamEvents->begin();
	if ( eventTypeItr != teamEvents->end() )
	{
		tvEventList::iterator itr = eventTypeItr->second.begin();
		while (itr == eventTypeItr->second.end())
		{
			if (*itr == theEvetnt)
				itr = eventTypeItr->second.erase(itr);
			else
				itr++;
		}
	}
}

tvEventList WorldEventManager::getEventList ( teEventType eventType, int team )

{
	tvEventList	eventList;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	tmEventTypeList::iterator teamItr = teamEvents->find(eventType);
	if ( teamItr == teamEvents->end() )
		return eventList;

	eventList = teamItr->second;
	return eventList;
}

void WorldEventManager::callEvents ( teEventType eventType, int team, BaseEventData	*eventData )
{
	if (!eventData)
		return;

	tvEventList	eventList = getEventList(eventType,team);

	for ( unsigned int i = 0; i < eventList.size(); i++)
		eventList[i]->process(eventData);
}

tmEventTypeList* WorldEventManager::getTeamEventList ( int team )
{
	if (eventtMap.find(team) == eventtMap.end())
	{
		tmEventTypeList newList;
		eventtMap[team] = newList;
	}
	return &(eventtMap.find(team)->second);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>don't delete a null<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

/* bzflag special common - 1st one */
#include "common.h"

#include <iostream>
#include <string>

#include "WorldEventManager.h"

//-------------------BaseEventData--------------------
BaseEventData::BaseEventData()
{
	eventType = eNullEvent;
}

//-------------------CTFCaptureEventData--------------------
CTFCaptureEventData::CTFCaptureEventData()
{
	eventType = eCaptureEvent;
	teamCAped = -1;
	teamCaping = -1;
	playerCaping = -1;
}

CTFCaptureEventData::~CTFCaptureEventData()
{
}

//-------------------PlayerDieEventData--------------------
PlayerDieEventData::PlayerDieEventData()
{
	eventType = ePlayerDieEvent;
	playerID = -1;
	teamID = -1;
	killerID = -1;
	killerTeamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerDieEventData::~PlayerDieEventData()
{
}

//-------------------PlayerSpawnEventData--------------------
PlayerSpawnEventData::PlayerSpawnEventData()
{
	eventType = ePlayerSpawnEvent;
	playerID = -1;
	teamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerSpawnEventData::~PlayerSpawnEventData()
{
}

//-------------------ZoneEntryExitEventData--------------------
ZoneEntryExitEventData::ZoneEntryExitEventData()
{
	eventType = eZoneEntryEvent;
	playerID = -1;
	teamID = -1;
	zoneID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

ZoneEntryExitEventData::~ZoneEntryExitEventData()
{
}

//-------------------PlayerJoinPartEventData--------------------
PlayerJoinPartEventData::PlayerJoinPartEventData()
{
	eventType = ePlayerJoinEvent;

	playerID = -1;
	teamID = -1;
	time = 0.0;
}

PlayerJoinPartEventData::~PlayerJoinPartEventData()
{
}

//-------------------WorldEventManager--------------------
WorldEventManager::WorldEventManager()
{
}

WorldEventManager::~WorldEventManager()
{
	tmEventMap::iterator teamItr = eventtMap.begin();
	while ( teamItr != eventtMap.end() )
	{
		tmEventTypeList::iterator eventItr = teamItr->second.begin();
		while (eventItr == teamItr->second.end())
		{
			tvEventList::iterator itr = eventItr->second.begin();
			while ( itr != eventItr->second.end() )
			{
				if ((*itr) && (*itr)->autoDelete())
					delete (*itr++);
			}
			eventItr++;
		}
		teamItr++;
	}
}

void WorldEventManager::addEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
	{
		tvEventList newList;
		(*teamEvents)[eventType] = newList;
	}

	teamEvents->find(eventType)->second.push_back(theEvetnt);
}

void WorldEventManager::removeEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
		return;

	tmEventTypeList::iterator eventTypeItr = teamEvents->begin();
	if ( eventTypeItr != teamEvents->end() )
	{
		tvEventList::iterator itr = eventTypeItr->second.begin();
		while (itr == eventTypeItr->second.end())
		{
			if (*itr == theEvetnt)
				itr = eventTypeItr->second.erase(itr);
			else
				itr++;
		}
	}
}

tvEventList WorldEventManager::getEventList ( teEventType eventType, int team )

{
	tvEventList	eventList;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	tmEventTypeList::iterator teamItr = teamEvents->find(eventType);
	if ( teamItr == teamEvents->end() )
		return eventList;

	eventList = teamItr->second;
	return eventList;
}

void WorldEventManager::callEvents ( teEventType eventType, int team, BaseEventData	*eventData )
{
	if (!eventData)
		return;

	tvEventList	eventList = getEventList(eventType,team);

	for ( unsigned int i = 0; i < eventList.size(); i++)
		eventList[i]->process(eventData);
}

tmEventTypeList* WorldEventManager::getTeamEventList ( int team )
{
	if (eventtMap.find(team) == eventtMap.end())
	{
		tmEventTypeList newList;
		eventtMap[team] = newList;
	}
	return &(eventtMap.find(team)->second);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/******************************************************************************\

          This file is part of the C! library.  A.K.A the cbang library.

                Copyright (c) 2003-2019, Cauldron Development LLC
                   Copyright (c) 2003-2017, Stanford University
                               All rights reserved.

         The C! library is free software: you can redistribute it and/or
        modify it under the terms of the GNU Lesser General Public License
       as published by the Free Software Foundation, either version 2.1 of
               the License, or (at your option) any later version.

        The C! library is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
                 Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
                 License along with the C! library.  If not, see
                         <http://www.gnu.org/licenses/>.

        In addition, BSD licensing may be granted on a case by case basis
        by written permission from at least one of the copyright holders.
           You may request written permission by emailing the authors.

                  For information regarding this software email:
                                 Joseph Coffland
                          joseph@cauldrondevelopment.com

\******************************************************************************/

#include "IPAddress.h"

#include <cbang/socket/Winsock.h>

#include <cbang/Exception.h>
#include <cbang/String.h>

#include <cbang/log/Logger.h>

#include <cbang/socket/Socket.h>

#include <cbang/os/SysError.h>

#ifdef _WIN32
#include <ws2tcpip.h>
#include <wspiapi.h>

#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#endif

#include <string.h>

using namespace std;
using namespace cb;

IPAddress::IPAddress(uint32_t ip, const std::string &host, uint16_t port) :
  host(host), ip(ip), port(port ? port : portFromString(host)) {
  Socket::initialize(); // Windows needs this

  size_t ptr = host.find(":");
  if (ptr != string::npos) this->host = host.substr(0, ptr);

  if (this->host == "0") this->host = "0.0.0.0"; // OSX & Windows need this
}

IPAddress::IPAddress(uint32_t ip, uint16_t port) :
  host(ipToString(ip)), ip(ip), port(port) {}

IPAddress::IPAddress(const string &host, uint16_t port) :
  IPAddress(ipFromString(host), host, port) {}

bool IPAddress::hasHost() const {
  return host.find_first_not_of("1234567890. \t\n\r") != string::npos;
}

void IPAddress::lookupHost() {host = hostFromIP(*this);}

string IPAddress::toString() const {
  return getHost() + (getPort() ? String::printf(":%u", getPort()) : string());
}

string IPAddress::ipToString(uint32_t ip) {
  return String::printf("%u.%u.%u.%u", ip >> 24, (ip >> 16) & 0xff,
                        (ip >> 8) & 0xff, ip & 0xff);
}

uint32_t IPAddress::ipFromString(const string &host) {
  vector<IPAddress> addrs;

  if (!ipsFromString(host, addrs, 0, 1))
    THROW("Could not get IP address for " << host);

  return addrs[0].getIP();
}

unsigned IPAddress::ipsFromString(const string &host, vector<IPAddress> &addrs,
                                  uint16_t port, unsigned max) {
  // TODO support IPv6 addresses

  Socket::initialize(); // Windows needs this

  string hostname;
  size_t ptr = host.find_last_of(":");
  if (ptr != string::npos) {
    hostname = host.substr(0, ptr);
    port = String::parseU16(host.substr(ptr + 1));

  } else hostname = host;

  if (hostname == "0") hostname = "0.0.0.0";

  struct addrinfo hints;
  struct addrinfo *res = 0;
  int err;

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = PF_INET; // Force IPv4 for now
  hints.ai_socktype = SOCK_STREAM;

  if ((err = getaddrinfo(hostname.c_str(), 0, &hints, &res)))
    THROW("Could not get IP address for " << hostname << ": "
           << gai_strerror(err));

  unsigned count = 0;
  struct addrinfo *info;
  for (info = res; info && (!max || count < max); info = info->ai_next) {
    if (!info->ai_addr) continue;
    uint32_t ip = ntohl(((struct sockaddr_in *)info->ai_addr)->sin_addr.s_addr);
    IPAddress addr(ip, port);
    addr.host = hostname;
    addrs.push_back(addr);
    count++;
  }

  freeaddrinfo(res);

  return count;
}

string IPAddress::hostFromIP(const IPAddress &ip) {
  if (ip.hasHost()) return ip.getHost();

  // Force 127.0.0.1 to localhost
  if (ip.getIP() == 0x7f000001) return "localhost";

  Socket::initialize(); // Windows needs this

  struct sockaddr_in addr;
  char buffer[1024];

  // TODO support IPv6
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(ip.getPort());
  addr.sin_addr.s_addr = htonl(ip.getIP());

  if (getnameinfo((struct sockaddr *)&addr, sizeof(addr), buffer,
                  sizeof(buffer), 0, 0, 0))
    THROW("Reverse lookup for " << ip << " failed: " << SysError());

  return buffer;
}

uint16_t IPAddress::portFromString(const string &host) {
  size_t ptr = host.find_last_of(":");
  if (ptr == string::npos) return 0;
  return String::parseU16(host.substr(ptr + 1));
}
<commit_msg>Adding a missing header for FreeBSD.<commit_after>/******************************************************************************\

          This file is part of the C! library.  A.K.A the cbang library.

                Copyright (c) 2003-2019, Cauldron Development LLC
                   Copyright (c) 2003-2017, Stanford University
                               All rights reserved.

         The C! library is free software: you can redistribute it and/or
        modify it under the terms of the GNU Lesser General Public License
       as published by the Free Software Foundation, either version 2.1 of
               the License, or (at your option) any later version.

        The C! library is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
                 Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
                 License along with the C! library.  If not, see
                         <http://www.gnu.org/licenses/>.

        In addition, BSD licensing may be granted on a case by case basis
        by written permission from at least one of the copyright holders.
           You may request written permission by emailing the authors.

                  For information regarding this software email:
                                 Joseph Coffland
                          joseph@cauldrondevelopment.com

\******************************************************************************/

#include "IPAddress.h"

#include <cbang/socket/Winsock.h>

#include <cbang/Exception.h>
#include <cbang/String.h>

#include <cbang/log/Logger.h>

#include <cbang/socket/Socket.h>

#include <cbang/os/SysError.h>

#ifdef _WIN32
#include <ws2tcpip.h>
#include <wspiapi.h>

#else
#include <sys/types.h>
#include <sys/socket.h>
#  ifdef __FreeBSD__
#include <netinet/in.h>
#  endif
#include <netdb.h>
#endif

#include <string.h>

using namespace std;
using namespace cb;

IPAddress::IPAddress(uint32_t ip, const std::string &host, uint16_t port) :
  host(host), ip(ip), port(port ? port : portFromString(host)) {
  Socket::initialize(); // Windows needs this

  size_t ptr = host.find(":");
  if (ptr != string::npos) this->host = host.substr(0, ptr);

  if (this->host == "0") this->host = "0.0.0.0"; // OSX & Windows need this
}

IPAddress::IPAddress(uint32_t ip, uint16_t port) :
  host(ipToString(ip)), ip(ip), port(port) {}

IPAddress::IPAddress(const string &host, uint16_t port) :
  IPAddress(ipFromString(host), host, port) {}

bool IPAddress::hasHost() const {
  return host.find_first_not_of("1234567890. \t\n\r") != string::npos;
}

void IPAddress::lookupHost() {host = hostFromIP(*this);}

string IPAddress::toString() const {
  return getHost() + (getPort() ? String::printf(":%u", getPort()) : string());
}

string IPAddress::ipToString(uint32_t ip) {
  return String::printf("%u.%u.%u.%u", ip >> 24, (ip >> 16) & 0xff,
                        (ip >> 8) & 0xff, ip & 0xff);
}

uint32_t IPAddress::ipFromString(const string &host) {
  vector<IPAddress> addrs;

  if (!ipsFromString(host, addrs, 0, 1))
    THROW("Could not get IP address for " << host);

  return addrs[0].getIP();
}

unsigned IPAddress::ipsFromString(const string &host, vector<IPAddress> &addrs,
                                  uint16_t port, unsigned max) {
  // TODO support IPv6 addresses

  Socket::initialize(); // Windows needs this

  string hostname;
  size_t ptr = host.find_last_of(":");
  if (ptr != string::npos) {
    hostname = host.substr(0, ptr);
    port = String::parseU16(host.substr(ptr + 1));

  } else hostname = host;

  if (hostname == "0") hostname = "0.0.0.0";

  struct addrinfo hints;
  struct addrinfo *res = 0;
  int err;

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = PF_INET; // Force IPv4 for now
  hints.ai_socktype = SOCK_STREAM;

  if ((err = getaddrinfo(hostname.c_str(), 0, &hints, &res)))
    THROW("Could not get IP address for " << hostname << ": "
           << gai_strerror(err));

  unsigned count = 0;
  struct addrinfo *info;
  for (info = res; info && (!max || count < max); info = info->ai_next) {
    if (!info->ai_addr) continue;
    uint32_t ip = ntohl(((struct sockaddr_in *)info->ai_addr)->sin_addr.s_addr);
    IPAddress addr(ip, port);
    addr.host = hostname;
    addrs.push_back(addr);
    count++;
  }

  freeaddrinfo(res);

  return count;
}

string IPAddress::hostFromIP(const IPAddress &ip) {
  if (ip.hasHost()) return ip.getHost();

  // Force 127.0.0.1 to localhost
  if (ip.getIP() == 0x7f000001) return "localhost";

  Socket::initialize(); // Windows needs this

  struct sockaddr_in addr;
  char buffer[1024];

  // TODO support IPv6
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(ip.getPort());
  addr.sin_addr.s_addr = htonl(ip.getIP());

  if (getnameinfo((struct sockaddr *)&addr, sizeof(addr), buffer,
                  sizeof(buffer), 0, 0, 0))
    THROW("Reverse lookup for " << ip << " failed: " << SysError());

  return buffer;
}

uint16_t IPAddress::portFromString(const string &host) {
  size_t ptr = host.find_last_of(":");
  if (ptr == string::npos) return 0;
  return String::parseU16(host.substr(ptr + 1));
}
<|endoftext|>


<commit_before>/******************************************************************************\

          This file is part of the C! library.  A.K.A the cbang library.

                Copyright (c) 2003-2019, Cauldron Development LLC
                   Copyright (c) 2003-2017, Stanford University
                               All rights reserved.

         The C! library is free software: you can redistribute it and/or
        modify it under the terms of the GNU Lesser General Public License
       as published by the Free Software Foundation, either version 2.1 of
               the License, or (at your option) any later version.

        The C! library is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
                 Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
                 License along with the C! library.  If not, see
                         <http://www.gnu.org/licenses/>.

        In addition, BSD licensing may be granted on a case by case basis
        by written permission from at least one of the copyright holders.
           You may request written permission by emailing the authors.

                  For information regarding this software email:
                                 Joseph Coffland
                          joseph@cauldrondevelopment.com

\******************************************************************************/

#include "SystemInfo.h"
#include "PowerManagement.h"
#include "CPUInfo.h"

#include <cbang/Info.h>
#include <cbang/SStream.h>
#include <cbang/String.h>

#include <cbang/os/Thread.h>
#include <cbang/os/SystemUtilities.h>

#include <cbang/log/Logger.h>
#include <cbang/util/HumanSize.h>

#include <boost/filesystem/operations.hpp>

#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN // Avoid including winsock.h
#include <windows.h>

#elif defined(__APPLE__)
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>

#include <mach/vm_statistics.h>
#include <mach/mach_types.h>
#include <mach/mach_init.h>
#include <mach/mach_host.h>

#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>

#include "MacOSUtilities.h"

#else // !_MSC_VER && !__APPLE__
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#endif

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace cb;
using namespace std;

namespace fs = boost::filesystem;

SystemInfo::SystemInfo(Inaccessible) {
  detectThreads();
}

uint32_t SystemInfo::getCPUCount() const {
#if defined(_WIN32)
  SYSTEM_INFO sysinfo;
  GetSystemInfo(&sysinfo);
  return sysinfo.dwNumberOfProcessors;

#elif defined(__APPLE__) || defined(__FreeBSD__)
  int nm[2];
  size_t length = 4;
  uint32_t count;

  nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
  sysctl(nm, 2, &count, &length, 0, 0);

  if (count < 1) {
    nm[1] = HW_NCPU;
    sysctl(nm, 2, &count, &length, 0, 0);
    if (count < 1) count = 1;
  }

  return count;

#else
  return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}

uint64_t SystemInfo::getMemoryInfo(memory_info_t type) const {
#if defined(_WIN32)
  MEMORYSTATUSEX info;

  info.dwLength = sizeof(MEMORYSTATUSEX);
  GlobalMemoryStatusEx(&info);

  switch (type) {
  case MEM_INFO_TOTAL: return (uint64_t)info.ullTotalPhys;
  case MEM_INFO_FREE: return (uint64_t)info.ullAvailPhys;
  case MEM_INFO_SWAP: return (uint64_t)info.ullAvailPageFile;
  case MEM_INFO_USABLE:
    return (uint64_t)(info.ullAvailPhys + info.ullAvailPageFile);
  }

#elif defined(__APPLE__) || defined(__FreeBSD__)
  if (type == MEM_INFO_TOTAL) {
    int64_t memory;
    int mib[2];
    size_t length = 2;

    mib[0] = CTL_HW;
    mib[1] = HW_MEMSIZE;
    length = sizeof(int64_t);

    if (!sysctl(mib, 2, &memory, &length, 0, 0)) return memory;

  } else {
    vm_size_t page;
    vm_statistics_data_t stats;
    mach_msg_type_number_t count = sizeof(stats) / sizeof(natural_t);
    mach_port_t port = mach_host_self();

    if (host_page_size(port, &page) == KERN_SUCCESS &&
        host_statistics(port, HOST_VM_INFO, (host_info_t)&stats, &count) ==
        KERN_SUCCESS)
      switch (type) {
      case MEM_INFO_TOTAL: break; // Handled above
      case MEM_INFO_FREE: return (uint64_t)(stats.free_count * page);
      case MEM_INFO_SWAP: return 0; // Not sure how to get this on OSX
      case MEM_INFO_USABLE:
        // An IBM article says this should be free + inactive + file-backed
        // pages.  No idea how to get at file-backed pages.
        return (uint64_t)((stats.free_count + stats.inactive_count) * page);
      }
  }

#else
  struct sysinfo info;
  if (!sysinfo(&info))
    switch (type) {
    case MEM_INFO_TOTAL: return (uint64_t)(info.totalram * info.mem_unit);
    case MEM_INFO_FREE: return (uint64_t)(info.freeram * info.mem_unit);
    case MEM_INFO_SWAP: return (uint64_t)(info.freeswap * info.mem_unit);
    case MEM_INFO_USABLE:
      return (uint64_t)((info.freeram + info.bufferram + info.freeswap) *
                        info.mem_unit);
    }
#endif

  return 0;
}

uint64_t SystemInfo::getFreeDiskSpace(const string &path) {
  fs::space_info si;

  try {
    si = fs::space(path);

  } catch (const fs::filesystem_error &e) {
    THROW("Could not get disk space at '" << path << "': " << e.what());
  }

  return si.available;
}

Version SystemInfo::getOSVersion() const {
#if defined(_WIN32)
  OSVERSIONINFO info;
  ZeroMemory(&info, sizeof(info));
  info.dwOSVersionInfoSize = sizeof(info);
  if (!GetVersionEx(&info)) THROW("Failed to get Windows version");

  return Version((uint8_t)info.dwMajorVersion, (uint8_t)info.dwMinorVersion);

#elif defined(__APPLE__)
  return MacOSUtilities::getMacOSVersion();

#else
  struct utsname i;

  uname(&i);
  string release = i.release;
  size_t dot = release.find('.');
  uint8_t major = String::parseU32(release.substr(0, dot));
  uint8_t minor = String::parseU32(release.substr(dot + 1));

  return Version(major, minor);
#endif
}

void SystemInfo::add(Info &info) {
  const char *category = "System";
  auto cpuInfo = CPUInfo::create();

  info.add(category, "CPU", cpuInfo->getBrand());
  info.add(category, "CPU ID", SSTR(
             cpuInfo->getVendor()
             << " Family "   << cpuInfo->getFamily()
             << " Model "    << cpuInfo->getModel()
             << " Stepping " << cpuInfo->getStepping()));
  info.add(category, "CPUs", String(getCPUCount()));

  info.add(category, "Memory", HumanSize(getTotalMemory()).toString() + "B");
  info.add(category, "Free Memory",
           HumanSize(getFreeMemory()).toString() + "B");
  info.add(category, "Threads", getThreadsType().toString());

  Version osVersion = getOSVersion();
  info.add(category, "OS Version", osVersion.toString());

  info.add(category, "Has Battery",
           String(PowerManagement::instance().hasBattery()));
  info.add(category, "On Battery",
           String(PowerManagement::instance().onBattery()));
}

void SystemInfo::detectThreads() {
  // Threads type
#ifdef _WIN32
  threadsType = ThreadsType::WINDOWS_THREADS;

#elif __linux__
  // Test for LinuxThreads which has a different PID for each thread
  struct TestThread : public Thread {
    unsigned pid;
    TestThread() : pid(0) {}
    void run() {pid = SystemUtilities::getPID();}
  };

  TestThread testThread;
  testThread.start();
  testThread.join();

  if (testThread.pid != SystemUtilities::getPID())
    threadsType = ThreadsType::LINUX_THREADS;
  else threadsType = ThreadsType::POSIX_THREADS;

#else // __linux__
  // Assume POSIX
  threadsType = ThreadsType::POSIX_THREADS;
#endif
}
<commit_msg>Improve CPU count detection in Windows. re:#81<commit_after>/******************************************************************************\

          This file is part of the C! library.  A.K.A the cbang library.

                Copyright (c) 2003-2019, Cauldron Development LLC
                   Copyright (c) 2003-2017, Stanford University
                               All rights reserved.

         The C! library is free software: you can redistribute it and/or
        modify it under the terms of the GNU Lesser General Public License
       as published by the Free Software Foundation, either version 2.1 of
               the License, or (at your option) any later version.

        The C! library is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
                 Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
                 License along with the C! library.  If not, see
                         <http://www.gnu.org/licenses/>.

        In addition, BSD licensing may be granted on a case by case basis
        by written permission from at least one of the copyright holders.
           You may request written permission by emailing the authors.

                  For information regarding this software email:
                                 Joseph Coffland
                          joseph@cauldrondevelopment.com

\******************************************************************************/

#include "SystemInfo.h"
#include "PowerManagement.h"
#include "CPUInfo.h"

#include <cbang/Info.h>
#include <cbang/SStream.h>
#include <cbang/String.h>

#include <cbang/os/Thread.h>
#include <cbang/os/SystemUtilities.h>

#include <cbang/log/Logger.h>
#include <cbang/util/HumanSize.h>

#include <boost/filesystem/operations.hpp>

#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN // Avoid including winsock.h
#include <windows.h>
#include <sysinfoapi.h>

#elif defined(__APPLE__)
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>

#include <mach/vm_statistics.h>
#include <mach/mach_types.h>
#include <mach/mach_init.h>
#include <mach/mach_host.h>

#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>

#include "MacOSUtilities.h"

#else // !_MSC_VER && !__APPLE__
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#endif

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace cb;
using namespace std;

namespace fs = boost::filesystem;

SystemInfo::SystemInfo(Inaccessible) {
  detectThreads();
}

uint32_t SystemInfo::getCPUCount() const {
#if defined(_WIN32)
  // Count active CPU threads
  DWORD len = 0;

  if (!GetLogicalProcessorInformationEx(RelationGroup, 0, &len)) {
    SmartPointer<uint8_t>::Array buffer = new uint8_t[len];
    auto info = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)buffer.get();

    if (!GetLogicalProcessorInformationEx(RelationGroup, info, &len)) {
      uint32_t cpus = 0;

      for (unsigned i = 0; i < len;) {
        info = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)&buffer[i];

        for (unsigned j = 0; j < info->Group.ActiveGroupCount; j++) {
          cpus += info->Group.GroupInfo[j].ActiveProcessorCount;

        i += info->Size;
      }

      if (cpus) return cpus;
    }
  }

  // Fallback to old method
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  return info.dwNumberOfProcessors;

#elif defined(__APPLE__) || defined(__FreeBSD__)
  int nm[2];
  size_t length = 4;
  uint32_t count;

  nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;
  sysctl(nm, 2, &count, &length, 0, 0);

  if (count < 1) {
    nm[1] = HW_NCPU;
    sysctl(nm, 2, &count, &length, 0, 0);
    if (count < 1) count = 1;
  }

  return count;

#else
  return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}

uint64_t SystemInfo::getMemoryInfo(memory_info_t type) const {
#if defined(_WIN32)
  MEMORYSTATUSEX info;

  info.dwLength = sizeof(MEMORYSTATUSEX);
  GlobalMemoryStatusEx(&info);

  switch (type) {
  case MEM_INFO_TOTAL: return (uint64_t)info.ullTotalPhys;
  case MEM_INFO_FREE: return (uint64_t)info.ullAvailPhys;
  case MEM_INFO_SWAP: return (uint64_t)info.ullAvailPageFile;
  case MEM_INFO_USABLE:
    return (uint64_t)(info.ullAvailPhys + info.ullAvailPageFile);
  }

#elif defined(__APPLE__) || defined(__FreeBSD__)
  if (type == MEM_INFO_TOTAL) {
    int64_t memory;
    int mib[2];
    size_t length = 2;

    mib[0] = CTL_HW;
    mib[1] = HW_MEMSIZE;
    length = sizeof(int64_t);

    if (!sysctl(mib, 2, &memory, &length, 0, 0)) return memory;

  } else {
    vm_size_t page;
    vm_statistics_data_t stats;
    mach_msg_type_number_t count = sizeof(stats) / sizeof(natural_t);
    mach_port_t port = mach_host_self();

    if (host_page_size(port, &page) == KERN_SUCCESS &&
        host_statistics(port, HOST_VM_INFO, (host_info_t)&stats, &count) ==
        KERN_SUCCESS)
      switch (type) {
      case MEM_INFO_TOTAL: break; // Handled above
      case MEM_INFO_FREE: return (uint64_t)(stats.free_count * page);
      case MEM_INFO_SWAP: return 0; // Not sure how to get this on OSX
      case MEM_INFO_USABLE:
        // An IBM article says this should be free + inactive + file-backed
        // pages.  No idea how to get at file-backed pages.
        return (uint64_t)((stats.free_count + stats.inactive_count) * page);
      }
  }

#else
  struct sysinfo info;
  if (!sysinfo(&info))
    switch (type) {
    case MEM_INFO_TOTAL: return (uint64_t)(info.totalram * info.mem_unit);
    case MEM_INFO_FREE: return (uint64_t)(info.freeram * info.mem_unit);
    case MEM_INFO_SWAP: return (uint64_t)(info.freeswap * info.mem_unit);
    case MEM_INFO_USABLE:
      return (uint64_t)((info.freeram + info.bufferram + info.freeswap) *
                        info.mem_unit);
    }
#endif

  return 0;
}

uint64_t SystemInfo::getFreeDiskSpace(const string &path) {
  fs::space_info si;

  try {
    si = fs::space(path);

  } catch (const fs::filesystem_error &e) {
    THROW("Could not get disk space at '" << path << "': " << e.what());
  }

  return si.available;
}

Version SystemInfo::getOSVersion() const {
#if defined(_WIN32)
  OSVERSIONINFO info;
  ZeroMemory(&info, sizeof(info));
  info.dwOSVersionInfoSize = sizeof(info);
  if (!GetVersionEx(&info)) THROW("Failed to get Windows version");

  return Version((uint8_t)info.dwMajorVersion, (uint8_t)info.dwMinorVersion);

#elif defined(__APPLE__)
  return MacOSUtilities::getMacOSVersion();

#else
  struct utsname i;

  uname(&i);
  string release = i.release;
  size_t dot = release.find('.');
  uint8_t major = String::parseU32(release.substr(0, dot));
  uint8_t minor = String::parseU32(release.substr(dot + 1));

  return Version(major, minor);
#endif
}

void SystemInfo::add(Info &info) {
  const char *category = "System";
  auto cpuInfo = CPUInfo::create();

  info.add(category, "CPU", cpuInfo->getBrand());
  info.add(category, "CPU ID", SSTR(
             cpuInfo->getVendor()
             << " Family "   << cpuInfo->getFamily()
             << " Model "    << cpuInfo->getModel()
             << " Stepping " << cpuInfo->getStepping()));
  info.add(category, "CPUs", String(getCPUCount()));

  info.add(category, "Memory", HumanSize(getTotalMemory()).toString() + "B");
  info.add(category, "Free Memory",
           HumanSize(getFreeMemory()).toString() + "B");
  info.add(category, "Threads", getThreadsType().toString());

  Version osVersion = getOSVersion();
  info.add(category, "OS Version", osVersion.toString());

  info.add(category, "Has Battery",
           String(PowerManagement::instance().hasBattery()));
  info.add(category, "On Battery",
           String(PowerManagement::instance().onBattery()));
}

void SystemInfo::detectThreads() {
  // Threads type
#ifdef _WIN32
  threadsType = ThreadsType::WINDOWS_THREADS;

#elif __linux__
  // Test for LinuxThreads which has a different PID for each thread
  struct TestThread : public Thread {
    unsigned pid;
    TestThread() : pid(0) {}
    void run() {pid = SystemUtilities::getPID();}
  };

  TestThread testThread;
  testThread.start();
  testThread.join();

  if (testThread.pid != SystemUtilities::getPID())
    threadsType = ThreadsType::LINUX_THREADS;
  else threadsType = ThreadsType::POSIX_THREADS;

#else // __linux__
  // Assume POSIX
  threadsType = ThreadsType::POSIX_THREADS;
#endif
}
<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <ostream>
// StdAir
#include <stdair/basic/BasConst_BomDisplay.hpp>
#include <stdair/bom/BomManager.hpp>
// SEvMgr
#include <sevmgr/SEVMGR_Service.hpp>
#include <sevmgr/SEVMGR_Types.hpp>
// TraDemGen
#include <trademgen/bom/DemandStream.hpp>
#include <trademgen/bom/BomDisplay.hpp>

namespace TRADEMGEN {

  /**
   * Helper singleton structure to store the current formatting flags
   * of any given output stream. The flags are re-set at the
   * structure destruction.
   */
  struct FlagSaver {
  public:
    /** Constructor. */
    FlagSaver (std::ostream& oStream)
      : _oStream (oStream), _streamFlags (oStream.flags()) {
    }

    /** Destructor. */
    ~FlagSaver() {
      // Reset formatting flags of the given output stream
      _oStream.flags (_streamFlags);
    }

  private:
    /** Reference on the STL stream, for which the flags must be saved. */
    std::ostream& _oStream;
    /** Saved STL stream flags. */
    std::ios::fmtflags _streamFlags;
  };

  // ////////////////////////////////////////////////////////////////////
  std::string BomDisplay::csvDisplay (const SEVMGR::SEVMGR_ServicePtr_T iSEVMGR_ServicePtr) {
    std::ostringstream oStream;

    /**
     * Bom root level (only)
     */
    oStream << std::endl;
    oStream << "==============================================================="
            << std::endl;
    oStream << "EventQueue: " << iSEVMGR_ServicePtr->describeKey() << std::endl;
    oStream << "==============================================================="
            << std::endl;

    // Check whether there are DemandStream objects
    const bool hasEventGeneratorList =
      iSEVMGR_ServicePtr->hasEventGeneratorList<DemandStream>();
    if (hasEventGeneratorList == false) {
      return oStream.str();
    }

    // Retrieve the DemandStream list
    const DemandStreamList_T& lDemandStreamList =
      iSEVMGR_ServicePtr->getEventGeneratorList<DemandStream>();

    // Browse the inventories
    for (DemandStreamList_T::const_iterator itDemandStream =
           lDemandStreamList.begin();
         itDemandStream != lDemandStreamList.end(); ++itDemandStream) {
      DemandStream* lDemandStream_ptr = *itDemandStream;
      assert (lDemandStream_ptr != NULL);

      // Display the demand stream
      csvDisplay (oStream, *lDemandStream_ptr);
    }

    return oStream.str();
  }

  // ////////////////////////////////////////////////////////////////////
  void BomDisplay::csvDisplay (std::ostream& oStream,
                               const DemandStream& iDemandStream) {
    // Save the formatting flags for the given STL output stream
    FlagSaver flagSaver (oStream);

    /**
     * DemandStream level (only)
     */
    oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
    oStream << iDemandStream.display();
    oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
  }

}
<commit_msg>[Dev] Added an assertion around a (shared) pointer.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <ostream>
// StdAir
#include <stdair/basic/BasConst_BomDisplay.hpp>
#include <stdair/bom/BomManager.hpp>
// SEvMgr
#include <sevmgr/SEVMGR_Service.hpp>
#include <sevmgr/SEVMGR_Types.hpp>
// TraDemGen
#include <trademgen/bom/DemandStream.hpp>
#include <trademgen/bom/BomDisplay.hpp>

namespace TRADEMGEN {

  /**
   * Helper singleton structure to store the current formatting flags
   * of any given output stream. The flags are re-set at the
   * structure destruction.
   */
  struct FlagSaver {
  public:
    /** Constructor. */
    FlagSaver (std::ostream& oStream)
      : _oStream (oStream), _streamFlags (oStream.flags()) {
    }

    /** Destructor. */
    ~FlagSaver() {
      // Reset formatting flags of the given output stream
      _oStream.flags (_streamFlags);
    }

  private:
    /** Reference on the STL stream, for which the flags must be saved. */
    std::ostream& _oStream;
    /** Saved STL stream flags. */
    std::ios::fmtflags _streamFlags;
  };

  // ////////////////////////////////////////////////////////////////////
  std::string BomDisplay::csvDisplay (const SEVMGR::SEVMGR_ServicePtr_T iSEVMGR_ServicePtr) {
    std::ostringstream oStream;

	//
	assert (iSEVMGR_ServicePtr != NULL);

    /**
     * Bom root level (only)
     */
    oStream << std::endl;
    oStream << "==============================================================="
            << std::endl;
    oStream << "EventQueue: " << iSEVMGR_ServicePtr->describeKey() << std::endl;
    oStream << "==============================================================="
            << std::endl;

    // Check whether there are DemandStream objects
    const bool hasEventGeneratorList =
      iSEVMGR_ServicePtr->hasEventGeneratorList<DemandStream>();
    if (hasEventGeneratorList == false) {
      return oStream.str();
    }

    // Retrieve the DemandStream list
    const DemandStreamList_T& lDemandStreamList =
      iSEVMGR_ServicePtr->getEventGeneratorList<DemandStream>();

    // Browse the inventories
    for (DemandStreamList_T::const_iterator itDemandStream =
           lDemandStreamList.begin();
         itDemandStream != lDemandStreamList.end(); ++itDemandStream) {
      DemandStream* lDemandStream_ptr = *itDemandStream;
      assert (lDemandStream_ptr != NULL);

      // Display the demand stream
      csvDisplay (oStream, *lDemandStream_ptr);
    }

    return oStream.str();
  }

  // ////////////////////////////////////////////////////////////////////
  void BomDisplay::csvDisplay (std::ostream& oStream,
                               const DemandStream& iDemandStream) {
    // Save the formatting flags for the given STL output stream
    FlagSaver flagSaver (oStream);

    /**
     * DemandStream level (only)
     */
    oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
    oStream << iDemandStream.display();
    oStream << "+++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
  }

}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// values_runtime.cpp
//
// Identification: src/codegen/values_runtime.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/values_runtime.h"

#include "common/logger.h"
#include "type/type_util.h"
#include "type/value_factory.h"
#include "type/value_peeker.h"

namespace peloton {
namespace codegen {

void ValuesRuntime::OutputTinyInt(char *values, uint32_t idx, int8_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetTinyIntValue(val);
}

void ValuesRuntime::OutputSmallInt(char *values, uint32_t idx, int16_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetSmallIntValue(val);
}

void ValuesRuntime::OutputInteger(char *values, uint32_t idx, int32_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetIntegerValue(val);
}

void ValuesRuntime::OutputBigInt(char *values, uint32_t idx, int64_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetBigIntValue(val);
}

void ValuesRuntime::OutputTimestamp(char *values, uint32_t idx, int64_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetTimestampValue(val);
}

void ValuesRuntime::OutputDecimal(char *values, uint32_t idx, double val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetDecimalValue(val);
}

void ValuesRuntime::OutputVarchar(char *values, uint32_t idx, char *str,
                                  uint32_t len) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  std::string string_val{str, len - 1};
  vals[idx] = type::ValueFactory::GetVarcharValue(string_val);
}

int32_t ValuesRuntime::CompareStrings(const char *str1, uint32_t len1,
                                      const char *str2, uint32_t len2) {
  return type::TypeUtil::CompareStrings(str1, len1, str2, len2);
}

}  // namespace codegen
}  // namespace peloton
<commit_msg>Fix memory leak<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// values_runtime.cpp
//
// Identification: src/codegen/values_runtime.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/values_runtime.h"

#include "common/logger.h"
#include "type/type_util.h"
#include "type/value_factory.h"
#include "type/value_peeker.h"

namespace peloton {
namespace codegen {

void ValuesRuntime::OutputTinyInt(char *values, uint32_t idx, int8_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetTinyIntValue(val);
}

void ValuesRuntime::OutputSmallInt(char *values, uint32_t idx, int16_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetSmallIntValue(val);
}

void ValuesRuntime::OutputInteger(char *values, uint32_t idx, int32_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetIntegerValue(val);
}

void ValuesRuntime::OutputBigInt(char *values, uint32_t idx, int64_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetBigIntValue(val);
}

void ValuesRuntime::OutputTimestamp(char *values, uint32_t idx, int64_t val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetTimestampValue(val);
}

void ValuesRuntime::OutputDecimal(char *values, uint32_t idx, double val) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetDecimalValue(val);
}

void ValuesRuntime::OutputVarchar(char *values, uint32_t idx, char *str,
                                  UNUSED_ATTRIBUTE uint32_t len) {
  type::Value *vals = reinterpret_cast<type::Value *>(values);
  vals[idx] = type::ValueFactory::GetVarcharValue(str, false);
}

int32_t ValuesRuntime::CompareStrings(const char *str1, uint32_t len1,
                                      const char *str2, uint32_t len2) {
  return type::TypeUtil::CompareStrings(str1, len1, str2, len2);
}

}  // namespace codegen
}  // namespace peloton
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          util.cpp
* Purpose:       Implementation of wxExtension utility methods
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/clipbrd.h>
#include <wx/config.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/frame.h>
#include <wx/extension/frd.h>

const wxString wxExAlignText(
  const wxString& lines,
  const wxString& header,
  bool fill_out_with_space,
  bool fill_out,
  const wxExLexer& lexer)
{
  const size_t line_length = lexer.UsableCharactersPerLine();

  // Use the header, with one space extra to separate, or no header at all.
  const wxString header_with_spaces =
    (header.size() == 0) ? wxEmptyString : wxString(' ', header.size());

  wxString in = lines, line = header;

  bool at_begin = true;
  wxString out;

  while (!in.empty())
  {
    const wxString word = wxExGetWord(in, false, false);

    if (line.size() + 1 + word.size() > line_length)
    {
      out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";

      line = header_with_spaces + word;
    }
    else
    {
      line += (!line.empty() && !at_begin ? wxString(" "): wxEmptyString) + word;
      at_begin = false;
    }
  }

  out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out);

  return out;
}

bool wxExClipboardAdd(const wxString& text)
{
  wxClipboardLocker locker;
  if (!locker) return false;
  if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;

  // Take care that clipboard data remain after exiting
  // This is a boolean method as well, we don't check it, as
  // clipboard data is copied.
  // At least on Ubuntu 8.10 FLush returns false.
  wxTheClipboard->Flush();

  return true;
}

const wxString wxExClipboardGet()
{
  wxBusyCursor wait;
  wxClipboardLocker locker;

  if (!locker)
  {
    wxLogError("Cannot open clipboard");
    return wxEmptyString;
  }

  if (!wxTheClipboard->IsSupported(wxDF_TEXT))
  {
    wxLogError("Clipboard format not supported");
    return wxEmptyString;
  }

  wxTextDataObject data;
  if (!wxTheClipboard->GetData(data))
  {
    wxLogError("Cannot get clipboard data");
    return wxEmptyString;
  }

  return data.GetText();
}

#if wxUSE_GUI
void wxExComboBoxFromString(
  wxComboBox* cb,
  const wxString& text)
{
  wxASSERT(cb != NULL);

  wxStringTokenizer tkz(
    text,
    wxExFindReplaceData::Get()->GetFieldSeparator());

  while (tkz.HasMoreTokens())
  {
    const wxString val = tkz.GetNextToken();
    if (cb->FindString(val) == wxNOT_FOUND)
    {
      cb->Append(val);
    }
  }

  if (cb->GetCount() > 0)
  {
    cb->SetValue(cb->GetString(0));
  }
}

const wxString wxExComboBoxToString(
  const wxComboBox* cb,
  size_t max_items)
{
  wxASSERT(cb != NULL);

  wxString text = cb->GetValue();

  switch (cb->FindString(cb->GetValue()))
  {
    case 0:
      text.clear();
      // No change necessary, the string is already present as the first one.
      for (size_t i = 0; i < max_items; i++)
        if (i < cb->GetCount())
          text += cb->GetString(i) + wxExFindReplaceData::Get()->GetFieldSeparator();
      break;

    case wxNOT_FOUND:
      // Add the string, as it is not in the combo box, to the text,
      // simply by appending all combobox items.
      for (size_t i = 0; i < max_items - 1; i++)
        if (i < cb->GetCount())
          text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb->GetString(i);
    break;

    default:
      // Reorder. The new first element already present, just add all others.
      for (size_t i = 0; i < cb->GetCount(); i++)
      {
        const wxString cb_element = cb->GetString(i);
        if (cb_element != cb->GetValue())
          text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb_element;
      }
  }

  return text;
}

const wxString wxExConfigFirstOf(const wxString& key)
{
  const wxString value = wxConfigBase::Get()->Read(key);
  return value.BeforeFirst(wxExFindReplaceData::Get()->GetFieldSeparator());
}

#endif // wxUSE_GUI

const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
  return text + "..." + (!control.empty() ? "\t" + control: wxEmptyString);
}

void wxExFindResult(
  const wxString& find_text,
  bool find_next,
  bool recursive)
{
  if (!recursive)
  {
    const wxString where = (find_next) ? _("bottom"): _("top");

#if wxUSE_STATUSBAR
    wxExFrame::StatusText(
      _("Searching for") + " " + wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " +
      _("hit") + " " + where);
#endif
  }
  else
  {
    wxBell();

#if wxUSE_STATUSBAR
    wxExFrame::StatusText(
      wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " + _("not found"));
#endif
  }
}

const wxString wxExGetEndOfText(
  const wxString& text,
  size_t max_chars)
{
  wxString text_out(text);

  if (text_out.length() > max_chars)
  {
    text_out = "..." + text_out.substr(text_out.length() - max_chars);
  }

  return text_out;
}

int wxExGetNumberOfLines(const wxString& text)
{
  if (text.empty())
  {
    return 0;
  }
  else if (text.Find(wxUniChar('\r')) != wxNOT_FOUND)
  {
    return text.Freq(wxUniChar('\r')) + 1;
  }
  else if (text.Find(wxUniChar('\n')) != wxNOT_FOUND)
  {
    return text.Freq(wxUniChar('\n')) + 1;
  }
  else
  {
    return 1;
  }
}

int wxExGetLineNumberFromText(const wxString& text)
{
  // Get text after :.
  const size_t pos_char = text.rfind(":");

  if (pos_char == wxString::npos)
  {
    return 0;
  }

  const wxString linenumber = text.substr(pos_char + 1);

  long line;

  if (linenumber.ToLong(&line))
  {
    return line;
  }
  else
  {
    return 0;
  }
}

const wxString wxExGetWord(
  wxString& text,
  bool use_other_field_separators,
  bool use_path_separator)
{
  wxString field_separators = " \t";
  if (use_other_field_separators) field_separators += ":";
  if (use_path_separator) field_separators = wxFILE_SEP_PATH;
  wxString token;
  wxStringTokenizer tkz(text, field_separators);
  if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
  text = tkz.GetString();
  text.Trim(false);
  return token;
}

bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
  if (pattern == "*") return true; // asterix matches always.

  const wxString fullname_uppercase = filename.GetFullName().Upper();

  wxStringTokenizer tokenizer(pattern.Upper(), ";");
  while (tokenizer.HasMoreTokens())
  {
    if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
  }

  return false;
}

#if wxUSE_GUI
bool wxExOpenFile(const wxFileName& filename, long open_flags)
{
  wxASSERT(wxTheApp != NULL);

  wxWindow* window = wxTheApp->GetTopWindow();
  wxExFrame* frame = wxDynamicCast(window, wxExFrame);

  if (frame != NULL)
  {
    return frame->OpenFile(
      wxExFileName(filename.GetFullPath()), -1, wxEmptyString, open_flags);
  }
  else
  {
    return false;
  }
}
#endif

const wxString wxExPrintCaption(const wxFileName& filename)
{
  if (filename.FileExists())
  {
    return filename.GetFullPath();
  }
  else
  {
    return _("Printout");
  }
}

const wxString wxExPrintFooter()
{
  return _("Page @PAGENUM@ of @PAGESCNT@");
}

const wxString wxExPrintHeader(const wxFileName& filename)
{
  if (filename.FileExists())
  {
    return
      wxExGetEndOfText(filename.GetFullPath(), 20) + " " +
      filename.GetModificationTime().Format() + " " +
      wxDateTime::Now().Format();
  }
  else
  {
    return _("Printed") + ": " + wxDateTime::Now().Format();
  }
}

const wxString wxExQuoted(const wxString& text)
{
  return "'" + text + "'";
}

const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
  wxString output = text;
  wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
  return output;
}

const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
  wxString translation = text;
  wxString num;

  num.Printf("%i", pageNum);
  translation.Replace("@PAGENUM@", num);

  num.Printf("%i", numPages);
  translation.Replace("@PAGESCNT@", num);

  return translation;
}
<commit_msg>fix for Ubuntu?\011<commit_after>/******************************************************************************\
* File:          util.cpp
* Purpose:       Implementation of wxExtension utility methods
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/clipbrd.h>
#include <wx/config.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/frame.h>
#include <wx/extension/frd.h>

const wxString wxExAlignText(
  const wxString& lines,
  const wxString& header,
  bool fill_out_with_space,
  bool fill_out,
  const wxExLexer& lexer)
{
  const size_t line_length = lexer.UsableCharactersPerLine();

  // Use the header, with one space extra to separate, or no header at all.
  const wxString header_with_spaces =
    (header.size() == 0) ? wxEmptyString : wxString(' ', header.size());

  wxString in = lines, line = header;

  bool at_begin = true;
  wxString out;

  while (!in.empty())
  {
    const wxString word = wxExGetWord(in, false, false);

    if (line.size() + 1 + word.size() > line_length)
    {
      out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";

      line = header_with_spaces + word;
    }
    else
    {
      line += (!line.empty() && !at_begin ? wxString(" "): wxEmptyString) + word;
      at_begin = false;
    }
  }

  out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out);

  return out;
}

bool wxExClipboardAdd(const wxString& text)
{
  wxClipboardLocker locker;
  if (!locker) return false;
  if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;

  // Take care that clipboard data remain after exiting
  // This is a boolean method as well, we don't check it, as
  // clipboard data is copied.
  // At least on Ubuntu 8.10 FLush returns false.
  wxTheClipboard->Flush();

  return true;
}

const wxString wxExClipboardGet()
{
  wxBusyCursor wait;
  wxClipboardLocker locker;

  if (!locker)
  {
    wxLogError("Cannot open clipboard");
    return wxEmptyString;
  }

  if (!wxTheClipboard->IsSupported(wxDF_TEXT))
  {
    wxLogError("Clipboard format not supported");
    return wxEmptyString;
  }

  wxTextDataObject data;
  if (!wxTheClipboard->GetData(data))
  {
    wxLogError("Cannot get clipboard data");
    return wxEmptyString;
  }

  return data.GetText();
}

#if wxUSE_GUI
void wxExComboBoxFromString(
  wxComboBox* cb,
  const wxString& text)
{
  wxASSERT(cb != NULL);

  wxStringTokenizer tkz(
    text,
    wxExFindReplaceData::Get()->GetFieldSeparator());

  while (tkz.HasMoreTokens())
  {
    const wxString val = tkz.GetNextToken();
    if (cb->FindString(val) == wxNOT_FOUND)
    {
      cb->Append(val);
    }
  }

  if (cb->GetCount() > 0)
  {
    cb->SetValue(cb->GetString(0));
  }
}

const wxString wxExComboBoxToString(
  const wxComboBox* cb,
  size_t max_items)
{
  wxASSERT(cb != NULL);

  wxString text = cb->GetValue();

  switch (cb->FindString(cb->GetValue()))
  {
    case 0:
      text.clear();
      // No change necessary, the string is already present as the first one.
      for (size_t i = 0; i < max_items; i++)
        if (i < cb->GetCount())
          text += cb->GetString(i) + wxExFindReplaceData::Get()->GetFieldSeparator();
      break;

    case wxNOT_FOUND:
      // Add the string, as it is not in the combo box, to the text,
      // simply by appending all combobox items.
      for (size_t i = 0; i < max_items - 1; i++)
        if (i < cb->GetCount())
          text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb->GetString(i);
    break;

    default:
      // Reorder. The new first element already present, just add all others.
      for (size_t i = 0; i < cb->GetCount(); i++)
      {
        const wxString cb_element = cb->GetString(i);
        if (cb_element != cb->GetValue())
          text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb_element;
      }
  }

  return text;
}

const wxString wxExConfigFirstOf(const wxString& key)
{
  const wxString value = wxConfigBase::Get()->Read(key);
  return value.BeforeFirst(wxExFindReplaceData::Get()->GetFieldSeparator());
}

#endif // wxUSE_GUI

const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
  return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}

void wxExFindResult(
  const wxString& find_text,
  bool find_next,
  bool recursive)
{
  if (!recursive)
  {
    const wxString where = (find_next) ? _("bottom"): _("top");

#if wxUSE_STATUSBAR
    wxExFrame::StatusText(
      _("Searching for") + " " + wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " +
      _("hit") + " " + where);
#endif
  }
  else
  {
    wxBell();

#if wxUSE_STATUSBAR
    wxExFrame::StatusText(
      wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " + _("not found"));
#endif
  }
}

const wxString wxExGetEndOfText(
  const wxString& text,
  size_t max_chars)
{
  wxString text_out(text);

  if (text_out.length() > max_chars)
  {
    text_out = "..." + text_out.substr(text_out.length() - max_chars);
  }

  return text_out;
}

int wxExGetNumberOfLines(const wxString& text)
{
  if (text.empty())
  {
    return 0;
  }
  else if (text.Find(wxUniChar('\r')) != wxNOT_FOUND)
  {
    return text.Freq(wxUniChar('\r')) + 1;
  }
  else if (text.Find(wxUniChar('\n')) != wxNOT_FOUND)
  {
    return text.Freq(wxUniChar('\n')) + 1;
  }
  else
  {
    return 1;
  }
}

int wxExGetLineNumberFromText(const wxString& text)
{
  // Get text after :.
  const size_t pos_char = text.rfind(":");

  if (pos_char == wxString::npos)
  {
    return 0;
  }

  const wxString linenumber = text.substr(pos_char + 1);

  long line;

  if (linenumber.ToLong(&line))
  {
    return line;
  }
  else
  {
    return 0;
  }
}

const wxString wxExGetWord(
  wxString& text,
  bool use_other_field_separators,
  bool use_path_separator)
{
  wxString field_separators = " \t";
  if (use_other_field_separators) field_separators += ":";
  if (use_path_separator) field_separators = wxFILE_SEP_PATH;
  wxString token;
  wxStringTokenizer tkz(text, field_separators);
  if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
  text = tkz.GetString();
  text.Trim(false);
  return token;
}

bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
  if (pattern == "*") return true; // asterix matches always.

  const wxString fullname_uppercase = filename.GetFullName().Upper();

  wxStringTokenizer tokenizer(pattern.Upper(), ";");
  while (tokenizer.HasMoreTokens())
  {
    if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
  }

  return false;
}

#if wxUSE_GUI
bool wxExOpenFile(const wxFileName& filename, long open_flags)
{
  wxASSERT(wxTheApp != NULL);

  wxWindow* window = wxTheApp->GetTopWindow();
  wxExFrame* frame = wxDynamicCast(window, wxExFrame);

  if (frame != NULL)
  {
    return frame->OpenFile(
      wxExFileName(filename.GetFullPath()), -1, wxEmptyString, open_flags);
  }
  else
  {
    return false;
  }
}
#endif

const wxString wxExPrintCaption(const wxFileName& filename)
{
  if (filename.FileExists())
  {
    return filename.GetFullPath();
  }
  else
  {
    return _("Printout");
  }
}

const wxString wxExPrintFooter()
{
  return _("Page @PAGENUM@ of @PAGESCNT@");
}

const wxString wxExPrintHeader(const wxFileName& filename)
{
  if (filename.FileExists())
  {
    return
      wxExGetEndOfText(filename.GetFullPath(), 20) + " " +
      filename.GetModificationTime().Format() + " " +
      wxDateTime::Now().Format();
  }
  else
  {
    return _("Printed") + ": " + wxDateTime::Now().Format();
  }
}

const wxString wxExQuoted(const wxString& text)
{
  return "'" + text + "'";
}

const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
  wxString output = text;
  wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
  return output;
}

const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
  wxString translation = text;
  wxString num;

  num.Printf("%i", pageNum);
  translation.Replace("@PAGENUM@", num);

  num.Printf("%i", numPages);
  translation.Replace("@PAGESCNT@", num);

  return translation;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <iostream>
#include <cstdio>

#include "activ_driver.hpp"
#include "bn_driver.hpp"
#include "conv_driver.hpp"
#include "driver.hpp"
#include "gemm_driver.hpp"
#include "lrn_driver.hpp"
#include "pool_driver.hpp"
#include "softmax_driver.hpp"
#include "rnn_driver.hpp"
#include "miopen/config.h"

int main(int argc, char* argv[])
{
    // show command
    std::cout << "MIOpenDriver:";
    for(int i = 1; i < argc; i++)
        std::cout << " " << argv[i];
    std::cout << std::endl;

    std::string base_arg = ParseBaseArg(argc, argv);

    Driver* drv;
    if(base_arg == "conv")
    {
        drv = new ConvDriver<float, float>();
    }
    else if(base_arg == "convfp16")
    {
        drv = new ConvDriver<float16, double>();
    }
    else if(base_arg == "pool")
    {
        drv = new PoolDriver<float, double>();
    }
    else if(base_arg == "poolfp16")
    {
        drv = new PoolDriver<float16, double>();
    }
    else if(base_arg == "lrn")
    {
        drv = new LRNDriver<float, double>();
    }
    else if(base_arg == "lrnfp16")
    {
        drv = new LRNDriver<float16, double>();
    }
    else if(base_arg == "activ")
    {
        drv = new ActivationDriver<float, double>();
    }
    else if(base_arg == "activfp16")
    {
        drv = new ActivationDriver<float16, double>();
    }
    else if(base_arg == "softmax")
    {
        drv = new SoftmaxDriver<float, double>();
    }
    else if(base_arg == "softmaxfp16")
    {
        drv = new SoftmaxDriver<float16, double>();
    }
    else if(base_arg == "gemm")
    {
        drv = new GemmDriver<float>();
    }
    // TODO half is not supported in gemm
    //#if MIOPEN_USE_MIOPENGEMM
    //    else if(base_arg == "gemmfp16")
    //    {
    //        drv = new GemmDriver<float16>();
    //    }
    //#endif
    else if(base_arg == "bnorm")
    {
        drv = new BatchNormDriver<float, double>();
    }
    else if(base_arg == "bnormfp16")
    {
        drv = new BatchNormDriver<float16, double>();
    }
    else if(base_arg == "rnn")
    {
        drv = new RNNDriver<float>();
    }
    else
    {
        printf("Incorrect BaseArg\n");
        exit(0);
    }

    drv->AddCmdLineArgs();
    drv->ParseCmdLineArgs(argc, argv);
    drv->GetandSetData();
    drv->AllocateBuffersAndCopy();

    int fargval     = drv->GetInputFlags().GetValueInt("forw");
    bool bnFwdInVer = (fargval == 2 && (base_arg == "bnorm"));
    bool verifyarg  = (drv->GetInputFlags().GetValueInt("verify") == 1);

    if((fargval != 2) || bnFwdInVer)
    {
        drv->RunForwardGPU();
    }

    if(verifyarg)
    {
        if(base_arg != "gemm")
        {
            if(fargval != 2 || bnFwdInVer)
            {
                drv->VerifyForward();
            }
        }
        else
        {
            printf("GEMM verification done in the GEMM library\n");
        }
    }

    if(fargval != 1)
    {
        if(base_arg != "gemm")
        {
            drv->RunBackwardGPU();
            if(verifyarg)
            {
                drv->VerifyBackward();
            }
        }
    }

    return 0;
}
<commit_msg>use double to validate on CPU<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <iostream>
#include <cstdio>

#include "activ_driver.hpp"
#include "bn_driver.hpp"
#include "conv_driver.hpp"
#include "driver.hpp"
#include "gemm_driver.hpp"
#include "lrn_driver.hpp"
#include "pool_driver.hpp"
#include "softmax_driver.hpp"
#include "rnn_driver.hpp"
#include "miopen/config.h"

int main(int argc, char* argv[])
{
    // show command
    std::cout << "MIOpenDriver:";
    for(int i = 1; i < argc; i++)
        std::cout << " " << argv[i];
    std::cout << std::endl;

    std::string base_arg = ParseBaseArg(argc, argv);

    Driver* drv;
    if(base_arg == "conv")
    {
        drv = new ConvDriver<float, double>();
    }
    else if(base_arg == "convfp16")
    {
        drv = new ConvDriver<float16, double>();
    }
    else if(base_arg == "pool")
    {
        drv = new PoolDriver<float, double>();
    }
    else if(base_arg == "poolfp16")
    {
        drv = new PoolDriver<float16, double>();
    }
    else if(base_arg == "lrn")
    {
        drv = new LRNDriver<float, double>();
    }
    else if(base_arg == "lrnfp16")
    {
        drv = new LRNDriver<float16, double>();
    }
    else if(base_arg == "activ")
    {
        drv = new ActivationDriver<float, double>();
    }
    else if(base_arg == "activfp16")
    {
        drv = new ActivationDriver<float16, double>();
    }
    else if(base_arg == "softmax")
    {
        drv = new SoftmaxDriver<float, double>();
    }
    else if(base_arg == "softmaxfp16")
    {
        drv = new SoftmaxDriver<float16, double>();
    }
    else if(base_arg == "gemm")
    {
        drv = new GemmDriver<float>();
    }
    // TODO half is not supported in gemm
    //#if MIOPEN_USE_MIOPENGEMM
    //    else if(base_arg == "gemmfp16")
    //    {
    //        drv = new GemmDriver<float16>();
    //    }
    //#endif
    else if(base_arg == "bnorm")
    {
        drv = new BatchNormDriver<float, double>();
    }
    else if(base_arg == "bnormfp16")
    {
        drv = new BatchNormDriver<float16, double>();
    }
    else if(base_arg == "rnn")
    {
        drv = new RNNDriver<float>();
    }
    else
    {
        printf("Incorrect BaseArg\n");
        exit(0);
    }

    drv->AddCmdLineArgs();
    drv->ParseCmdLineArgs(argc, argv);
    drv->GetandSetData();
    drv->AllocateBuffersAndCopy();

    int fargval     = drv->GetInputFlags().GetValueInt("forw");
    bool bnFwdInVer = (fargval == 2 && (base_arg == "bnorm"));
    bool verifyarg  = (drv->GetInputFlags().GetValueInt("verify") == 1);

    if((fargval != 2) || bnFwdInVer)
    {
        drv->RunForwardGPU();
    }

    if(verifyarg)
    {
        if(base_arg != "gemm")
        {
            if(fargval != 2 || bnFwdInVer)
            {
                drv->VerifyForward();
            }
        }
        else
        {
            printf("GEMM verification done in the GEMM library\n");
        }
    }

    if(fargval != 1)
    {
        if(base_arg != "gemm")
        {
            drv->RunBackwardGPU();
            if(verifyarg)
            {
                drv->VerifyBackward();
            }
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>//
// Copyright © 2015 Slack Technologies, Inc. All rights reserved.
//

#include "slack/http.h"

namespace slack
{
namespace http
{

std::function<response(std::string url, params)> get;
std::function<response(std::string url, params)> post;

} //namespace http
} //namespace slack
<commit_msg>Use CPR by default now.<commit_after>//
// Copyright © 2015 Slack Technologies, Inc. All rights reserved.
//

#include "slack/http.h"
#include <cpr.h>

namespace slack
{
namespace http
{

std::function<response(std::string url, params)> get = [](std::string url, slack::http::params params) -> slack::http::response {
    cpr::Parameters p;
    for (auto &kv : params)
    {
        p.AddParameter({kv.first, kv.second});
    }

    auto response = cpr::Get(cpr::Url{url}, p);

    return {static_cast<uint32_t>(response.status_code), response.text};
};

std::function<response(std::string url, params)> post = [](std::string url, slack::http::params params) -> slack::http::response {
    cpr::Parameters p;
    for (auto &kv : params)
    {
        p.AddParameter({kv.first, kv.second});
    }

    auto response = cpr::Post(cpr::Url{url}, p);

    return {static_cast<uint32_t>(response.status_code), response.text};
};

} //namespace http
} //namespace slack
<|endoftext|>


<commit_before><commit_msg>Fixed issue being stuck on non x64 arch<commit_after><|endoftext|>