<commit_before>#include "QTesseract.h"
#include <QSettings>
#include <QApplication>
#include <QMessageBox>
#include <QTextStream>
#include <QProcess>
#include <iostream>

static const char * const SETTING_ORGANIZATION_NAME = "marshmallow-tesseract-trainer";
static const char * const SETTING_APP_NAME = "MarshmallowTesseractTrainer";

QTesseract::QTesseract() :
    m_api(new tesseract::TessBaseAPI())
{
    QSettings settings(QSettings::IniFormat, QSettings::UserScope,
            SETTING_ORGANIZATION_NAME, SETTING_APP_NAME);
    QString lang;
    if(settings.contains("Tesseract/Lang")){
        lang = settings.value("Tesseract/Lang").toString();
    }
    QString dataPath;
    if(settings.contains("Tesseract/DataPath")){
        dataPath = settings.value("Tesseract/DataPath").toString();
    }

    if(lang.isNull()){
        showMsg("You need to configure tesseract in Settings!");
    }

    setlocale(LC_NUMERIC, "C");
    //QByteArray byteArray = lang.toAscii();
    //const char *apiLang = byteArray.constData();
    //UNIX only
    //QByteArray byteArray1 = dataPath.toUtf8();
    //const char *datapath = byteArray1.data();
    //setenv("TESSDATA_PREFIX", datapath, 1);
#if 0 //TODO: implemented
    if(m_api->Init(NULL, apiLang)){
        showMsg("Could not initialize tesseract.\n");
    }
#else
    if(m_api->Init(NULL, "eng")){
        showMsg("Could not initialize tesseract.\n");
    }
#endif
}

QString QTesseract::getBoxes(const QImage &qImage, const int page){
    PIX *pixs;

    if((pixs = qImage2PIX(qImage)) == NULL){
        showMsg("Unsupported image type");
        return "";
    }

    m_api->SetVariable("tessedit_create_boxfile", "1");
    STRING text_out;
    QApplication::setOverrideCursor(Qt::WaitCursor);

    if(!m_api->ProcessPage(pixs, page, NULL, NULL, 0, &text_out)){
        showMsg("Error during processing.\n");
    }

    QApplication::restoreOverrideCursor();

    pixDestroy(&pixs);
    return QString::fromUtf8(text_out.string());
}

void QTesseract::makeUnicharsetFile(const QString &boxFile, const int exp){
    QStringList arg;
    arg << QString("eng.%1.exp%2.box").arg(boxFile).arg(exp);
    runProcess("unicharset_extractor", arg);
}

void QTesseract::makeTrainingFile(){
    runProcess("tesseract", QStringList() << "eng.hiragi.exp0.png"
            << "eng.hiragi.exp0" << "nobatch" << "box.train.stderr");
}

PIX* QTesseract::qImage2PIX(const QImage &qImage){
    QImage qImg = qImage.rgbSwapped();
    const int wpl = qImg.bytesPerLine() / 4;

    PIX * pixs = pixCreate(qImg.width(), qImg.height(), qImg.depth());
    pixSetWpl(pixs, wpl);
    pixSetColormap(pixs, NULL);
    l_uint32 *datas = pixs->data;

    for(int y = 0; y < qImg.height(); y++){
        l_uint32 *lines = datas + y * wpl;
        QByteArray a((const char*)qImg.scanLine(y), qImg.bytesPerLine());
        for(int j = 0; j < a.size(); j++){
            *((l_uint8 *)lines + j) = a[j];
        }
    }

    const qreal toDPM = 1.0 / 0.0254;
    int resolutionX = qImg.dotsPerMeterX() / toDPM;
    int resolutionY = qImg.dotsPerMeterY() / toDPM;

    if(resolutionX < 300) resolutionX = 300;
    if(resolutionY < 300) resolutionY = 300;
    pixSetResolution(pixs, resolutionX, resolutionY);

    return pixEndianByteSwapNew(pixs);
}

QImage QTesseract::PIX2qImage(PIX *pixImage){

}

void QTesseract::showMsg(const QString &text){
    QMessageBox msgBox;
    msgBox.setText(text);
    msgBox.exec();
}

void QTesseract::runProcess(const QString &name, const QStringList &args){
    QProcess proc;
    proc.start(name, args);
    if(!proc.waitForStarted())
        std::cout << "debug01" << std::endl;

    proc.write("Qt rocks!");
    proc.closeWriteChannel();

    if(!proc.waitForFinished())
        std::cout << "debug02" << std::endl;
}

bool training(){
    return true;
}

QTesseract::~QTesseract(){
    m_api->End();
    delete m_api;
}

<commit_msg>WIP: Provisional Implemented makeFontPropertiesFile<commit_after>#include "QTesseract.h"
#include <QSettings>
#include <QApplication>
#include <QMessageBox>
#include <QTextStream>
#include <QProcess>
#include <iostream>

static const char * const SETTING_ORGANIZATION_NAME = "marshmallow-tesseract-trainer";
static const char * const SETTING_APP_NAME = "MarshmallowTesseractTrainer";

QTesseract::QTesseract() :
    m_api(new tesseract::TessBaseAPI())
{
    QSettings settings(QSettings::IniFormat, QSettings::UserScope,
            SETTING_ORGANIZATION_NAME, SETTING_APP_NAME);
    QString lang;
    if(settings.contains("Tesseract/Lang")){
        lang = settings.value("Tesseract/Lang").toString();
    }
    QString dataPath;
    if(settings.contains("Tesseract/DataPath")){
        dataPath = settings.value("Tesseract/DataPath").toString();
    }

    if(lang.isNull()){
        showMsg("You need to configure tesseract in Settings!");
    }

    setlocale(LC_NUMERIC, "C");
    //QByteArray byteArray = lang.toAscii();
    //const char *apiLang = byteArray.constData();
    //UNIX only
    //QByteArray byteArray1 = dataPath.toUtf8();
    //const char *datapath = byteArray1.data();
    //setenv("TESSDATA_PREFIX", datapath, 1);
#if 0 //TODO: implemented
    if(m_api->Init(NULL, apiLang)){
        showMsg("Could not initialize tesseract.\n");
    }
#else
    if(m_api->Init(NULL, "eng")){
        showMsg("Could not initialize tesseract.\n");
    }
#endif
}

QString QTesseract::getBoxes(const QImage &qImage, const int page){
    PIX *pixs;

    if((pixs = qImage2PIX(qImage)) == NULL){
        showMsg("Unsupported image type");
        return "";
    }

    m_api->SetVariable("tessedit_create_boxfile", "1");
    STRING text_out;
    QApplication::setOverrideCursor(Qt::WaitCursor);

    if(!m_api->ProcessPage(pixs, page, NULL, NULL, 0, &text_out)){
        showMsg("Error during processing.\n");
    }

    QApplication::restoreOverrideCursor();

    pixDestroy(&pixs);
    return QString::fromUtf8(text_out.string());
}

void QTesseract::makeUnicharsetFile(const QString &boxFile, const int exp){
    QStringList arg;
    arg << QString("eng.%1.exp%2.box").arg(boxFile).arg(exp);
    runProcess("unicharset_extractor", arg);
}

void QTesseract::makeTrainingFile(){
    runProcess("tesseract", QStringList() << "eng.hiragi.exp0.png"
            << "eng.hiragi.exp0" << "nobatch" << "box.train.stderr");
}

void QTesseract::makeFontPropertiesFile(const FontProperties &prop){

}

PIX* QTesseract::qImage2PIX(const QImage &qImage){
    QImage qImg = qImage.rgbSwapped();
    const int wpl = qImg.bytesPerLine() / 4;

    PIX * pixs = pixCreate(qImg.width(), qImg.height(), qImg.depth());
    pixSetWpl(pixs, wpl);
    pixSetColormap(pixs, NULL);
    l_uint32 *datas = pixs->data;

    for(int y = 0; y < qImg.height(); y++){
        l_uint32 *lines = datas + y * wpl;
        QByteArray a((const char*)qImg.scanLine(y), qImg.bytesPerLine());
        for(int j = 0; j < a.size(); j++){
            *((l_uint8 *)lines + j) = a[j];
        }
    }

    const qreal toDPM = 1.0 / 0.0254;
    int resolutionX = qImg.dotsPerMeterX() / toDPM;
    int resolutionY = qImg.dotsPerMeterY() / toDPM;

    if(resolutionX < 300) resolutionX = 300;
    if(resolutionY < 300) resolutionY = 300;
    pixSetResolution(pixs, resolutionX, resolutionY);

    return pixEndianByteSwapNew(pixs);
}

QImage QTesseract::PIX2qImage(PIX *pixImage){

}

void QTesseract::showMsg(const QString &text){
    QMessageBox msgBox;
    msgBox.setText(text);
    msgBox.exec();
}

void QTesseract::runProcess(const QString &name, const QStringList &args){
    QProcess proc;
    proc.start(name, args);
    if(!proc.waitForStarted())
        std::cout << "debug01" << std::endl;

    proc.write("Qt rocks!");
    proc.closeWriteChannel();

    if(!proc.waitForFinished())
        std::cout << "debug02" << std::endl;
}

bool training(){
    return true;
}

QTesseract::~QTesseract(){
    m_api->End();
    delete m_api;
}

<|endoftext|>


<commit_before>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program 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 Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* ScriptData
Name: achievement_commandscript
%Complete: 100
Comment: All achievement related commands
Category: commandscripts
EndScriptData */

#include "AchievementMgr.h"
#include "Chat.h"
#include "Language.h"
#include "Player.h"
#include "ScriptMgr.h"

using namespace Acore::ChatCommands;

class achievement_commandscript : public CommandScript
{
public:
    achievement_commandscript() : CommandScript("achievement_commandscript") { }

    ChatCommandTable GetCommands() const override
    {
        static ChatCommandTable achievementCommandTable =
        {
            { "add",      HandleAchievementAddCommand,      SEC_GAMEMASTER,    Console::No },
            { "checkall", HandleAchievementCheckAllCommand, SEC_ADMINISTRATOR, Console::No }
        };
        static ChatCommandTable commandTable =
        {
            { "achievement", achievementCommandTable }
        };
        return commandTable;
    }

    static bool HandleAchievementAddCommand(ChatHandler* handler, AchievementEntry const* achievementEntry)
    {
        Player* target = handler->getSelectedPlayer();
        if (!target)
        {
            handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
            handler->SetSentErrorMessage(true);
            return false;
        }
        target->CompletedAchievement(achievementEntry);

        return true;
    }

    static bool HandleAchievementCheckAllCommand(ChatHandler* handler)
    {
        Player* target = handler->getSelectedPlayer();
        if (!target)
        {
            handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
            handler->SetSentErrorMessage(true);
            return false;
        }

        target->CheckAllAchievementCriteria();
        return true;
    }
};

void AddSC_achievement_commandscript()
{
    new achievement_commandscript();
}
<commit_msg>fix(Core/Commands): Achievement checkall (#12649)<commit_after>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program 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 Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* ScriptData
Name: achievement_commandscript
%Complete: 100
Comment: All achievement related commands
Category: commandscripts
EndScriptData */

#include "AchievementMgr.h"
#include "Chat.h"
#include "Language.h"
#include "Player.h"
#include "ScriptMgr.h"

using namespace Acore::ChatCommands;

class achievement_commandscript : public CommandScript
{
public:
    achievement_commandscript() : CommandScript("achievement_commandscript") { }

    ChatCommandTable GetCommands() const override
    {
        static ChatCommandTable achievementCommandTable =
        {
            { "add",      HandleAchievementAddCommand,      SEC_GAMEMASTER,    Console::No },
            { "checkall", HandleAchievementCheckAllCommand, SEC_ADMINISTRATOR, Console::Yes }
        };
        static ChatCommandTable commandTable =
        {
            { "achievement", achievementCommandTable }
        };
        return commandTable;
    }

    static bool HandleAchievementAddCommand(ChatHandler* handler, AchievementEntry const* achievementEntry)
    {
        Player* target = handler->getSelectedPlayer();
        if (!target)
        {
            handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
            handler->SetSentErrorMessage(true);
            return false;
        }
        target->CompletedAchievement(achievementEntry);

        return true;
    }

    static bool HandleAchievementCheckAllCommand(ChatHandler* handler, Optional<PlayerIdentifier> player)
    {
        if (!player)
        {
            player = PlayerIdentifier::FromTarget(handler);
        }

        if (!player)
        {
            handler->SendSysMessage(LANG_PLAYER_NOT_FOUND);
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (player->IsConnected())
        {
            if (Player* target = player->GetConnectedPlayer())
                target->CheckAllAchievementCriteria();
        }
        else
        {
            auto* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG);
            stmt->SetData(0, uint16(AT_LOGIN_CHECK_ACHIEVS));
            stmt->SetData(1, player->GetGUID().GetCounter());
            CharacterDatabase.Execute(stmt);
        }

        return true;
    }
};

void AddSC_achievement_commandscript()
{
    new achievement_commandscript();
}
<|endoftext|>


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

#include "android_util.h"
#include <android_native_app_glue.h>
#include <cassert>
#include <vector>
#include <string>
#include <sstream>
#include <stdlib.h>

extern "C" {

// Convert Intents to arg list, returning argc and argv
// Note that this C routine mallocs memory that the caller must free
char **get_args(struct android_app *app, const char *intent_extra_data_key, const char *appTag, int *count) {
    std::vector<std::string> args;
    JavaVM &vm = *app->activity->vm;
    JNIEnv *p_env;
    if (vm.AttachCurrentThread(&p_env, nullptr) != JNI_OK) return nullptr;

    JNIEnv &env = *p_env;
    jobject activity = app->activity->clazz;
    jmethodID get_intent_method = env.GetMethodID(env.GetObjectClass(activity), "getIntent", "()Landroid/content/Intent;");
    jobject intent = env.CallObjectMethod(activity, get_intent_method);
    jmethodID get_string_extra_method =
        env.GetMethodID(env.GetObjectClass(intent), "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;");
    jvalue get_string_extra_args;
    get_string_extra_args.l = env.NewStringUTF(intent_extra_data_key);
    jstring extra_str = static_cast<jstring>(env.CallObjectMethodA(intent, get_string_extra_method, &get_string_extra_args));

    std::string args_str;
    if (extra_str) {
        const char *extra_utf = env.GetStringUTFChars(extra_str, nullptr);
        args_str = extra_utf;
        env.ReleaseStringUTFChars(extra_str, extra_utf);
        env.DeleteLocalRef(extra_str);
    }

    env.DeleteLocalRef(get_string_extra_args.l);
    env.DeleteLocalRef(intent);
    vm.DetachCurrentThread();

    // split args_str
    std::stringstream ss(args_str);
    std::string arg;
    while (std::getline(ss, arg, ' ')) {
        if (!arg.empty()) args.push_back(arg);
    }

    // Convert our STL results to C friendly constructs
    assert(count != nullptr);
    *count = args.size() + 1;
    char **vector = (char **)malloc(*count * sizeof(char *));
    const char *appName = appTag ? appTag : (const char *)"appTag";

    vector[0] = (char *)malloc(strlen(appName) * sizeof(char));
    strcpy(vector[0], appName);

    for (uint32_t i = 0; i < args.size(); i++) {
        vector[i + 1] = (char *)malloc(strlen(args[i].c_str()) * sizeof(char));
        strcpy(vector[i + 1], args[i].c_str());
    }

    return vector;
}

}  // extern "C"
<commit_msg>Add missing include in android_util.cpp<commit_after>/*
 * Copyright (c) 2016 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Relicensed from the WTFPL (http://www.wtfpl.net/faq/).
 */

#include "android_util.h"
#include <android_native_app_glue.h>
#include <cassert>
#include <cstring>
#include <vector>
#include <string>
#include <sstream>
#include <stdlib.h>

extern "C" {

// Convert Intents to arg list, returning argc and argv
// Note that this C routine mallocs memory that the caller must free
char **get_args(struct android_app *app, const char *intent_extra_data_key, const char *appTag, int *count) {
    std::vector<std::string> args;
    JavaVM &vm = *app->activity->vm;
    JNIEnv *p_env;
    if (vm.AttachCurrentThread(&p_env, nullptr) != JNI_OK) return nullptr;

    JNIEnv &env = *p_env;
    jobject activity = app->activity->clazz;
    jmethodID get_intent_method = env.GetMethodID(env.GetObjectClass(activity), "getIntent", "()Landroid/content/Intent;");
    jobject intent = env.CallObjectMethod(activity, get_intent_method);
    jmethodID get_string_extra_method =
        env.GetMethodID(env.GetObjectClass(intent), "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;");
    jvalue get_string_extra_args;
    get_string_extra_args.l = env.NewStringUTF(intent_extra_data_key);
    jstring extra_str = static_cast<jstring>(env.CallObjectMethodA(intent, get_string_extra_method, &get_string_extra_args));

    std::string args_str;
    if (extra_str) {
        const char *extra_utf = env.GetStringUTFChars(extra_str, nullptr);
        args_str = extra_utf;
        env.ReleaseStringUTFChars(extra_str, extra_utf);
        env.DeleteLocalRef(extra_str);
    }

    env.DeleteLocalRef(get_string_extra_args.l);
    env.DeleteLocalRef(intent);
    vm.DetachCurrentThread();

    // split args_str
    std::stringstream ss(args_str);
    std::string arg;
    while (std::getline(ss, arg, ' ')) {
        if (!arg.empty()) args.push_back(arg);
    }

    // Convert our STL results to C friendly constructs
    assert(count != nullptr);
    *count = args.size() + 1;
    char **vector = (char **)malloc(*count * sizeof(char *));
    const char *appName = appTag ? appTag : (const char *)"appTag";

    vector[0] = (char *)malloc(strlen(appName) * sizeof(char));
    strcpy(vector[0], appName);

    for (uint32_t i = 0; i < args.size(); i++) {
        vector[i + 1] = (char *)malloc(strlen(args[i].c_str()) * sizeof(char));
        strcpy(vector[i + 1], args[i].c_str());
    }

    return vector;
}

}  // extern "C"
<|endoftext|>


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

/**
 * @file socket_can_client.cc
 * @brief the encapsulate call the api of socket can card according to
 *can_client.h interface
 **/

#include "modules/drivers/canbus/can_client/socket/socket_can_client_raw.h"

namespace apollo {
namespace drivers {
namespace canbus {
namespace can {

using apollo::common::ErrorCode;

bool SocketCanClientRaw::Init(const CANCardParameter &parameter) {
  if (!parameter.has_channel_id()) {
    AERROR << "Init CAN failed: parameter does not have channel id. The "
              "parameter is "
           << parameter.DebugString();
    return false;
  }

  port_ = parameter.channel_id();
  return true;
}

SocketCanClientRaw::~SocketCanClientRaw() {
  if (dev_handler_) {
    Stop();
  }
}

ErrorCode SocketCanClientRaw::Start() {
  if (is_started_) {
    return ErrorCode::OK;
  }
  struct sockaddr_can addr;
  struct ifreq ifr;

  // open device
  // guss net is the device minor number, if one card is 0,1
  // if more than one card, when install driver u can specify the minior id
  // int32_t ret = canOpen(net, pCtx->mode, txbufsize, rxbufsize, 0, 0,
  // &dev_handler_);
  if (port_ > MAX_CAN_PORT || port_ < 0) {
    AERROR << "can port number [" << port_ << "] is out of the range [0,"
           << MAX_CAN_PORT << "]";
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  dev_handler_ = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  if (dev_handler_ < 0) {
    AERROR << "open device error code [" << dev_handler_ << "]: ";
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  // init config and state
  // 1. set receive message_id filter, ie white list
  struct can_filter filter[2048];
  for (int i = 0; i < 2048; ++i) {
    filter[i].can_id = 0x000 + i;
    filter[i].can_mask = CAN_SFF_MASK;
  }

  int ret = setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FILTER, &filter,
                       sizeof(filter));
  if (ret < 0) {
    AERROR << "add receive msg id filter error code: " << ret;
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  // 2. enable reception of can frames.
  int enable = 1;
  ret = ::setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable,
                     sizeof(enable));
  if (ret < 0) {
    AERROR << "enable reception of can frame error code: " << ret;
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  // strcpy(ifr.ifr_name, "can0");
  std::strncpy(ifr.ifr_name, "can0", IFNAMSIZ);
  if (ioctl(dev_handler_, SIOCGIFINDEX, &ifr) < 0) {
    AERROR << "ioctl error";
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  // bind socket to network interface

  addr.can_family = AF_CAN;
  addr.can_ifindex = ifr.ifr_ifindex;
  ret = ::bind(dev_handler_, reinterpret_cast<struct sockaddr *>(&addr),
               sizeof(addr));

  if (ret < 0) {
    AERROR << "bind socket to network interface error code: " << ret;
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  is_started_ = true;
  return ErrorCode::OK;
}

void SocketCanClientRaw::Stop() {
  if (is_started_) {
    is_started_ = false;

    int ret = close(dev_handler_);
    if (ret < 0) {
      AERROR << "close error code:" << ret << ", " << GetErrorString(ret);
    } else {
      AINFO << "close socket can ok. port:" << port_;
    }
  }
}

// Synchronous transmission of CAN messages
ErrorCode SocketCanClientRaw::Send(const std::vector<CanFrame> &frames,
                                   int32_t *const frame_num) {
  CHECK_NOTNULL(frame_num);
  CHECK_EQ(frames.size(), static_cast<size_t>(*frame_num));

  if (!is_started_) {
    AERROR << "Nvidia can client has not been initiated! Please init first!";
    return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;
  }
  for (size_t i = 0; i < frames.size() && i < MAX_CAN_SEND_FRAME_LEN; ++i) {
    if (frames[i].len != CANBUS_MESSAGE_LENGTH) {
      AERROR << "frames[" << i << "].len = " << frames[i].len
             << ", which is not equal to can message data length ("
             << CANBUS_MESSAGE_LENGTH << ").";
      return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;
    }
    send_frames_[i].can_id = frames[i].id;
    send_frames_[i].can_dlc = frames[i].len;
    std::memcpy(send_frames_[i].data, frames[i].data, frames[i].len);

    // Synchronous transmission of CAN messages
    int ret = write(dev_handler_, &send_frames_[i], sizeof(send_frames_[i]));
    if (ret <= 0) {
      AERROR << "send message failed, error code: " << ret;
      return ErrorCode::CAN_CLIENT_ERROR_BASE;
    }
  }

  return ErrorCode::OK;
}

// buf size must be 8 bytes, every time, we receive only one frame
ErrorCode SocketCanClientRaw::Receive(std::vector<CanFrame> *const frames,
                                      int32_t *const frame_num) {
  if (!is_started_) {
    AERROR << "Nvidia can client is not init! Please init first!";
    return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
  }

  if (*frame_num > MAX_CAN_RECV_FRAME_LEN || *frame_num < 0) {
    AERROR << "recv can frame num not in range[0, " << MAX_CAN_RECV_FRAME_LEN
           << "], frame_num:" << *frame_num;
    // TODO(Authors): check the difference of returning frame_num/error_code
    return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
  }

  for (int32_t i = 0; i < *frame_num && i < MAX_CAN_RECV_FRAME_LEN; ++i) {
    CanFrame cf;
    int ret = read(dev_handler_, &recv_frames_[i], sizeof(recv_frames_[i]));

    if (ret < 0) {
      AERROR << "receive message failed, error code: " << ret;
      return ErrorCode::CAN_CLIENT_ERROR_BASE;
    }
    if (recv_frames_[i].can_dlc != CANBUS_MESSAGE_LENGTH) {
      AERROR << "recv_frames_[" << i
             << "].can_dlc = " << recv_frames_[i].can_dlc
             << ", which is not equal to can message data length ("
             << CANBUS_MESSAGE_LENGTH << ").";
      return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
    }
    cf.id = recv_frames_[i].can_id;
    cf.len = recv_frames_[i].can_dlc;
    std::memcpy(cf.data, recv_frames_[i].data, recv_frames_[i].can_dlc);
    frames->push_back(cf);
  }
  return ErrorCode::OK;
}

std::string SocketCanClientRaw::GetErrorString(const int32_t /*status*/) {
  return "";
}

}  // namespace can
}  // namespace canbus
}  // namespace drivers
}  // namespace apollo
<commit_msg>canbus: fix hardcode can0. use config to pick up socket can name.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file socket_can_client.cc
 * @brief the encapsulate call the api of socket can card according to
 *can_client.h interface
 **/

#include "modules/drivers/canbus/can_client/socket/socket_can_client_raw.h"

namespace apollo {
namespace drivers {
namespace canbus {
namespace can {

using apollo::common::ErrorCode;

bool SocketCanClientRaw::Init(const CANCardParameter &parameter) {
  if (!parameter.has_channel_id()) {
    AERROR << "Init CAN failed: parameter does not have channel id. The "
              "parameter is "
           << parameter.DebugString();
    return false;
  }

  port_ = parameter.channel_id();
  return true;
}

SocketCanClientRaw::~SocketCanClientRaw() {
  if (dev_handler_) {
    Stop();
  }
}

ErrorCode SocketCanClientRaw::Start() {
  if (is_started_) {
    return ErrorCode::OK;
  }
  struct sockaddr_can addr;
  struct ifreq ifr;

  // open device
  // guss net is the device minor number, if one card is 0,1
  // if more than one card, when install driver u can specify the minior id
  // int32_t ret = canOpen(net, pCtx->mode, txbufsize, rxbufsize, 0, 0,
  // &dev_handler_);
  if (port_ > MAX_CAN_PORT || port_ < 0) {
    AERROR << "can port number [" << port_ << "] is out of the range [0,"
           << MAX_CAN_PORT << "]";
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  dev_handler_ = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  if (dev_handler_ < 0) {
    AERROR << "open device error code [" << dev_handler_ << "]: ";
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  // init config and state
  // 1. set receive message_id filter, ie white list
  struct can_filter filter[2048];
  for (int i = 0; i < 2048; ++i) {
    filter[i].can_id = 0x000 + i;
    filter[i].can_mask = CAN_SFF_MASK;
  }

  int ret = setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FILTER, &filter,
                       sizeof(filter));
  if (ret < 0) {
    AERROR << "add receive msg id filter error code: " << ret;
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  // 2. enable reception of can frames.
  int enable = 1;
  ret = ::setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable,
                     sizeof(enable));
  if (ret < 0) {
    AERROR << "enable reception of can frame error code: " << ret;
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  std::string can_name("can" + std::to_string(port_));
  std::strncpy(ifr.ifr_name, can_name.c_str(), IFNAMSIZ);
  if (ioctl(dev_handler_, SIOCGIFINDEX, &ifr) < 0) {
    AERROR << "ioctl error";
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  // bind socket to network interface

  addr.can_family = AF_CAN;
  addr.can_ifindex = ifr.ifr_ifindex;
  ret = ::bind(dev_handler_, reinterpret_cast<struct sockaddr *>(&addr),
               sizeof(addr));

  if (ret < 0) {
    AERROR << "bind socket to network interface error code: " << ret;
    return ErrorCode::CAN_CLIENT_ERROR_BASE;
  }

  is_started_ = true;
  return ErrorCode::OK;
}

void SocketCanClientRaw::Stop() {
  if (is_started_) {
    is_started_ = false;

    int ret = close(dev_handler_);
    if (ret < 0) {
      AERROR << "close error code:" << ret << ", " << GetErrorString(ret);
    } else {
      AINFO << "close socket can ok. port:" << port_;
    }
  }
}

// Synchronous transmission of CAN messages
ErrorCode SocketCanClientRaw::Send(const std::vector<CanFrame> &frames,
                                   int32_t *const frame_num) {
  CHECK_NOTNULL(frame_num);
  CHECK_EQ(frames.size(), static_cast<size_t>(*frame_num));

  if (!is_started_) {
    AERROR << "Nvidia can client has not been initiated! Please init first!";
    return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;
  }
  for (size_t i = 0; i < frames.size() && i < MAX_CAN_SEND_FRAME_LEN; ++i) {
    if (frames[i].len != CANBUS_MESSAGE_LENGTH) {
      AERROR << "frames[" << i << "].len = " << frames[i].len
             << ", which is not equal to can message data length ("
             << CANBUS_MESSAGE_LENGTH << ").";
      return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;
    }
    send_frames_[i].can_id = frames[i].id;
    send_frames_[i].can_dlc = frames[i].len;
    std::memcpy(send_frames_[i].data, frames[i].data, frames[i].len);

    // Synchronous transmission of CAN messages
    int ret = write(dev_handler_, &send_frames_[i], sizeof(send_frames_[i]));
    if (ret <= 0) {
      AERROR << "send message failed, error code: " << ret;
      return ErrorCode::CAN_CLIENT_ERROR_BASE;
    }
  }

  return ErrorCode::OK;
}

// buf size must be 8 bytes, every time, we receive only one frame
ErrorCode SocketCanClientRaw::Receive(std::vector<CanFrame> *const frames,
                                      int32_t *const frame_num) {
  if (!is_started_) {
    AERROR << "Nvidia can client is not init! Please init first!";
    return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
  }

  if (*frame_num > MAX_CAN_RECV_FRAME_LEN || *frame_num < 0) {
    AERROR << "recv can frame num not in range[0, " << MAX_CAN_RECV_FRAME_LEN
           << "], frame_num:" << *frame_num;
    // TODO(Authors): check the difference of returning frame_num/error_code
    return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
  }

  for (int32_t i = 0; i < *frame_num && i < MAX_CAN_RECV_FRAME_LEN; ++i) {
    CanFrame cf;
    int ret = read(dev_handler_, &recv_frames_[i], sizeof(recv_frames_[i]));

    if (ret < 0) {
      AERROR << "receive message failed, error code: " << ret;
      return ErrorCode::CAN_CLIENT_ERROR_BASE;
    }
    if (recv_frames_[i].can_dlc != CANBUS_MESSAGE_LENGTH) {
      AERROR << "recv_frames_[" << i
             << "].can_dlc = " << recv_frames_[i].can_dlc
             << ", which is not equal to can message data length ("
             << CANBUS_MESSAGE_LENGTH << ").";
      return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
    }
    cf.id = recv_frames_[i].can_id;
    cf.len = recv_frames_[i].can_dlc;
    std::memcpy(cf.data, recv_frames_[i].data, recv_frames_[i].can_dlc);
    frames->push_back(cf);
  }
  return ErrorCode::OK;
}

std::string SocketCanClientRaw::GetErrorString(const int32_t /*status*/) {
  return "";
}

}  // namespace can
}  // namespace canbus
}  // namespace drivers
}  // namespace apollo
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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.
*/

/**
  \file    SystemInfo.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    July 2008
*/

#include "SystemInfo.h"

#include "StdDefines.h"
#ifdef _WIN32
  #include <windows.h>
#else
  #ifdef DETECTED_OS_APPLE
    #include <sys/sysctl.h>
  #else
    #include <cstdio>
    #include <iostream>
    #include <sstream>
    #include <sys/resource.h>
    #include <sys/sysinfo.h>
    #include <sys/time.h>
    #include "IO/KeyValueFileParser.h"
  #endif
#endif

SystemInfo::SystemInfo(std::string strProgramPath,
                       UINT64 iDefaultCPUMemSize,
                       UINT64 iDefaultGPUMemSize) :
  m_strProgramPath(strProgramPath),
  m_iProgramBitWidth(sizeof(void*)*8),
  m_iUseMaxCPUMem(iDefaultCPUMemSize),
  m_iUseMaxGPUMem(iDefaultGPUMemSize),
  m_iCPUMemSize(iDefaultCPUMemSize),
  m_iGPUMemSize(iDefaultGPUMemSize),
  m_bIsCPUSizeComputed(false),
  m_bIsGPUSizeComputed(false),
  m_bIsNumberOfCPUsComputed(false),
  m_bIsDirectX10Capable(false)
{
  UINT32 iNumberOfCPUs = ComputeNumCPUs();
  if (iNumberOfCPUs > 0) {
    m_iNumberOfCPUs = iNumberOfCPUs;
    m_bIsNumberOfCPUsComputed = true;
  }

  UINT64 iCPUMemSize = ComputeCPUMemSize();
  if (iCPUMemSize > 0) {
    m_iCPUMemSize = iCPUMemSize;
    m_bIsCPUSizeComputed = true;
  }

  UINT64 iGPUMemSize = ComputeGPUMemory();  // also sets m_bIsDirectX10Capable
  if (iGPUMemSize > 0) {
    m_iGPUMemSize = iGPUMemSize;
    m_bIsGPUSizeComputed = true;
  }
}

UINT32 SystemInfo::ComputeNumCPUs() {
  #ifdef _WIN32
    SYSTEM_INFO siSysInfo;
    GetSystemInfo(&siSysInfo);
    return siSysInfo.dwNumberOfProcessors;
  #else
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else
      return 0;
    #endif
  #endif
}

#ifdef __linux__

#ifndef NDEBUG
#   define DBG(str) do { std::cerr << str << std::endl; } while(0)
#else
#   define DBG(str) /* nothing */
#endif
static unsigned long lnx_mem_sysinfo() {
  struct sysinfo si;
  if(sysinfo(&si) < 0) {
    perror("sysinfo");
    return 0;
  }
  return si.totalram;
}

static UINT64 lnx_mem_rlimit() {
    struct rlimit limit;
    // RLIMIT_MEMLOCK returns 32768 (that's *bytes*) on my 6gb-RAM system, so
    // that number is worthless to us.
    // RLIMIT_DATA isn't great, because it gets the entire data segment size
    // allowable, not just the heap size ...
    if(getrlimit(RLIMIT_DATA, &limit) != 0) {
        perror("getrlimit");
        return 0;
    }
    // Frequently the information given by getrlimit(2) is essentially
    // worthless, because it assumes we don't care about swapping.
    if(limit.rlim_cur == RLIM_INFINITY || limit.rlim_max == RLIM_INFINITY) {
        DBG("getrlimit gave useless info...");
        return 0;
    }
    return limit.rlim_max;
}

static UINT64 lnx_mem_proc() {
  KeyValueFileParser meminfo("/proc/meminfo");

  if(!meminfo.FileReadable()) {
    DBG("could not open proc memory filesystem");
    return 0;
  }

  KeyValPair *mem_total = meminfo.GetData("MemTotal");
  if(mem_total == NULL) {
    DBG("proc mem fs did not have a `MemTotal' entry.");
    return 0;
  }
  std::istringstream mem_strm(mem_total->strValue);
  UINT64 mem;
  mem_strm >> mem;
  return mem * 1024;
}

static UINT64 lnx_mem() {
  UINT64 m;
  if((m = lnx_mem_proc()) == 0) {
    DBG("proc failed, falling back to rlimit");
    if((m = lnx_mem_rlimit()) == 0) {
      DBG("rlimit failed, falling back to sysinfo");
      if((m = lnx_mem_sysinfo()) == 0) {
        DBG("all memory lookups failed; pretending you have 1Gb of memory.");
        return 1024*1024*1024;
      }
    }
  }
  return m;
}
#endif

UINT64 SystemInfo::ComputeCPUMemSize() {
  #ifdef _WIN32
    MEMORYSTATUSEX statex;
    statex.dwLength = sizeof (statex);
    GlobalMemoryStatusEx (&statex);
    return statex.ullTotalPhys;
  #else
    #ifdef DETECTED_OS_APPLE
      UINT64 phys = 0;
      int mib[2] = { CTL_HW, HW_MEMSIZE };
      size_t len = sizeof(phys);
      if(sysctl(mib, sizeof(mib)/sizeof(mib[0]), &phys, &len, NULL, 0) != 0) {
        perror("max memory query");
        return 0;
      }
      return phys;
    #elif defined(__linux__)
      return static_cast<UINT64>(lnx_mem());
    #else
      std::cerr << "Unknown system, can't lookup max memory.  "
                << "Using a hard setting of 10 gb." << std::endl;
      return 1024*1024*1024*10;
    #endif
  #endif
}

#if defined(_WIN32) && defined(USE_DIRECTX)
  #define INITGUID
  #include <string.h>
  #include <stdio.h>
  #include <assert.h>
  #include <d3d9.h>
  #include <multimon.h>

  #pragma comment( lib, "d3d9.lib" )

  HRESULT GetVideoMemoryViaDirectDraw( HMONITOR hMonitor, DWORD* pdwAvailableVidMem );
  HRESULT GetVideoMemoryViaDXGI( HMONITOR hMonitor, SIZE_T* pDedicatedVideoMemory, SIZE_T* pDedicatedSystemMemory, SIZE_T* pSharedSystemMemory );

  #ifndef SAFE_RELEASE
    #define SAFE_RELEASE(p)      { if (p) { (p)->Release(); (p)=NULL; } }
  #endif

  typedef IDirect3D9* ( WINAPI* LPDIRECT3DCREATE9 )( UINT  );
  LPDIRECT3DCREATE9 pDirect3DCreate9;

  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    HINSTANCE hD3D9 = LoadLibrary( L"d3d9.dll" );
    if (!hD3D9) return 0;
    pDirect3DCreate9 = ( LPDIRECT3DCREATE9 )GetProcAddress( hD3D9, "Direct3DCreate9" );

    if (!pDirect3DCreate9) {
      FreeLibrary( hD3D9 );
      return 0;
    }

    IDirect3D9* pD3D9 = NULL;
    pD3D9 = pDirect3DCreate9( D3D_SDK_VERSION );
    if( pD3D9 )
    {
        UINT dwAdapterCount = pD3D9->GetAdapterCount();
        if (dwAdapterCount > 0) {
            UINT iAdapter = 0;

            HMONITOR hMonitor = pD3D9->GetAdapterMonitor( iAdapter );

            SIZE_T DedicatedVideoMemory;
            SIZE_T DedicatedSystemMemory;
            SIZE_T SharedSystemMemory;
            if( SUCCEEDED( GetVideoMemoryViaDXGI( hMonitor, &DedicatedVideoMemory, &DedicatedSystemMemory, &SharedSystemMemory ) ) )
            {
              m_bIsDirectX10Capable = true;
              SAFE_RELEASE( pD3D9 );
              return UINT64(DedicatedVideoMemory);
            } else {
              DWORD dwAvailableVidMem;
              if( SUCCEEDED( GetVideoMemoryViaDirectDraw( hMonitor, &dwAvailableVidMem ) ) ) {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return UINT64(dwAvailableVidMem);
              } else {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return 0;
              }
            }
        }

        SAFE_RELEASE( pD3D9 );
        FreeLibrary( hD3D9 );
        return 0;
    }
    else
    {
        FreeLibrary( hD3D9 );
        return 0;
    }
  }

#else
  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else // Linux
      return 0;
    #endif
  }
#endif
<commit_msg>Fix integer overflow issue.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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.
*/

/**
  \file    SystemInfo.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    July 2008
*/

#include "SystemInfo.h"

#include "StdDefines.h"
#ifdef _WIN32
  #include <windows.h>
#else
  #ifdef DETECTED_OS_APPLE
    #include <sys/sysctl.h>
  #else
    #include <cstdio>
    #include <iostream>
    #include <sstream>
    #include <sys/resource.h>
    #include <sys/sysinfo.h>
    #include <sys/time.h>
    #include "IO/KeyValueFileParser.h"
  #endif
#endif

SystemInfo::SystemInfo(std::string strProgramPath,
                       UINT64 iDefaultCPUMemSize,
                       UINT64 iDefaultGPUMemSize) :
  m_strProgramPath(strProgramPath),
  m_iProgramBitWidth(sizeof(void*)*8),
  m_iUseMaxCPUMem(iDefaultCPUMemSize),
  m_iUseMaxGPUMem(iDefaultGPUMemSize),
  m_iCPUMemSize(iDefaultCPUMemSize),
  m_iGPUMemSize(iDefaultGPUMemSize),
  m_bIsCPUSizeComputed(false),
  m_bIsGPUSizeComputed(false),
  m_bIsNumberOfCPUsComputed(false),
  m_bIsDirectX10Capable(false)
{
  UINT32 iNumberOfCPUs = ComputeNumCPUs();
  if (iNumberOfCPUs > 0) {
    m_iNumberOfCPUs = iNumberOfCPUs;
    m_bIsNumberOfCPUsComputed = true;
  }

  UINT64 iCPUMemSize = ComputeCPUMemSize();
  if (iCPUMemSize > 0) {
    m_iCPUMemSize = iCPUMemSize;
    m_bIsCPUSizeComputed = true;
  }

  UINT64 iGPUMemSize = ComputeGPUMemory();  // also sets m_bIsDirectX10Capable
  if (iGPUMemSize > 0) {
    m_iGPUMemSize = iGPUMemSize;
    m_bIsGPUSizeComputed = true;
  }
}

UINT32 SystemInfo::ComputeNumCPUs() {
  #ifdef _WIN32
    SYSTEM_INFO siSysInfo;
    GetSystemInfo(&siSysInfo);
    return siSysInfo.dwNumberOfProcessors;
  #else
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else
      return 0;
    #endif
  #endif
}

#ifdef __linux__

#ifndef NDEBUG
#   define DBG(str) do { std::cerr << str << std::endl; } while(0)
#else
#   define DBG(str) /* nothing */
#endif
static unsigned long lnx_mem_sysinfo() {
  struct sysinfo si;
  if(sysinfo(&si) < 0) {
    perror("sysinfo");
    return 0;
  }
  return si.totalram;
}

static UINT64 lnx_mem_rlimit() {
    struct rlimit limit;
    // RLIMIT_MEMLOCK returns 32768 (that's *bytes*) on my 6gb-RAM system, so
    // that number is worthless to us.
    // RLIMIT_DATA isn't great, because it gets the entire data segment size
    // allowable, not just the heap size ...
    if(getrlimit(RLIMIT_DATA, &limit) != 0) {
        perror("getrlimit");
        return 0;
    }
    // Frequently the information given by getrlimit(2) is essentially
    // worthless, because it assumes we don't care about swapping.
    if(limit.rlim_cur == RLIM_INFINITY || limit.rlim_max == RLIM_INFINITY) {
        DBG("getrlimit gave useless info...");
        return 0;
    }
    return limit.rlim_max;
}

static UINT64 lnx_mem_proc() {
  KeyValueFileParser meminfo("/proc/meminfo");

  if(!meminfo.FileReadable()) {
    DBG("could not open proc memory filesystem");
    return 0;
  }

  KeyValPair *mem_total = meminfo.GetData("MemTotal");
  if(mem_total == NULL) {
    DBG("proc mem fs did not have a `MemTotal' entry.");
    return 0;
  }
  std::istringstream mem_strm(mem_total->strValue);
  UINT64 mem;
  mem_strm >> mem;
  return mem * 1024;
}

static UINT64 lnx_mem() {
  UINT64 m;
  if((m = lnx_mem_proc()) == 0) {
    DBG("proc failed, falling back to rlimit");
    if((m = lnx_mem_rlimit()) == 0) {
      DBG("rlimit failed, falling back to sysinfo");
      if((m = lnx_mem_sysinfo()) == 0) {
        DBG("all memory lookups failed; pretending you have 1Gb of memory.");
        return 1024*1024*1024;
      }
    }
  }
  return m;
}
#endif

UINT64 SystemInfo::ComputeCPUMemSize() {
  #ifdef _WIN32
    MEMORYSTATUSEX statex;
    statex.dwLength = sizeof (statex);
    GlobalMemoryStatusEx (&statex);
    return statex.ullTotalPhys;
  #else
    #ifdef DETECTED_OS_APPLE
      UINT64 phys = 0;
      int mib[2] = { CTL_HW, HW_MEMSIZE };
      size_t len = sizeof(phys);
      if(sysctl(mib, sizeof(mib)/sizeof(mib[0]), &phys, &len, NULL, 0) != 0) {
        perror("max memory query");
        return 0;
      }
      return phys;
    #elif defined(__linux__)
      return static_cast<UINT64>(lnx_mem());
    #else
      std::cerr << "Unknown system, can't lookup max memory.  "
                << "Using a hard setting of 10 gb." << std::endl;
      return 1024ULL*1024ULL*1024ULL*10ULL;
    #endif
  #endif
}

#if defined(_WIN32) && defined(USE_DIRECTX)
  #define INITGUID
  #include <string.h>
  #include <stdio.h>
  #include <assert.h>
  #include <d3d9.h>
  #include <multimon.h>

  #pragma comment( lib, "d3d9.lib" )

  HRESULT GetVideoMemoryViaDirectDraw( HMONITOR hMonitor, DWORD* pdwAvailableVidMem );
  HRESULT GetVideoMemoryViaDXGI( HMONITOR hMonitor, SIZE_T* pDedicatedVideoMemory, SIZE_T* pDedicatedSystemMemory, SIZE_T* pSharedSystemMemory );

  #ifndef SAFE_RELEASE
    #define SAFE_RELEASE(p)      { if (p) { (p)->Release(); (p)=NULL; } }
  #endif

  typedef IDirect3D9* ( WINAPI* LPDIRECT3DCREATE9 )( UINT  );
  LPDIRECT3DCREATE9 pDirect3DCreate9;

  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    HINSTANCE hD3D9 = LoadLibrary( L"d3d9.dll" );
    if (!hD3D9) return 0;
    pDirect3DCreate9 = ( LPDIRECT3DCREATE9 )GetProcAddress( hD3D9, "Direct3DCreate9" );

    if (!pDirect3DCreate9) {
      FreeLibrary( hD3D9 );
      return 0;
    }

    IDirect3D9* pD3D9 = NULL;
    pD3D9 = pDirect3DCreate9( D3D_SDK_VERSION );
    if( pD3D9 )
    {
        UINT dwAdapterCount = pD3D9->GetAdapterCount();
        if (dwAdapterCount > 0) {
            UINT iAdapter = 0;

            HMONITOR hMonitor = pD3D9->GetAdapterMonitor( iAdapter );

            SIZE_T DedicatedVideoMemory;
            SIZE_T DedicatedSystemMemory;
            SIZE_T SharedSystemMemory;
            if( SUCCEEDED( GetVideoMemoryViaDXGI( hMonitor, &DedicatedVideoMemory, &DedicatedSystemMemory, &SharedSystemMemory ) ) )
            {
              m_bIsDirectX10Capable = true;
              SAFE_RELEASE( pD3D9 );
              return UINT64(DedicatedVideoMemory);
            } else {
              DWORD dwAvailableVidMem;
              if( SUCCEEDED( GetVideoMemoryViaDirectDraw( hMonitor, &dwAvailableVidMem ) ) ) {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return UINT64(dwAvailableVidMem);
              } else {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return 0;
              }
            }
        }

        SAFE_RELEASE( pD3D9 );
        FreeLibrary( hD3D9 );
        return 0;
    }
    else
    {
        FreeLibrary( hD3D9 );
        return 0;
    }
  }

#else
  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else // Linux
      return 0;
    #endif
  }
#endif
<|endoftext|>


<commit_before>#pragma once

#include <cmath>
#include <vector>

namespace bayesian_ab {

double logbeta(double a, double b) {
  return std::lgamma(a) + std::lgamma(b) - std::lgamma(a + b);
}

double prob_b_beats_a(int alpha_a, int beta_a, int alpha_b, int beta_b) {
  double total = 0.0;
  double logbeta_aa_ba = logbeta(alpha_a, beta_a);
  double beta_ba = beta_b + beta_a;

  for (auto i = 0; i < alpha_b; i++) {
    total += exp(logbeta(alpha_a + i, beta_ba) - log(beta_b + i) - logbeta(1 + i, beta_b) - logbeta_aa_ba);
  }

  return total;
}

double prob_c_beats_a_and_b(int alpha_a, int beta_a, int alpha_b, int beta_b, int alpha_c, int beta_c) {
  double total = 0.0;

  double logbeta_ac_bc = logbeta(alpha_c, beta_c);

  std::vector<double> log_bb_j;
  log_bb_j.reserve(alpha_b);
  std::vector<double> logbeta_j_bb;
  logbeta_j_bb.reserve(alpha_b);

  for (auto j = 0; j < alpha_b; j++) {
    log_bb_j.push_back(log(beta_b + j));
    logbeta_j_bb.push_back(logbeta(1 + j, beta_b));
  }

  double abc = beta_a + beta_b + beta_c;
  std::vector<double> logbeta_ac_i_j;
  logbeta_ac_i_j.reserve(alpha_a + alpha_b);

  for (auto i = 0; i < alpha_a + alpha_b; i++) {
    logbeta_ac_i_j.push_back(logbeta(alpha_c + i, abc));
  }

  for (auto i = 0; i < alpha_a; i++) {
    double log_ba_i = log(beta_a + i);
    double logbeta_i_ba = logbeta(1 + i, beta_a);

    for (auto j = 0; j < alpha_b; j++) {
      total += exp(logbeta_ac_i_j[i + j] -
        log_ba_i - log_bb_j[j] -
        logbeta_i_ba - logbeta_j_bb[j] -
        logbeta_ac_bc);
    }
  }

  return 1 - prob_b_beats_a(alpha_c, beta_c, alpha_a, beta_a) -
    prob_b_beats_a(alpha_c, beta_c, alpha_b, beta_b) + total;
}

double prob_d_beats_a_and_b_and_c(int alpha_a, int beta_a, int alpha_b, int beta_b, int alpha_c, int beta_c, int alpha_d, int beta_d) {
  double total = 0.0;

  double logbeta_ad_bd = logbeta(alpha_d, beta_d);

  std::vector<double> log_bb_j;
  log_bb_j.reserve(alpha_b);
  std::vector<double> logbeta_j_bb;
  logbeta_j_bb.reserve(alpha_b);

  for (auto j = 0; j < alpha_b; j++) {
    log_bb_j.push_back(log(beta_b + j));
    logbeta_j_bb.push_back(logbeta(1 + j, beta_b));
  }

  std::vector<double> log_bc_k;
  log_bc_k.reserve(alpha_c);
  std::vector<double> logbeta_k_bc;
  logbeta_k_bc.reserve(alpha_c);

  for (auto k = 0; k < alpha_c; k++) {
    log_bc_k.push_back(log(beta_c + k));
    logbeta_k_bc.push_back(logbeta(1 + k, beta_c));
  }

  double abcd = beta_a + beta_b + beta_c + beta_d;
  std::vector<double> logbeta_bd_i_j_k;
  logbeta_bd_i_j_k.reserve(alpha_a + alpha_b + alpha_c);

  for (auto i = 0; i < alpha_a + alpha_b + alpha_c; i++) {
    logbeta_bd_i_j_k.push_back(logbeta(alpha_d + i, abcd));
  }

  for (auto i = 0; i < alpha_a; i++) {
    double log_ba_i = log(beta_a + i);
    double logbeta_i_ba = logbeta(1 + i, beta_a);
    double sum_i = -log_ba_i - logbeta_i_ba - logbeta_ad_bd;

    for (auto j = 0; j < alpha_b; j++) {
      // TODO cache
      double sum_j = sum_i - log_bb_j[j] - logbeta_j_bb[j];

      for (auto k = 0; k < alpha_c; k++) {
        total += exp(sum_j + logbeta_bd_i_j_k[i + j + k] - log_bc_k[k] - logbeta_k_bc[k]);
      }
    }
  }

  return 1 - prob_b_beats_a(alpha_a, beta_a, alpha_d, beta_d) -
    prob_b_beats_a(alpha_b, beta_b, alpha_d, beta_d) -
    prob_b_beats_a(alpha_c, beta_c, alpha_d, beta_d) +
    prob_c_beats_a_and_b(alpha_a, beta_a, alpha_b, beta_b, alpha_d, beta_d) +
    prob_c_beats_a_and_b(alpha_a, beta_a, alpha_c, beta_c, alpha_d, beta_d) +
    prob_c_beats_a_and_b(alpha_b, beta_b, alpha_c, beta_c, alpha_d, beta_d) - total;
}

}
<commit_msg>Improved code [skip ci]<commit_after>#pragma once

#include <cmath>
#include <vector>

namespace bayesian_ab {

double logbeta(double a, double b) {
  return std::lgamma(a) + std::lgamma(b) - std::lgamma(a + b);
}

double prob_b_beats_a(int alpha_a, int beta_a, int alpha_b, int beta_b) {
  double total = 0.0;
  double logbeta_aa_ba = logbeta(alpha_a, beta_a);
  double beta_ba = beta_b + beta_a;

  for (auto i = 0; i < alpha_b; i++) {
    total += exp(logbeta(alpha_a + i, beta_ba) - log(beta_b + i) - logbeta(1 + i, beta_b) - logbeta_aa_ba);
  }

  return total;
}

double prob_c_beats_a_and_b(int alpha_a, int beta_a, int alpha_b, int beta_b, int alpha_c, int beta_c) {
  double total = 0.0;

  double logbeta_ac_bc = logbeta(alpha_c, beta_c);

  std::vector<double> log_bb_j;
  log_bb_j.reserve(alpha_b);
  std::vector<double> logbeta_j_bb;
  logbeta_j_bb.reserve(alpha_b);

  for (auto j = 0; j < alpha_b; j++) {
    log_bb_j.push_back(log(beta_b + j));
    logbeta_j_bb.push_back(logbeta(1 + j, beta_b));
  }

  double abc = beta_a + beta_b + beta_c;
  std::vector<double> logbeta_ac_i_j;
  logbeta_ac_i_j.reserve(alpha_a + alpha_b);

  for (auto i = 0; i < alpha_a + alpha_b; i++) {
    logbeta_ac_i_j.push_back(logbeta(alpha_c + i, abc));
  }

  for (auto i = 0; i < alpha_a; i++) {
    double log_ba_i = log(beta_a + i);
    double logbeta_i_ba = logbeta(1 + i, beta_a);

    for (auto j = 0; j < alpha_b; j++) {
      total += exp(logbeta_ac_i_j[i + j] -
        log_ba_i - log_bb_j[j] -
        logbeta_i_ba - logbeta_j_bb[j] -
        logbeta_ac_bc);
    }
  }

  return 1 - prob_b_beats_a(alpha_c, beta_c, alpha_a, beta_a) -
    prob_b_beats_a(alpha_c, beta_c, alpha_b, beta_b) + total;
}

double prob_d_beats_a_and_b_and_c(int alpha_a, int beta_a, int alpha_b, int beta_b, int alpha_c, int beta_c, int alpha_d, int beta_d) {
  double total = 0.0;

  double logbeta_ad_bd = logbeta(alpha_d, beta_d);

  std::vector<double> log_bb_j;
  log_bb_j.reserve(alpha_b);
  std::vector<double> logbeta_j_bb;
  logbeta_j_bb.reserve(alpha_b);

  for (auto j = 0; j < alpha_b; j++) {
    log_bb_j.push_back(log(beta_b + j));
    logbeta_j_bb.push_back(logbeta(1 + j, beta_b));
  }

  std::vector<double> log_bc_k;
  log_bc_k.reserve(alpha_c);
  std::vector<double> logbeta_k_bc;
  logbeta_k_bc.reserve(alpha_c);

  for (auto k = 0; k < alpha_c; k++) {
    log_bc_k.push_back(log(beta_c + k));
    logbeta_k_bc.push_back(logbeta(1 + k, beta_c));
  }

  double abcd = beta_a + beta_b + beta_c + beta_d;
  std::vector<double> logbeta_bd_i_j_k;
  logbeta_bd_i_j_k.reserve(alpha_a + alpha_b + alpha_c);

  for (auto i = 0; i < alpha_a + alpha_b + alpha_c; i++) {
    logbeta_bd_i_j_k.push_back(logbeta(alpha_d + i, abcd));
  }

  for (auto i = 0; i < alpha_a; i++) {
    double sum_i = -log(beta_a + i) - logbeta(1 + i, beta_a) - logbeta_ad_bd;

    for (auto j = 0; j < alpha_b; j++) {
      // TODO cache
      double sum_j = sum_i - log_bb_j[j] - logbeta_j_bb[j];

      for (auto k = 0; k < alpha_c; k++) {
        total += exp(sum_j + logbeta_bd_i_j_k[i + j + k] - log_bc_k[k] - logbeta_k_bc[k]);
      }
    }
  }

  return 1 - prob_b_beats_a(alpha_a, beta_a, alpha_d, beta_d) -
    prob_b_beats_a(alpha_b, beta_b, alpha_d, beta_d) -
    prob_b_beats_a(alpha_c, beta_c, alpha_d, beta_d) +
    prob_c_beats_a_and_b(alpha_a, beta_a, alpha_b, beta_b, alpha_d, beta_d) +
    prob_c_beats_a_and_b(alpha_a, beta_a, alpha_c, beta_c, alpha_d, beta_d) +
    prob_c_beats_a_and_b(alpha_b, beta_b, alpha_c, beta_c, alpha_d, beta_d) - total;
}

}
<|endoftext|>


<commit_before>#ifndef SOL_FUNCTION_HPP
#define SOL_FUNCTION_HPP

#include <sol.hpp>
#include <sol/tuple.hpp>
#include <sol/reference.hpp>

namespace sol {
class function : virtual public reference {
private:
	template<typename... Args>
	void push_args( Args&&... args ) {
		auto L = state( );
		using swallow = char [];
		void( swallow{ ( stack::push( L, std::forward<Args>( args ) ), '\0' )... } );
	}
public:
	function( ) : reference( ) {}
	function( lua_State* L, int index = -1 ) : reference( L, index ) {
		type_assert( L, index, type::function );
	}

	template<typename T, typename... Args>
	T invoke( Args&&... args ) {
		push( );
		push_args( std::forward<Args>( args )... );
		lua_pcall( state( ), sizeof...( Args ), 1, 0 );
		return stack::pop<T>( state( ) );
	}

	template<typename... Args>
	void invoke( Args&&... args ) {
		push( );
		push_args( std::forward<Args>( args )... );
		lua_pcall( state( ), sizeof...( Args ), 0, 0 );
	}
};
} // sol

#endif // SOL_FUNCTION_HPP<commit_msg>Formatting corrections<commit_after>#ifndef SOL_FUNCTION_HPP
#define SOL_FUNCTION_HPP

#include "reference.hpp"
#include "tuple.hpp"
#include "stack.hpp"

namespace sol {
class function : virtual public reference {
private:
	template<typename... Args>
	void push_args(Args&&... args) {
		auto L = state();
		using swallow = char [];
		void( swallow{ (stack::push(L, std::forward<Args>(args)), '\0')... } );
	}
public:
	function() : reference() {}
	function(lua_State* L, int index = -1) : reference(L, index) {
		type_assert(L, index, type::function);
	}

	template<typename T, typename... Args>
	T invoke(Args&&... args) {
		push();
		push_args(std::forward<Args>(args)...);
		lua_pcall(state(), sizeof...(Args), 1, 0);
		return stack::pop<T>(state());
	}

	template<typename... Args>
	void invoke(Args&&... args) {
		push();
		push_args(std::forward<Args>(args)...);
		lua_pcall(state(), sizeof...(Args), 0, 0);
	}
};
} // sol

#endif // SOL_FUNCTION_HPP<|endoftext|>


<commit_before>
/**
 * @file   soundManager.cpp
 * @brief  SE,BGMなどサウンド関係を管理します
 *
 * @author y.akira
 * @date   2017.01.15
 */

#include "precompiled.h"

//! サウンドを配列で保管
vector<shared_ptr<ofSoundPlayer>> g_sounds;

/**
 * @brief ゲームで使うサウンドを全て読み込む
 */
void LoadAllSound(const string& path) {
  ofxJSON json;
  json.open(path);

  // enumとjson内の数に相違がないか確認
  assert(json["Sounds"].size() == SOUND_NUM);

  // 配列の初期化、メモリ確保
  g_sounds.clear();
  g_sounds.resize(SOUND_NUM);

  // サウンドの名前を配列で取得
  auto names = json["Sounds"].getMemberNames();

  // jsonまでのパスの取得
  string root = json["Root"].asString();

  // サウンドの読み込み
  for (unsigned int i = 0; i < SOUND_NUM; i++) {
    g_sounds[i] = make_shared<ofSoundPlayer>();
    g_sounds[i]->load(root + names[i]);

    // 読み込めてなかった時のためヌルチェック
    if (auto sound = g_sounds[i]) {
      auto j = json["Sounds"][names[i]];

      // パラメータの設定
      if (j.isMember("volume")) {
        sound->setVolume(j["volume"].asFloat());
      }
      if (j.isMember("speed")) {
        sound->setSpeed(j["speed"].asFloat());
      }
      if (j.isMember("loop")) {
        sound->setLoop(j["loop"].asBool());
      }
      if (j.isMember("multiplay")) {
        sound->setMultiPlay(j["multiplay"].asBool());
      }
    }
  }
}

/**
 * @brief サウンドの取得
 * @brief 細かな設定をしたい時に使用してください
 */
shared_ptr<ofSoundPlayer> FindSound(SoundTag tag) {
  return g_sounds[tag];
}

//! サウンドの再生
void PlaySound(SoundTag tag) {
  g_sounds[tag]->play();
}

//! サウンドを止める
void StopSound(SoundTag tag) {
  g_sounds[tag]->stop();
}
<commit_msg>use lvalue reference<commit_after>
/**
 * @file   soundManager.cpp
 * @brief  SE,BGMなどサウンド関係を管理します
 *
 * @author y.akira
 * @date   2017.01.15
 */

#include "precompiled.h"

//! サウンドを配列で保管
vector<shared_ptr<ofSoundPlayer>> g_sounds;

/**
 * @brief ゲームで使うサウンドを全て読み込む
 */
void LoadAllSound(const string& path) {
  ofxJSON json;
  json.open(path);

  // enumとjson内の数に相違がないか確認
  assert(json["Sounds"].size() == SOUND_NUM);

  // 配列の初期化、メモリ確保
  g_sounds.clear();
  g_sounds.resize(SOUND_NUM);

  // サウンドの名前を配列で取得
  auto names = json["Sounds"].getMemberNames();

  // jsonまでのパスの取得
  string root = json["Root"].asString();

  // サウンドの読み込み
  for (unsigned int i = 0; i < SOUND_NUM; i++) {
    g_sounds[i] = make_shared<ofSoundPlayer>();
    g_sounds[i]->load(root + names[i]);

    // 読み込めてなかった時のためヌルチェック
    if (auto& sound = g_sounds[i]) {
      auto j = json["Sounds"][names[i]];

      // パラメータの設定
      if (j.isMember("volume")) {
        sound->setVolume(j["volume"].asFloat());
      }
      if (j.isMember("speed")) {
        sound->setSpeed(j["speed"].asFloat());
      }
      if (j.isMember("loop")) {
        sound->setLoop(j["loop"].asBool());
      }
      if (j.isMember("multiplay")) {
        sound->setMultiPlay(j["multiplay"].asBool());
      }
    }
  }
}

/**
 * @brief サウンドの取得
 * @brief 細かな設定をしたい時に使用してください
 */
shared_ptr<ofSoundPlayer> FindSound(SoundTag tag) {
  return g_sounds[tag];
}

//! サウンドの再生
void PlaySound(SoundTag tag) {
  g_sounds[tag]->play();
}

//! サウンドを止める
void StopSound(SoundTag tag) {
  g_sounds[tag]->stop();
}
<|endoftext|>


<commit_before>// MPI_Cannon.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>

using namespace std;

// rozmiar macierzy (NxN)
int matrixRows = 3;
int matrixCols = 3;
int matrixSize = matrixRows * matrixCols;

// funkcje
void printMatrix(int* M);
void matrixMultAdd(int* A, int* B, int* C, int len); // w k krokach mnozy poszczegolne komorki maciezy i wynik dodaje do maciezy wynikowej

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

	// macierz wejsciowa A
	int* A = new int[matrixSize];
	A[0] = 3;	A[1] = 8;	A[2] = 6;
	A[3] = 7;	A[4] = 1;	A[5] = 6;
	A[6] = 8;	A[7] = 4;	A[8] = 6;

	// macierz wejsciowa B
	int* B = new int[matrixSize];
	B[0] = 4;	B[1] = 2;	B[2] = 4;
	B[3] = 1;	B[4] = 8;	B[5] = 6;
	B[6] = 4;	B[7] = 2;	B[8] = 7;

	// macierz wynikowa C
	int* C = new int[matrixSize];
	fill_n(C, matrixSize, 0);

	// CAPTURE TIME
	clock_t begin_pt = clock();

	cout << "Tablica A:" << endl;
	printMatrix(A);
	cout << endl << "Tablica B:" << endl;
	printMatrix(B);
	cout << endl << "Tablica C:" << endl;
	printMatrix(C);

	matrixMultAdd(A, B, C, matrixRows);
	cout << endl << "Macierze pomnozone sekwencyjnie:" << endl;
	printMatrix(C);

	cout << endl << "Czas trwania programu: " << double(clock() - begin_pt) / CLOCKS_PER_SEC << endl;

	system("PAUSE");

	return 0;
}

void printMatrix(int* M)
{
	for (int i = 0; i < matrixRows; i++)
	{
		for (int j = 0; j < matrixCols; j++)
		{
			cout << M[i * matrixRows + j] << "\t";
		}
		cout << endl;
	}
}

void matrixMultAdd(int* A, int* B, int* C, int len)
{
	int i, j, k;
	for (i = 0; i < len; i++) {
		for (j = 0; j < len; j++) {
			for (k = 0; k < len; k++) {
				C[i * len + j] += A[i * len + k] * B[k * len + j];
			}
		}
	}
}

<commit_msg>working single thread version<commit_after>// MPI_Cannon.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>

using namespace std;

// rozmiar macierzy (NxN)
int matrixDim = 3;
int matrixSize = matrixDim * matrixDim;

// funkcje
void printMatrix(int* M);

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

	// macierz wejsciowa A
	int* A = new int[matrixSize];
	A[0] = 3;	A[1] = 8;	A[2] = 6;
	A[3] = 7;	A[4] = 1;	A[5] = 6;
	A[6] = 8;	A[7] = 4;	A[8] = 6;

	// macierz wejsciowa B
	int* B = new int[matrixSize];
	B[0] = 4;	B[1] = 2;	B[2] = 4;
	B[3] = 1;	B[4] = 8;	B[5] = 6;
	B[6] = 4;	B[7] = 2;	B[8] = 7;

	// macierz wynikowa C
	int* C = new int[matrixSize];
	fill_n(C, matrixSize, 0);

	cout << "Tablica A:" << endl;
	printMatrix(A);
	cout << endl << "Tablica B:" << endl;
	printMatrix(B);
	cout << endl << "Tablica C:" << endl;
	printMatrix(C);

	// czas start
	clock_t begin_pt = clock();

	// faza przygotowawcza - pierwsze przesuniecie
	int* tempMatrix = new int[matrixDim];
	int pos = 0;

	// shift A
	for (int i = 1; i < matrixDim; ++i)
	{
		pos = i;
		for (int j = 0; j < matrixDim; ++j)
		{
			tempMatrix[j] = A[(i * matrixDim) + (pos % matrixDim)];
			++pos;
		}

		for (int j = 0; j < matrixDim; ++j)
		{
			A[(i * matrixDim) + (j)] = tempMatrix[j];
		}
	}

	// shift B
	for (int i = 1; i < matrixDim; ++i)
	{
		pos = i;
		for (int j = 0; j < matrixDim; ++j)
		{
			tempMatrix[j] = B[((pos % matrixDim) * matrixDim) + (i)];
			++pos;
		}

		for (int j = 0; j < matrixDim; ++j)
		{
			B[(j * matrixDim) + (i)] = tempMatrix[j];
		}
	}

	// po shificie:
	cout << endl << "A po shifice: " << endl;
	printMatrix(A);

	cout << endl << "B po shifice: " << endl;
	printMatrix(B);

	// przemnazanie komorek w k krokach z sumowaniem z przesunieciami
	for (int k = 0; k < matrixDim; ++k)
	{
		for (int i = 0; i < matrixDim; ++i)
		{
			for (int j = 0; j < matrixDim; ++j)
			{
				C[i * matrixDim + j] += A[(i * matrixDim) + ((j + k) % matrixDim)] * B[(((i + k) % matrixDim) * matrixDim) + (j)];
			}
		}

		cout << endl << "krok " << k << ": " << endl;
		printMatrix(C);
	}

	// podsumowanie czasu
	cout << endl << "Czas trwania programu: " << double(clock() - begin_pt) / CLOCKS_PER_SEC << endl;

	// sprzatanie
	delete(A);
	delete(B);
	delete(C);
	delete(tempMatrix);

	system("PAUSE");

	return 0;
}

void printMatrix(int* M)
{
	for (int i = 0; i < matrixDim; i++)
	{
		for (int j = 0; j < matrixDim; j++)
		{
			cout << M[i * matrixDim + j] << "\t";
		}
		cout << endl;
	}
}

<|endoftext|>


<commit_before>#include "logger.hpp"
#include "manipulator/details/post_event_to_virtual_devices.hpp"
#include "thread_utility.hpp"
#include "time_utility.hpp"
#include "virtual_hid_device_client.hpp"

int main(int argc, const char* argv[]) {
  krbn::thread_utility::register_main_thread();

  auto client = krbn::console_user_server_client::get_shared_instance();

  client->connected.connect([client] {
    std::string shell_command = "open /Applications/Safari.app";
    client->shell_command_execution(shell_command);
  });

  client->connect_failed.connect([](auto&& error_code) {
    krbn::logger::get_logger().error("Failed to connect");
  });

  client->start();

  CFRunLoopRun();

  return 0;
}
<commit_msg>update appendix/console_user_server_client<commit_after>#include "logger.hpp"
#include "manipulator/details/post_event_to_virtual_devices.hpp"
#include "thread_utility.hpp"
#include "time_utility.hpp"
#include "virtual_hid_device_client.hpp"

int main(int argc, const char* argv[]) {
  krbn::thread_utility::register_main_thread();

  signal(SIGINT, [](int) {
    CFRunLoopStop(CFRunLoopGetMain());
  });

  auto client = std::make_shared<krbn::console_user_server_client>();

  client->connected.connect([client] {
    std::string shell_command = "open /Applications/Safari.app";
    client->async_shell_command_execution(shell_command);
  });

  client->connect_failed.connect([](auto&& error_code) {
    krbn::logger::get_logger().error("Failed to connect");
  });

  client->async_start();

  CFRunLoopRun();

  client = nullptr;

  return 0;
}
<|endoftext|>


<commit_before>
#include <string>
#include <sstream>

#include "scsi/base.h"
#include "pyscsi.h"

#define NO_IMPORT_ARRAY
#define PY_ARRAY_UNIQUE_SYMBOL USCSI_PyArray_API
#include <numpy/ndarrayobject.h>

#if SIZE_MAX==NPY_MAX_UINT32
#define NPY_SIZE_T NPY_UINT32
#elif SIZE_MAX==NPY_MAX_UINT64
#define NPY_SIZE_T NPY_UINT64
#else
#error logic error with SIZE_MAX
#endif

#define TRY PyState *state = (PyState*)raw; try

namespace {

struct PyState {
    PyObject_HEAD
    PyObject *dict, *weak; //  __dict__ and __weakref__
    PyObject *attrs; // lookup name to attribute index (for StateBase)
    StateBase *state;
};

static
int PyState_traverse(PyObject *raw, visitproc visit, void *arg)
{
    PyState *state = (PyState*)raw;
    Py_VISIT(state->attrs);
    Py_VISIT(state->dict);
    return 0;
}

static
int PyState_clear(PyObject *raw)
{
    PyState *state = (PyState*)raw;
    Py_CLEAR(state->dict);
    Py_CLEAR(state->attrs);
    return 0;
}

static
void PyState_free(PyObject *raw)
{
    TRY {
        std::auto_ptr<StateBase> S(state->state);
        state->state = NULL;

        if(state->weak)
            PyObject_ClearWeakRefs(raw);

        PyState_clear(raw);

        Py_TYPE(raw)->tp_free(raw);
    } CATCH2V(std::exception, RuntimeError)
}

static
PyObject *PyState_getattro(PyObject *raw, PyObject *attr)
{
    TRY {
        PyObject *idx = PyDict_GetItem(state->attrs, attr);
        if(!idx) {
            return PyErr_Format(PyExc_KeyError, "Unknown State attribute");
        }
        int i = PyInt_AsLong(idx);

        StateBase::ArrayInfo info;

        if(!state->state->getArray(i, info))
            return PyErr_Format(PyExc_AttributeError, "invalid attribute name");

        if(info.ndim==0) { // Scalar
            switch(info.type) {
            case StateBase::ArrayInfo::Double:
                return PyFloat_FromDouble(*(double*)info.ptr);
            case StateBase::ArrayInfo::Sizet:
                return PyLong_FromSize_t(*(size_t*)info.ptr);
            }
            return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type);
        }

        int pytype;
        switch(info.type) {
        case StateBase::ArrayInfo::Double: pytype = NPY_DOUBLE; break;
        case StateBase::ArrayInfo::Sizet: pytype = NPY_SIZE_T; break;
        default:
            return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type);
        }

        npy_intp dims[5];
        memcpy(dims, info.dim, sizeof(dims));

        PyRef<> obj(PyArray_SimpleNewFromData(info.ndim, dims, pytype, info.ptr));

        Py_INCREF(state);
        PyArray_BASE(obj.py()) = (PyObject*)state;

        return obj.releasePy();
    } CATCH()
}

static
int PyState_setattro(PyObject *raw, PyObject *attr, PyObject *val)
{
    TRY {
        PyObject *idx = PyDict_GetItem(state->attrs, attr);
        if(!idx)
            return -1;
        int i = PyInt_AsLong(idx);

        StateBase::ArrayInfo info;

        if(!state->state->getArray(i, info)) {
            PyErr_SetString(PyExc_AttributeError, "invalid attribute name");
            return -1;
        }

        if(info.ndim!=0) {
            PyErr_SetString(PyExc_NotImplementedError, "Can't set array attributes (hint, use state.attr[:] = ...)");
            return -1;
        }

        switch(info.type) {
        case StateBase::ArrayInfo::Double: {
            double *dest = (double*)info.ptr;
            if(PyFloat_Check(val))
                *dest = PyFloat_AsDouble(val);
            else if(PyLong_Check(val))
                *dest = PyLong_AsDouble(val);
            else if(PyInt_Check(val))
                *dest = PyInt_AsLong(val);
            else
                PyErr_Format(PyExc_ValueError, "Can't assign to double field");
        }
            break;
        case StateBase::ArrayInfo::Sizet: {
            size_t *dest = (size_t*)info.ptr;
            if(PyFloat_Check(val))
                *dest = PyFloat_AsDouble(val);
            else if(PyLong_Check(val))
                *dest = PyLong_AsUnsignedLongLong(val);
            else if(PyInt_Check(val))
                *dest = PyInt_AsLong(val);
            else
                PyErr_Format(PyExc_ValueError, "Can't assign to double field");
        }
            break;
        default:
            PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type);
        }
        return PyErr_Occurred() ? -1 : 0;

    } CATCH3(std::exception, RuntimeError, -1)
}

static
PyObject* PyState_str(PyObject *raw)
{
    TRY {
        std::ostringstream strm;
        state->state->show(strm, 0);
        return PyString_FromString(strm.str().c_str());
    } CATCH()
}

static PyMethodDef PyState_methods[] = {
    {NULL, NULL, 0, NULL}
};

static PyTypeObject PyStateType = {
#if PY_MAJOR_VERSION >= 3
    PyVarObject_HEAD_INIT(NULL, 0)
#else
    PyObject_HEAD_INIT(NULL)
    0,
#endif
    "uscsi._internal.State",
    sizeof(PyState),
};

} // namespace

PyObject* wrapstate(StateBase* b)
{
    try {

        PyRef<PyState> state((PyState*)PyStateType.tp_alloc(&PyStateType, 0));

        state->state = b;
        state->attrs = state->weak = state->dict = 0;

        state->attrs = PyDict_New();
        if(!state->attrs)
            return NULL;

        for(unsigned i=0; true; i++)
        {
            StateBase::ArrayInfo info;

            if(!b->getArray(i, info))
                break;

            PyRef<> name(PyInt_FromLong(i));
            if(PyDict_SetItemString(state->attrs, info.name.c_str(), name.py()))
                throw std::runtime_error("Failed to insert into Dict");

        }

        return state.releasePy();
    } CATCH()
}

StateBase* unwrapstate(PyObject* raw)
{
    if(!PyObject_TypeCheck(raw, &PyStateType))
        throw std::invalid_argument("Argument is not a State");
    PyState *state = (PyState*)raw;
    return state->state;
}

int registerModState(PyObject *mod)
{
    PyStateType.tp_str = &PyState_str;
    PyStateType.tp_repr = &PyState_str;
    PyStateType.tp_dealloc = &PyState_free;

    PyStateType.tp_weaklistoffset = offsetof(PyState, weak);
    PyStateType.tp_traverse = &PyState_traverse;
    PyStateType.tp_clear = &PyState_clear;

    PyStateType.tp_dictoffset = offsetof(PyState, dict);
    PyStateType.tp_getattro = &PyState_getattro;
    PyStateType.tp_setattro = &PyState_setattro;

    PyStateType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC;
    PyStateType.tp_methods = PyState_methods;

    if(PyType_Ready(&PyStateType))
        return -1;

    Py_INCREF(&PyStateType);
    if(PyModule_AddObject(mod, "State", (PyObject*)&PyStateType)) {
        Py_DECREF(&PyStateType);
        return -1;
    }

    return 0;
}
<commit_msg>PyState_getattro should raise AttributeError<commit_after>
#include <string>
#include <sstream>

#include "scsi/base.h"
#include "pyscsi.h"

#define NO_IMPORT_ARRAY
#define PY_ARRAY_UNIQUE_SYMBOL USCSI_PyArray_API
#include <numpy/ndarrayobject.h>

#if SIZE_MAX==NPY_MAX_UINT32
#define NPY_SIZE_T NPY_UINT32
#elif SIZE_MAX==NPY_MAX_UINT64
#define NPY_SIZE_T NPY_UINT64
#else
#error logic error with SIZE_MAX
#endif

#define TRY PyState *state = (PyState*)raw; try

namespace {

struct PyState {
    PyObject_HEAD
    PyObject *dict, *weak; //  __dict__ and __weakref__
    PyObject *attrs; // lookup name to attribute index (for StateBase)
    StateBase *state;
};

static
int PyState_traverse(PyObject *raw, visitproc visit, void *arg)
{
    PyState *state = (PyState*)raw;
    Py_VISIT(state->attrs);
    Py_VISIT(state->dict);
    return 0;
}

static
int PyState_clear(PyObject *raw)
{
    PyState *state = (PyState*)raw;
    Py_CLEAR(state->dict);
    Py_CLEAR(state->attrs);
    return 0;
}

static
void PyState_free(PyObject *raw)
{
    TRY {
        std::auto_ptr<StateBase> S(state->state);
        state->state = NULL;

        if(state->weak)
            PyObject_ClearWeakRefs(raw);

        PyState_clear(raw);

        Py_TYPE(raw)->tp_free(raw);
    } CATCH2V(std::exception, RuntimeError)
}

static
PyObject *PyState_getattro(PyObject *raw, PyObject *attr)
{
    TRY {
        PyObject *idx = PyDict_GetItem(state->attrs, attr);
        if(!idx) {
            return PyErr_Format(PyExc_AttributeError, "Unknown State attribute");
        }
        int i = PyInt_AsLong(idx);

        StateBase::ArrayInfo info;

        if(!state->state->getArray(i, info))
            return PyErr_Format(PyExc_AttributeError, "invalid attribute name");

        if(info.ndim==0) { // Scalar
            switch(info.type) {
            case StateBase::ArrayInfo::Double:
                return PyFloat_FromDouble(*(double*)info.ptr);
            case StateBase::ArrayInfo::Sizet:
                return PyLong_FromSize_t(*(size_t*)info.ptr);
            }
            return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type);
        }

        int pytype;
        switch(info.type) {
        case StateBase::ArrayInfo::Double: pytype = NPY_DOUBLE; break;
        case StateBase::ArrayInfo::Sizet: pytype = NPY_SIZE_T; break;
        default:
            return PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type);
        }

        npy_intp dims[5];
        memcpy(dims, info.dim, sizeof(dims));

        PyRef<> obj(PyArray_SimpleNewFromData(info.ndim, dims, pytype, info.ptr));

        Py_INCREF(state);
        PyArray_BASE(obj.py()) = (PyObject*)state;

        return obj.releasePy();
    } CATCH()
}

static
int PyState_setattro(PyObject *raw, PyObject *attr, PyObject *val)
{
    TRY {
        PyObject *idx = PyDict_GetItem(state->attrs, attr);
        if(!idx)
            return -1;
        int i = PyInt_AsLong(idx);

        StateBase::ArrayInfo info;

        if(!state->state->getArray(i, info)) {
            PyErr_SetString(PyExc_AttributeError, "invalid attribute name");
            return -1;
        }

        if(info.ndim!=0) {
            PyErr_SetString(PyExc_NotImplementedError, "Can't set array attributes (hint, use state.attr[:] = ...)");
            return -1;
        }

        switch(info.type) {
        case StateBase::ArrayInfo::Double: {
            double *dest = (double*)info.ptr;
            if(PyFloat_Check(val))
                *dest = PyFloat_AsDouble(val);
            else if(PyLong_Check(val))
                *dest = PyLong_AsDouble(val);
            else if(PyInt_Check(val))
                *dest = PyInt_AsLong(val);
            else
                PyErr_Format(PyExc_ValueError, "Can't assign to double field");
        }
            break;
        case StateBase::ArrayInfo::Sizet: {
            size_t *dest = (size_t*)info.ptr;
            if(PyFloat_Check(val))
                *dest = PyFloat_AsDouble(val);
            else if(PyLong_Check(val))
                *dest = PyLong_AsUnsignedLongLong(val);
            else if(PyInt_Check(val))
                *dest = PyInt_AsLong(val);
            else
                PyErr_Format(PyExc_ValueError, "Can't assign to double field");
        }
            break;
        default:
            PyErr_Format(PyExc_TypeError, "unsupported type code %d", info.type);
        }
        return PyErr_Occurred() ? -1 : 0;

    } CATCH3(std::exception, RuntimeError, -1)
}

static
PyObject* PyState_str(PyObject *raw)
{
    TRY {
        std::ostringstream strm;
        state->state->show(strm, 0);
        return PyString_FromString(strm.str().c_str());
    } CATCH()
}

static PyMethodDef PyState_methods[] = {
    {NULL, NULL, 0, NULL}
};

static PyTypeObject PyStateType = {
#if PY_MAJOR_VERSION >= 3
    PyVarObject_HEAD_INIT(NULL, 0)
#else
    PyObject_HEAD_INIT(NULL)
    0,
#endif
    "uscsi._internal.State",
    sizeof(PyState),
};

} // namespace

PyObject* wrapstate(StateBase* b)
{
    try {

        PyRef<PyState> state((PyState*)PyStateType.tp_alloc(&PyStateType, 0));

        state->state = b;
        state->attrs = state->weak = state->dict = 0;

        state->attrs = PyDict_New();
        if(!state->attrs)
            return NULL;

        for(unsigned i=0; true; i++)
        {
            StateBase::ArrayInfo info;

            if(!b->getArray(i, info))
                break;

            PyRef<> name(PyInt_FromLong(i));
            if(PyDict_SetItemString(state->attrs, info.name.c_str(), name.py()))
                throw std::runtime_error("Failed to insert into Dict");

        }

        return state.releasePy();
    } CATCH()
}

StateBase* unwrapstate(PyObject* raw)
{
    if(!PyObject_TypeCheck(raw, &PyStateType))
        throw std::invalid_argument("Argument is not a State");
    PyState *state = (PyState*)raw;
    return state->state;
}

int registerModState(PyObject *mod)
{
    PyStateType.tp_str = &PyState_str;
    PyStateType.tp_repr = &PyState_str;
    PyStateType.tp_dealloc = &PyState_free;

    PyStateType.tp_weaklistoffset = offsetof(PyState, weak);
    PyStateType.tp_traverse = &PyState_traverse;
    PyStateType.tp_clear = &PyState_clear;

    PyStateType.tp_dictoffset = offsetof(PyState, dict);
    PyStateType.tp_getattro = &PyState_getattro;
    PyStateType.tp_setattro = &PyState_setattro;

    PyStateType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC;
    PyStateType.tp_methods = PyState_methods;

    if(PyType_Ready(&PyStateType))
        return -1;

    Py_INCREF(&PyStateType);
    if(PyModule_AddObject(mod, "State", (PyObject*)&PyStateType)) {
        Py_DECREF(&PyStateType);
        return -1;
    }

    return 0;
}
<|endoftext|>